Java Code Examples for javax.management.MBeanServer#invoke()

The following examples show how to use javax.management.MBeanServer#invoke() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CacheMBStatisticsBeanTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void testClear() throws Exception {
  // increment all counters
  cache.get(1L);
  cache.put(1L, "Put one");
  cache.get(1L);
  cache.remove(1L);
  // clear statistics
  MBeanServer mBeanServer = TestSupport.resolveMBeanServer();
  ObjectName objectName = calculateObjectName(cache, CacheStatistics);
  mBeanServer.invoke(objectName, "clear", null, null);
  assertEventually(new Runnable() {
    @Override
    public void run() {
      assertEquals(0L, lookupManagementAttribute(cache, CacheStatistics, "CachePuts"));
      assertEquals(0L, lookupManagementAttribute(cache, CacheStatistics, "CacheHits"));
      assertEquals(0L, lookupManagementAttribute(cache, CacheStatistics, "CacheGets"));
      assertEquals(0L, lookupManagementAttribute(cache, CacheStatistics, "CacheRemovals"));
      assertEquals(0L, lookupManagementAttribute(cache, CacheStatistics, "CacheMisses"));
      assertEquals(0f, lookupManagementAttribute(cache, CacheStatistics, "AverageGetTime"));
      assertEquals(0f, lookupManagementAttribute(cache, CacheStatistics, "AveragePutTime"));
      assertEquals(0f, lookupManagementAttribute(cache, CacheStatistics, "AverageRemoveTime"));
    }
  });
}
 
Example 2
Source File: Main.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void startMBeans(MBeanServer server, Set mbeans)
{
   for (Iterator i = mbeans.iterator(); i.hasNext();)
   {
      try
      {
         ObjectInstance instance = (ObjectInstance)i.next();
         if (server.isInstanceOf(instance.getObjectName(), "org.apache.avalon.framework.activity.Startable"))
         {
            try
            {
               server.invoke(instance.getObjectName(), "start", null, null);
            }
            catch (ReflectionException ignored)
            {
               // The start method is not part of the management interface, ignore
            }
         }
      }
      catch (Exception x)
      {
         x.printStackTrace();
      }
   }
}
 
Example 3
Source File: AgentImpl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private void createRMIRegistry() throws Exception {
  if (!this.agentConfig.isRmiRegistryEnabled()) {
    return;
  }
  MBeanServer mbs = getMBeanServer();
  String host = this.agentConfig.getRmiBindAddress();
  int    port = this.agentConfig.getRmiPort();

  /* Register and start the rmi-registry naming MBean, which is
   * needed by JSR 160 RMIConnectorServer */
  ObjectName registryName = getRMIRegistryNamingName();
  try {
    RMIRegistryService registryNamingService = null;
    if (host != null && !("".equals(host.trim()))) {
      registryNamingService = new RMIRegistryService(host, port);
    } else {
      registryNamingService = new RMIRegistryService(port);
    }
    mbs.registerMBean(registryNamingService, registryName);
  } catch (javax.management.InstanceAlreadyExistsException e) {
    this.logWriter.info(LocalizedStrings.AgentImpl_0__IS_ALREADY_REGISTERED,
                        registryName);
  }
  mbs.invoke(registryName, "start", null, null);
}
 
Example 4
Source File: MappingProvidersDecodeAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** Decrypt the secret using the cipherKey.
 *
 * @param secret - the encrypted secret to decrypt.
 * @return the decrypted secret
 * @throws Exception
 */
private byte[] decode64(String secret)
   throws Exception
{
   SecurityManager sm = System.getSecurityManager();
   if( sm != null )
      sm.checkPermission(decodePermission);

   MBeanServer server = MBeanServerLocator.locateJBoss();
   return (byte[]) server.invoke(serviceName, "decode64", new Object[] {secret}, 
         new String[] {String.class.getName()});
}
 
