VirtualMachine保证JMX Agent已启动,
并向JMXClient提供连接地址地址样例：service:jmx:rmi://127.0
.0.1/stub/rO0ABXN9AAAAAQAl...
341029
public String attachToGetConnectorAddress() throws Exception {
		VirtualMachine vm = null;

		// 1. attach vm
		vm = VirtualMachine.attach(pid);

		try {
			// 2. 检查smartAgent是否已启动
			Properties agentProps = vm.getAgentProperties();
			String address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);

			if (address != null) {
				return address;
			}

			// 3. 未启动，尝试启动
			String home = vm.getSystemProperties().getProperty("java.home");

			// Normally in ${java.home}/jre/lib/management-agent.jar but might
			// be in ${java.home}/lib in build environments.

			String agentPath = home + File.separator + "jre" + File.separator + "lib" + File.separator
					+ "management-agent.jar";
			File f = new File(agentPath);
			if (!f.exists()) {
				agentPath = home + File.separator + "lib" + File.separator + "management-agent.jar";
				f = new File(agentPath);
				if (!f.exists()) {
					throw new IOException("Management agent not found");
				}
			}

			agentPath = f.getCanonicalPath();
			vm.loadAgent(agentPath, "com.sun.management.jmxremote");

			// 4. 再次获取connector address
			agentProps = vm.getAgentProperties();
			address = (String) agentProps.get(LOCAL_CONNECTOR_ADDRESS_PROP);

			if (address == null) {
				throw new IOException("Fails to find connector address");
			}

			return address;
		} finally {
			vm.detach();
		}
	}
302602
public JMXConnector getJMXConnector(String controllerHost, int controllerPort, String user, String password) throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException {
        HashMap<String, Object> environment = createJMXEnvironment(user, password, setUpSSLContext());
        JMXConnector connector = getMBeanServerConnection(controllerHost, controllerPort, environment);
        connector.connect();
        return connector;
    }
171849
private JvmOperation getJvmOperation(IMethod method, JvmType context)
			throws JavaModelException {
		if (context instanceof JvmDeclaredType) {
			final JvmDeclaredType declaredType = (JvmDeclaredType) context;
			final ActionParameterTypes jdtSignature = this.actionPrototypeProvider.createParameterTypes(
					Flags.isVarargs(method.getFlags()),
					getFormalParameterProvider(method));
			for (final JvmOperation jvmOperation : declaredType.getDeclaredOperations()) {
				final ActionParameterTypes jvmSignature = this.actionPrototypeProvider.createParameterTypesFromJvmModel(
						jvmOperation.isVarArgs(),
						jvmOperation.getParameters());
				if (jvmSignature.equals(jdtSignature)) {
					return jvmOperation;
				}
			}
		}
		return null;
	}
881707
public static JMXConnector connect(final String hostportOrPid, final String login, final String password)
			throws IOException {
		// ./vjmxcli.sh - 127.0.0.1:8060 gcutil
		if (hostportOrPid.contains(":")) {
			JMXServiceURL rmiurl = new JMXServiceURL(
					"service:jmx:rmi://" + hostportOrPid + "/jndi/rmi://" + hostportOrPid + "/jmxrmi");
			return JMXConnectorFactory.connect(rmiurl, formatCredentials(login, password));
		} else {
			// ./vjmxcli.sh - 112222 gcutil
			String localAddress = getLocalConnectorAddress(hostportOrPid);
			JMXServiceURL localRmiurl = new JMXServiceURL(localAddress);
			return JMXConnectorFactory.connect(localRmiurl);
		}
	}
805671
@Override
    public void onConnect(final int rst, final HuaweiApiClient client) {
        //需要在子线程中执行删除TOKEN操作
        ThreadUtil.INST.excute(new Runnable() {
            @Override
            public void run() {
                //调用删除TOKEN需要传入通过getToken接口获取到TOKEN，并且需要对TOKEN进行非空判断
                if (!TextUtils.isEmpty(token)){
                    if (client == null || !ApiClientMgr.INST.isConnect(client)) {
                        HMSAgentLog.e("client not connted");
                        onDeleteTokenResult(rst);
                    } else {
                        try {
                            HuaweiPush.HuaweiPushApi.deleteToken(client, token);
                            onDeleteTokenResult(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS);
                        } catch (Exception e) {
                            HMSAgentLog.e("删除TOKEN失败:" + e.getMessage());
                            onDeleteTokenResult(HMSAgent.AgentResultCode.CALL_EXCEPTION);
                        }
                    }
                } else {
                    HMSAgentLog.e("删除TOKEN失败: 要删除的token为空");
                    onDeleteTokenResult(HMSAgent.AgentResultCode.EMPTY_PARAM);
                }
            }
        });
    }
