VirtualMachineManager

Java Code Examples for com.sun.jdi.VirtualMachineManager

https://www.programcreek.com/java-api-examples/index.php?api=com.sun.jdi.VirtualMachineManager

The following are top voted examples for showing how to use com.sun.jdi.VirtualMachineManager. 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 product more good examples.

+Save this class to your library

Example 1

Project: fiji   File: StartDebugging.java View source code 6 votes
private  VirtualMachine launchVirtualMachine() {

		VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
		LaunchingConnector defConnector = vmm.defaultConnector();
		Transport transport = defConnector.transport();
		List<LaunchingConnector> list = vmm.launchingConnectors();
		for (LaunchingConnector conn: list)
			System.out.println(conn.name());
		Map<String, Connector.Argument> arguments = defConnector.defaultArguments();
		Set<String> s = arguments.keySet();
		for (String string: s)
			System.out.println(string);
		Connector.Argument mainarg = arguments.get("main");
		String s1 = System.getProperty("java.class.path");
		mainarg.setValue("-classpath \"" + s1 + "\" fiji.MainClassForDebugging " + plugInName);

		try {
			return defConnector.launch(arguments);
		} catch (IOException exc) {
			throw new Error("Unable to launch target VM: " + exc);
		} catch (IllegalConnectorArgumentsException exc) {
			IJ.handleException(exc);
		} catch (VMStartException exc) {
			throw new Error("Target VM failed to initialize: " +
			                exc.getMessage());
		}
		return null;
	}

Example 2

Project: proxyhotswap   File: JDIRedefiner.java View source code 6 votes
private VirtualMachine connect(int port) throws IOException {
    VirtualMachineManager manager = Bootstrap.virtualMachineManager();

    // Find appropiate connector
    List<AttachingConnector> connectors = manager.attachingConnectors();
    AttachingConnector chosenConnector = null;
    for (AttachingConnector c : connectors) {
        if (c.transport().name().equals(TRANSPORT_NAME)) {
            chosenConnector = c;
            break;
        }
    }
    if (chosenConnector == null) {
        throw new IllegalStateException("Could not find socket connector");
    }

    // Set port argument
    AttachingConnector connector = chosenConnector;
    Map<String, Argument> defaults = connector.defaultArguments();
    Argument arg = defaults.get(PORT_ARGUMENT_NAME);
    if (arg == null) {
        throw new IllegalStateException("Could not find port argument");
    }
    arg.setValue(Integer.toString(port));

    // Attach
    try {
        System.out.println("Connector arguments: " + defaults);
        return connector.attach(defaults);
    } catch (IllegalConnectorArgumentsException e) {
        throw new IllegalArgumentException("Illegal connector arguments", e);
    }
}

Example 3

Project: robovm-eclipse   File: AbstractLaunchConfigurationDelegate.java View source code 6 votes
private VirtualMachine attachToVm(IProgressMonitor monitor, int port) throws CoreException {
    VirtualMachineManager manager = Bootstrap.virtualMachineManager();
    AttachingConnector connector = null;
    for (Iterator<?> it = manager.attachingConnectors().iterator(); it.hasNext();) {
        AttachingConnector con = (AttachingConnector) it.next();
        if ("dt_socket".equalsIgnoreCase(con.transport().name())) {
            connector = con;
            break;
        }
    }
    if (connector == null) {
        throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID, "Couldn‘t find socket transport"));
    }
    Map<String, Argument> defaultArguments = connector.defaultArguments();
    defaultArguments.get("hostname").setValue("localhost");
    defaultArguments.get("port").setValue("" + port);
    int retries = 60;
    CoreException exception = null;
    while (retries > 0) {
        try {
            return connector.attach(defaultArguments);
        } catch (Exception e) {
            exception = new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Couldn‘t connect to JDWP server at localhost:" + port, e));
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        if (monitor.isCanceled()) {
            return null;
        }
        retries--;
    }
    throw exception;
}

Example 4

