Java Code Examples for com.sun.tools.attach.VirtualMachine

The following are top voted examples for showing how to use com.sun.tools.attach.VirtualMachine. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Recaf   File: Attach.java   View source code 9 votes vote down vote up
/**
 * Spawn recaf in the JVM by the given descriptor.
 * 
 * @param vm
 */
public static void attach(VirtualMachineDescriptor vm) {
	try {
		// Run attach
		VirtualMachine target = VirtualMachine.attach(vm);
		String agentPath = getAgentJar();
		if (!agentPath.endsWith(".jar")) {
			Recaf.INSTANCE.logging.error(new RuntimeException("Recaf could not resolve a path to itself."));
			return;
		}
		File agent = new File(agentPath);
		if (agent.exists()) {
			Recaf.INSTANCE.logging.info("Attempting to attach to '" + vm.displayName() + "' with agent '" + agent.getAbsolutePath() + "'.");
			target.loadAgent(agent.getAbsolutePath());
			target.detach();
		} else {
			Recaf.INSTANCE.logging.error(new RuntimeException("Recaf could not resolve a path to itself, attempt gave: " + agent.getAbsolutePath()));
		}
	} catch (Exception e) {
		Recaf.INSTANCE.logging.error(e);
	}
}
 
Example 2
Project: util4j   File: AgentLoad.java   View source code 7 votes vote down vote up
public static void main(String[] args) throws IOException,
		AttachNotSupportedException, AgentLoadException,
		AgentInitializationException, InterruptedException {
	// 获取当前jvm的进程pid
	String pid = ManagementFactory.getRuntimeMXBean().getName();
	int indexOf = pid.indexOf('@');
	if (indexOf > 0) {
		pid = pid.substring(0, indexOf);
	}
	System.out.println("当前JVM Process ID: " + pid);
	// 获取当前jvm
	VirtualMachine vm = VirtualMachine.attach(pid);
	// 当前jvm加载代理jar包,参数1是jar包路径地址,参数2是给jar包代理类传递的参数
	vm.loadAgent("D:/123.jar", "my agent:123.jar");
	Thread.sleep(1000);
	vm.detach();
}
 
Example 3
Project: SuitAgent   File: JMXUtil.java   View source code 6 votes vote down vote up
/**
 * 获取指定服务名的本地JMX VM 描述对象
 * @param serverName
 * @return
 */
public static List<VirtualMachineDescriptor> getVmDescByServerName(String serverName){
    List<VirtualMachineDescriptor> vmDescList = new ArrayList<>();
    if (StringUtils.isEmpty(serverName)){
        return vmDescList;
    }
    List<VirtualMachineDescriptor> vms = VirtualMachine.list();
    for (VirtualMachineDescriptor desc : vms) {
        //java -jar 形式启动的Java应用
        if(desc.displayName().matches(".*\\.jar(\\s*-*.*)*") && desc.displayName().contains(serverName)){
            vmDescList.add(desc);
        }else if(hasContainsServerName(desc.displayName(),serverName)){
            vmDescList.add(desc);
        }else if (isJSVC(desc.id(),serverName)){
            VirtualMachineDescriptor descriptor = new VirtualMachineDescriptor(desc.provider(),desc.id(),serverName);
            vmDescList.add(descriptor);
        }
    }
    return vmDescList;
}
 
Example 4
Project: util4j   File: TestSpringLoaded.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws AttachNotSupportedException,
		IOException, AgentLoadException, AgentInitializationException,
		InterruptedException {
	VirtualMachine vm=AgentUtil.getCurrentVm();
	//先载入agent
	vm.loadAgent("d:/springloaded-1.2.1.RELEASE.jar","myagent");
	System.out.println("加载agent成功");
	vm.detach();
	TestSpringLoacedClass t1=new TestSpringLoacedClass();
	for(int i=0;i<10000;i++)
	{
		TestSpringLoacedClass t2=new TestSpringLoacedClass();
		t1.say2();
		t2.say2();
		Thread.sleep(1000);
	}
}
 
