001package org.apache.archiva.checksum; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, 015 * software distributed under the License is distributed on an 016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 017 * KIND, either express or implied. See the License for the 018 * specific language governing permissions and limitations 019 * under the License. 020 */ 021 022import java.io.IOException; 023import java.io.InputStream; 024import java.io.OutputStream; 025import java.util.List; 026import java.util.stream.Collectors; 027 028/** 029 * 030 * Class that handles checksums with streams. 031 * 032 * @author Martin Stockhammer <martin_s@apache.org> 033 */ 034public class StreamingChecksum 035{ 036 static final int BUFFER_SIZE=4096; 037 038 public static void updateChecksums( InputStream input, List<ChecksumAlgorithm> algorithms, List<OutputStream> checksumOutput) { 039 List<Checksum> checksums = algorithms.stream().map(a -> new Checksum( a )).collect( Collectors.toList()); 040 byte[] buffer = new byte[BUFFER_SIZE]; 041 int read; 042 try 043 { 044 while ( ( read = input.read( buffer ) ) >= 0 ) 045 { 046 for (Checksum cs : checksums ) { 047 cs.update( buffer, 0, read ); 048 } 049 } 050 int minIndex = Math.min(algorithms.size(), checksums.size()); 051 for (int csIndex = 0; csIndex<minIndex; csIndex++) { 052 Checksum cs = checksums.get(csIndex); 053 cs.finish(); 054 OutputStream os =checksumOutput.get(csIndex); 055 if (os!=null) 056 { 057 os.write( cs.getChecksum( ).getBytes( ) ); 058 } 059 } 060 061 } catch ( IOException e ) { 062 063 } 064 } 065}