668888
public static JMX connect(String host, int port, String user, char[] password)
   {
 
	   return new JMX(host,port,user,password);
	   
   }
928077
public static String getVMStatus(String hostIpPort, String id) throws TargetException {

		if(id.startsWith("urn:uuid:")) id = id.substring(9);
		String status = null;
		URL url = null;
		try {
			CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
			url = new URL("http://" + hostIpPort + "/compute/" + id);
		} catch (MalformedURLException e) {
			throw new TargetException(e);
		}

		HttpURLConnection httpURLConnection = null;
		DataInputStream in = null;
		try {
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setRequestProperty("Accept", "application/json");

			in = new DataInputStream(httpURLConnection.getInputStream());
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			Utils.copyStreamSafely(in, out);

			// Parse JSON response to extract VM status
			ObjectMapper objectMapper = new ObjectMapper();
			JsonResponse rsp = objectMapper.readValue(out.toString( "UTF-8" ), JsonResponse.class);
			status = rsp.getState();

		} catch (IOException e) {
			throw new TargetException(e);

		}  finally {
			Utils.closeQuietly(in);
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}

		return status;
	}
378628
public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
        try {
            if (com.google.api.ads.adwords.axis.v201809.cm.OfflineConversionAdjustmentFeedServiceInterface.class.isAssignableFrom(serviceEndpointInterface)) {
                com.google.api.ads.adwords.axis.v201809.cm.OfflineConversionAdjustmentFeedServiceSoapBindingStub _stub = new com.google.api.ads.adwords.axis.v201809.cm.OfflineConversionAdjustmentFeedServiceSoapBindingStub(new java.net.URL(OfflineConversionAdjustmentFeedServiceInterfacePort_address), this);
                _stub.setPortName(getOfflineConversionAdjustmentFeedServiceInterfacePortWSDDServiceName());
                return _stub;
            }
        }
        catch (java.lang.Throwable t) {
            throw new javax.xml.rpc.ServiceException(t);
        }
        throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface:  " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName()));
    }
881929
public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
        try {
            if (com.google.api.ads.adwords.axis.v201809.cm.TrialServiceInterface.class.isAssignableFrom(serviceEndpointInterface)) {
                com.google.api.ads.adwords.axis.v201809.cm.TrialServiceSoapBindingStub _stub = new com.google.api.ads.adwords.axis.v201809.cm.TrialServiceSoapBindingStub(new java.net.URL(TrialServiceInterfacePort_address), this);
                _stub.setPortName(getTrialServiceInterfacePortWSDDServiceName());
                return _stub;
            }
        }
        catch (java.lang.Throwable t) {
            throw new javax.xml.rpc.ServiceException(t);
        }
        throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface:  " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName()));
    }
784304
private static void initJmxConn() throws IOException {
        if (jmxUrl != null) {
            JMXServiceURL url = new JMXServiceURL(jmxUrl);
            Map<String, String[]> env = null;
            if (jmxUsername != null) {
                env = Maps.newHashMap();
                String[] credentials = new String[]{jmxUsername, jmxPassword};
                env.put(JMXConnector.CREDENTIALS, credentials);
            }
            JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
            conn = jmxc.getMBeanServerConnection();
        }
    }
688375
public static MBeanServerConnection connectMBeanServer(String server) throws MBeanServerException {
        String url = "service:jmx:rmi://localhost/jndi/rmi://"+server+"/jmxrmi";
        try {
            JMXServiceURL jmxUrl = new JMXServiceURL(url);
            JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl);
            return jmxConnector.getMBeanServerConnection();
        } catch (MalformedURLException e) {
            throw new MBeanServerException(
                    "Problem with JMXServiceURL based on " + url +
                            ": " + e.getMessage());
        } catch (IOException e) {
            throw new MBeanServerException(
                    "Failed to connect to JMX server: " + server +
                            ": " + e.getMessage());
        }  
    }
49117
String collectMBeanAttribute(String jmxValueParameter) throws IOException {
		final URL mbeanAttributeUrl = new URL(
				url.toString() + '&' + HttpParameter.JMX_VALUE + '=' + jmxValueParameter);
		return collectForUrl(mbeanAttributeUrl);
	}
1206613
function getOriginApi(apiMap, apiName) {
    // 如果为全局mock模式，则直接修改apiName对应的mock路径，例如：
    // http://127.0.0.1:3000/__MOCK__/blog/blogApi
    if (config.isFullMock) {
      return `${config.mockPath}/${apiName}/`
    } else {
      const originApi = apiMap[apiName];

      // 如果在api配置中查找不到对应的api则报错
      if (!originApi) {
        throw `Undefined proxy url：${path} , please check your api config!`;
      }

      // 对于路由结尾强制添加"/"
      return originApi.replace(/([^\/])$/,'$1/');
    }


  }