Project: openjdk   File: SACoreAttachingConnector.java View source code 6 votes
private VirtualMachine createVirtualMachine(Class vmImplClass,
                                            String javaExec, String corefile)
    throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    java.lang.reflect.Method connectByCoreMethod = vmImplClass.getMethod(
                             "createVirtualMachineForCorefile",
                              new Class[] {
                                  VirtualMachineManager.class,
                                  String.class, String.class,
                                  Integer.TYPE
                              });
    return (VirtualMachine) connectByCoreMethod.invoke(null,
                              new Object[] {
                                  Bootstrap.virtualMachineManager(),
                                  javaExec,
                                  corefile,
                                  new Integer(0)
                              });
}

Example 5

Project: eclipse.jdt.debug   File: JDIDebugPlugin.java View source code 6 votes
/**
 * Returns the detected version of JDI support. This is intended to
 * distinguish between clients that support JDI 1.4 methods like hot code
 * replace.
 *
 * @return an array of version numbers, major followed by minor
 * @since 2.1
 */
public static int[] getJDIVersion() {
	if (fJDIVersion == null) {
		fJDIVersion = new int[2];
		VirtualMachineManager mgr = Bootstrap.virtualMachineManager();
		fJDIVersion[0] = mgr.majorInterfaceVersion();
		fJDIVersion[1] = mgr.minorInterfaceVersion();
	}
	return fJDIVersion;
}

Example 6

Project: Sorbet   File: Main.java View source code 6 votes
public static VirtualMachine createVirtualMachine(String main, String args) {

	VirtualMachineManager manager = Bootstrap.virtualMachineManager();

	LaunchingConnector connector = manager.defaultConnector();

	Map<String, Connector.Argument> arguments = connector.defaultArguments();

	arguments.get("main").setValue(main);
	if (args != null) {
		arguments.get("options").setValue(args);
	}

	try {
		VirtualMachine vm = connector.launch(arguments);

		// Forward standard out and standard error
		new StreamTunnel(vm.process().getInputStream(), System.out);
		new StreamTunnel(vm.process().getErrorStream(), System.err);

		return vm;
	} catch (IOException e) {
           throw new Error("Error: Could not launch target VM: " + e.getMessage());
       } catch (IllegalConnectorArgumentsException e) {
		StringBuffer illegalArguments = new StringBuffer();

		for (String arg : e.argumentNames()) {
			illegalArguments.append(arg);
		}

           throw new Error("Error: Could not launch target VM because of illegal arguments: " + illegalArguments.toString());
       } catch (VMStartException e) {
           throw new Error("Error: Could not launch target VM: " + e.getMessage());
       }
}

Example 7

Project: HotswapAgent   File: JDIRedefiner.java View source code 6 votes
private VirtualMachine connect(int port) throws IOException {
	VirtualMachineManager manager = Bootstrap.virtualMachineManager();

	// Find appropiate connector
	List<AttachingConnector> connectors = manager.attachingConnectors();
	AttachingConnector chosenConnector = null;
	for (AttachingConnector c : connectors) {
		if (c.transport().name().equals(TRANSPORT_NAME)) {
			chosenConnector = c;
			break;
		}
	}
	if (chosenConnector == null) {
		throw new IllegalStateException("Could not find socket connector");
	}

	// Set port argument
	AttachingConnector connector = chosenConnector;
	Map<String, Argument> defaults = connector.defaultArguments();
	Argument arg = defaults.get(PORT_ARGUMENT_NAME);
	if (arg == null) {
		throw new IllegalStateException("Could not find port argument");
	}
	arg.setValue(Integer.toString(port));

	// Attach
	try {
		System.out.println("Connector arguments: " + defaults);
		return connector.attach(defaults);
	} catch (IllegalConnectorArgumentsException e) {
		throw new IllegalArgumentException("Illegal connector arguments", e);
	}
}

Example 8

Project: gravel   File: VMAcquirer.java View source code 6 votes
private AttachingConnector getConnector() {
  VirtualMachineManager vmManager = Bootstrap
      .virtualMachineManager();
  for (AttachingConnector connector : vmManager
      .attachingConnectors()) {
    if ("com.sun.jdi.SocketAttach".equals(connector
        .name())) {
      return (AttachingConnector) connector;
    }
  }
  throw new IllegalStateException();
}

Example 9