Example 5
Source File: InstrumentationManagerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
// try to get WorkQueue information
public void testWorkQueueInstrumentation() throws Exception {
    SpringBusFactory factory = new SpringBusFactory();
    bus = factory.createBus("managed-spring.xml", true);
    im = bus.getExtension(InstrumentationManager.class);
    assertNotNull("Instrumentation Manager should not be null", im);
    WorkQueueManagerImpl wqm = new WorkQueueManagerImpl();
    wqm.setBus(bus);
    wqm.getAutomaticWorkQueue();

    MBeanServer mbs = im.getMBeanServer();
    assertNotNull("MBeanServer should be available.", mbs);
    ObjectName name = new ObjectName(ManagementConstants.DEFAULT_DOMAIN_NAME
                                     + ":type=WorkQueues,*");
    Set<ObjectName> s = mbs.queryNames(name, null);
    assertEquals(2, s.size());
    Iterator<ObjectName> it = s.iterator();
    while (it.hasNext()) {
        ObjectName n = it.next();
        Long result =
            (Long)mbs.invoke(n, "getWorkQueueMaxSize", new Object[0], new String[0]);
        assertEquals(result, Long.valueOf(256));
        Integer hwm =
            (Integer)mbs.invoke(n, "getHighWaterMark", new Object[0], new String[0]);
        if (n.getCanonicalName().contains("test-wq")) {
            assertEquals(10, hwm.intValue());
        } else {
            assertEquals(15, hwm.intValue());
        }
    }

    bus.shutdown(true);
}
 
