• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  *    Evgeny Mandrikov - initial API and implementation
10  *
11  *******************************************************************************/
12 package org.jacoco.examples;
13 
14 import java.io.FileOutputStream;
15 
16 import javax.management.MBeanServerConnection;
17 import javax.management.MBeanServerInvocationHandler;
18 import javax.management.ObjectName;
19 import javax.management.remote.JMXConnector;
20 import javax.management.remote.JMXConnectorFactory;
21 import javax.management.remote.JMXServiceURL;
22 
23 /**
24  * This example connects to a JaCoCo agent that runs with the option
25  * <code>jmx=yes</code> and requests execution data. The collected data is
26  * dumped to a local file.
27  */
28 public final class MBeanClient {
29 
30 	private static final String DESTFILE = "jacoco-client.exec";
31 
32 	private static final String SERVICE_URL = "service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi";
33 
34 	/**
35 	 * Execute the example.
36 	 *
37 	 * @param args
38 	 * @throws Exception
39 	 */
main(final String[] args)40 	public static void main(final String[] args) throws Exception {
41 		// Open connection to the coverage agent:
42 		final JMXServiceURL url = new JMXServiceURL(SERVICE_URL);
43 		final JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
44 		final MBeanServerConnection connection = jmxc
45 				.getMBeanServerConnection();
46 
47 		final IProxy proxy = (IProxy) MBeanServerInvocationHandler
48 				.newProxyInstance(connection, new ObjectName(
49 						"org.jacoco:type=Runtime"), IProxy.class, false);
50 
51 		// Retrieve JaCoCo version and session id:
52 		System.out.println("Version: " + proxy.getVersion());
53 		System.out.println("Session: " + proxy.getSessionId());
54 
55 		// Retrieve dump and write to file:
56 		final byte[] data = proxy.getExecutionData(false);
57 		final FileOutputStream localFile = new FileOutputStream(DESTFILE);
58 		localFile.write(data);
59 		localFile.close();
60 
61 		// Close connection:
62 		jmxc.close();
63 	}
64 
65 	interface IProxy {
getVersion()66 		String getVersion();
67 
getSessionId()68 		String getSessionId();
69 
setSessionId(String id)70 		void setSessionId(String id);
71 
getExecutionData(boolean reset)72 		byte[] getExecutionData(boolean reset);
73 
dump(boolean reset)74 		void dump(boolean reset);
75 
reset()76 		void reset();
77 	}
78 
MBeanClient()79 	private MBeanClient() {
80 	}
81 }
82