Project: ceylon-compiler   File: TracerImpl.java View source code 6 votes
public void start() throws Exception {
    VirtualMachineManager vmm = com.sun.jdi.Bootstrap.virtualMachineManager();
    LaunchingConnector conn = vmm.defaultConnector();
    Map<String, Argument> defaultArguments = conn.defaultArguments();
    defaultArguments.get("main").setValue(mainClass);
    defaultArguments.get("options").setValue("-cp " + classPath);
    System.out.println(defaultArguments);
    vm = conn.launch(defaultArguments);
    err = vm.process().getErrorStream();
    out = vm.process().getInputStream();
    eq = vm.eventQueue();
    rm = vm.eventRequestManager();
    outer: while (true) {
        echo(err, System.err);
        echo(out, System.out);
        events = eq.remove();
        for (Event event : events) {
            if (event instanceof VMStartEvent) {
                System.out.println(event);
                break outer;
            } else if (event instanceof VMDisconnectEvent
                    || event instanceof VMDeathEvent) {
                System.out.println(event);
                vm = null;
                rm = null;
                eq = null;
                break outer;
            }
        }
        events.resume();
    }
    echo(err, System.err);
    echo(out, System.out);
}

Example 10

Project: j   File: VMConnection.java View source code 6 votes
public static VMConnection getConnection(Jdb jdb)
{
    VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
    LaunchingConnector connector = vmm.defaultConnector();
    Map map = connector.defaultArguments();
    String javaHome = jdb.getJavaHome();
    ((Connector.Argument)map.get("home")).setValue(javaHome);
    String javaExecutable = jdb.getJavaExecutable();
    ((Connector.Argument)map.get("vmexec")).setValue(javaExecutable);

    // Command line.
    FastStringBuffer sb = new FastStringBuffer(jdb.getMainClass());
    String mainClassArgs = jdb.getMainClassArgs();
    if (mainClassArgs != null && mainClassArgs.length() > 0) {
        sb.append(‘ ‘);
        sb.append(mainClassArgs);
    }
    ((Connector.Argument)map.get("main")).setValue(sb.toString());

    // CLASSPATH and VM options.
    sb.setLength(0);
    String vmArgs = jdb.getVMArgs();
    if (vmArgs != null) {
        vmArgs = vmArgs.trim();
        if (vmArgs.length() > 0) {
            sb.append(vmArgs);
            sb.append(‘ ‘);
        }
    }
    String classPath = jdb.getClassPath();
    if (classPath != null) {
        classPath = classPath.trim();
        if (classPath.length() > 0) {
            sb.append("-classpath ");
            sb.append(classPath);
        }
    }
    ((Connector.Argument)map.get("options")).setValue(sb.toString());

    ((Connector.Argument)map.get("suspend")).setValue("true");
    return new VMConnection(connector, map);
}

Example 11

Project: eclipse.jdt.ui   File: InvocationCountPerformanceMeter.java View source code 6 votes
private void attach(String host, int port) throws IOException, IllegalConnectorArgumentsException {
	VirtualMachineManager manager= Bootstrap.virtualMachineManager();
	List<AttachingConnector> connectors= manager.attachingConnectors();
	AttachingConnector connector= connectors.get(0);
	Map<String, Connector.Argument> args= connector.defaultArguments();

	args.get("port").setValue(String.valueOf(port)); //$NON-NLS-1$
	args.get("hostname").setValue(host); //$NON-NLS-1$
	fVM= connector.attach(args);
}

Example 12

Project: dcevm   File: JDIRedefiner.java View source code 6 votes
private VirtualMachine connect(int port) throws IOException {
    VirtualMachineManager manager = Bootstrap.virtualMachineManager();

    // Find appropiate connector
    List<AttachingConnector> connectors = manager.attachingConnectors();
    AttachingConnector chosenConnector = null;
    for (AttachingConnector c : connectors) {
        if (c.transport().name().equals(TRANSPORT_NAME)) {
            chosenConnector = c;
            break;
        }
    }
    if (chosenConnector == null) {
        throw new IllegalStateException("Could not find socket connector");
    }

    // Set port argument
    AttachingConnector connector = chosenConnector;
    Map<String, Argument> defaults = connector.defaultArguments();
    Argument arg = defaults.get(PORT_ARGUMENT_NAME);
    if (arg == null) {
        throw new IllegalStateException("Could not find port argument");
    }
    arg.setValue(Integer.toString(port));

    // Attach
    try {
        System.out.println("Connector arguments: " + defaults);
        return connector.attach(defaults);
    } catch (IllegalConnectorArgumentsException e) {
        throw new IllegalArgumentException("Illegal connector arguments", e);
    }
}

