/** * Obtain the default JBoss JCA WorkManager through a JMX lookup * for the JBossWorkManagerMBean. * @param mbeanName the JMX object name to use * @see org.jboss.resource.work.JBossWorkManagerMBean */ public static WorkManager getWorkManager(String mbeanName) { Assert.hasLength(mbeanName, "JBossWorkManagerMBean name must not be empty"); try { Class<?> mbeanClass = JBossWorkManagerUtils.class.getClassLoader().loadClass(JBOSS_WORK_MANAGER_MBEAN_CLASS_NAME); InitialContext jndiContext = new InitialContext(); MBeanServerConnection mconn = (MBeanServerConnection) jndiContext.lookup(MBEAN_SERVER_CONNECTION_JNDI_NAME); ObjectName objectName = ObjectName.getInstance(mbeanName); Object workManagerMBean = MBeanServerInvocationHandler.newProxyInstance(mconn, objectName, mbeanClass, false); Method getInstanceMethod = workManagerMBean.getClass().getMethod("getInstance"); return (WorkManager) getInstanceMethod.invoke(workManagerMBean); } catch (Exception ex) { throw new IllegalStateException( "Could not initialize JBossWorkManagerTaskExecutor because JBoss API is not available", ex); } }
/** * Transfroms a proxy implementing T in a proxy implementing T plus * NotificationEmitter * **/ public static <T> T makeNotificationEmitter(T proxy, Class<T> mbeanInterface) { if (proxy instanceof NotificationEmitter) return proxy; if (proxy == null) return null; if (!(proxy instanceof Proxy)) throw new IllegalArgumentException("not a "+Proxy.class.getName()); final Proxy p = (Proxy) proxy; final InvocationHandler handler = Proxy.getInvocationHandler(proxy); if (!(handler instanceof MBeanServerInvocationHandler)) throw new IllegalArgumentException("not a JMX Proxy"); final MBeanServerInvocationHandler h = (MBeanServerInvocationHandler)handler; final ObjectName name = h.getObjectName(); final MBeanServerConnection mbs = h.getMBeanServerConnection(); final boolean isMXBean = h.isMXBean(); final T newProxy; if (isMXBean) newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true); else newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true); return newProxy; }
/** * Ensures that an {@code MBeanServerConnection} is configured and attempts * to detect a local connection if one is not supplied. */ public void prepare() { synchronized (this.preparationMonitor) { if (this.server != null) { this.serverToUse = this.server; } else { this.serverToUse = null; this.serverToUse = this.connector.connect(this.serviceUrl, this.environment, this.agentId); } this.invocationHandler = null; if (this.useStrictCasing) { // Use the JDK's own MBeanServerInvocationHandler, in particular for native MXBean support. this.invocationHandler = new MBeanServerInvocationHandler(this.serverToUse, this.objectName, (this.managementInterface != null && JMX.isMXBeanInterface(this.managementInterface))); } else { // Non-strict casing can only be achieved through custom invocation handling. // Only partial MXBean support available! retrieveMBeanInfo(); } } }
/** * Reads the counters from the prior instance of this class, increments this instances counters and closes the prior. */ protected void carryOverAndClose() { final ManagedScriptMBean oldScript = MBeanServerInvocationHandler.newProxyInstance(JMXHelper.getHeliosMBeanServer(), objectName, ManagedScriptMBean.class, false); deploymentId = oldScript.getDeploymentId()+1; totalErrors.add(oldScript.getTotalCollectionErrors()); Date dt = oldScript.getLastCollectionErrorDate(); if(dt!=null) { lastError.set(dt.getTime()); } dt = oldScript.getLastCollectionDate(); if(dt!=null) { lastCompleteCollection.set(dt.getTime()); } final Long lastElapsed = oldScript.getLastCollectionElapsed(); if(lastElapsed!=null) { lastCollectionElapsed.set(lastElapsed); } try { oldScript.close(); } catch (Exception x) {/* No Op */} }
public static void main(String[] args) throws Exception { // The RMI server's host: this is actually ignored by JSR 160 // since this information is stored in the RMI stub. String serverHost = "localhost"; // The host where the rmiregistry runs. String namingHost = "localhost"; String jndiPath = "/ssljmxconnector"; JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + serverHost + "/jndi/rmi://" + namingHost + jndiPath); JMXConnector connector = JMXConnectorFactory.connect(url); MBeanServerConnection connection = connector.getMBeanServerConnection(); // Call the server side ObjectName delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"); Object proxy = MBeanServerInvocationHandler.newProxyInstance(connection, delegateName, MBeanServerDelegateMBean.class, true); MBeanServerDelegateMBean delegate = (MBeanServerDelegateMBean)proxy; System.out.println(delegate.getImplementationVendor() + " is cool !"); }
private void displayAllDestinations() throws Exception { String query = JmxMBeansUtil.createQueryString(queryString, "*"); List<?> queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), query); final String header = "%-50s %10s %10s %10s %10s %10s %10s"; final String tableRow = "%-50s %10d %10d %10d %10d %10d %10d"; context.print(String.format(Locale.US, header, "Name", "Queue Size", "Producer #", "Consumer #", "Enqueue #", "Dequeue #", "Memory %")); // Iterate through the queue result for (Object view : queueList) { ObjectName queueName = ((ObjectInstance)view).getObjectName(); QueueViewMBean queueView = MBeanServerInvocationHandler. newProxyInstance(createJmxConnection(), queueName, QueueViewMBean.class, true); context.print(String.format(Locale.US, tableRow, queueView.getName(), queueView.getQueueSize(), queueView.getProducerCount(), queueView.getConsumerCount(), queueView.getEnqueueCount(), queueView.getDequeueCount(), queueView.getMemoryPercentUsage())); } }
private void displayQueueStats() throws Exception { String query = JmxMBeansUtil.createQueryString(queryString, "Queue"); List<?> queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), query); final String header = "%-50s %10s %10s %10s %10s %10s %10s"; final String tableRow = "%-50s %10d %10d %10d %10d %10d %10d"; context.print(String.format(Locale.US, header, "Name", "Queue Size", "Producer #", "Consumer #", "Enqueue #", "Dequeue #", "Memory %")); // Iterate through the queue result for (Object view : queueList) { ObjectName queueName = ((ObjectInstance)view).getObjectName(); QueueViewMBean queueView = MBeanServerInvocationHandler. newProxyInstance(createJmxConnection(), queueName, QueueViewMBean.class, true); context.print(String.format(Locale.US, tableRow, queueView.getName(), queueView.getQueueSize(), queueView.getProducerCount(), queueView.getConsumerCount(), queueView.getEnqueueCount(), queueView.getDequeueCount(), queueView.getMemoryPercentUsage())); } }
private void displayTopicStats() throws Exception { String query = JmxMBeansUtil.createQueryString(queryString, "Topic"); List<?> topicsList = JmxMBeansUtil.queryMBeans(createJmxConnection(), query); final String header = "%-50s %10s %10s %10s %10s %10s %10s"; final String tableRow = "%-50s %10d %10d %10d %10d %10d %10d"; context.print(String.format(Locale.US, header, "Name", "Queue Size", "Producer #", "Consumer #", "Enqueue #", "Dequeue #", "Memory %")); // Iterate through the topics result for (Object view : topicsList) { ObjectName topicName = ((ObjectInstance)view).getObjectName(); TopicViewMBean topicView = MBeanServerInvocationHandler. newProxyInstance(createJmxConnection(), topicName, TopicViewMBean.class, true); context.print(String.format(Locale.US, tableRow, topicView.getName(), topicView.getQueueSize(), topicView.getProducerCount(), topicView.getConsumerCount(), topicView.getEnqueueCount(), topicView.getDequeueCount(), topicView.getMemoryPercentUsage())); } }
public void testBrowseExpiredMessages() throws Exception { JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); JMXConnector connector = JMXConnectorFactory.connect(url, null); connector.connect(); MBeanServerConnection connection = connector.getMBeanServerConnection(); ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + "destinationType=Queue,destinationName=TEST.Q"); QueueViewMBean queueMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, QueueViewMBean.class, true); HashMap<String, String> headers = new HashMap<>(); headers.put("timeToLive", Long.toString(2000)); headers.put("JMSDeliveryMode", Integer.toString(DeliveryMode.PERSISTENT)); queueMbean.sendTextMessage(headers, "test", "system", "manager"); // allow message to expire on the queue TimeUnit.SECONDS.sleep(4); Connection c = new ActiveMQConnectionFactory("vm://localhost").createConnection("system", "manager"); c.start(); // browser consumer will force expiration check on addConsumer QueueBrowser browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("TEST.Q")); assertTrue("no message in the q", !browser.getEnumeration().hasMoreElements()); // verify dlq got the message, no security exception as brokers context is now used browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("ActiveMQ.DLQ")); assertTrue("one message in the dlq", browser.getEnumeration().hasMoreElements()); }
/** * This test ensures that the queueViewMbean will work. * * @throws Exception */ public void testQueueViewMbean() throws Exception { try { addMessages(); validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); List<String> tokens = Arrays.asList(new String[]{"*"}); for (String token : tokens) { List<ObjectInstance> queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), "type=Broker,brokerName=localbroker,destinationType=Queue,destinationName=" + token); for (ObjectInstance queue : queueList) { ObjectName queueName = queue.getObjectName(); QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(createJmxConnection(), queueName, QueueViewMBean.class, true); int removed = proxy.removeMatchingMessages(MSG_SEL_WITH_PROPERTY); LOG.info("Removed: " + removed); } } validateCounts(0, MESSAGE_COUNT, MESSAGE_COUNT); } finally { purgeAllMessages(); } }
/** * This method will force metric manager to collect metrics by invoking report() method * using remote jmx * @throws IOException * @throws MalformedObjectNameException */ private void invokeJMXReportOperation() throws IOException, MalformedObjectNameException, XPathExpressionException { int JMXServicePort = Integer.parseInt(cepServer.getInstance().getPorts().get("jmxserver")); int RMIRegistryPort = Integer.parseInt(cepServer.getInstance().getPorts().get("rmiregistry")); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + JMXServicePort + "/jndi/rmi://localhost:" + RMIRegistryPort + "/jmxrmi"); Map<String, String[]> env = new HashMap<>(); String[] credentials = {"admin", "admin"}; env.put(JMXConnector.CREDENTIALS, credentials); JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env); MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection(); ObjectName mbeanName = new ObjectName("org.wso2.carbon:type=MetricManager"); MetricManagerMXBean mbeanProxy = MBeanServerInvocationHandler.newProxyInstance( mbeanServerConnection, mbeanName, MetricManagerMXBean.class, true); mbeanProxy.report(); jmxConnector.close(); }
/** * get an mbean instance for a remote jmx-enabled jvm. * * @param jmxServerUrl * jmx service url, for example * <code>service:jmx:rmi:///jndi/rmi://:9999/jmxrmi</code> * @param host * channel pool's tcp host * @param port * channel pool's tcp port * @return a proxy for the monitor associated with the pool */ public static ChannelPoolMonitorMBean getMonitor(String jmxServerUrl, String host, int port) throws IOException { ObjectName objectName = null; try { objectName = makeObjectName(host, port); } catch (MalformedObjectNameException e) { throw new IllegalArgumentException(e); } JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi"); JMXConnector jmxc = JMXConnectorFactory.connect(url, null); MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); Set<ObjectInstance> set = mbsc.queryMBeans(objectName, null); if (set == null || set.isEmpty()) { return null; } else { return MBeanServerInvocationHandler.newProxyInstance(mbsc, objectName, ChannelPoolMonitorMBean.class, true); } }
private boolean expireAppMasterZKSession(TwillController controller, long timeout, TimeUnit timeoutUnit) { MBeanServer mbeanServer = MBeanRegistry.getInstance().getPlatformMBeanServer(); QueryExp query = Query.isInstanceOf(new StringValueExp(ConnectionMXBean.class.getName())); Stopwatch stopwatch = new Stopwatch(); do { // Find the AM session and expire it Set<ObjectName> connectionBeans = mbeanServer.queryNames(ObjectName.WILDCARD, query); for (ObjectName objectName : connectionBeans) { ConnectionMXBean connectionBean = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, objectName, ConnectionMXBean.class, false); for (String node : connectionBean.getEphemeralNodes()) { if (node.endsWith("/instances/" + controller.getRunId().getId())) { // This is the AM, expire the session. LOG.info("Kill AM session {}", connectionBean.getSessionId()); connectionBean.terminateSession(); return true; } } } } while (stopwatch.elapsedTime(timeoutUnit) < timeout); return false; }
private void connect() throws IOException { JMXServiceURL jmxUrl = new JMXServiceURL(String.format(fmtUrl, host, port)); JMXConnector jmxc = JMXConnectorFactory.connect(jmxUrl, null); mbeanServerConn = jmxc.getMBeanServerConnection(); try { ObjectName name = new ObjectName(DOMAINLIST_OBJECT_NAME); domainListProcxy = (DomainListManagementMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServerConn, name, DomainListManagementMBean.class, true); name = new ObjectName(VIRTUALUSERTABLE_OBJECT_NAME); virtualUserTableProxy = (RecipientRewriteTableManagementMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServerConn, name, RecipientRewriteTableManagementMBean.class, true); name = new ObjectName(USERSREPOSITORY_OBJECT_NAME); usersRepositoryProxy = (UsersRepositoryManagementMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServerConn, name, UsersRepositoryManagementMBean.class, true); } catch (MalformedObjectNameException e) { throw new RuntimeException("Invalid ObjectName? Please report this as a bug.", e); } }
/** * Ensures that an {@code MBeanServerConnection} is configured and attempts * to detect a local connection if one is not supplied. */ public void prepare() { synchronized (this.preparationMonitor) { if (this.server != null) { this.serverToUse = this.server; } else { this.serverToUse = null; this.serverToUse = this.connector.connect(this.serviceUrl, this.environment, this.agentId); } this.invocationHandler = null; if (this.useStrictCasing) { // Use the JDK's own MBeanServerInvocationHandler, // in particular for native MXBean support on Java 6. if (JmxUtils.isMXBeanSupportAvailable()) { this.invocationHandler = new MBeanServerInvocationHandler(this.serverToUse, this.objectName, (this.managementInterface != null && JMX.isMXBeanInterface(this.managementInterface))); } else { this.invocationHandler = new MBeanServerInvocationHandler(this.serverToUse, this.objectName); } } else { // Non-strict casing can only be achieved through custom // invocation handling. Only partial MXBean support available! retrieveMBeanInfo(); } } }
synchronized ObjectName mxbeanToObjectName(Object mxbean) throws OpenDataException { String wrong; if (mxbean instanceof Proxy) { InvocationHandler ih = Proxy.getInvocationHandler(mxbean); if (ih instanceof MBeanServerInvocationHandler) { MBeanServerInvocationHandler mbsih = (MBeanServerInvocationHandler) ih; if (mbsih.getMBeanServerConnection().equals(mbsc)) return mbsih.getObjectName(); else wrong = "proxy for a different MBeanServer"; } else wrong = "not a JMX proxy"; } else { ObjectName name = mxbeanToObjectName.get(mxbean); if (name != null) return name; wrong = "not an MXBean registered in this MBeanServer"; } String s = (mxbean == null) ? "null" : "object of type " + mxbean.getClass().getName(); throw new OpenDataException( "Could not convert " + s + " to an ObjectName: " + wrong); // Message will be strange if mxbean is null but it is not // supposed to be. }
/** * Returns the ObjectName of the MBean that a proxy object * is proxying. **/ public static ObjectName getObjectName(Object proxy) { if (!(proxy instanceof Proxy)) throw new IllegalArgumentException("not a "+Proxy.class.getName()); final Proxy p = (Proxy) proxy; final InvocationHandler handler = Proxy.getInvocationHandler(proxy); if (handler instanceof MBeanServerInvocationHandler) return ((MBeanServerInvocationHandler)handler).getObjectName(); throw new IllegalArgumentException("not a JMX Proxy"); }
static boolean equal(Object o1, Object o2, NamedMXBeans namedMXBeans) { if (o1 == o2) return true; if (o1 == null || o2 == null) return false; if (o1.getClass().isArray()) { if (!o2.getClass().isArray()) return false; return deepEqual(o1, o2, namedMXBeans); } if (o1 instanceof Map) { if (!(o2 instanceof Map)) return false; return equalMap((Map) o1, (Map) o2, namedMXBeans); } if (o1 instanceof CompositeData && o2 instanceof CompositeData) { return compositeDataEqual((CompositeData) o1, (CompositeData) o2, namedMXBeans); } if (Proxy.isProxyClass(o1.getClass())) { if (Proxy.isProxyClass(o2.getClass())) return proxyEqual(o1, o2, namedMXBeans); InvocationHandler ih = Proxy.getInvocationHandler(o1); // if (ih instanceof MXBeanInvocationHandler) { // return proxyEqualsObject((MXBeanInvocationHandler) ih, // o2, namedMXBeans); if (ih instanceof MBeanServerInvocationHandler) { return true; } else if (ih instanceof CompositeDataInvocationHandler) { return o2.equals(o1); // We assume the other object has a reasonable equals method } } else if (Proxy.isProxyClass(o2.getClass())) return equal(o2, o1, namedMXBeans); return o1.equals(o2); }
public Ex4Service() throws URISyntaxException { CachingProvider cachingProvider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider"); CacheManager cacheManager = cachingProvider.getCacheManager( getClass().getResource("/ehcache-ex4.xml").toURI(), getClass().getClassLoader()); cache = cacheManager.getCache("someCache4", Long.class, Person.class); try { MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName("javax.cache:type=CacheStatistics,CacheManager=" + getClass().getResource("/ehcache-ex4.xml") .toURI() .toString() .replace(":", ".") + ",Cache=someCache4"); cacheStatisticsMXBean = MBeanServerInvocationHandler.newProxyInstance(beanServer, objectName, CacheStatisticsMXBean.class, false); } catch (Exception e) { throw new RuntimeException(e); } }