创建JMX连接并构造VMInfo实例
174382
public static VMInfo processNewVM(String pid, String jmxHostAndPort) {
		try {
			final JmxClient jmxClient = new JmxClient();
			jmxClient.connect(pid, jmxHostAndPort);

			// 注册JMXClient注销的钩子
			Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
				@Override
				public void run() {
					jmxClient.disconnect();
				}
			}));

			return new VMInfo(jmxClient, pid);
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}

		return createDeadVM(pid, VMInfoState.ERROR_DURING_ATTACH);
	}
1088736
private void unregisterJmxExpose() {
		if (jmxNames.isEmpty()) {
			return;
		}
		try {
			final MBeanServer platformMBeanServer = MBeans.getPlatformMBeanServer();
			for (final ObjectName name : jmxNames) {
				platformMBeanServer.unregisterMBean(name);
			}
		} catch (final JMException e) {
			LOG.warn("failed to unregister JMX beans", e);
		}
	}
1211880
private static String getProcessId() {
        // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
        final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
        final int index = jvmName.indexOf('@');
        return index < 0 ? jvmName : jvmName.substring(0, index);
    }
1324360
public void main() {

        fMain = new Frame("HSQLDB Database Manager for Zaurus");
        imgEmpty = createImage(new MemoryImageSource(2, 2, new int[4 * 4], 2,
                2));

        fMain.setIconImage(imgEmpty);
        fMain.addWindowListener(this);

        MenuBar bar = new MenuBar();

        // no shortcuts used
        String[] fitems = {
            "-Connect...", "--", "-Open Script...", "-Save Script...",
            "-Save Result...", "--", "-Exit"
        };

        addMenu(bar, "File", fitems);

        String[] vitems = {
            "-Refresh Tree", "--", "-View Tree", "-View Command",
            "-View Result", "-View Editor", "--", "-Results in Grid",
            "-Results in Text"
        };

        addMenu(bar, "View", vitems);

        String[] sitems = {
            "-SELECT", "-INSERT", "-UPDATE", "-DELETE", "--", "-CREATE TABLE",
            "-DROP TABLE", "-CREATE INDEX", "-DROP INDEX", "--", "-SCRIPT",
            "-SHUTDOWN", "--", "-Test Script"
        };

        addMenu(bar, "SQL", sitems);

        Menu recent = new Menu("Recent");

        mRecent = new Menu("Recent");

        bar.add(mRecent);

        String[] soptions = {
            "-AutoCommit on", "-AutoCommit off", "-Commit", "-Rollback", "--",
            "-Disable MaxRows", "-Set MaxRows to 100", "--", "-Logging on",
            "-Logging off", "--",
            "-Insert test data"    // , "-Transfer"
        };

        addMenu(bar, "Options", soptions);

        String[] shelp = { "-Show HTML-Help in browser" };

        addMenu(bar, "?", shelp);
        fMain.setMenuBar(bar);
        fMain.setSize(defWidth, defHeight);
        fMain.add("Center", this);
        initGUI();

        sRecent = new String[iMaxRecent];

        Dimension d    = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension size = fMain.getSize();

        // (ulrivo): arguments from command line or
        // full size on screen with less than 640 width
        if (d.width > 640) {
            fMain.setLocation((d.width - size.width) / 2,
                              (d.height - size.height) / 2);
        } else if (defWidth > 0 && defHeight > 0) {
            fMain.setLocation(defLocX, defLocY);
            fMain.setSize(defWidth, defHeight);
        } else {
            fMain.setLocation(0, 0);
            fMain.setSize(d);
        }

        fMain.show();

        // (ulrivo): load query from command line
        if (defQuery != null) {
            txtCommand.setText(DatabaseManagerCommon.readFile(defQuery));
        }

        txtCommand.requestFocus();
    }
82919
@Override
	public final void register( ObjectName name , Object mBean ) throws JMSException
	{
		log.debug("Registering object " + name);
		try
		{
			this.mBeanServer.registerMBean(mBean, name);
		}
		catch (Exception e)
		{
			throw new FFMQException("Cannot register MBean", "JMX_ERROR", e);
		}
	}