Example 13

Project: visage-compiler   File: VisageBootstrap.java View source code 6 votes
public static VirtualMachineManager virtualMachineManager() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        JDIPermission vmmPermission =
                new JDIPermission("virtualMachineManager");
        sm.checkPermission(vmmPermission);
    }
    synchronized (lock) {
        if (vmm == null) {
            vmm = new VisageVirtualMachineManager();
        }
    }
    return vmm;
}

Example 14

Project: XRobot   File: LaunchEV3ConfigDelegate.java View source code 5 votes
public void run() {
  		try {
		Thread.sleep(5000);
	} catch (InterruptedException e) {
	}

	LeJOSEV3Util.message("Starting debugger ...");

	// Find the socket attach connector
	VirtualMachineManager mgr=Bootstrap.virtualMachineManager();

	List<?> connectors = mgr.attachingConnectors();

	AttachingConnector chosen=null;
	for (Iterator<?> iterator = connectors.iterator(); iterator
			.hasNext();) {
		AttachingConnector conn = (AttachingConnector) iterator.next();
		if(conn.name().contains("SocketAttach")) {
			chosen=conn;
			break;
		}
	}

	if(chosen == null) {
		LeJOSEV3Util.error("No suitable connector");
	} else {
		Map<String, Argument> connectorArgs = chosen.defaultArguments();

		Connector.IntegerArgument portArg = (IntegerArgument) connectorArgs.get("port");
		Connector.StringArgument hostArg = (StringArgument) connectorArgs.get("hostname");
		portArg.setValue(8000);

		//LeJOSEV3Util.message("hostArg is " + hostArg);
		hostArg.setValue(brickName);

		VirtualMachine vm;

		int retries = 10;
		while (true) {
			try {
				vm = chosen.attach(connectorArgs);
				break;
			} catch (Exception e) {
				if (--retries == 0) {
					LeJOSEV3Util.message("Failed to attach to the debugger: " + e);
					return;
				}
	    		try {
					Thread.sleep(2000);
				} catch (InterruptedException e1) {
				}
			}
		}
		LeJOSEV3Util.message("Connection established");

		JDIDebugModel.newDebugTarget(launch, vm, simpleName, null, true, true, true);
	}
}

Example 15