Example 5
Project: OpenJSharp   File: JMap.java   View source code 6 votes vote down vote up
private static void dump(String pid, String options) throws IOException {
    // parse the options to get the dump filename
    String filename = parseDumpOptions(options);
    if (filename == null) {
        usage(1);  // invalid options or no filename
    }

    // get the canonical path - important to avoid just passing
    // a "heap.bin" and having the dump created in the target VM
    // working directory rather than the directory where jmap
    // is executed.
    filename = new File(filename).getCanonicalPath();

    // dump live objects only or not
    boolean live = isDumpLiveObjects(options);

    VirtualMachine vm = attach(pid);
    System.out.println("Dumping heap to " + filename + " ...");
    InputStream in = ((HotSpotVirtualMachine)vm).
        dumpHeap((Object)filename,
                 (live ? LIVE_OBJECTS_OPTION : ALL_OBJECTS_OPTION));
    drain(vm, in);
}
 
Example 6
Project: OpenJSharp   File: JMap.java   View source code 6 votes vote down vote up
private static VirtualMachine attach(String pid) {
    try {
        return VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        if ((x instanceof AttachNotSupportedException) && haveSA()) {
            System.err.println("The -F option can be used when the " +
              "target process is not responding");
        }
        System.exit(1);
        return null; // keep compiler happy
    }
}
 
Example 7
Project: OpenJSharp   File: LocalVirtualMachine.java   View source code 6 votes vote down vote up
private void loadManagementAgent() throws IOException {
    VirtualMachine vm = null;
    String name = String.valueOf(vmid);
    try {
        vm = VirtualMachine.attach(name);
    } catch (AttachNotSupportedException x) {
        IOException ioe = new IOException(x.getMessage());
        ioe.initCause(x);
        throw ioe;
    }

    vm.startLocalManagementAgent();

    // get the connector address
    Properties agentProps = vm.getAgentProperties();
    address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);

    vm.detach();
}
 
