AbstractRuntime.java revision 10a3ed3d5af2cbfbec2b35405d8d9420a9bf8776
1/*******************************************************************************
2 * Copyright (c) Copyright (c) Copyright (c) 2009, 2012 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.util.Random;
15
16import org.jacoco.core.data.ExecutionDataStore;
17import org.jacoco.core.data.IExecutionDataVisitor;
18import org.jacoco.core.data.ISessionInfoVisitor;
19import org.jacoco.core.data.SessionInfo;
20
21/**
22 * Base {@link IRuntime} implementation.
23 */
24public abstract class AbstractRuntime implements IRuntime {
25
26	/** store for execution data */
27	protected final ExecutionDataStore store;
28
29	/** access for this runtime instance */
30	protected final ExecutionDataAccess access;
31
32	private long startTimeStamp;
33
34	private String sessionId;
35
36	/**
37	 * Creates a new runtime.
38	 */
39	protected AbstractRuntime() {
40		store = new ExecutionDataStore();
41		access = new ExecutionDataAccess(store);
42		sessionId = createRandomId();
43	}
44
45	/**
46	 * Subclasses need to call this method in their {@link #startup()}
47	 * implementation to record the timestamp of session startup.
48	 */
49	protected final void setStartTimeStamp() {
50		startTimeStamp = System.currentTimeMillis();
51	}
52
53	public void setSessionId(final String id) {
54		sessionId = id;
55	}
56
57	public String getSessionId() {
58		return sessionId;
59	}
60
61	public final void collect(final IExecutionDataVisitor executionDataVisitor,
62			final ISessionInfoVisitor sessionInfoVisitor, final boolean reset) {
63		synchronized (store) {
64			if (sessionInfoVisitor != null) {
65				final SessionInfo info = new SessionInfo(sessionId,
66						startTimeStamp, System.currentTimeMillis());
67				sessionInfoVisitor.visitSessionInfo(info);
68			}
69			store.accept(executionDataVisitor);
70			if (reset) {
71				reset();
72			}
73		}
74	}
75
76	public final void reset() {
77		synchronized (store) {
78			store.reset();
79			setStartTimeStamp();
80		}
81	}
82
83	private static final Random RANDOM = new Random();
84
85	/**
86	 * Creates a random session identifier.
87	 *
88	 * @return random session identifier
89	 */
90	public static String createRandomId() {
91		return Integer.toHexString(RANDOM.nextInt());
92	}
93
94}
95