133520
private MBeanInfo buildMbeanInfo(JmxAttributeFieldInfo[] attributeFieldInfos,
			JmxAttributeMethodInfo[] attributeMethodInfos, JmxOperationInfo[] operationInfos, boolean ignoreErrors) {

		// NOTE: setup the maps that track previous class configuration
		Map<String, JmxAttributeFieldInfo> attributeFieldInfoMap = null;
		if (attributeFieldInfos != null) {
			attributeFieldInfoMap = new HashMap<String, JmxAttributeFieldInfo>();
			for (JmxAttributeFieldInfo info : attributeFieldInfos) {
				attributeFieldInfoMap.put(info.getFieldName(), info);
			}
		}
		Map<String, JmxAttributeMethodInfo> attributeMethodInfoMap = null;
		if (attributeMethodInfos != null) {
			attributeMethodInfoMap = new HashMap<String, JmxAttributeMethodInfo>();
			for (JmxAttributeMethodInfo info : attributeMethodInfos) {
				attributeMethodInfoMap.put(info.getMethodName(), info);
			}
		}
		Map<String, JmxOperationInfo> attributeOperationInfoMap = null;
		if (operationInfos != null) {
			attributeOperationInfoMap = new HashMap<String, JmxOperationInfo>();
			for (JmxOperationInfo info : operationInfos) {
				attributeOperationInfoMap.put(info.getMethodName(), info);
			}
		}

		Set<String> attributeNameSet = new HashSet<String>();
		List<MBeanAttributeInfo> attributes = new ArrayList<MBeanAttributeInfo>();
		// NOTE: methods override fields so subclasses can stop exposing of fields
		discoverAttributeMethods(attributeMethodInfoMap, attributeNameSet, attributes, ignoreErrors);
		discoverAttributeFields(attributeFieldInfoMap, attributeNameSet, attributes);
		List<MBeanOperationInfo> operations = discoverOperations(attributeOperationInfoMap);

		return new MBeanInfo(target.getClass().getName(), description,
				attributes.toArray(new MBeanAttributeInfo[attributes.size()]), null,
				operations.toArray(new MBeanOperationInfo[operations.size()]), null);
	}
589821
function HyperServer($){

    //setup
    $ = Object.assign( defaults, $ ); 

    //injection
    let gx   = $.generator;
    let hx   = $.handler;

    //prototype
    let $ns, $n = proto();
    let dev  = ( 'development' == $n.get('env') || process.env.NODE_ENV  == 'development' );
    let port = (( dev ? $.LOCAL_PORT : $.APP_PORT ) || process.env.NODE_PORT );
 
    //config mapping
    $n.set( 'port', port );
    $n.set( 'view engine', $.VIEW_ENGINE );

    //middleware in out next
    if( dev ) $n.use( errorHandler({ dumpExceptions: true, showStack: true }) );
    $n.use( bodyParser.json() );
    $n.use( bodyParser.urlencoded({ extended:true }) );
    $n.use( override() );
    $n.use( cookieParser() );
    $n.use( sss({secret: 'secret', key:$.SESSION_ID, resave:true, saveUninitialized:true }));
    $n.use( ( i, o, n ) => { o.set('X-Powered-By', $.SERVER_ID ); n(); });
    $n.use( ( i, o, n ) => { i.baseUrl = i.originalUrl.split("?").shift(); n(); });
    $n.use( ( i, o, n ) => { console.info( `[${i.method} ${i.baseUrl}]`) || n(); }); //| q:${k(i.query)} \t | c:${k(i.cookies)}` ) || n(); });
    $n.use( favicon( $.PUBLIC_WWW + '/favicon.ico') );
    $n.use( proto.static( $.PUBLIC_WWW, {  
        setHeaders: ( res, path, stat ) => res.set('X-Timestamp', Date.now())
    }));

    //route stubs
    $.router.route( $n );

    //boot
    $ns = http.createServer($n)
          .on( 'close', ()=> {
            console.error( $.SERVER_ID + " - Shutting Down..");
          })
          .listen( port, data => {
            console.info( `Env  : [ ${( dev ? "DEV" : "UAT" )} ] \nPort : [ ${port} ]` );
            console.info( `URL  :  http://localhost:${port}` );
          });

    //termsigs
    process.once( 'SIGUSR2', ()=> {
            console.warn( 'Attempting to graceful kill...' );
            process.kill( process.pid, 'SIGUSR2');
          })
          .once( 'EADDRINUSE', ()=> {
            console.warn( 'Required port unavailable' );
            process.exit(1);
          });

    return $n;
  }