Example 8
Project: OpenJSharp   File: SolarisAttachProvider.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new SolarisVirtualMachine(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 9
Project: OpenJSharp   File: LinuxAttachProvider.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new LinuxVirtualMachine(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 10
Project: jdk8u-jdk   File: JMap.java   View source code 6 votes vote down vote up
private static void dump(String pid, String options) throws IOException {
    // parse the options to get the dump filename
    String filename = parseDumpOptions(options);
    if (filename == null) {
        usage(1);  // invalid options or no filename
    }

    // get the canonical path - important to avoid just passing
    // a "heap.bin" and having the dump created in the target VM
    // working directory rather than the directory where jmap
    // is executed.
    filename = new File(filename).getCanonicalPath();

    // dump live objects only or not
    boolean live = isDumpLiveObjects(options);

    VirtualMachine vm = attach(pid);
    System.out.println("Dumping heap to " + filename + " ...");
    InputStream in = ((HotSpotVirtualMachine)vm).
        dumpHeap((Object)filename,
                 (live ? LIVE_OBJECTS_OPTION : ALL_OBJECTS_OPTION));
    drain(vm, in);
}
 
Example 11
Project: jdk8u-jdk   File: JMap.java   View source code 6 votes vote down vote up
private static VirtualMachine attach(String pid) {
    try {
        return VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        if ((x instanceof AttachNotSupportedException) && haveSA()) {
            System.err.println("The -F option can be used when the " +
              "target process is not responding");
        }
        System.exit(1);
        return null; // keep compiler happy
    }
}
 
Example 12
Project: jdk8u-jdk   File: LocalVirtualMachine.java   View source code 6 votes vote down vote up
private void loadManagementAgent() throws IOException {
    VirtualMachine vm = null;
    String name = String.valueOf(vmid);
    try {
        vm = VirtualMachine.attach(name);
    } catch (AttachNotSupportedException x) {
        IOException ioe = new IOException(x.getMessage());
        ioe.initCause(x);
        throw ioe;
    }

    vm.startLocalManagementAgent();

    // get the connector address
    Properties agentProps = vm.getAgentProperties();
    address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);

    vm.detach();
}
 
Example 13
Project: jdk8u-jdk   File: SolarisAttachProvider.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new SolarisVirtualMachine(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 14
Project: jdk8u-jdk   File: BsdAttachProvider.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new BsdVirtualMachine(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 15
Project: jdk8u-jdk   File: LinuxAttachProvider.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new LinuxVirtualMachine(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 16
Project: jdk8u-jdk   File: AixAttachProvider.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new AixVirtualMachine(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 17
Project: jdk8u-jdk   File: StartManagementAgent.java   View source code 6 votes vote down vote up
public static void testLocalAgent(VirtualMachine vm) throws Exception {
    Properties agentProps = vm.getAgentProperties();
    String address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
    if (address != null) {
        throw new Exception("Local management agent already started");
    }

    String result = vm.startLocalManagementAgent();

    // try to parse the return value as a JMXServiceURL
    new JMXServiceURL(result);

    agentProps = vm.getAgentProperties();
    address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
    if (address == null) {
        throw new Exception("Local management agent could not be started");
    }
}
 
Example 18
Project: jdk8u-jdk   File: PermissionTest.java   View source code 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    SecurityManager sm = System.getSecurityManager();
    if (sm == null) {
        throw new RuntimeException("Test configuration error - no security manager set");
    }

    String pid = args[0];
    boolean shouldFail = Boolean.parseBoolean(args[1]);

    try {
        VirtualMachine.attach(pid).detach();
        if (shouldFail) {
            throw new RuntimeException("SecurityException should be thrown");
        }
        System.out.println(" - attached to target VM as expected.");
    } catch (Exception x) {
        // AttachNotSupportedException thrown when no providers can be loaded
        if (shouldFail && ((x instanceof AttachNotSupportedException) ||
            (x instanceof SecurityException))) {
            System.out.println(" - exception thrown as expected.");
        } else {
            throw x;
        }
    }
}
 
Example 19
Project: Agent-Lib   File: AgentLoader.java   View source code 6 votes vote down vote up
public static void attach(Class<? extends Agent> agentClass, List<Class<?>> classes, File... libs) throws AgentInstantiationException, AttachNotSupportedException, AgentLoadException, AgentInitializationException, NotFoundException, CannotCompileException, IOException {
    try {
        Agent agent = agentClass.newInstance();
        VirtualMachine vm;
        switch (agent.type()) {
            case MAIN:
                vm = get1(agent.target());
                break;
            case PID:
                vm = get2(agent.target());
                break;
            default:
                vm = null;
                break;
        }
        load(vm, agent, classes, libs);
    } catch (IllegalAccessException | InstantiationException e) {
        throw new AgentInstantiationException();
    }
}
 
Example 20
Project: openjdk-jdk10   File: PermissionTest.java   View source code 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    SecurityManager sm = System.getSecurityManager();
    if (sm == null) {
        throw new RuntimeException("Test configuration error - no security manager set");
    }

    String pid = args[0];
    boolean shouldFail = Boolean.parseBoolean(args[1]);

    try {
        VirtualMachine.attach(pid).detach();
        if (shouldFail) {
            throw new RuntimeException("SecurityException should be thrown");
        }
        System.out.println(" - attached to target VM as expected.");
    } catch (Exception x) {
        // AttachNotSupportedException thrown when no providers can be loaded
        if (shouldFail && ((x instanceof AttachNotSupportedException) ||
            (x instanceof SecurityException))) {
            System.out.println(" - exception thrown as expected.");
        } else {
            throw x;
        }
    }
}
 
Example 21
Project: openjdk-jdk10   File: DefineClass.java   View source code 6 votes vote down vote up
private static void loadInstrumentationAgent(String myName, byte[] buf) throws Exception {
    // Create agent jar file on the fly
    Manifest m = new Manifest();
    m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    m.getMainAttributes().put(new Attributes.Name("Agent-Class"), myName);
    m.getMainAttributes().put(new Attributes.Name("Can-Redefine-Classes"), "true");
    File jarFile = File.createTempFile("agent", ".jar");
    jarFile.deleteOnExit();
    JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile), m);
    jar.putNextEntry(new JarEntry(myName.replace('.', '/') + ".class"));
    jar.write(buf);
    jar.close();
    String pid = Long.toString(ProcessTools.getProcessId());
    System.out.println("Our pid is = " + pid);
    VirtualMachine vm = VirtualMachine.attach(pid);
    vm.loadAgent(jarFile.getAbsolutePath());
}
 
Example 22
Project: openjdk-jdk10   File: LocalVirtualMachine.java   View source code 6 votes vote down vote up
private void loadManagementAgent() throws IOException {
    VirtualMachine vm = null;
    String name = String.valueOf(vmid);
    try {
        vm = VirtualMachine.attach(name);
    } catch (AttachNotSupportedException x) {
        IOException ioe = new IOException(x.getMessage());
        ioe.initCause(x);
        throw ioe;
    }

    vm.startLocalManagementAgent();

    // get the connector address
    Properties agentProps = vm.getAgentProperties();
    address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);

    vm.detach();
}
 
