public Object executeMethod(String bean, String method, Object[] params, String[] signature) { MBeanServerConnection server = getMBeanServerConnection(); try { Object value = server.invoke(new ObjectName(bean), method, params, signature); if (LOG.isDebugEnabled()) { LOG.debug( "The bean: " + bean + " method: " + method + " params=" + Arrays.toString(params) + " signature=" + Arrays.toString(signature) + " returned: " + value); } return value; } catch (IOException e) { throw new RuntimeException("Failed to invoke method: " + method + ", for MBean: " + bean, e); } catch (InstanceNotFoundException e) { throw new RuntimeException("Failed to invoke method: " + method + ", for MBean: " + bean, e); } catch (MalformedObjectNameException e) { throw new RuntimeException("Failed to invoke method: " + method + ", for MBean: " + bean, e); } catch (MBeanException e) { throw new RuntimeException("Failed to invoke method: " + method + ", for MBean: " + bean, e); } catch (ReflectionException e) { throw new RuntimeException("Failed to invoke method: " + method + ", for MBean: " + bean, e); } catch (NullPointerException e) { throw new RuntimeException("Failed to invoke method: " + method + ", for MBean: " + bean, e); } }
public Object getAttributeValue(String bean, String attribute) { MBeanServerConnection server = getMBeanServerConnection(); try { Object value = server.getAttribute(new ObjectName(bean), attribute); if (LOG.isDebugEnabled()) { LOG.debug("The bean: " + bean + " attribute: " + attribute + " has the value: " + value); } return value; } catch (IOException e) { throw new RuntimeException( "Failed to get attribute: " + attribute + ", for MBean: " + bean, e); } catch (AttributeNotFoundException e) { throw new RuntimeException( "Failed to get attribute: " + attribute + ", for MBean: " + bean, e); } catch (InstanceNotFoundException e) { throw new RuntimeException( "Failed to get attribute: " + attribute + ", for MBean: " + bean, e); } catch (MalformedObjectNameException e) { throw new RuntimeException( "Failed to get attribute: " + attribute + ", for MBean: " + bean, e); } catch (MBeanException e) { throw new RuntimeException( "Failed to get attribute: " + attribute + ", for MBean: " + bean, e); } catch (ReflectionException e) { throw new RuntimeException( "Failed to get attribute: " + attribute + ", for MBean: " + bean, e); } catch (NullPointerException e) { throw new RuntimeException( "Failed to get attribute: " + attribute + ", for MBean: " + bean, e); } }
private static void workOnSingletoBean( MBeanServerConnection server, String jndiName, int numThreads, int numTimes) throws Exception { int singletonBeanInstances = (Integer) server.invoke( new ObjectName("jboss:name=ejb3-test,type=service"), "lookupSingleton", new Object[] {jndiName, numThreads, numTimes}, new String[] { String.class.getName(), Integer.TYPE.getName(), Integer.TYPE.getName() }); System.out.println("Number of singleton bean instances created is: " + singletonBeanInstances); int count = (Integer) server.invoke( new ObjectName("jboss:name=ejb3-test,type=service"), "invokeSingleton", new Object[] {jndiName, numThreads, numTimes}, new String[] { String.class.getName(), Integer.TYPE.getName(), Integer.TYPE.getName() }); System.out.println("Count is: " + count); }
/** List all MBeans and their attributes. */ public static void listMBeans(MBeanServerConnection server) throws IOException { final Set names = server.queryNames(null, null); for (final Iterator i = names.iterator(); i.hasNext(); ) { ObjectName name = (ObjectName) i.next(); System.out.println("Got MBean: " + name); try { MBeanInfo info = server.getMBeanInfo((ObjectName) name); MBeanAttributeInfo[] attrs = info.getAttributes(); if (attrs == null) continue; for (int j = 0; j < attrs.length; j++) { if (attrs[j].isReadable()) { try { Object o = server.getAttribute(name, attrs[j].getName()); System.out.println("\t\t" + attrs[j].getName() + " = " + o); } catch (Exception x) { System.err.println("JmxClient failed to get " + attrs[j].getName()); x.printStackTrace(System.err); } } } } catch (Exception x) { System.err.println("JmxClient failed to get MBeanInfo: " + x); x.printStackTrace(System.err); } } }
/** Constructs a PrintGCStat object to monitor a remote JVM. */ public PrintGCStat(MBeanServerConnection server) throws IOException { // Create the platform mxbean proxies this.rmbean = newPlatformMXBeanProxy(server, RUNTIME_MXBEAN_NAME, RuntimeMXBean.class); this.mmbean = newPlatformMXBeanProxy(server, MEMORY_MXBEAN_NAME, MemoryMXBean.class); ObjectName poolName = null; ObjectName gcName = null; try { poolName = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",*"); gcName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*"); } catch (MalformedObjectNameException e) { // should not reach here assert (false); } Set<ObjectName> mbeans = server.queryNames(poolName, null); if (mbeans != null) { pools = new ArrayList<MemoryPoolMXBean>(); for (ObjectName objName : mbeans) { MemoryPoolMXBean p = newPlatformMXBeanProxy(server, objName.getCanonicalName(), MemoryPoolMXBean.class); pools.add(p); } } mbeans = server.queryNames(gcName, null); if (mbeans != null) { gcmbeans = new ArrayList<GarbageCollectorMXBean>(); for (ObjectName objName : mbeans) { GarbageCollectorMXBean gc = newPlatformMXBeanProxy( server, objName.getCanonicalName(), GarbageCollectorMXBean.class); gcmbeans.add(gc); } } }
private String invokeEndpoint(String operation, String operationPara) throws Exception { ObjectName endpointName = null; ObjectName queryEndpointName; String ret = ""; Object[] jmxPara = null; String[] jmxSig = null; if (operationPara != null) { jmxPara = new Object[] {operationPara}; jmxSig = new String[] {String.class.getName()}; } else { jmxPara = new Object[0]; jmxSig = new String[0]; } queryEndpointName = getEndpointObjectName(); Set<ObjectName> endpointNames = CastUtils.cast(mbsc.queryNames(queryEndpointName, null)); // now get the ObjectName with the busId Iterator<ObjectName> it = endpointNames.iterator(); if (it.hasNext()) { // only deal with the first endpoint object which return from the list. endpointName = it.next(); ret = (String) mbsc.invoke(endpointName, operation, jmxPara, jmxSig); LOG.info("invoke endpoint " + endpointName + " operation " + operation + " succeed!"); } return ret; }
private static boolean test(String proto, MBeanServer mbs) throws Exception { System.out.println("Testing for proto " + proto); JMXConnectorServer cs; JMXServiceURL url = new JMXServiceURL(proto, null, 0); try { cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); } catch (MalformedURLException e) { System.out.println("System does not recognize URL: " + url + "; ignoring"); return true; } cs.start(); JMXServiceURL addr = cs.getAddress(); JMXServiceURL rmiurl = new JMXServiceURL("rmi", null, 0); JMXConnector client = JMXConnectorFactory.connect(addr); MBeanServerConnection mbsc = client.getMBeanServerConnection(); ObjectName on = new ObjectName("x:proto=" + proto + ",ok=yes"); mbsc.createMBean( RMIConnectorServer.class.getName(), on, mletName, new Object[] {rmiurl, null}, new String[] {JMXServiceURL.class.getName(), Map.class.getName()}); System.out.println("Successfully deserialized with " + proto); mbsc.unregisterMBean(on); client.close(); cs.stop(); return true; }
/** * Get full MBean name with given bean name, domain and session * * @param bean Name of bean. It can be NULL so that session#getBean() is returned * @param domain Domain for bean * @param session Current session * @return Full qualified name of MBean * @throws JMException Thrown when given MBean name is malformed * @throws IOException */ public static String getBeanName(String bean, String domain, Session session) throws JMException, IOException { Validate.notNull(session, "Session can't be NULL"); if (bean == null) { return session.getBean(); } if (SyntaxUtils.isNull(bean)) { return null; } MBeanServerConnection con = session.getConnection().getServerConnection(); if (bean.indexOf(':') != -1) { try { ObjectName name = new ObjectName(bean); con.getMBeanInfo(name); return bean; } catch (MalformedObjectNameException e) { } catch (InstanceNotFoundException e) { } } String domainName = DomainCommand.getDomainName(domain, session); if (domainName == null) { throw new IllegalArgumentException( "Please specify domain using either -d option or domain command"); } try { ObjectName name = new ObjectName(domainName + ":" + bean); con.getMBeanInfo(name); return domainName + ":" + bean; } catch (MalformedObjectNameException e) { } catch (InstanceNotFoundException e) { } throw new IllegalArgumentException("Bean name " + bean + " isn't valid"); }
@Test public void renameViaMBean() throws Exception { JMXConnector connector = null; try { connector = this.getJMXConnector(); MBeanServerConnection connection = connector.getMBeanServerConnection(); ObjectName name = new ObjectName("org.apache.karaf:type=instance,name=root"); connection.invoke( name, "createInstance", new Object[] {"itest5", 0, 0, 0, null, null, null, null}, new String[] { "java.lang.String", "int", "int", "int", "java.lang.String", "java.lang.String", "java.lang.String", "java.lang.String" }); connection.invoke( name, "renameInstance", new Object[] {"itest5", "new_itest5"}, new String[] {"java.lang.String", "java.lang.String"}); } finally { if (connector != null) connector.close(); } }
@Test(groups = "wso2.esb", description = "JMS Consumer Test after resume") public void testJMSResume() throws Exception { // redeploy proxy service addProxyService(AXIOMUtil.stringToOM(getJMSProxy())); // give it max time to deploy Thread.sleep(16000); // JMS should still be paused. assertTrue(!stringExistsInLog(msgAfter)); // resume JMS Listener from JMXClient Set<ObjectInstance> objSet = mbsc.queryMBeans( new ObjectName("org.apache.axis2:Type=Transport,ConnectorName=jms-listener-*"), null); Iterator i = objSet.iterator(); while (i.hasNext()) { ObjectInstance obj = (ObjectInstance) i.next(); mbsc.invoke(obj.getObjectName(), "resume", null, null); } Thread.sleep(10000); assertTrue(stringExistsInLog("Listener resumed")); assertTrue(stringExistsInLog(msgAfter)); }
@Test public void createDestroyViaMBean() throws Exception { JMXConnector connector = null; try { connector = this.getJMXConnector(); MBeanServerConnection connection = connector.getMBeanServerConnection(); ObjectName name = new ObjectName("org.apache.karaf:type=instance,name=root"); int oldNum = getInstancesNum(connection, name); connection.invoke( name, "createInstance", new Object[] {"itest2", 0, 0, 0, null, null, null, null}, new String[] { "java.lang.String", "int", "int", "int", "java.lang.String", "java.lang.String", "java.lang.String", "java.lang.String" }); Assert.assertEquals(oldNum + 1, getInstancesNum(connection, name)); connection.invoke( name, "destroyInstance", new Object[] {"itest2"}, new String[] {"java.lang.String"}); Assert.assertEquals(oldNum, getInstancesNum(connection, name)); } finally { if (connector != null) close(connector); } }
private Set<String> enumerateIndexes(ProbeDescSummary summary) { MBeanServerConnection mbean = cnx.getConnection().connection; Set<String> indexes = new HashSet<String>(); for (String name : summary.specifics.get("mbeanNames").split(" *; *")) { try { Set<ObjectName> mbeanNames = mbean.queryNames(new ObjectName(name), null); Pattern p = Pattern.compile(summary.specifics.get("mbeanIndex")); for (ObjectName oneMbean : mbeanNames) { log(Level.DEBUG, "%s", oneMbean.getCanonicalName()); Matcher m = p.matcher(oneMbean.toString()); if (m.matches() && !m.group(1).isEmpty()) { log(Level.DEBUG, "index found: %s for %s", m.group(1), summary.name); indexes.add(m.group(1)); } } } catch (MalformedObjectNameException e) { log( Level.WARN, "invalid name for auto discovery of probe %s: %s", summary.name, e.getMessage()); } catch (IOException e) { log( Level.WARN, "Connection failed for auto discovery of probe %s: %s", summary.name, e.getMessage()); } } return indexes; }
@Override public boolean isGoodProbeDesc(ProbeDescSummary summary) { MBeanServerConnection mbean = cnx.getConnection().connection; boolean valid = true; boolean enumerated = false; for (String name : summary.specifics.get("mbeanNames").split(" *; *")) { enumerated = true; try { Set<ObjectName> mbeanNames = mbean.queryNames(new ObjectName(name), null); log(Level.TRACE, "%s", "found mbeans %s for %s", mbeanNames, summary.name); if (mbeanNames.size() > 1 && !summary.isIndexed) { log(Level.WARN, "not indexed probe %s return more than one mbean", summary.name); valid = false; } else if (mbeanNames.size() > 0) { valid &= true; } else { valid = false; } } catch (MalformedObjectNameException e) { log( Level.WARN, "invalid name for auto discovery of probe %s: %s", summary.name, e.getMessage()); } catch (IOException e) { log( Level.WARN, "Connection failed for auto discovery of probe %s: %s", summary.name, e.getMessage()); } } return valid && enumerated; }
@Override public void run(String... args) throws Exception { // TODO Auto-generated method stub final AttachProvider attachProvider = AttachProvider.providers().get(0); VirtualMachineDescriptor descriptor = null; for (VirtualMachineDescriptor virtualMachineDescriptor : attachProvider.listVirtualMachines()) { if (virtualMachineDescriptor.displayName().equals(applicationName)) { descriptor = virtualMachineDescriptor; } } final VirtualMachine virtualMachine = attachProvider.attachVirtualMachine(descriptor); virtualMachine.loadAgent(managmentAgentJar, "com.sun.management.jmxremote"); final Object portObject = virtualMachine .getAgentProperties() .get("com.sun.management.jmxremote.localConnectorAddress"); final JMXServiceURL target = new JMXServiceURL(portObject + ""); final JMXConnector connector = JMXConnectorFactory.connect(target); final MBeanServerConnection remote = connector.getMBeanServerConnection(); final ObjectName objectName = new ObjectName("Catalina:type=Manager,host=localhost,context=" + context); System.out.println("Start"); System.out.println("ActiveSession = " + remote.getAttribute(objectName, "activeSessions")); System.out.println("End"); }
/** Calls a method. */ public Object __call(String name, Value values) { try { int size = values.getSize(); Object[] args = new Object[values.getSize()]; for (int i = 0; i < size; i++) { args[i] = values.get(LongValue.create(i)).toJavaObject(); } MBeanOperationInfo opInfo = findClosestOperation(name, args); if (opInfo != null) { String[] mbeanSig = createMBeanSig(opInfo); marshall(args, mbeanSig); Object value = _server.invoke(_name, name, args, mbeanSig); return unmarshall(value); } else { return _server.invoke(_name, name, args, null); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); return null; } }
@Override public boolean isRegistered(ObjectName name) throws IOException { try { return connection.isRegistered(name); } catch (IOException e) { checkConnection(); return connection.isRegistered(name); } }
@Override public Integer getMBeanCount() throws IOException { try { return connection.getMBeanCount(); } catch (IOException e) { checkConnection(); return connection.getMBeanCount(); } }
@Override public Set<ObjectName> queryNames(ObjectName name, QueryExp query) throws IOException { try { return connection.queryNames(name, query); } catch (IOException e) { checkConnection(); return connection.queryNames(name, query); } }
@Override public String[] getDomains() throws IOException { try { return connection.getDomains(); } catch (IOException e) { checkConnection(); return connection.getDomains(); } }
@Override public ObjectInstance getObjectInstance(ObjectName name) throws InstanceNotFoundException, IOException { try { return connection.getObjectInstance(name); } catch (IOException e) { checkConnection(); return connection.getObjectInstance(name); } }
@Override public boolean isInstanceOf(ObjectName name, String className) throws InstanceNotFoundException, IOException { try { return connection.isInstanceOf(name, className); } catch (IOException e) { checkConnection(); return connection.isInstanceOf(name, className); } }
@Override public MBeanInfo getMBeanInfo(ObjectName name) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException { try { return connection.getMBeanInfo(name); } catch (IOException e) { checkConnection(); return connection.getMBeanInfo(name); } }
@Override public AttributeList getAttributes(ObjectName name, String[] attributes) throws InstanceNotFoundException, ReflectionException, IOException { try { return connection.getAttributes(name, attributes); } catch (IOException e) { checkConnection(); return connection.getAttributes(name, attributes); } }
private static void test(String proto) throws Exception { System.out.println(">>> Test for protocol " + proto); JMXServiceURL u = null; JMXConnectorServer server = null; HashMap env = new HashMap(2); // server will close a client connection after 1 second env.put("jmx.remote.x.server.connection.timeout", "1000"); // disable the client ping env.put("jmx.remote.x.client.connection.check.period", "0"); try { u = new JMXServiceURL(proto, null, 0); server = JMXConnectorServerFactory.newJMXConnectorServer(u, env, mbs); } catch (MalformedURLException e) { System.out.println(">>> Skipping unsupported URL " + proto); } server.start(); JMXServiceURL addr = server.getAddress(); long st = 2000; MyListener myListener; // a cycle to make sure that we test the blocking problem. do { JMXConnector client = JMXConnectorFactory.connect(addr, env); MBeanServerConnection conn = client.getMBeanServerConnection(); myListener = new MyListener(conn); client.addConnectionNotificationListener(myListener, null, null); // wait the server to close the client connection Thread.sleep(st); // makes the listener to do a remote request via the connection // which should be closed by the server. conn.getDefaultDomain(); // allow the listner to have time to work Thread.sleep(100); // get a closed notif, should no block. client.close(); Thread.sleep(100); st += 2000; } while (!myListener.isDone()); server.stop(); }
private Object getJMXMBeanAttributeValue(String mBeanName, String attributeName) { try { MBeanServerConnection mBeanServerConnection = getJMXConnection(); ObjectName mbeanName = new ObjectName(mBeanName); return mBeanServerConnection.getAttribute(mbeanName, attributeName); } catch (Exception e) { throw new RuntimeException(JMX_RETRIEVAL_ERROR + mBeanName + ": " + attributeName, e); } }
@Override public Object getAttribute(ObjectName name, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException { try { return connection.getAttribute(name, attribute); } catch (IOException e) { checkConnection(); return connection.getAttribute(name, attribute); } }
public void setJMXMBeanAttributeValue(String mBeanName, String attributeName, Object value) { try { MBeanServerConnection mBeanServerConnection = getJMXConnection(); ObjectName mbeanName = new ObjectName(mBeanName); Attribute attr = new Attribute(attributeName, value); mBeanServerConnection.setAttribute(mbeanName, attr); } catch (Exception e) { throw new RuntimeException(JMX_RETRIEVAL_ERROR + mBeanName + ": " + attributeName, e); } }
@Test public void testMBean() throws Exception { final JMXConnector connector = JMXConnectorFactory.connect(managementClient.getRemoteJMXURL()); try { MBeanServerConnection mbeanServer = connector.getMBeanServerConnection(); ObjectName objectName = new ObjectName("jboss:name=test,type=config"); mbeanServer.getAttribute(objectName, "IntervalSeconds"); mbeanServer.setAttribute(objectName, new Attribute("IntervalSeconds", 2)); } finally { IoUtils.safeClose(connector); } }
private Object getRemoteValue() throws Exception { if (TangoConnectionFactory.isMockMode()) { // We also send this back to the workbench. final MBeanServerConnection client = getRemoteClient(); return client.invoke( RemoteWorkbenchAgent.REMOTE_WORKBENCH, "getMockMotorValue", new Object[] {getName()}, new String[] {String.class.getName()}); } else { throw new Exception("Cannot set Mock Values when not in mock mode!"); } }
@Override public void removeNotificationListener(ObjectName name, NotificationListener listener) throws InstanceNotFoundException, ListenerNotFoundException, IOException { try { connection.removeNotificationListener(name, listener); } catch (IOException e) { if (!checkConnection()) { connection.removeNotificationListener(name, listener); } else { throw e; } } }