View Javadoc
1   /*
2    * dpkg - Debian Package library and the Debian Package Maven plugin
3    * (c) Copyright 2016 Gerrit Hohl
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18   */
19  package net.sourceforge.javadpkg.io.impl;
20  
21  import java.io.IOException;
22  import java.security.MessageDigest;
23  
24  import net.sourceforge.javadpkg.io.DataConsumer;
25  
26  
27  /**
28   * <p>
29   * A {@link DataConsumer} which updates a {@link MessageDigest}.
30   * </p>
31   *
32   * @author Gerrit Hohl (gerrit-hohl@users.sourceforge.net)
33   * @version <b>1.0</b>, 27.04.2016 by Gerrit Hohl
34   */
35  public class DataDigestConsumer implements DataConsumer {
36  	
37  	
38  	/** The digest. */
39  	private MessageDigest	digest;
40  	/** The name of the consumer in the exception (if one is thrown). */
41  	private String			name;
42  							
43  							
44  	/**
45  	 * <p>
46  	 * Creates a consumer.
47  	 * </p>
48  	 *
49  	 * @param digest
50  	 *            The digest.
51  	 * @param name
52  	 *            The name of the consumer in the exception (if one is thrown).
53  	 * @throws IllegalArgumentException
54  	 *             If any of the parameters are <code>null</code>.
55  	 */
56  	public DataDigestConsumer(MessageDigest digest, String name) {
57  		super();
58  		
59  		if (digest == null)
60  			throw new IllegalArgumentException("Argument digest is null.");
61  		if (name == null)
62  			throw new IllegalArgumentException("Argument name is null.");
63  
64  		this.digest = digest;
65  		this.name = name;
66  	}
67  	
68  	
69  	@Override
70  	public String getName() {
71  		return this.name;
72  	}
73  	
74  	
75  	@Override
76  	public void consume(byte[] buffer, int length) throws IOException {
77  		if (buffer == null)
78  			throw new IllegalArgumentException("Argument buffer is null.");
79  		if (length < 0)
80  			throw new IllegalArgumentException("Argument length is negative: " + length);
81  		if (length > buffer.length)
82  			throw new IllegalArgumentException("Argument length is greater than the buffer length. Length: " + length
83  					+ "; buffer length: " + buffer.length);
84  					
85  		this.digest.update(buffer, 0, length);
86  	}
87  	
88  }