1/*******************************************************************************
2 * Copyright (c) 2009, 2018 Mountainminds GmbH & Co. KG and Contributors
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 *    Marc R. Hoffmann - initial API and implementation
10 *
11 *******************************************************************************/
12package org.jacoco.core.runtime;
13
14import java.io.IOException;
15import java.io.InputStream;
16
17import org.jacoco.core.data.ExecutionDataReader;
18
19/**
20 * {@link ExecutionDataReader} with commands added for runtime remote control.
21 */
22public class RemoteControlReader extends ExecutionDataReader {
23
24	private IRemoteCommandVisitor remoteCommandVisitor;
25
26	/**
27	 * Create a new read based on the given input stream.
28	 *
29	 * @param input
30	 *            input stream to read commands from
31	 * @throws IOException
32	 *             if the stream does not have a valid header
33	 */
34	public RemoteControlReader(final InputStream input) throws IOException {
35		super(input);
36	}
37
38	@Override
39	protected boolean readBlock(final byte blockid) throws IOException {
40		switch (blockid) {
41		case RemoteControlWriter.BLOCK_CMDDUMP:
42			readDumpCommand();
43			return true;
44		case RemoteControlWriter.BLOCK_CMDOK:
45			return false;
46		default:
47			return super.readBlock(blockid);
48		}
49	}
50
51	/**
52	 * Sets an listener for agent commands.
53	 *
54	 * @param visitor
55	 *            visitor to retrieve agent commands
56	 */
57	public void setRemoteCommandVisitor(final IRemoteCommandVisitor visitor) {
58		this.remoteCommandVisitor = visitor;
59	}
60
61	private void readDumpCommand() throws IOException {
62		if (remoteCommandVisitor == null) {
63			throw new IOException("No remote command visitor.");
64		}
65		final boolean dump = in.readBoolean();
66		final boolean reset = in.readBoolean();
67		remoteCommandVisitor.visitDumpCommand(dump, reset);
68	}
69
70}
71