Skip to main content
summaryrefslogtreecommitdiffstats
blob: 3fef57d03ac806885e1a62135f66318eb85b7dc7 (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
69
/*******************************************************************************
 * Copyright (c) 2018, 2018 Mykola Nikishov.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Mykola Nikishov - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.internal.p2.artifact.processors.checksum;

import java.io.IOException;
import java.nio.BufferOverflowException;
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
	// TODO template method, should be final but MD5Verifier prevents this
	public void write(int b) throws IOException {
		getDestination().write(b);

		// TODO exceptions are expensive
		try {
			buffer.put((byte) b);
		} catch (BufferOverflowException e) {
			processBufferredBytes();
			buffer.put((byte) b);
		}
	}

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

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

	@Override
	// TODO should be final but MD5Verifier prevents this
	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