1 /******************************************************************************* 2 * Copyright (c) 2009, 2021 Mountainminds GmbH & Co. KG and Contributors 3 * This program and the accompanying materials are made available under 4 * the terms of the Eclipse Public License 2.0 which is available at 5 * http://www.eclipse.org/legal/epl-2.0 6 * 7 * SPDX-License-Identifier: EPL-2.0 8 * 9 * Contributors: 10 * Evgeny Mandrikov - initial API and implementation 11 * 12 *******************************************************************************/ 13 package org.jacoco.examples; 14 15 import java.io.FileOutputStream; 16 17 import javax.management.MBeanServerConnection; 18 import javax.management.MBeanServerInvocationHandler; 19 import javax.management.ObjectName; 20 import javax.management.remote.JMXConnector; 21 import javax.management.remote.JMXConnectorFactory; 22 import javax.management.remote.JMXServiceURL; 23 24 /** 25 * This example connects to a JaCoCo agent that runs with the option 26 * <code>jmx=yes</code> and requests execution data. The collected data is 27 * dumped to a local file. 28 */ 29 public final class MBeanClient { 30 31 private static final String DESTFILE = "jacoco-client.exec"; 32 33 private static final String SERVICE_URL = "service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi"; 34 35 /** 36 * Execute the example. 37 * 38 * @param args 39 * @throws Exception 40 */ main(final String[] args)41 public static void main(final String[] args) throws Exception { 42 // Open connection to the coverage agent: 43 final JMXServiceURL url = new JMXServiceURL(SERVICE_URL); 44 final JMXConnector jmxc = JMXConnectorFactory.connect(url, null); 45 final MBeanServerConnection connection = jmxc 46 .getMBeanServerConnection(); 47 48 final IProxy proxy = (IProxy) MBeanServerInvocationHandler 49 .newProxyInstance(connection, 50 new ObjectName("org.jacoco:type=Runtime"), IProxy.class, 51 false); 52 53 // Retrieve JaCoCo version and session id: 54 System.out.println("Version: " + proxy.getVersion()); 55 System.out.println("Session: " + proxy.getSessionId()); 56 57 // Retrieve dump and write to file: 58 final byte[] data = proxy.getExecutionData(false); 59 final FileOutputStream localFile = new FileOutputStream(DESTFILE); 60 localFile.write(data); 61 localFile.close(); 62 63 // Close connection: 64 jmxc.close(); 65 } 66 67 interface IProxy { getVersion()68 String getVersion(); 69 getSessionId()70 String getSessionId(); 71 setSessionId(String id)72 void setSessionId(String id); 73 getExecutionData(boolean reset)74 byte[] getExecutionData(boolean reset); 75 dump(boolean reset)76 void dump(boolean reset); 77 reset()78 void reset(); 79 } 80 MBeanClient()81 private MBeanClient() { 82 } 83 } 84