Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: ba25d4ff32271e682b40f4c8ec67566d7c4e7c1e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*******************************************************************************
 * Copyright (c) 2018, 2018 Mykola Nikishov.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *    Mykola Nikishov - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.internal.p2.artifact.processors.checksum;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import org.eclipse.equinox.internal.p2.repository.helpers.ChecksumHelper;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep;

/**
 * @noreference This class is not intended to be referenced by clients.
 */
public abstract class MessageDigestProcessingStep extends ProcessingStep {

	protected MessageDigest messageDigest;
	private static final int BUFFER_SIZE = 16 * 1024;
	private ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);

	@Override
	final public void write(int b) throws IOException {
		getDestination().write(b);

		boolean isBufferFull = buffer.remaining() == 0;
		if (isBufferFull) {
			processBufferredBytes();
		}

		buffer.put((byte) b);
	}

	private void processBufferredBytes() {
		buffer.flip();
		updateDigest();
		buffer.clear();
	}

	private void updateDigest() {
		messageDigest.update(buffer);
	}

	@Override
	final public void close() throws IOException {
		processBufferredBytes();
		String digestString = digest();
		onClose(digestString);
		super.close();
	}

	private String digest() {
		byte[] digestBytes = messageDigest.digest();
		return ChecksumHelper.toHexString(digestBytes);
	}

	protected abstract void onClose(String digestString);

}

Back to the top