This project has retired. For details please refer to its Attic page.
StreamingChecksum xref
View Javadoc
1   package org.apache.archiva.checksum;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.OutputStream;
25  import java.util.List;
26  import java.util.stream.Collectors;
27  
28  /**
29   *
30   * Class that handles checksums with streams.
31   *
32   * @author Martin Stockhammer <martin_s@apache.org>
33   */
34  public class StreamingChecksum
35  {
36      static final int BUFFER_SIZE=4096;
37  
38      public static void updateChecksums( InputStream input, List<ChecksumAlgorithm> algorithms, List<OutputStream> checksumOutput) {
39          List<Checksum> checksums = algorithms.stream().map(a -> new Checksum( a )).collect( Collectors.toList());
40          byte[] buffer = new byte[BUFFER_SIZE];
41          int read;
42          try
43          {
44              while ( ( read = input.read( buffer ) ) >= 0 )
45              {
46                  for (Checksum cs : checksums ) {
47                      cs.update( buffer, 0, read );
48                  }
49              }
50              int minIndex = Math.min(algorithms.size(), checksums.size());
51              for (int csIndex = 0; csIndex<minIndex; csIndex++) {
52                  Checksum cs = checksums.get(csIndex);
53                  cs.finish();
54                  OutputStream os =checksumOutput.get(csIndex);
55                  if (os!=null)
56                  {
57                      os.write( cs.getChecksum( ).getBytes( ) );
58                  }
59              }
60  
61          } catch ( IOException e ) {
62  
63          }
64      }
65  }