Project: eclipse.jdt.core   File: DebugEvaluationSetup.java View source code 5 votes
protected void setUp() {
	if (this.context == null) {
		// Launch VM in evaluation mode
		int debugPort = Util.getFreePort();
		int evalPort = Util.getFreePort();
		LocalVMLauncher launcher;
		try {
			launcher = LocalVMLauncher.getLauncher();
			launcher.setVMArguments(new String[]{"-verify"});
			launcher.setVMPath(JRE_PATH);
			launcher.setEvalPort(evalPort);
			launcher.setEvalTargetPath(EVAL_DIRECTORY);
			launcher.setDebugPort(debugPort);
			this.launchedVM = launcher.launch();
		} catch (TargetException e) {
			throw new Error(e.getMessage());
		}

		// Thread that read the stout of the VM so that the VM doesn‘t block
		try {
			startReader("VM‘s stdout reader", this.launchedVM.getInputStream(), System.out);
		} catch (TargetException e) {
		}

		// Thread that read the sterr of the VM so that the VM doesn‘t block
		try {
			startReader("VM‘s sterr reader", this.launchedVM.getErrorStream(), System.err);
		} catch (TargetException e) {
		}

		// Start JDI connection (try 10 times)
		for (int i = 0; i < 10; i++) {
			try {
				VirtualMachineManager manager = org.eclipse.jdi.Bootstrap.virtualMachineManager();
				List connectors = manager.attachingConnectors();
				if (connectors.size() == 0)
					break;
				AttachingConnector connector = (AttachingConnector)connectors.get(0);
				Map args = connector.defaultArguments();
				Connector.Argument argument = (Connector.Argument)args.get("port");
				if (argument != null) {
					argument.setValue(String.valueOf(debugPort));
				}
				argument = (Connector.Argument)args.get("hostname");
				if (argument != null) {
					argument.setValue(launcher.getTargetAddress());
				}
				argument = (Connector.Argument)args.get("timeout");
				if (argument != null) {
					argument.setValue("10000");
				}
				this.vm = connector.attach(args);

				// workaround pb with some VMs
				this.vm.resume();

				break;
			} catch (IllegalConnectorArgumentsException e) {
				e.printStackTrace();
				try {
					System.out.println("Could not contact the VM at " + launcher.getTargetAddress() + ":" + debugPort + ". Retrying...");
					Thread.sleep(100);
				} catch (InterruptedException e2) {
				}
			} catch (IOException e) {
				e.printStackTrace();
				try {
					System.out.println("Could not contact the VM at " + launcher.getTargetAddress() +":"+ debugPort +". Retrying...");Thread.sleep(100);}catch(InterruptedException e2){}}}if(this.vm ==null){if(this.launchedVM !=null){// If the VM is not running, output error streamtry{if(!this.launchedVM.isRunning()){InputStreamin=this.launchedVM.getErrorStream();int read;do{
							read =in.read();if(read !=-1)System.out.print((char)read);}while(read !=-1);}}catch(TargetException e){}catch(IOException e){}// Shut it downtry{if(this.target !=null){this.target.disconnect();// Close the socket first so that the OS resource has a chance to be freed.}intretry=0;while(this.launchedVM.isRunning()&&(++retry<20)){try{Thread.sleep(retry*100);}catch(InterruptedException e){}}if(this.launchedVM.isRunning()){this.launchedVM.shutDown();}}catch(TargetException e){}}System.err.println("Could not contact the VM");return;}// Create contextthis.context =newEvaluationContext();// Create targetthis.target =newTargetInterface();this.target.connect("localhost", evalPort,30000);// allow 30s max to connect (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=188127)// Create name environmentthis.env =newFileSystem(Util.getJavaClassLibs(),newString[0],null);}super.setUp();}

Example 16

Project: jnode   File: Hotswap.java View source code 5 votes
private void connect(String host, String port, String name) throws Exception {
        // connect to JVM
        boolean useSocket = (port != null);

        VirtualMachineManager manager = Bootstrap.virtualMachineManager();
        List<AttachingConnector> connectors = manager.attachingConnectors();
        AttachingConnector connector = null;
//      System.err.println("Connectors available");
        for (int i = 0; i < connectors.size(); i++) {
            AttachingConnector tmp = connectors.get(i);
//          System.err.println("conn "+i+"  name="+tmp.name()+" transport="+tmp.transport().name()+
//          " description="+tmp.description());
            if (!useSocket && tmp.transport().name().equals("dt_shmem")) {
                connector = tmp;
                break;
            }
            if (useSocket && tmp.transport().name().equals("dt_socket")) {
                connector = tmp;
                break;
            }
        }
        if (connector == null) {
            throw new IllegalStateException("Cannot find shared memory connector");
        }

        Map<String, Argument> args = connector.defaultArguments();
//      Iterator iter = args.keySet().iterator();
//      while (iter.hasNext()) {
//          Object key = iter.next();
//          Object val = args.get(key);
//          System.err.println("key:"+key.toString()+" = "+val.toString());
//      }
        Connector.Argument arg;
        // use name if using dt_shmem
        if (!useSocket) {
            arg = (Connector.Argument) args.get("name");
            arg.setValue(name);
        } else {
            // use port if using dt_socket
            arg = (Connector.Argument) args.get("port");
            arg.setValue(port);
            if (host != null) {
                arg = (Connector.Argument) args.get("hostname");
                arg.setValue(host);
            }
        }
        vm = connector.attach(args);

        // query capabilities
        if (!vm.canRedefineClasses()) {
            throw new Exception("JVM doesn‘t support class replacement");
        }
//      if (!vm.canAddMethod()) {
//          throw new Exception("JVM doesn‘t support adding method");
//      }
//      System.err.println("attached!");
    }

Example 17

Project: Greenfoot   File: VMReference.java View source code 5 votes
/**
 * Launch a remote debug VM using a TCP/IP socket.
 *
 * @param initDir
 *            the directory to have as a current directory in the remote VM
 * @param mgr
 *            the virtual machine manager
 * @return an instance of a VirtualMachine or null if there was an error
 */
public VirtualMachine localhostSocketLaunch(File initDir, DebuggerTerminal term, VirtualMachineManager mgr)
{
    final int CONNECT_TRIES = 5; // try to connect max of 5 times
    final int CONNECT_WAIT = 500; // wait half a sec between each connect

    int portNumber;
    String [] launchParams;

    // launch the VM using the runtime classpath.
    Boot boot = Boot.getInstance();
    File [] filesPath = BPClassLoader.toFiles(boot.getRuntimeUserClassPath());
    String allClassPath = BPClassLoader.toClasspathString(filesPath);

    ArrayList<String> paramList = new ArrayList<String>(10);
    paramList.add(Config.getJDKExecutablePath(null, "java"));

    //check if any vm args are specified in Config, at the moment these
    //are only Locale options: user.language and user.country

    paramList.addAll(Config.getDebugVMArgs());

    paramList.add("-classpath");
    paramList.add(allClassPath);
    paramList.add("-Xdebug");
    paramList.add("-Xnoagent");
    if (Config.isMacOS()) {
        paramList.add("-Xdock:icon=" + Config.getBlueJIconPath() + "/" + Config.getVMIconsName());
        paramList.add("-Xdock:name=" + Config.getVMDockName());
    }
    paramList.add("-Xrunjdwp:transport=dt_socket,server=y");

    // set index of memory transport, this may be used later if socket launch
    // will not work
    transportIndex = paramList.size() - 1;
    paramList.add(SERVER_CLASSNAME);

    // set output encoding if specified, default is to use system default
    // this gets passed to ExecServer‘s main as an arg which can then be
    // used to specify encoding
    streamEncoding = Config.getPropString("bluej.terminal.encoding", null);
    isDefaultEncoding = (streamEncoding == null);
    if(!isDefaultEncoding) {
        paramList.add(streamEncoding);
    }

    launchParams = (String[]) paramList.toArray(new String[0]);

    String transport = Config.getPropString("bluej.vm.transport");

    AttachingConnector tcpipConnector = null;
    AttachingConnector shmemConnector = null;

    Throwable tcpipFailureReason = null;
    Throwable shmemFailureReason = null;

    // Attempt to connect via TCP/IP transport

    List connectors = mgr.attachingConnectors();
    AttachingConnector connector = null;

    // find the known connectors
    Iterator it = connectors.iterator();
    while (it.hasNext()) {
        AttachingConnector c = (AttachingConnector) it.next();

        if (c.transport().name().equals("dt_socket")) {
            tcpipConnector = c;
        }
        else if (c.transport().name().equals("dt_shmem")) {
            shmemConnector = c;
        }
    }

    connector = tcpipConnector;

    // If the transport has been explicitly set the shmem in bluej.defs,
    // try to use the dt_shmem connector first.
    if (transport.equals("dt_shmem") && shmemConnector != null)
        connector = null;

    for (int i = 0; i < CONNECT_TRIES; i++) {

        if (connector != null) {
            try {
                final StringBuffer listenMessage = new StringBuffer();
                remoteVMprocess = launchVM(initDir, launchParams, listenMessage, term);

                portNumber = extractPortNumber(listenMessage.toString());if(portNumber ==-1){
                    closeIO();
                    remoteVMprocess.destroy();
                    remoteVMprocess =null;thrownewException(){publicvoid printStackTrace(){Debug.message("Could not find port number to connect to debugger");Debug.message("Line received from debugger was: "+ listenMessage);}};}Map arguments = connector.defaultArguments();Connector.Argument hostnameArg =(Connector.Argument) arguments.get("hostname");Connector.Argument portArg =(Connector.Argument) arguments.get("port");Connector.Argument timeoutArg =(Connector.Argument) arguments.get("timeout");if(hostnameArg ==null|| portArg ==null){thrownewException(){publicvoid printStackTrace(){Debug.message("incompatible JPDA socket launch connector");}};}

                hostnameArg.setValue("127.0.0.1");
                portArg.setValue(Integer.toString(portNumber));if(timeoutArg !=null){// The timeout appears to be in milliseconds.// The default is apparently no timeout.
                    timeoutArg.setValue("1000");}VirtualMachine m =null;try{
                    m = connector.attach(arguments);}catch(Throwable t){// failed to connect.
                    closeIO();
                    remoteVMprocess.destroy();
                    remoteVMprocess =null;throw t;}Debug.log("Connected to debug VM via dt_socket transport...");
                machine = m;
                setupEventHandling();
                waitForStartup();Debug.log("Communication with debug VM fully established.");return m;}catch(Throwable t){
                tcpipFailureReason = t;}}// Attempt launch using shared memory transport, if available

        connector = shmemConnector;if(connector !=null){try{Map arguments = connector.defaultArguments();Connector.Argument addressArg =(Connector.Argument) arguments.get("name");if(addressArg ==null){thrownewException(){publicvoid printStackTrace(){Debug.message("Shared memory connector is incompatible - no ‘name‘ argument");}};}else{String shmName ="bluej"+ shmCount++;
                    addressArg.setValue(shmName);

                    launchParams[transportIndex]="-Xrunjdwp:transport=dt_shmem,address="+ shmName +",server=y,suspend=y";StringBuffer listenMessage =newStringBuffer();
                    remoteVMprocess = launchVM(initDir, launchParams, listenMessage,term);VirtualMachine m =null;try{
                        m = connector.attach(arguments);}catch(Throwable t){// failed to connect.
                        closeIO();
                        remoteVMprocess.destroy();
                        remoteVMprocess =null;throw t;}Debug.log("Connected to debug VM via dt_shmem transport...");
                    machine = m;
                    setupEventHandling();
                    waitForStartup();Debug.log("Communication with debug VM fully established.");return m;}}catch(Throwable t){
                shmemFailureReason = t;}}// Do a small wait between connection attemptstry{if(i != CONNECT_TRIES -1)Thread.sleep(CONNECT_WAIT);}catch(InterruptedException ie){break;}
        connector = tcpipConnector;}// failed to connectDebug.message("Failed to connect to debug VM. Reasons follow:");if(tcpipConnector !=null&& tcpipFailureReason !=null){Debug.message("dt_socket transport:");
        tcpipFailureReason.printStackTrace();}if(shmemConnector !=null&& shmemFailureReason !=null){Debug.message("dt_shmem transport:");
        tcpipFailureReason.printStackTrace();}if(shmemConnector ==null&& tcpipConnector ==null){Debug.message(" No suitable transports available.");}returnnull;}