Example 23
Project: openjdk-jdk10   File: JMap.java   View source code 6 votes vote down vote up
private static void executeCommandForPid(String pid, String command, Object ... args)
    throws AttachNotSupportedException, IOException,
           UnsupportedEncodingException {
    VirtualMachine vm = VirtualMachine.attach(pid);

    // Cast to HotSpotVirtualMachine as this is an
    // implementation specific method.
    HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;
    try (InputStream in = hvm.executeCommand(command, args)) {
      // read to EOF and just print output
      byte b[] = new byte[256];
      int n;
      do {
          n = in.read(b);
          if (n > 0) {
              String s = new String(b, 0, n, "UTF-8");
              System.out.print(s);
          }
      } while (n > 0);
    }
    vm.detach();
}
 
Example 24
Project: openjdk-jdk10   File: AttachSelf.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        String value = System.getProperty("jdk.attach.allowAttachSelf");
        boolean canAttachSelf = (value != null) && !value.equals("false");

        String vmid = "" + ProcessHandle.current().pid();

        VirtualMachine vm = null;
        try {
            vm = VirtualMachine.attach(vmid);
            if (!canAttachSelf)
                throw new RuntimeException("Attached to self not expected");
        } catch (IOException ioe) {
            if (canAttachSelf)
                throw ioe;
        } finally {
            if (vm != null) vm.detach();
        }

    }
 