675329
private void doJmxValue(HttpServletResponse httpResponse, String jmxValueParameter)
			throws IOException {
		httpResponse.setContentType("text/plain");
		httpResponse.getWriter().write(MBeans.getConvertedAttributes(jmxValueParameter));
		httpResponse.flushBuffer();
	}
396090
private void reportOnJavaInformations() {
		// sessions
		if (javaInformations.getSessionCount() >= 0) {
			printLong(MetricType.GAUGE, "sessions_active_count", "active session count",
					javaInformations.getSessionCount());
			printLong(MetricType.GAUGE, "sessions_age_avg_minutes", "session avg age in minutes",
					javaInformations.getSessionMeanAgeInMinutes());
		}

		// connections
		if (!Parameters.isNoDatabase()) {
			printLong(MetricType.COUNTER, "transactions_count", "transactions count",
					javaInformations.getTransactionCount());
			printLong(MetricType.GAUGE, "connections_used_count", "used connections count",
					javaInformations.getActiveConnectionCount());
			printLong(MetricType.GAUGE, "connections_active_count", "active connections",
					javaInformations.getActiveConnectionCount());
			if (javaInformations.getMaxConnectionCount() > 0) {
				printLong(MetricType.GAUGE, "connections_max_count", "max connections",
						javaInformations.getMaxConnectionCount());
				printDouble(MetricType.GAUGE, "connections_used_pct", "used connections percentage",
						javaInformations.getUsedConnectionPercentage());
			}
		}

		// system
		if (javaInformations.getSystemLoadAverage() >= 0) {
			printDouble(MetricType.GAUGE, "system_load_avg", "system load average",
					javaInformations.getSystemLoadAverage());
		}
		if (javaInformations.getSystemCpuLoad() >= 0) {
			printDouble(MetricType.GAUGE, "system_cpu_load_pct", "system cpu load",
					javaInformations.getSystemCpuLoad());
		}
		if (javaInformations.getUnixOpenFileDescriptorCount() >= 0) {
			printDouble(MetricType.GAUGE, "system_unix_file_descriptors_open_count",
					"unix open file descriptors count",
					javaInformations.getUnixOpenFileDescriptorCount());
			printDouble(MetricType.GAUGE, "system_unix_file_descriptors_max",
					"unix file descriptors max", javaInformations.getUnixMaxFileDescriptorCount());
			printDouble(MetricType.GAUGE, "system_unix_file_descriptors_open_pct",
					"unix open file descriptors percentage",
					javaInformations.getUnixOpenFileDescriptorPercentage());
		}
		if (javaInformations.getFreeDiskSpaceInTemp() >= 0) {
			printLong(MetricType.GAUGE, "system_tmp_space_free_bytes", "tmp space available",
					javaInformations.getFreeDiskSpaceInTemp());
		}

		// jvm
		printLong(MetricType.GAUGE, "jvm_start_time", "jvm start time",
				javaInformations.getStartDate().getTime());
		printLong(MetricType.COUNTER, "jvm_cpu_millis", "jvm cpu millis",
				javaInformations.getProcessCpuTimeMillis());
		printLong(MetricType.GAUGE, "system_processors_count", "processors available",
				javaInformations.getAvailableProcessors());

		// threads
		printLong(MetricType.GAUGE, "threads_count", "threads count",
				javaInformations.getThreadCount());
		printLong(MetricType.GAUGE, "threads_max_count", "threads peak count",
				javaInformations.getPeakThreadCount());
		printLong(MetricType.COUNTER, "threads_started_count", "total threads started",
				javaInformations.getTotalStartedThreadCount());
		printLong(MetricType.GAUGE, "threads_active_count", "active thread count",
				javaInformations.getActiveThreadCount());

		// jobs
		if (javaInformations.isJobEnabled()) {
			printLong(MetricType.GAUGE, "job_executing_count", "executing job count",
					javaInformations.getCurrentlyExecutingJobCount());
		}
	}
500729
private JMSContext createJMSContext(JMSContextInfo info, boolean tranIsActive) throws NamingException {
        inTransaction = tranIsActive;

        ConnectionFactory cf = (ConnectionFactory) new InitialContext().lookup(info.getConnectionFactoryString());

        if (inTransaction && cf instanceof XAConnectionFactory) {

            XAJMSContext xaContext = ((XAConnectionFactory) cf).createXAContext(info.getUserName(), info.getPassword());
            return xaContext.getContext();

        } else {

            return cf.createContext(info.getUserName(), info.getPassword(), info.getAcknowledgeMode());
        }
    }