395468
public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
        try {
            if (com.google.api.ads.admanager.axis.v201805.CreativeWrapperServiceInterface.class.isAssignableFrom(serviceEndpointInterface)) {
                com.google.api.ads.admanager.axis.v201805.CreativeWrapperServiceSoapBindingStub _stub = new com.google.api.ads.admanager.axis.v201805.CreativeWrapperServiceSoapBindingStub(new java.net.URL(CreativeWrapperServiceInterfacePort_address), this);
                _stub.setPortName(getCreativeWrapperServiceInterfacePortWSDDServiceName());
                return _stub;
            }
        }
        catch (java.lang.Throwable t) {
            throw new javax.xml.rpc.ServiceException(t);
        }
        throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface:  " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName()));
    }
780547
@Override
	public String retrievePublicIpAddress( TargetHandlerParameters parameters, String machineId )
	throws TargetException {

		String result = null;
		try {
			ServiceInstance vmwareServiceInstance = VmwareIaasHandler.getServiceInstance( parameters.getTargetProperties());
			String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());
			VirtualMachine vm = VmwareIaasHandler.getVirtualMachine( vmwareServiceInstance, rootInstanceName );
			if( vm != null )
				result = vm.getGuest().getIpAddress();

		} catch( Exception e ) {
			throw new TargetException( e );
		}

		return result;
	}
355782
public static void main(String[] args) throws Exception {
      String hostPort = "";
      if (args.length > 0) {
        hostPort = args[0];
      }
      JmxCollector jc = new JmxCollector(("{"
      + "`hostPort`: `" + hostPort + "`,"
      + "}").replace('`', '"'));
      for(MetricFamilySamples mfs : jc.collect()) {
        System.out.println(mfs);
      }
    }
1081294
function getModelFromServer(pagePath, callback, req) {
  let modelServerOptions = ROOT.MODEL_SERVER;
  let reqUrl = modelServerOptions.path;
  if (typeof reqUrl === 'function') {
    reqUrl = reqUrl({
      host: modelServerOptions.host,
      queries: modelServerOptions.queries,
      headers: modelServerOptions.headers,
      path: pagePath
    });
  }
  // 如果没有设置path，则默认为页面的path
  if (!reqUrl) {
    reqUrl = pagePath;
  }
  if (!reqUrl.startsWith('http')) {
    if (!modelServerOptions.host.endsWith('/')) {
      modelServerOptions.host += '/';
    }
    if (reqUrl.startsWith('/')) {
      reqUrl = reqUrl.slice(1);
    }
    // 是相对地址，加上主机地址
    reqUrl = `${modelServerOptions.host}${reqUrl}`;
  }
  // 处理查询参数
  if (modelServerOptions.queries && Object.keys(modelServerOptions.queries).length) {
    let qs = querystring.stringify(modelServerOptions.queries);
    reqUrl += (reqUrl.includes('?') ? `&` : `?`) + qs;
  }
  let reqHeaders = {};
  // 需要判断有没有 cookie，没有的话，值是 undefined，最后发请求的时候会报错
  // 重现方法：本地删除cookie再发请求
  if (req.headers.cookie) {
    reqHeaders.cookie = req.headers.cookie;
  }
  // 处理请求头
  if (modelServerOptions.headers) {
    Object.keys(modelServerOptions.headers).forEach(function (headerKey) {
      reqHeaders[headerKey] = modelServerOptions.headers[headerKey];
    });
  }
  let urlParseResult = url.parse(reqUrl);
  let options = {
    hostname: urlParseResult.hostname,
    port: urlParseResult.port,
    path: urlParseResult.path,
    headers: reqHeaders,
    protocol: urlParseResult.protocol
  };
  console.log(`页面 ${pagePath} 的模型请求信息：${JSON.stringify(options)}`);
  require(urlParseResult.protocol.slice(0,-1)).get(options, function (res) {
    let ret = [];
    res.on('data', function (chunk) {
      ret.push(chunk.toString());
    });
    res.on('end', function () {
      let json = {};
      try {
        json = JSON.parse(ret.join(''));
        console.log(`页面 ${pagePath} 的模型请求返回的 json 数据为：${JSON.stringify(json)}`);
      } catch (ex) {
        console.log(`页面 ${pagePath} 的模型请求没有返回 json 数据：${JSON.stringify(ret)}`);
      }
      callback(json);
    });
  }).on('error', function (error) {
    callback(error.message);
  });
}