protected void undeployJsr77( MBeanServer server, VFSDeploymentUnit unit, ServiceDeployment metaData) { List<ServiceMetaData> beans = metaData.getServices(); if (beans != null && beans.isEmpty() == false) { ListIterator<ServiceMetaData> iter = beans.listIterator(beans.size()); while (iter.hasPrevious()) { ObjectName name = iter.previous().getObjectName(); try { // Destroy JSR-77 MBean MBean.destroy(server, name.toString()); log.debug("Destroy MBean, name: " + name); } catch (Throwable e) { log.debug("Failed to remove remove JSR-77 MBean", e); } } } // Remove JSR-77 SAR-Module String moduleName = unit.getSimpleName(); try { ServiceModule.destroy(server, moduleName); log.debug("Removed JSR-77 SAR: " + moduleName); } catch (Throwable e) { log.debug("Failed to remove JSR-77 SAR: " + moduleName); } }
private int getHttpsPort() { try { MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0); QueryExp query = Query.eq(Query.attr("Scheme"), Query.value("https")); Set<ObjectName> objectNames = mBeanServer.queryNames(null, query); if (objectNames != null && objectNames.size() > 0) { for (ObjectName objectName : objectNames) { String name = objectName.toString(); if (name.indexOf("port=") > -1) { String[] parts = name.split("port="); String port = parts[1]; try { int portNum = Integer.parseInt(port); return portNum; } catch (NumberFormatException e) { logger.error("Error parsing https port:" + port); return -1; } } } } } catch (Throwable t) { logger.error("Error getting https port:", t); } return -1; }
public void testNotificationListenerRegistrar() throws Exception { ObjectName objectName = ObjectName.getInstance("spring:name=Test"); JmxTestBean bean = new JmxTestBean(); Map<String, Object> beans = new HashMap<String, Object>(); beans.put(objectName.getCanonicalName(), bean); MBeanExporter exporter = new MBeanExporter(); exporter.setServer(server); exporter.setBeans(beans); exporter.afterPropertiesSet(); CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener(); NotificationListenerRegistrar registrar = new NotificationListenerRegistrar(); registrar.setServer(server); registrar.setNotificationListener(listener); registrar.setMappedObjectName(objectName); registrar.afterPropertiesSet(); // update the attribute String attributeName = "Name"; server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); assertEquals("Listener not notified", 1, listener.getCount(attributeName)); registrar.destroy(); // try to update the attribute again server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); assertEquals("Listener notified after destruction", 1, listener.getCount(attributeName)); }
public void testTwoManagedCamelContextNoClashCustomPattern() throws Exception { camel1 = createCamelContext("foo", "killer-#counter#"); camel2 = createCamelContext("foo", "killer-#counter#"); camel1.start(); assertTrue("Should be started", camel1.getStatus().isStarted()); MBeanServer mbeanServer = camel1.getManagementStrategy().getManagementAgent().getMBeanServer(); ObjectName on = ObjectName.getInstance( "org.apache.camel:context=" + camel1.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on)); // the pattern has a counter so no clash camel2.start(); ObjectName on2 = ObjectName.getInstance( "org.apache.camel:context=" + camel2.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on2)); assertTrue("Should still be registered after name clash", mbeanServer.isRegistered(on)); assertTrue("Should still be registered after name clash", mbeanServer.isRegistered(on2)); }
public void testTwoManagedCamelContextNoClashDefault() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } camel1 = createCamelContext("foo", null); camel2 = createCamelContext("foo", null); camel1.start(); assertTrue("Should be started", camel1.getStatus().isStarted()); MBeanServer mbeanServer = camel1.getManagementStrategy().getManagementAgent().getMBeanServer(); ObjectName on = ObjectName.getInstance( "org.apache.camel:context=" + camel1.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on)); // the default name pattern will ensure the JMX names is unique camel2.start(); ObjectName on2 = ObjectName.getInstance( "org.apache.camel:context=" + camel2.getManagementName() + ",type=context,name=\"foo\""); assertTrue("Should be registered", mbeanServer.isRegistered(on2)); assertTrue("Should still be registered after name clash", mbeanServer.isRegistered(on)); assertTrue("Should still be registered after name clash", mbeanServer.isRegistered(on2)); }
public Object handleBeanUnregister(Method method, Object[] args) throws IllegalAccessException, InvocationTargetException, MalformedObjectNameException, MBeanRegistrationException, InstanceNotFoundException { ObjectName objectName = (ObjectName) args[0]; if (mBeanServer.isRegistered(objectName)) { return method.invoke(mBeanServer, args); } Object ret = null; for (int i = 0; i < 200; i++) { if (!mBeanServer.isRegistered(objectName)) { break; } ObjectName currentObjectName = new ObjectName(objectName.getCanonicalName() + i); if (mBeanServer.isRegistered(currentObjectName)) { if (ret == null) { ret = method.invoke(mBeanServer, new Object[] {currentObjectName}); } else { mBeanServer.unregisterMBean(currentObjectName); } } else { break; } } return ret; }
@SuppressWarnings({"rawtypes", "unchecked"}) public void testRegisterNotificationListenerWithWildcard() throws Exception { ObjectName objectName = ObjectName.getInstance("spring:name=Test"); JmxTestBean bean = new JmxTestBean(); Map<String, Object> beans = new HashMap<String, Object>(); beans.put(objectName.getCanonicalName(), bean); CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener(); Map notificationListeners = new HashMap(); notificationListeners.put("*", listener); MBeanExporter exporter = new MBeanExporter(); exporter.setServer(server); exporter.setBeans(beans); exporter.setNotificationListenerMappings(notificationListeners); exporter.afterPropertiesSet(); // update the attribute String attributeName = "Name"; server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); assertEquals("Listener not notified", 1, listener.getCount(attributeName)); }
@Test public void testLifecycleInEndpointWithoutMessageSource() throws Exception { context = new GenericXmlApplicationContext(getClass(), "lifecycle-no-source.xml"); messageChannelsMonitor = context.getBean(IntegrationMBeanExporter.class); assertNotNull(messageChannelsMonitor); MBeanServer server = context.getBean(MBeanServer.class); Set<ObjectName> names = server.queryNames( ObjectName.getInstance("org.springframework.integration:type=ManagedEndpoint,*"), null); assertEquals(1, names.size()); names = server.queryNames( ObjectName.getInstance("org.springframework.integration:name=gateway,*"), null); assertEquals(1, names.size()); MBeanOperationInfo[] operations = server.getMBeanInfo(names.iterator().next()).getOperations(); String startName = null; for (MBeanOperationInfo info : operations) { String name = info.getName(); if (name.startsWith("start")) { startName = name; } } // Lifecycle method name assertEquals("start", startName); }
@Test public void testCreateObjectName() throws Exception { RoundRobinSchedulerStats stats = new RoundRobinSchedulerStats(); ObjectName name = stats.createObjectName(); assertEquals("Wrong name.", RoundRobinSchedulerStats.OBJECT_NAME, name.getCanonicalName()); }
@Test public void testLifecycleInEndpointWithMessageSource() throws Exception { context = new GenericXmlApplicationContext(getClass(), "lifecycle-source.xml"); messageChannelsMonitor = context.getBean(IntegrationMBeanExporter.class); assertNotNull(messageChannelsMonitor); MBeanServer server = context.getBean(MBeanServer.class); Set<ObjectName> names = server.queryNames( ObjectName.getInstance("org.springframework.integration:type=ManagedEndpoint,*"), null); assertEquals(0, names.size()); names = server.queryNames( ObjectName.getInstance("org.springframework.integration:name=explicit,*"), null); assertEquals(1, names.size()); MBeanOperationInfo[] operations = server.getMBeanInfo(names.iterator().next()).getOperations(); String startName = null; for (MBeanOperationInfo info : operations) { String name = info.getName(); if (name.startsWith("start")) { startName = name; } } // Lifecycle method name assertEquals("start", startName); assertTrue((Boolean) server.invoke(names.iterator().next(), "isRunning", null, null)); messageChannelsMonitor.stopActiveComponents(false, 3000); assertFalse((Boolean) server.invoke(names.iterator().next(), "isRunning", null, null)); ActiveChannel activeChannel = context.getBean("activeChannel", ActiveChannel.class); assertTrue(activeChannel.isStopCalled()); OtherActiveComponent otherActiveComponent = context.getBean(OtherActiveComponent.class); assertTrue(otherActiveComponent.isBeforeCalled()); assertTrue(otherActiveComponent.isAfterCalled()); }
@Test public void testHHH6635() throws Exception { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); Set<ObjectName> set = mBeanServer.queryNames(null, null); boolean mbeanfound = false; for (ObjectName obj : set) { if (obj.getKeyPropertyListString().indexOf("PooledDataSource") > 0) { mbeanfound = true; // see according c3p0 settings in META-INF/persistence.xml int actual_minPoolSize = (Integer) mBeanServer.getAttribute(obj, "minPoolSize"); assertEquals(50, actual_minPoolSize); int actual_maxPoolSize = (Integer) mBeanServer.getAttribute(obj, "maxPoolSize"); assertEquals(800, actual_maxPoolSize); int actual_maxStatements = (Integer) mBeanServer.getAttribute(obj, "maxStatements"); assertEquals(50, actual_maxStatements); int actual_maxIdleTime = (Integer) mBeanServer.getAttribute(obj, "maxIdleTime"); assertEquals(300, actual_maxIdleTime); int actual_idleConnectionTestPeriod = (Integer) mBeanServer.getAttribute(obj, "idleConnectionTestPeriod"); assertEquals(3000, actual_idleConnectionTestPeriod); break; } } assertTrue("PooledDataSource BMean not found, please verify version of c3p0", mbeanfound); }
@Override public List<Map<String, String>> getEndpoints(String camelContextName) throws Exception { if (jolokia == null) { throw new IllegalStateException("Need to connect to remote jolokia first"); } List<Map<String, String>> answer = new ArrayList<Map<String, String>>(); ObjectName found = lookupCamelContext(camelContextName); if (found != null) { String pattern = String.format( "%s:context=%s,type=endpoints,*", found.getDomain(), found.getKeyProperty("context")); J4pSearchResponse sr = jolokia.execute(new J4pSearchRequest(pattern)); List<J4pReadRequest> list = new ArrayList<J4pReadRequest>(); for (ObjectName on : sr.getObjectNames()) { list.add(new J4pReadRequest(on, "CamelId", "EndpointUri", "State")); } List<J4pReadResponse> lrr = jolokia.execute(list); for (J4pReadResponse rr : lrr) { Map<String, String> row = new LinkedHashMap<String, String>(); row.put("camelContextName", rr.getValue("CamelId").toString()); row.put("uri", rr.getValue("EndpointUri").toString()); row.put("state", rr.getValue("State").toString()); answer.add(row); } } return answer; }
StatsProviderManagerDelegateImpl( ProbeClientMediator pcm, ProbeRegistry probeRegistry, MonitoringRuntimeDataRegistry mrdr, Domain domain, String iName, MonitoringService monitoringService) { this.pcm = pcm; this.mrdr = mrdr; this.domain = domain; this.instanceName = iName; this.monitoringService = monitoringService; this.probeRegistry = probeRegistry; // serverNode is special, construct that first if doesn't exist serverNode = constructServerPP(); statsProviderRegistry = new StatsProviderRegistry(mrdr); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, " In the ctor : instance name " + instanceName); logger.log(Level.FINE, " In the ctor : MONITORING SERVER " + MONITORING_SERVER); } MONITORING_SERVER = AMXGlassfish.DEFAULT.serverMon(instanceName); DOMAIN = MONITORING_SERVER.getDomain(); PP = MONITORING_SERVER.getKeyProperty(PARENT_PATH_KEY); TYPE = MONITORING_SERVER.getKeyProperty(TYPE_KEY); NAME = MONITORING_SERVER.getKeyProperty(NAME_KEY); PARENT_PATH = PP + "/" + TYPE + "[" + NAME + "]"; }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (!method.getName().equals("registerMBean")) { if (method.getName().equals("unregisterMBean")) { return handleBeanUnregister(method, args); } else { return method.invoke(mBeanServer, args); } } ObjectName objectName = (ObjectName) args[1]; String canonicalName = objectName.getCanonicalName(); if (!canonicalName.contains(".sensei") && !canonicalName.contains(".linkedin") && !canonicalName.contains(".zoie") && !canonicalName.contains(".bobo")) { return method.invoke(mBeanServer, args); } for (int i = 0; i < 200; i++) { if (!mBeanServer.isRegistered(objectName)) { break; } logger.warn( "The JMX bean with name [" + canonicalName + "] is already registered. Trying to add a numeric suffix to register the another one"); objectName = new ObjectName(canonicalName + i); } args[1] = objectName; return method.invoke(mBeanServer, args); }
/** * Allows the MBean to perform any operations it needs before being registered in the MBean * server. If the name of the MBean is not specified, the MBean can provide a name for its * registration. If any exception is raised, the MBean will not be registered in the MBean server. * * @param server The MBean server in which the MBean will be registered. * @param name The object name of the MBean. * @return The name of the MBean registered. * @exception java.lang.Exception This exception should be caught by the MBean server and * re-thrown as an {@link javax.management.MBeanRegistrationException}. */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception { if (logger.finerOn()) { logger.finer("preRegister ", "object name = " + name); } responderObjectName = name; // ---------------- // Should we act as a spy ? // ---------------- spy = (String) name.getKeyProperty(SPY); // ---------------- // Should we Send event // ---------------- noEvent = (String) name.getKeyProperty("PRIVATE_NO_EVENT"); // ---------------- // Initialise local pointer to the Core Management MBeanServer // ---------------- this.cmf = server; // ---------------- // Return part // ---------------- return name; }
public synchronized Collection<GarbageCollectorMXBean> getGarbageCollectorMXBeans() throws IOException { // TODO: How to deal with changes to the list?? if (garbageCollectorMBeans == null) { ObjectName gcName = null; try { gcName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*"); } catch (MalformedObjectNameException e) { // should not reach here assert (false); } Set<ObjectName> mbeans = server.queryNames(gcName, null); if (mbeans != null) { garbageCollectorMBeans = new ArrayList<GarbageCollectorMXBean>(); Iterator<ObjectName> iterator = mbeans.iterator(); while (iterator.hasNext()) { ObjectName on = (ObjectName) iterator.next(); String name = GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",name=" + on.getKeyProperty("name"); GarbageCollectorMXBean mBean = newPlatformMXBeanProxy(server, name, GarbageCollectorMXBean.class); garbageCollectorMBeans.add(mBean); } } } return garbageCollectorMBeans; }
/** 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); } } }
@Override public String getRouteStatsAsXml( String routeId, String camelContextName, boolean fullStats, boolean includeProcessors) throws Exception { if (jolokia == null) { throw new IllegalStateException("Need to connect to remote jolokia first"); } ObjectName found = lookupCamelContext(camelContextName); if (found != null) { String pattern = String.format( "%s:context=%s,type=routes,name=\"%s\"", found.getDomain(), found.getKeyProperty("context"), routeId); ObjectName on = ObjectName.getInstance(pattern); J4pExecResponse response = jolokia.execute( new J4pExecRequest( on, "dumpRouteStatsAsXml(boolean,boolean)", fullStats, includeProcessors)); if (response != null) { String xml = response.getValue(); return xml; } } return null; }
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; }
public HashMap<String, ArrayList<ObjectName>> getDomains( final MBeanServer mBeanServer, String mbeanDomain, String mBean) throws ReflectionException, InstanceNotFoundException, IntrospectionException, MalformedObjectNameException, NullPointerException { final HashMap<String, ArrayList<ObjectName>> result = new HashMap<String, ArrayList<ObjectName>>(); ObjectName queryObjectName = null; if (mbeanDomain != null && !mbeanDomain.isEmpty()) queryObjectName = new ObjectName(mbeanDomain + (mBean != null ? ":" + mBean : ":*")); final Set mbeans = mBeanServer.queryMBeans(queryObjectName, null); final Iterator iter = mbeans.iterator(); while (iter.hasNext()) { final ObjectInstance objectInstance = (ObjectInstance) iter.next(); final ObjectName objectName = objectInstance.getObjectName(); final String domain = objectName.getDomain(); // if (result.containsKey(domain)) { final ArrayList<ObjectName> list = result.get(domain); list.add(objectName); result.put(domain, list); } else { final ArrayList<ObjectName> list = new ArrayList<ObjectName>(); list.add(objectName); result.put(domain, list); } } return result; }
public void testManageStatistics() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } // get the stats for the route MBeanServer mbeanServer = getMBeanServer(); Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null); assertEquals(1, set.size()); ObjectName on = set.iterator().next(); // use route to get the total time Long completed = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted"); assertEquals(0, completed.longValue()); MockEndpoint result = getMockEndpoint("mock:result"); result.expectedMessageCount(5); // send in 5 messages template.sendBody("direct:start", "A"); template.sendBody("direct:start", "B"); template.sendBody("direct:start", "C"); template.sendBody("direct:start", "D"); template.sendBody("direct:start", "E"); assertMockEndpointsSatisfied(); // should be 5 on the route completed = (Long) mbeanServer.getAttribute(on, "ExchangesCompleted"); assertEquals(5, completed.longValue()); String first = (String) mbeanServer.getAttribute(on, "FirstExchangeCompletedExchangeId"); assertEquals(result.getReceivedExchanges().get(0).getExchangeId(), first); String firstFail = (String) mbeanServer.getAttribute(on, "FirstExchangeFailureExchangeId"); assertNull(firstFail); String last = (String) mbeanServer.getAttribute(on, "LastExchangeCompletedExchangeId"); assertEquals(result.getReceivedExchanges().get(4).getExchangeId(), last); String lastFail = (String) mbeanServer.getAttribute(on, "LastExchangeFailureExchangeId"); assertNull(lastFail); // should be 5 on the processors ObjectName foo = ObjectName.getInstance( "org.apache.camel:context=localhost/camel-1,type=processors,name=\"foo\""); completed = (Long) mbeanServer.getAttribute(foo, "ExchangesCompleted"); assertEquals(5, completed.longValue()); ObjectName mock = ObjectName.getInstance( "org.apache.camel:context=localhost/camel-1,type=processors,name=\"mock\""); completed = (Long) mbeanServer.getAttribute(mock, "ExchangesCompleted"); assertEquals(5, completed.longValue()); }
@Override public List<Map<String, String>> getEndpointRuntimeStatistics(String camelContextName) throws Exception { if (jolokia == null) { throw new IllegalStateException("Need to connect to remote jolokia first"); } List<Map<String, String>> answer = new ArrayList<Map<String, String>>(); ObjectName found = lookupCamelContext(camelContextName); if (found != null) { String pattern = String.format( "%s:context=%s,type=services,name=DefaultRuntimeEndpointRegistry", found.getDomain(), found.getKeyProperty("context")); ObjectName on = ObjectName.getInstance(pattern); J4pExecResponse response = jolokia.execute(new J4pExecRequest(on, "endpointStatistics()")); if (response != null) { JSONObject data = response.getValue(); for (Object obj : data.values()) { JSONObject data2 = (JSONObject) obj; JSONObject service = (JSONObject) data2.values().iterator().next(); Map<String, String> row = new LinkedHashMap<String, String>(); row.put("index", asString(service.get("index"))); row.put("url", asString(service.get("url"))); row.put("routeId", asString(service.get("routeId"))); row.put("direction", asString(service.get("direction"))); row.put("static", asString(service.get("static"))); row.put("dynamic", asString(service.get("dynamic"))); row.put("hits", asString(service.get("hits"))); answer.add(row); } } // sort the list Collections.sort( answer, new Comparator<Map<String, String>>() { @Override public int compare(Map<String, String> endpoint1, Map<String, String> endpoint2) { // sort by route id String route1 = endpoint1.get("routeId"); String route2 = endpoint2.get("routeId"); int num = route1.compareTo(route2); if (num == 0) { // we want in before out String dir1 = endpoint1.get("direction"); String dir2 = endpoint2.get("direction"); num = dir1.compareTo(dir2); } return num; } }); } return answer; }
/** * Allows a named object to be created. * * @param objectName The object name of the object. * @param object A reference to the object. */ public NamedObject(ObjectName objectName, Object object) { if (objectName.isPattern()) { throw new RuntimeOperationsException( new IllegalArgumentException("Invalid name->" + objectName.toString())); } this.name = objectName; this.object = object; }
public static ObjectName buildObjectNameFilter(ObjectName mapName) throws Exception { StringBuffer sb = new StringBuffer(); sb.append(mapName.getDomain()).append(':'); sb.append(mapName.getKeyPropertyListString()); sb.append(','); sb.append("*"); return new ObjectName(sb.toString()); }
public static void main(String[] args) throws Exception { DevelopmentProvider dtp = new DevelopmentProvider(); Topology t = dtp.newTopology("DevelopmentSampleJobMXBean"); Random r = new Random(); TStream<Double> d = t.poll(() -> r.nextGaussian(), 100, TimeUnit.MILLISECONDS); d.sink(tuple -> System.out.print(".")); dtp.submit(t); System.out.println(dtp.getServices().getService(HttpServer.class).getConsoleUrl()); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); StringBuffer sbuf = new StringBuffer(); sbuf.append(DevelopmentProvider.JMX_DOMAIN); sbuf.append(":interface="); sbuf.append(ObjectName.quote("quarks.execution.mbeans.JobMXBean")); sbuf.append(",type="); sbuf.append(ObjectName.quote("job")); sbuf.append(",*"); System.out.println("Looking for MBeans of type job: " + sbuf.toString()); ObjectName jobObjName = new ObjectName(sbuf.toString()); Set<ObjectInstance> jobInstances = mBeanServer.queryMBeans(jobObjName, null); Iterator<ObjectInstance> jobIterator = jobInstances.iterator(); while (jobIterator.hasNext()) { ObjectInstance jobInstance = jobIterator.next(); ObjectName objectName = jobInstance.getObjectName(); String jobId = (String) mBeanServer.getAttribute(objectName, "Id"); String jobName = (String) mBeanServer.getAttribute(objectName, "Name"); String jobCurState = (String) mBeanServer.getAttribute(objectName, "CurrentState"); String jobNextState = (String) mBeanServer.getAttribute(objectName, "NextState"); String jobHealth = (String) mBeanServer.getAttribute(objectName, "Health"); String jobLastError = (String) mBeanServer.getAttribute(objectName, "LastError"); System.out.println( "Found a job with JobId: " + jobId + " Name: " + jobName + " CurrentState: " + jobCurState + " NextState: " + jobNextState + " Health: " + jobHealth + " LastError: \"" + jobLastError + "\""); } }
ObjectName findMatchingMBeanPattern(ObjectName pName) { // Check all stored patterns for a match and return the pattern if one is found for (ObjectName pattern : patterns) { if (pattern.apply(pName)) { return pattern; } } return null; }
@Override public List<Map<String, String>> getRestServices(String camelContextName) throws Exception { if (jolokia == null) { throw new IllegalStateException("Need to connect to remote jolokia first"); } List<Map<String, String>> answer = new ArrayList<Map<String, String>>(); ObjectName found = lookupCamelContext(camelContextName); if (found != null) { String pattern = String.format( "%s:context=%s,type=services,name=DefaultRestRegistry", found.getDomain(), found.getKeyProperty("context")); ObjectName on = ObjectName.getInstance(pattern); J4pExecResponse response = jolokia.execute(new J4pExecRequest(on, "listRestServices()")); if (response != null) { JSONObject data = response.getValue(); if (data != null) { for (Object obj : data.values()) { JSONObject data2 = (JSONObject) obj; JSONObject service = (JSONObject) data2.values().iterator().next(); Map<String, String> row = new LinkedHashMap<String, String>(); row.put("basePath", asString(service.get("basePath"))); row.put("baseUrl", asString(service.get("baseUrl"))); row.put("consumes", asString(service.get("consumes"))); row.put("description", asString(service.get("description"))); row.put("inType", asString(service.get("inType"))); row.put("method", asString(service.get("method"))); row.put("outType", asString(service.get("outType"))); row.put("produces", asString(service.get("produces"))); row.put("routeId", asString(service.get("routeId"))); row.put("state", asString(service.get("state"))); row.put("uriTemplate", asString(service.get("uriTemplate"))); row.put("url", asString(service.get("url"))); answer.add(row); } } } // sort the list Collections.sort( answer, new Comparator<Map<String, String>>() { @Override public int compare(Map<String, String> service1, Map<String, String> service2) { String url1 = service1.get("url"); String url2 = service2.get("url"); return url1.compareTo(url2); } }); } return answer; }
/** * Allows a named object to be created. * * @param objectName The string representation of the object name of the object. * @param object A reference to the object. * @exception MalformedObjectNameException The string passed does not have the format of a valid * ObjectName */ public NamedObject(String objectName, Object object) throws MalformedObjectNameException { ObjectName objName = new ObjectName(objectName); if (objName.isPattern()) { throw new RuntimeOperationsException( new IllegalArgumentException("Invalid name->" + objName.toString())); } this.name = objName; this.object = object; }
public static void main(String[] args) throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Boolean isNotificationSupported = AccessController.doPrivileged( new PrivilegedAction<Boolean>() { public Boolean run() { try { Class cl = Class.forName("sun.management.VMManagementImpl"); Field f = cl.getDeclaredField("gcNotificationSupport"); f.setAccessible(true); return f.getBoolean(null); } catch (ClassNotFoundException e) { return false; } catch (NoSuchFieldException e) { return false; } catch (IllegalAccessException e) { return false; } } }); if (!isNotificationSupported) { System.out.println("GC Notification not supported by the JVM, test skipped"); return; } final ObjectName gcMXBeanPattern = new ObjectName("java.lang:type=GarbageCollector,*"); Set<ObjectName> names = mbs.queryNames(gcMXBeanPattern, null); if (names.isEmpty()) throw new Exception("Test incorrect: no GC MXBeans"); number = names.size(); for (ObjectName n : names) { if (mbs.isInstanceOf(n, "javax.management.NotificationEmitter")) { listenerInvoked.put(n.getCanonicalName(), null); GcListener listener = new GcListener(); mbs.addNotificationListener(n, listener, null, null); } } // Invocation of System.gc() to trigger major GC System.gc(); // Allocation of many short living and small objects to trigger minor GC Object data[] = new Object[32]; for (int i = 0; i < 100000000; i++) { data[i % 32] = new int[8]; } int wakeup = 0; synchronized (synchronizer) { while (count != number) { synchronizer.wait(10000); wakeup++; if (wakeup > 10) break; } } for (GarbageCollectionNotificationInfo notif : listenerInvoked.values()) { checkGarbageCollectionNotificationInfoContent(notif); } System.out.println("Test passed"); }
protected void onEnvironmentSet() { deploymentDir = environment.getProperty("branch-file", File.class); classLoader = environment.getProperty("branch-cl", ClassLoader.class); ObjectName parentObjectName = environment.getProperty("parentObjectName", ObjectName.class); if (deploymentDir == null || !deploymentDir.isDirectory()) throw new IllegalArgumentException( "The passed deployment directory was invalid [" + deploymentDir + "]"); String[] dirPair = dirPair(deploymentDir); if (dirPair.length == 1) { dirPair = new String[] {"root", deploymentDir.getName()}; // throw new IllegalArgumentException("The passed deployment directory [" + deploymentDir + "] // is invalid: [" + dirPair[0] + "]"); } Path path = Paths.get(this.deploymentDir.getPath()); dirKey = dirPair[0]; if ("branch".equals(dirKey)) { throw new IllegalArgumentException( "The passed deployment directory [" + deploymentDir + "] has an illegal key: [" + dirPair[0] + "]"); } dirValue = dirPair[1]; if ("lib".equals(dirValue) || "xlib".equals(dirValue)) { dirKey = "ext"; dirPair[0] = "ext"; } // ObjectName parentObjectName = findParent(deploymentDir.getParentFile()); if (parentObjectName != null) { // env.put("branch-parent", parentBranch); parentBranch = environment.getProperty("branch-parent", DeploymentBranch.class); objectName = JMXHelper.objectName( new StringBuilder(parentObjectName.toString()) .append(",") .append(dirKey) .append("=") .append(dirValue)); if (parentBranch == null && JMXHelper.isRegistered(parentObjectName)) { parentBranch = (DeploymentBranch) JMXHelper.getAttribute(parentObjectName, "ParentBranch"); } root = false; } else { objectName = JMXHelper.objectName( new StringBuilder(OBJECT_NAME_BASE) .append(",") .append(dirKey) .append("=") .append(dirValue)); parentBranch = null; root = true; } }