Example 6
Source File: ListenerScaleTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static final long timeNotif(MBeanServer mbs) {
    try {
        startTime = System.nanoTime();
        nnotifs = 0;
        mbs.invoke(testObjectName, "send", null, null);
        sema.acquire();
        return elapsed;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: GreetingOpenMBeanBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // 获取当前平台 MBean Server
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    // 创建 GreetingMBean 的 ObjectName
    ObjectName objectName = new ObjectName("thinking.in.spring.boot.samples.production.ready.jmx:type=Greeting");
    mBeanServer.registerMBean(new GreetingOpenMBean(), objectName);
    Object[] params = of("World");
    System.out.printf("OpenMBean(ObjectName[%s])已注册到平台 MBean Server...\n", objectName);
    Object returnValue = mBeanServer.invoke(objectName, "greet", params, of());
    System.out.printf("OpenMBean(ObjectName[%s]) greet(\"%s\") 方法执行结果: %s\n", objectName, params[0], returnValue);
    System.out.println("按任意键结束...");
    System.in.read();
}
 
Example 8
Source File: MemoryMonitor.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Dump the current heap profile to a file in the given directory and return its name.
 *
 * <p>NOTE: We deliberately don't salt the heap dump filename so as to minimize disk impact of
 * repeated dumps. These files can be of comparable size to the local disk.
 */
@VisibleForTesting
static synchronized File dumpHeap(File directory)
    throws MalformedObjectNameException, InstanceNotFoundException, ReflectionException,
        MBeanException, IOException {
  boolean liveObjectsOnly = false;
  File fileName = new File(directory, "heap_dump.hprof");
  if (fileName.exists() && !fileName.delete()) {
    throw new IOException("heap_dump.hprof already existed and couldn't be deleted!");
  }

  MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  ObjectName oname = new ObjectName("com.sun.management:type=HotSpotDiagnostic");
  Object[] parameters = {fileName.getPath(), liveObjectsOnly};
  String[] signatures = {String.class.getName(), boolean.class.getName()};
  mbs.invoke(oname, "dumpHeap", parameters, signatures);

  Files.setPosixFilePermissions(
      fileName.toPath(),
      ImmutableSet.of(
          PosixFilePermission.OWNER_READ,
          PosixFilePermission.GROUP_READ,
          PosixFilePermission.OTHERS_READ));

  LOG.warn("Heap dumped to {}", fileName);

  return fileName;
}
 
Example 9
Source File: ListenerScaleTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static final long timeNotif(MBeanServer mbs) {
    try {
        startTime = System.nanoTime();
        nnotifs = 0;
        mbs.invoke(testObjectName, "send", null, null);
        sema.acquire();
        return elapsed;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: DecodeAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** Decrypt the secret using the cipherKey.
 *
 * @param secret - the encrypted secret to decrypt.
 * @return the decrypted secret
 * @throws Exception
 */
private byte[] decode64(String secret)
   throws Exception
{
   SecurityManager sm = System.getSecurityManager();
   if( sm != null )
      sm.checkPermission(decodePermission);

   MBeanServer server = MBeanServerLocator.locateJBoss();
   return (byte[]) server.invoke(serviceName, "decode64", new Object[] {secret}, 
         new String[] {String.class.getName()});
}
 
Example 11
Source File: ListenerScaleTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static final long timeNotif(MBeanServer mbs) {
    try {
        startTime = System.nanoTime();
        nnotifs = 0;
        mbs.invoke(testObjectName, "send", null, null);
        sema.acquire();
        return elapsed;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: EtlLauncherTest.java    From scriptella-etl with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if JMX monitoring is enabled during execution.
 */
public void testJmx() throws FileNotFoundException, MalformedURLException, MalformedObjectNameException {
    final EtlLauncher launcher = new EtlLauncher();
    final String fileName = getBasedir() + "src/test/scriptella/tools/launcher/EtlLauncherTestJmx";
    URL u = IOUtils.toUrl(launcher.resolveFile(null, fileName));
    final ObjectName mbeanName = new ObjectName("scriptella:type=etl,url=" + ObjectName.quote(u.toString()));
    final MBeanServer srv = ManagementFactory.getPlatformMBeanServer();
    Callable r = new Callable() {
        public String call() throws Exception {
            try {
                final Number n = (Number) srv.getAttribute(
                        mbeanName,
                        "ExecutedStatementsCount");
                assertEquals(2, n.intValue());
            } catch (Exception e) {
                fail(e.getMessage());
            }
            //Check if cancellation is working
            srv.invoke(mbeanName, "cancel", null, null);
            return "";
        }
    };
    launcher.setProperties(Collections.singletonMap("callback", r));

    assertEquals(EtlLauncher.ErrorCode.FAILED, launcher.launch(new String[]{fileName}));
    assertFalse(srv.isRegistered(mbeanName));
}
 
Example 13
Source File: JmxEtlManager.java    From scriptella-etl with Apache License 2.0 5 votes vote down vote up
/**
 * Cancels all in-progress ETL tasks.
 *
 * @return number of cancelled ETL tasks.
 */
public static int cancelAll() {
    Set<ObjectName> names = findEtlMBeans();
    MBeanServer srv = getMBeanServer();
    int cancelled = 0;
    for (ObjectName objectName : names) {
        try {
            srv.invoke(objectName, "cancel", null, null);
            cancelled++;
        } catch (Exception e) {
            LOG.log(Level.WARNING, "Cannot cancel ETL, MBean " + objectName, e);
        }
    }
    return cancelled;
}
 
Example 14
Source File: PropertyNamesTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName pointName = new ObjectName("a:type=Point");
    PointMXBean pointmx = new PointImpl();
    mbs.registerMBean(pointmx, pointName);
    Point point = new Point(1, 2);
    PointMXBean pointproxy =
        JMX.newMXBeanProxy(mbs, pointName, PointMXBean.class);
    Point point1 = pointproxy.identity(point);
    if (point1.getX() != point.getX() || point1.getY() != point.getY())
        throw new Exception("Point doesn't match");
    System.out.println("Point test passed");

    ObjectName evolveName = new ObjectName("a:type=Evolve");
    EvolveMXBean evolvemx = new EvolveImpl();
    mbs.registerMBean(evolvemx, evolveName);
    Evolve evolve =
        new Evolve(59, "tralala", Collections.singletonList("tiddly"));
    EvolveMXBean evolveProxy =
        JMX.newMXBeanProxy(mbs, evolveName, EvolveMXBean.class);
    Evolve evolve1 = evolveProxy.identity(evolve);
    if (evolve1.getOldInt() != evolve.getOldInt()
            || !evolve1.getNewString().equals(evolve.getNewString())
            || !evolve1.getNewerList().equals(evolve.getNewerList()))
        throw new Exception("Evolve doesn't match");
    System.out.println("Evolve test passed");

    ObjectName evolvedName = new ObjectName("a:type=Evolved");
    EvolveMXBean evolvedmx = new EvolveImpl();
    mbs.registerMBean(evolvedmx, evolvedName);
    CompositeType evolvedType =
        new CompositeType("Evolved", "descr", new String[] {"oldInt"},
                          new String[] {"oldInt descr"},
                          new OpenType[] {SimpleType.INTEGER});
    CompositeData evolvedData =
        new CompositeDataSupport(evolvedType, new String[] {"oldInt"},
                                 new Object[] {5});
    CompositeData evolved1 = (CompositeData)
        mbs.invoke(evolvedName, "identity", new Object[] {evolvedData},
                   new String[] {CompositeData.class.getName()});
    if ((Integer) evolved1.get("oldInt") != 5
            || !evolved1.get("newString").equals("defaultString")
            || ((String[]) evolved1.get("newerList")).length != 0)
        throw new Exception("Evolved doesn't match: " + evolved1);
    System.out.println("Evolved test passed");
}
 
Example 15
Source File: PropertyNamesTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName pointName = new ObjectName("a:type=Point");
    PointMXBean pointmx = new PointImpl();
    mbs.registerMBean(pointmx, pointName);
    Point point = new Point(1, 2);
    PointMXBean pointproxy =
        JMX.newMXBeanProxy(mbs, pointName, PointMXBean.class);
    Point point1 = pointproxy.identity(point);
    if (point1.getX() != point.getX() || point1.getY() != point.getY())
        throw new Exception("Point doesn't match");
    System.out.println("Point test passed");

    ObjectName evolveName = new ObjectName("a:type=Evolve");
    EvolveMXBean evolvemx = new EvolveImpl();
    mbs.registerMBean(evolvemx, evolveName);
    Evolve evolve =
        new Evolve(59, "tralala", Collections.singletonList("tiddly"));
    EvolveMXBean evolveProxy =
        JMX.newMXBeanProxy(mbs, evolveName, EvolveMXBean.class);
    Evolve evolve1 = evolveProxy.identity(evolve);
    if (evolve1.getOldInt() != evolve.getOldInt()
            || !evolve1.getNewString().equals(evolve.getNewString())
            || !evolve1.getNewerList().equals(evolve.getNewerList()))
        throw new Exception("Evolve doesn't match");
    System.out.println("Evolve test passed");

    ObjectName evolvedName = new ObjectName("a:type=Evolved");
    EvolveMXBean evolvedmx = new EvolveImpl();
    mbs.registerMBean(evolvedmx, evolvedName);
    CompositeType evolvedType =
        new CompositeType("Evolved", "descr", new String[] {"oldInt"},
                          new String[] {"oldInt descr"},
                          new OpenType[] {SimpleType.INTEGER});
    CompositeData evolvedData =
        new CompositeDataSupport(evolvedType, new String[] {"oldInt"},
                                 new Object[] {5});
    CompositeData evolved1 = (CompositeData)
        mbs.invoke(evolvedName, "identity", new Object[] {evolvedData},
                   new String[] {CompositeData.class.getName()});
    if ((Integer) evolved1.get("oldInt") != 5
            || !evolved1.get("newString").equals("defaultString")
            || ((String[]) evolved1.get("newerList")).length != 0)
        throw new Exception("Evolved doesn't match: " + evolved1);
    System.out.println("Evolved test passed");
}
 
Example 16
Source File: StatusTransformer.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Write detailed information about a wrapper.
 */
public static void writeWrapper(PrintWriter writer, ObjectName objectName,
                                MBeanServer mBeanServer, int mode)
    throws Exception {

    if (mode == 0) {
        String servletName = objectName.getKeyProperty("name");
        
        String[] mappings = (String[]) 
            mBeanServer.invoke(objectName, "findMappings", null, null);
        
        writer.print("<h2>");
        writer.print(filter(servletName));
        if ((mappings != null) && (mappings.length > 0)) {
            writer.print(" [ ");
            for (int i = 0; i < mappings.length; i++) {
                writer.print(filter(mappings[i]));
                if (i < mappings.length - 1) {
                    writer.print(" , ");
                }
            }
            writer.print(" ] ");
        }
        writer.print("</h2>");
        
        writer.print("<p>");
        writer.print(" Processing time: ");
        writer.print(formatTime(mBeanServer.getAttribute
                                (objectName, "processingTime"), true));
        writer.print(" Max time: ");
        writer.print(formatTime(mBeanServer.getAttribute
                                (objectName, "maxTime"), false));
        writer.print(" Request count: ");
        writer.print(mBeanServer.getAttribute(objectName, "requestCount"));
        writer.print(" Error count: ");
        writer.print(mBeanServer.getAttribute(objectName, "errorCount"));
        writer.print(" Load time: ");
        writer.print(formatTime(mBeanServer.getAttribute
                                (objectName, "loadTime"), false));
        writer.print(" Classloading time: ");
        writer.print(formatTime(mBeanServer.getAttribute
                                (objectName, "classLoadTime"), false));
        writer.print("</p>");
    } else if (mode == 1){
        // for now we don't write out the wrapper details
    }

}
 
Example 17
Source File: NotifReconnectDeadlockTest.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println(
       ">>> Tests reconnection done by a fetching notif thread.");

    ObjectName oname = new ObjectName ("Default:name=NotificationEmitter");
    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    Map env = new HashMap(2);
    env.put("jmx.remote.x.server.connection.timeout", new Long(serverTimeout));
    env.put("jmx.remote.x.client.connection.check.period", new Long(Long.MAX_VALUE));

    final MBeanServer mbs = MBeanServerFactory.newMBeanServer();

    mbs.registerMBean(new NotificationEmitter(), oname);
    JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(
                                                                           url,
                                                                           env,
                                                                           mbs);
    server.start();

    JMXServiceURL addr = server.getAddress();
    JMXConnector client = JMXConnectorFactory.connect(addr, env);

    Thread.sleep(100); // let pass the first client open notif if there is
    client.getMBeanServerConnection().addNotificationListener(oname,
                                                              listener,
                                                              null,
                                                              null);

    client.addConnectionNotificationListener(listener, null, null);

    // max test time: 2 minutes
    final long end = System.currentTimeMillis()+120000;

    synchronized(lock) {
        while(clientState == null && System.currentTimeMillis() < end) {
            mbs.invoke(oname, "sendNotifications",
                       new Object[] {new Notification("MyType", "", 0)},
                       new String[] {"javax.management.Notification"});

            try {
                lock.wait(10);
            } catch (Exception e) {}
        }
    }

    if (clientState == null) {
        throw new RuntimeException(
              "No reconnection happened, need to reconfigure the test.");
    } else if (JMXConnectionNotification.FAILED.equals(clientState) ||
               JMXConnectionNotification.CLOSED.equals(clientState)) {
        throw new RuntimeException("Failed to reconnect.");
    }

    System.out.println(">>> Passed!");

    client.removeConnectionNotificationListener(listener);
    client.close();
    server.stop();
}
 
Example 18
Source File: UnserializableTargetObjectTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName name = new ObjectName("a:b=c");
    Resource resource1 = new Resource();
    Resource resource2 = new Resource();
    Resource resource3 = new Resource();
    Method operationMethod = Resource.class.getMethod("operation");
    Method getCountMethod = Resource.class.getMethod("getCount");
    Method setCountMethod = Resource.class.getMethod("setCount", int.class);
    Descriptor operationDescriptor =
        new DescriptorSupport(new String[] {
                                "descriptorType", "name", "targetObject"
                              }, new Object[] {
                                "operation", "operation", resource1
                              });
    Descriptor getCountDescriptor =
        new DescriptorSupport(new String[] {
                                "descriptorType", "name", "targetObject"
                              }, new Object[] {
                                "operation", "getCount", resource2
                              });
    Descriptor setCountDescriptor =
        new DescriptorSupport(new String[] {
                                "descriptorType", "name", "targetObject"
                              }, new Object[] {
                                "operation", "setCount", resource2
                              });
    Descriptor countDescriptor =
        new DescriptorSupport(new String[] {
                                "descriptorType", "name", "getMethod", "setMethod"
                              }, new Object[] {
                                "attribute", "Count", "getCount", "setCount"
                              });
    ModelMBeanOperationInfo operationInfo =
        new ModelMBeanOperationInfo("operation description",
                                    operationMethod, operationDescriptor);
    ModelMBeanOperationInfo getCountInfo =
        new ModelMBeanOperationInfo("getCount description",
                                    getCountMethod, getCountDescriptor);
    ModelMBeanOperationInfo setCountInfo =
        new ModelMBeanOperationInfo("setCount description",
                                    setCountMethod, setCountDescriptor);
    ModelMBeanAttributeInfo countInfo =
        new ModelMBeanAttributeInfo("Count", "Count description",
                                    getCountMethod, setCountMethod,
                                    countDescriptor);
    ModelMBeanInfo mmbi =
        new ModelMBeanInfoSupport(Resource.class.getName(),
                                  "ModelMBean to test targetObject",
                                  new ModelMBeanAttributeInfo[] {countInfo},
                                  null,  // no constructors
                                  new ModelMBeanOperationInfo[] {
                                      operationInfo, getCountInfo, setCountInfo
                                  },
                                  null); // no notifications
    ModelMBean mmb = new RequiredModelMBean(mmbi);
    mmb.setManagedResource(resource3, "ObjectReference");
    mbs.registerMBean(mmb, name);
    mbs.invoke(name, "operation", null, null);
    mbs.setAttribute(name, new Attribute("Count", 53));
    if (resource1.operationCount != 1)
        throw new Exception("operationCount: " + resource1.operationCount);
    if (resource2.count != 53)
        throw new Exception("count: " + resource2.count);
    int got = (Integer) mbs.getAttribute(name, "Count");
    if (got != 53)
        throw new Exception("got count: " + got);

    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = cc.getMBeanServerConnection();
    ModelMBeanInfo rmmbi = (ModelMBeanInfo) mbsc.getMBeanInfo(name);
    // Above gets NotSerializableException if resource included in
    // serialized form
    cc.close();
    cs.stop();
    System.out.println("TEST PASSED");
}
 
Example 19
Source File: NotifReconnectDeadlockTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println(
       ">>> Tests reconnection done by a fetching notif thread.");

    ObjectName oname = new ObjectName ("Default:name=NotificationEmitter");
    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    Map env = new HashMap(2);
    env.put("jmx.remote.x.server.connection.timeout", new Long(serverTimeout));
    env.put("jmx.remote.x.client.connection.check.period", new Long(Long.MAX_VALUE));

    final MBeanServer mbs = MBeanServerFactory.newMBeanServer();

    mbs.registerMBean(new NotificationEmitter(), oname);
    JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(
                                                                           url,
                                                                           env,
                                                                           mbs);
    server.start();

    JMXServiceURL addr = server.getAddress();
    JMXConnector client = JMXConnectorFactory.connect(addr, env);

    Thread.sleep(100); // let pass the first client open notif if there is
    client.getMBeanServerConnection().addNotificationListener(oname,
                                                              listener,
                                                              null,
                                                              null);

    client.addConnectionNotificationListener(listener, null, null);

    // max test time: 2 minutes
    final long end = System.currentTimeMillis()+120000;

    synchronized(lock) {
        while(clientState == null && System.currentTimeMillis() < end) {
            mbs.invoke(oname, "sendNotifications",
                       new Object[] {new Notification("MyType", "", 0)},
                       new String[] {"javax.management.Notification"});

            try {
                lock.wait(10);
            } catch (Exception e) {}
        }
    }

    if (clientState == null) {
        throw new RuntimeException(
              "No reconnection happened, need to reconfigure the test.");
    } else if (JMXConnectionNotification.FAILED.equals(clientState) ||
               JMXConnectionNotification.CLOSED.equals(clientState)) {
        throw new RuntimeException("Failed to reconnect.");
    }

    System.out.println(">>> Passed!");

    client.removeConnectionNotificationListener(listener);
    client.close();
    server.stop();
}
 