Example 18

Project: classlib6   File: Hotswap.java View source code 5 votes
private void connect(String host, String port, String name) throws Exception {
        // connect to JVM
        boolean useSocket = (port != null);

        VirtualMachineManager manager = Bootstrap.virtualMachineManager();
        List connectors = manager.attachingConnectors();
        AttachingConnector connector = null;
//      System.err.println("Connectors available");
        for (int i = 0; i < connectors.size(); i++) {
            AttachingConnector tmp = (AttachingConnector) connectors.get(i);
//          System.err.println("conn "+i+"  name="+tmp.name()+" transport="+tmp.transport().name()+
//          " description="+tmp.description());
            if (!useSocket && tmp.transport().name().equals("dt_shmem")) {
                connector = tmp;
                break;
            }
            if (useSocket && tmp.transport().name().equals("dt_socket")) {
                connector = tmp;
                break;
            }
        }
        if (connector == null) {
            throw new IllegalStateException("Cannot find shared memory connector");
        }

        Map args = connector.defaultArguments();
//      Iterator iter = args.keySet().iterator();
//      while (iter.hasNext()) {
//          Object key = iter.next();
//          Object val = args.get(key);
//          System.err.println("key:"+key.toString()+" = "+val.toString());
//      }
        Connector.Argument arg;
        // use name if using dt_shmem
        if (!useSocket) {
            arg = (Connector.Argument) args.get("name");
            arg.setValue(name);
        } else {
            // use port if using dt_socket
            arg = (Connector.Argument) args.get("port");
            arg.setValue(port);
            if (host != null) {
                arg = (Connector.Argument) args.get("hostname");
                arg.setValue(host);
            }
        }
        vm = connector.attach(args);

        // query capabilities
        if (!vm.canRedefineClasses()) {
            throw new Exception("JVM doesn‘t support class replacement");
        }
//      if (!vm.canAddMethod()) {
//          throw new Exception("JVM doesn‘t support adding method");
//      }
//      System.err.println("attached!");
    }