478396
function addVariable() {
            variableService.addOrUpdate(vm.variable, function () {
                vm.variables[vm.variable.key] = vm.variable.value;
                vm.variable = {
                    key: undefined,
                    value: undefined
                };
            });
        }
513961
public synchronized void register() throws Exception {
        if (mbeanName != null) {
            throw new Exception("Agent already registered");
        }
        mbeanName = new ObjectName(getClass().getPackage().getName() + ":type=" + getClass().getSimpleName());
        logger.info("Registering JMX agent " + mbeanName);
        ManagementFactory.getPlatformMBeanServer().registerMBean(this, mbeanName);
        logger.info("JMX agent " + mbeanName + " registered");
    }
671684
public static void main(String[] args) throws Exception {
		try (Split ignored = SimonManager.getStopwatch("org.javasimon.examples.jmx.main").start()) {
			Class.forName("org.h2.Driver");
			Class.forName("org.javasimon.jdbc4.Driver");

			MonitoredApplication s = new MonitoredApplication();
			s.setUp();

			Connection conn = null;
			try {
				conn = DriverManager.getConnection("jdbc:simon:h2:mem:db1");

				//noinspection UnusedDeclaration
				try (Split ops = SimonManager.getStopwatch("org.javasimon.examples.jmx.sql").start()) {
					s.doInsert(conn);
					s.doSelect(conn);
				}
			} finally {
				if (conn != null) {
					conn.close();
				}
			}
		}

		System.out.println("Simon monitor hierarchy:\n" + SimonUtils.simonTreeString(SimonManager.getRootSimon()));

		register();
		waitForEnterPressed();
		unregister();
	}
72719
function (vmTraceIndex, trace) {
    var step = trace[vmTraceIndex]
    if (this.isCreateInstruction(step)) {
      return this.contractCreationToken(vmTraceIndex)
    } else if (this.isCallInstruction(step)) {
      var stack = step.stack // callcode, delegatecall, ...
      return ui.normalizeHexAddress(stack[stack.length - 2])
    }
    return undefined
  }
261494
function(data, vmodels) {
            var oldStyle = data.param,
                    text = data.value,
                    rightExpr
            data.handlerName = "class"
            if (!oldStyle || isFinite(oldStyle)) {
                data.param = "" //去掉数字
                var noExpr = text.replace(rexprg, function(a) {
                    return Math.pow(10, a.length - 1) //将插值表达式插入10的N-1次方来占位
                })
                var colonIndex = noExpr.indexOf(":") //取得第一个冒号的位置
                if (colonIndex === -1) { // 比如 ms-class="aaa bbb ccc" 的情况
                    var className = text
                } else { // 比如 ms-class-1="ui-state-active:checked" 的情况 
                    className = text.slice(0, colonIndex)
                    rightExpr = text.slice(colonIndex + 1)
                    parseExpr(rightExpr, vmodels, data) //决定是添加还是删除
                    if (!data.evaluator) {
                        log("debug: ms-class '" + (rightExpr || "").trim() + "' 不存在于VM中")
                        return false
                    } else {
                        data._evaluator = data.evaluator
                        data._args = data.args
                    }
                }
                var hasExpr = rexpr.test(className) //比如ms-class="width{{w}}"的情况
                if (!hasExpr) {
                    data._class = className
                }
                parseExprProxy("", vmodels, data, (hasExpr ? scanExpr(className) : null))
            } else if (data.type === "class") {
                parseExprProxy(text, vmodels, data)
            }
        }
598537
private MBeanServerConnection createServerConnection(String host, int port) throws IOException {
            jmxServiceURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
            JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceURL, null);
            return jmxc.getMBeanServerConnection();            
    }
411499
private void configureProcessName() throws XPathExpressionException {
		if (processName != null) {
			return;
		}
		processName = "";
		Node jvm = getXmlNode("/jmxetric-config/jvm", inputSource);
		if (jvm != null) {
			processName = jvm.getAttributes().getNamedItem("process")
					.getNodeValue();
		}
	}