Example 20
Source File: StatusTransformer.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Write detailed information about a wrapper.
 * @param writer The output writer
 * @param objectName The wrapper MBean names
 * @param mBeanServer MBean server
 * @param mode Mode <code>0</code> will generate HTML.
 *   Mode <code>1</code> will generate XML.
 * @throws Exception Propagated JMX error
 */
public static void writeWrapper(PrintWriter writer, ObjectName objectName,
                                MBeanServer mBeanServer, int mode)
    throws Exception {

    if (mode == 0) {
        String servletName = objectName.getKeyProperty("name");

        String[] mappings = (String[])
            mBeanServer.invoke(objectName, "findMappings", null, null);

        writer.print("<h2>");
        writer.print(Escape.htmlElementContext(servletName));
        if ((mappings != null) && (mappings.length > 0)) {
            writer.print(" [ ");
            for (int i = 0; i < mappings.length; i++) {
                writer.print(Escape.htmlElementContext(mappings[i]));
                if (i < mappings.length - 1) {
                    writer.print(" , ");
                }
            }
            writer.print(" ] ");
        }
        writer.print("</h2>");

        writer.print("<p>");
        writer.print(" Processing time: ");
        writer.print(formatTime(mBeanServer.getAttribute
                                (objectName, "processingTime"), true));
        writer.print(" Max time: ");
        writer.print(formatTime(mBeanServer.getAttribute
                                (objectName, "maxTime"), false));
        writer.print(" Request count: ");
        writer.print(mBeanServer.getAttribute(objectName, "requestCount"));
        writer.print(" Error count: ");
        writer.print(mBeanServer.getAttribute(objectName, "errorCount"));
        writer.print(" Load time: ");
        writer.print(formatTime(mBeanServer.getAttribute
                                (objectName, "loadTime"), false));
        writer.print(" Classloading time: ");
        writer.print(formatTime(mBeanServer.getAttribute
                                (objectName, "classLoadTime"), false));
        writer.print("</p>");
    } else if (mode == 1){
        // for now we don't write out the wrapper details
    }

}