时间: 2024-10-06 16:41:03

VirtualMachineManager的相关文章

PowerShell 批量创建Linux虚机

Write-Host -NoNewline -ForegroundColor Magenta '请输入要创建的虚机名称(如:VLNX******)' [String]$VM_Name = Read-Host Write-Host -NoNewline -ForegroundColor Magenta '请输入需要放在哪台宿主机上(如:PWSR******)' [String]$VM_HostName= Read-Host Write-Host -NoNewline -ForegroundColo

Asp.net使用powershell管理hyper-v

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Collections.Obje

[转]Running KVM and Openvswitch on Ubuntu 12.10

Running KVM and Openvswitch on Ubuntu 12.10 I've got an aging VMWare ESXi 4.0 server that needs to be replaced with something a little more modern and flexing. Obviously at home I don't need all the cool features that licensed VMWare comes with, but

JPDA(三):实现代码的HotSwap

JPDA系列: 1. JPDA(一):使用JDI写一个调试器 2. JPDA(二):架构源码浅析 redefineClasses JPDA提供了一个API,VirtualMachine#redefineClasses,我们可以通过这个API来实现Java代码的热替换. 下面直接上代码,我们的目标VM运行了如下代码,前面已经说过,目标VM启动时需要添加option,-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8787

JPDA 架构研究18 - JDI的Mirror机制