Example 25
Project: openjdk-jdk10   File: AttachProviderImpl.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new VirtualMachineImpl(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 26
Project: openjdk-jdk10   File: AttachProviderImpl.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new VirtualMachineImpl(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 27
Project: openjdk-jdk10   File: AttachProviderImpl.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new VirtualMachineImpl(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 28
Project: openjdk-jdk10   File: AttachProviderImpl.java   View source code 6 votes vote down vote up
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
    throws AttachNotSupportedException, IOException
{
    if (vmd.provider() != this) {
        throw new AttachNotSupportedException("provider mismatch");
    }
    // To avoid re-checking if the VM if attachable, we check if the descriptor
    // is for a hotspot VM - these descriptors are created by the listVirtualMachines
    // implementation which only returns a list of attachable VMs.
    if (vmd instanceof HotSpotVirtualMachineDescriptor) {
        assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable();
        checkAttachPermission();
        return new VirtualMachineImpl(this, vmd.id());
    } else {
        return attachVirtualMachine(vmd.id());
    }
}
 
Example 29
Project: openjdk-jdk10   File: Main.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("#modules loaded: " + moduleInfoCont());

    String vmid = "" + ProcessHandle.current().pid();
    VirtualMachine vm = VirtualMachine.attach(vmid);

    for (String test : args) {
        switch (test) {
            case "jmx" :
                startJMXAgent(vm);
                break;
            case "javaagent" :
                startJavaAgent(vm, createAgentJar());
                break;
        }

        System.out.println("#modules loaded: " + moduleInfoCont());
    }
}
 
Example 30
Project: openjdk-jdk10   File: StartManagementAgent.java   View source code 6 votes vote down vote up
public static void testLocalAgent(VirtualMachine vm) throws Exception {
    System.out.println("Getting VM properties");
    Properties agentProps = vm.getAgentProperties();
    String address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
    if (address != null) {
        throw new Exception("Local management agent already started");
    }

    System.out.println("Starting local agent");

    String result = vm.startLocalManagementAgent();

    System.out.println("Agent started");

    // try to parse the return value as a JMXServiceURL
    new JMXServiceURL(result);

    agentProps = vm.getAgentProperties();
    address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);
    if (address == null) {
        throw new Exception("Local management agent could not be started");
    }
}
 
Example 31
Project: RuntimeTransformer   File: TransformerUtils.java   View source code 5 votes vote down vote up
static void attachAgent(File agentFile, Class<?>[] transformers) {
    try {
        String pid = ManagementFactory.getRuntimeMXBean().getName();
        VirtualMachine vm = VirtualMachine.attach(pid.substring(0, pid.indexOf('@')));
        vm.loadAgent(agentFile.getAbsolutePath());
        vm.detach();

        Agent.getInstance().process(transformers);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 32
Project: util4j   File: JvmUtil.java   View source code 5 votes vote down vote up
/**
 * 获取当前JVM
 * @return
 * @throws IOException 
 * @throws AttachNotSupportedException 
 */
public static VirtualMachine getVirtualMachine() throws AttachNotSupportedException, IOException
{
	String pid = ManagementFactory.getRuntimeMXBean().getName();
	int indexOf = pid.indexOf('@');
	if (indexOf > 0) {
		pid = pid.substring(0, indexOf);
	}
	return VirtualMachine.attach(pid);
}
 
Example 33
Project: util4j   File: AgentUtil.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws AgentLoadException, AgentInitializationException, IOException, AttachNotSupportedException {
		VirtualMachine vm=VirtualMachine.attach("7876");
		vm.loadAgent("d:/springloaded-1.2.1.RELEASE.jar");
//		vm.loadAgent("d:/myagent.jar","myagent");
		System.out.println(vm.getAgentProperties().toString());
		System.in.read();
	}
 
Example 34
Project: OpenJSharp   File: JMap.java   View source code 5 votes vote down vote up
private static void drain(VirtualMachine vm, InputStream in) throws IOException {
    // read to EOF and just print output
    byte b[] = new byte[256];
    int n;
    do {
        n = in.read(b);
        if (n > 0) {
            String s = new String(b, 0, n, "UTF-8");
            System.out.print(s);
        }
    } while (n > 0);
    in.close();
    vm.detach();
}
 
Example 35
Project: OpenJSharp   File: JStack.java   View source code 5 votes vote down vote up
private static void runThreadDump(String pid, String args[]) throws Exception {
    VirtualMachine vm = null;
    try {
        vm = VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        if ((x instanceof AttachNotSupportedException) &&
            (loadSAClass() != null)) {
            System.err.println("The -F option can be used when the target " +
                "process is not responding");
        }
        System.exit(1);
    }

    // Cast to HotSpotVirtualMachine as this is implementation specific
    // method.
    InputStream in = ((HotSpotVirtualMachine)vm).remoteDataDump((Object[])args);

    // read to EOF and just print output
    byte b[] = new byte[256];
    int n;
    do {
        n = in.read(b);
        if (n > 0) {
            String s = new String(b, 0, n, "UTF-8");
            System.out.print(s);
        }
    } while (n > 0);
    in.close();
    vm.detach();
}
 
Example 36
Project: OpenJSharp   File: JCmd.java   View source code 5 votes vote down vote up
private static void executeCommandForPid(String pid, String command)
    throws AttachNotSupportedException, IOException,
           UnsupportedEncodingException {
    VirtualMachine vm = VirtualMachine.attach(pid);

    // Cast to HotSpotVirtualMachine as this is an
    // implementation specific method.
    HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;
    String lines[] = command.split("\\n");
    for (String line : lines) {
        if (line.trim().equals("stop")) {
            break;
        }
        try (InputStream in = hvm.executeJCmd(line);) {
            // read to EOF and just print output
            byte b[] = new byte[256];
            int n;
            boolean messagePrinted = false;
            do {
                n = in.read(b);
                if (n > 0) {
                    String s = new String(b, 0, n, "UTF-8");
                    System.out.print(s);
                    messagePrinted = true;
                }
            } while (n > 0);
            if (!messagePrinted) {
                System.out.println("Command executed successfully");
            }
        }
    }
    vm.detach();
}
 
Example 37
Project: OpenJSharp   File: JInfo.java   View source code 5 votes vote down vote up
private static VirtualMachine attach(String pid) {
    try {
        return VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        System.exit(1);
        return null; // keep compiler happy
    }
}
 
Example 38
Project: OpenJSharp   File: JInfo.java   View source code 5 votes vote down vote up
private static void drain(VirtualMachine vm, InputStream in) throws IOException {
    // read to EOF and just print output
    byte b[] = new byte[256];
    int n;
    do {
        n = in.read(b);
        if (n > 0) {
            String s = new String(b, 0, n, "UTF-8");
            System.out.print(s);
        }
    } while (n > 0);
    in.close();
    vm.detach();
}
 
Example 39
Project: OpenJSharp   File: WindowsAttachProvider.java   View source code 5 votes vote down vote up
public VirtualMachine attachVirtualMachine(String vmid)
    throws AttachNotSupportedException, IOException
{
    checkAttachPermission();

    // AttachNotSupportedException will be thrown if the target VM can be determined
    // to be not attachable.
    testAttachable(vmid);

    return new WindowsVirtualMachine(this, vmid);
}
 
Example 40
Project: OpenJSharp   File: SolarisAttachProvider.java   View source code 5 votes vote down vote up
public VirtualMachine attachVirtualMachine(String vmid)
    throws AttachNotSupportedException, IOException
{
    checkAttachPermission();

    // AttachNotSupportedException will be thrown if the target VM can be determined
    // to be not attachable.
    testAttachable(vmid);

    return new SolarisVirtualMachine(this, vmid);
}