引入: 上篇文章从整体上来看待JDI协议,这里结合Eclipse的实现代码来讨论下JDI的Mirror机制. 分析: 镜像机制是将目标虚拟机上的所有数据.类型.域.方法.事件.状态和资源,以及调试器发向目标虚拟机的事件请求等都映射成 Mirror 对象.其思想和我们经常说的O/R Mapping一样,其主要思想就是把2个异构的系统中的事物统一起来. Mirror接口是JDI规范中定义的主接口,它位于com.sun.jdi包中: public abstract interface Mirror {

SCVMM中“云”属性的备份和恢复

昨天快下班收到一个噩耗,SCVMM2012 SP1中的300多虚拟机的"云"属性没了--具体表现就是在各个已经存在的云中,看不到一台虚拟机,具体表现就是,查看虚拟机的时候,云这块是空的. 出现这种问题到底有多坑爹呢?那就是最终的租户无法啊在SCAC以及SCVMM的控制台的云中看到任何虚拟机,而虚拟机实际上是存在的. 所以现在的做法是要想办法恢复这些属性. 第一个操作,你需要导入VMM的模块 Import-Module virtualmachinemanager 首先拉个表,看看当前的用

JPDA(一):使用JDI写一个调试器

Debugging规范 简单来说,Java Platform Debugger Architecture(JPDA)就是Java提供的一套用于开发Java调试工具的规范,任何的JDK实现都需要实现这个规范.JPDA是一个Architecture,它包括了三个不同层次的规范,如下图, / |--------------| / | VM | debuggee - ( |--------------| <------- JVMTI - Java VM Tool Interface \ | back-e

JPDA 架构研究19 - JDI的连接模块

引入: 上文提到了JDI的Mirror机制,把整个目标虚拟机上的所有数据.类型.域.方法.事件.状态和资源,以及调试器发向目标虚拟机的事件请求等都映射成Mirror 对象.这里进一步讨论JDI的链接模块. 分析: 连接模块其主要目的是提供调试器(Debugger)到目标虚拟机(Target VM)之间的交互通道. 从连接的发起方来看:连接的发起方可以是调试器,也可以是目标虚拟机. 从连接的数量来看,一个调试器可以连接多个目标VM, 但是一个目标VM只可以连接一个调试器. 我们从调试器(Debug

PowerShell实现批量收集SCVMM中虚拟机IP-续

因为本人技术提升了,所以这个脚本又改进了,得益于同事给我悉心教导c#语法,这个脚本更好用了.废话不多说,直接上代码. #powerd by 九叔 #批量从VMM和Hyper-V中获取IP地址,方便比对.更准确. #转载必须注明出处,可以以此做改进. param(   [String]$vmmServer = "sc-vmmsp1"  ) Import-Module virtualmachinemanager Get-SCVMMServer -ComputerName $vmmServe