public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer, true);

    // Declare server handler collection
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);

    // Configure context "/" (root) for servlets
    ServletContextHandler root =
        new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
    // Add servlets to root context
    root.addServlet(new ServletHolder(new HelloServlet("Hello")), "/");
    root.addServlet(new ServletHolder(new HelloServlet("Ciao")), "/it/*");
    root.addServlet(new ServletHolder(new HelloServlet("Bonjoir")), "/fr/*");

    // Configure context "/other" for servlets
    ServletContextHandler other =
        new ServletContextHandler(contexts, "/other", ServletContextHandler.SESSIONS);
    // Add servlets to /other context
    other.addServlet(DefaultServlet.class.getCanonicalName(), "/");
    other.addServlet(new ServletHolder(new HelloServlet("YO!")), "*.yo");

    server.start();
    server.join();
  }
 public JettyServerImpl(JettyServerConfiguration jettyServerConfiguration) {
   server = new Server(jettyServerConfiguration.getPort());
   serverConfiguration = jettyServerConfiguration;
   server.addLifeCycleListener(getSystemPropertiesListener(systemProperties));
   server.addBean(new MBeanContainer(ManagementFactory.getPlatformMBeanServer()));
   server.setHandler(getWebAppHandler(jettyServerConfiguration.getWarLocation(), server));
 }
示例#3
0
 /**
  * Registers some MBeans to monitor Scalaris via JMX and then waits forever until interrupted.
  *
  * @param node the node name of the Erlang VM to connect to
  * @param verbose whether verbose information should be printed in case of connection failures
  */
 private static void startJmxService(final String node, final boolean verbose) {
   try {
     final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
     final ObjectName nodeMonitorName = new ObjectName("de.zib.scalaris:type=MonitorNode");
     final de.zib.scalaris.jmx.MonitorNode nodeMonitorMbean =
         new de.zib.scalaris.jmx.MonitorNode(node);
     final ObjectName serviceMonitorName = new ObjectName("de.zib.scalaris:type=MonitorService");
     final de.zib.scalaris.jmx.MonitorService serviceMonitorMbean =
         new de.zib.scalaris.jmx.MonitorService(node);
     mbs.registerMBean(nodeMonitorMbean, nodeMonitorName);
     mbs.registerMBean(serviceMonitorMbean, serviceMonitorName);
     System.out.println("Waiting forever...");
     Thread.sleep(Long.MAX_VALUE);
   } catch (final InterruptedException e) {
     System.out.println("stopped service");
   } catch (final MalformedObjectNameException e) {
     throw new RuntimeException(e);
   } catch (final NullPointerException e) {
     throw new RuntimeException(e);
   } catch (final ConnectionException e) {
     printException("JMX service failed with connection error", e, verbose);
   } catch (final InstanceAlreadyExistsException e) {
     throw new RuntimeException(e);
   } catch (final MBeanRegistrationException e) {
     throw new RuntimeException(e);
   } catch (final NotCompliantMBeanException e) {
     throw new RuntimeException(e);
   }
 }
  private void testDeployments(DeploymentExecutor deploymentExecutor) throws Exception {
    final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
    final ObjectName name = new ObjectName("jboss.test:service=testdeployments");
    final TestNotificationListener listener = new TestNotificationListener(name);
    mbeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, listener, null, null);
    try {
      // Initial deploy
      deploymentExecutor.initialDeploy();
      listener.await();
      Assert.assertNotNull(mbeanServer.getMBeanInfo(name));

      // Full replace
      listener.reset(2);
      deploymentExecutor.fullReplace();
      listener.await();
      Assert.assertNotNull(mbeanServer.getMBeanInfo(name));

      // Undeploy
      listener.reset(1);
      deploymentExecutor.undeploy();
      listener.await();
      try {
        mbeanServer.getMBeanInfo(name);
        Assert.fail("Should not have found MBean");
      } catch (InstanceNotFoundException expected) {
      }
    } finally {
      mbeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, listener);
    }
  }
示例#5
0
  @SuppressWarnings("unchecked")
  @Override
  public void init() throws ServletException {
    try {
      disruptor =
          new Disruptor<byte[]>(
              new EventFactory<byte[]>() {
                @Override
                public byte[] newInstance() {
                  return new byte[256];
                }
              },
              262144,
              executor);

      disruptor.handleEventsWith(new LogicHandler());
      disruptor.start();
      generator = new Generator(executor);

      MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
      mBeanServer.registerMBean(
          new StandardMBean(generator, GeneratorMBean.class),
          new ObjectName("com.lmax:type=generator"));
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
示例#6
0
  public static boolean registerDriver(Driver driver) {
    try {
      DriverManager.registerDriver(driver);

      try {
        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

        ObjectName objectName = new ObjectName(MBEAN_NAME);
        if (!mbeanServer.isRegistered(objectName)) {
          mbeanServer.registerMBean(instance, objectName);
        }
      } catch (Throwable ex) {
        if (LOG == null) {
          LOG = LogFactory.getLog(DruidDriver.class);
        }
        LOG.warn("register druid-driver mbean error", ex);
      }

      return true;
    } catch (Exception e) {
      if (LOG == null) {
        LOG = LogFactory.getLog(DruidDriver.class);
      }

      LOG.error("registerDriver error", e);
    }

    return false;
  }
示例#7
0
 private void waitForSpringApplication(long wait, int maxAttempts) throws MojoExecutionException {
   SpringApplicationAdminClient client =
       new SpringApplicationAdminClient(ManagementFactory.getPlatformMBeanServer(), this.jmxName);
   getLog().debug("Waiting for spring application to start...");
   for (int i = 0; i < maxAttempts; i++) {
     if (client.isReady()) {
       return;
     }
     String message =
         "Spring application is not ready yet, waiting " + wait + "ms (attempt " + (i + 1) + ")";
     getLog().debug(message);
     synchronized (this.lock) {
       try {
         this.lock.wait(wait);
       } catch (InterruptedException ex) {
         Thread.currentThread().interrupt();
         throw new IllegalStateException(
             "Interrupted while waiting for Spring Boot app to start.");
       }
     }
   }
   throw new MojoExecutionException(
       "Spring application did not start before the configured timeout ("
           + (wait * maxAttempts)
           + "ms");
 }
示例#8
0
  @Before
  public void setUp() throws Exception {
    jmxNodeInfo = new JMXNodeInfo(0);
    jmxCollector = new JMXCollectorImpl();
    platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName objectName = new ObjectName("org.opennms.netmgt.collectd.jmxhelper:type=JmxTest");
    JmxTestMBean testMBean = new JmxTest();
    platformMBeanServer.registerMBean(testMBean, objectName);

    collectionAgent = EasyMock.createMock(CollectionAgent.class);
    EasyMock.expect(collectionAgent.getAddress()).andReturn(InetAddress.getLocalHost()).anyTimes();
    EasyMock.expect(
            collectionAgent.getAttribute("org.opennms.netmgt.collectd.JMXCollector.nodeInfo"))
        .andReturn(jmxNodeInfo)
        .anyTimes();
    EasyMock.expect(collectionAgent.getNodeId()).andReturn(0).anyTimes();
    EasyMock.expect(collectionAgent.getStorageDir()).andReturn(new File("")).anyTimes();

    EasyMock.replay(collectionAgent);

    FileInputStream configFileStream =
        new FileInputStream("src/test/resources/etc/JmxCollectorConfigTest.xml");
    logger.debug("ConfigFileStream check '{}'", configFileStream.available());
    jmxConfigFactory = new JMXDataCollectionConfigFactory(configFileStream);
    JMXDataCollectionConfigFactory.setInstance(jmxConfigFactory);
  }
 /**
  * @return
  * @throws NullPointerException
  * @throws MalformedObjectNameException
  * @throws ReflectionException
  * @throws MBeanException
  * @throws InstanceNotFoundException
  * @throws AttributeNotFoundException
  */
 private String getServerId()
     throws MalformedObjectNameException, NullPointerException, AttributeNotFoundException,
         InstanceNotFoundException, MBeanException, ReflectionException {
   MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
   ObjectName name = new ObjectName("java.lang:type=Runtime");
   return ((String) mbeanServer.getAttribute(name, "Name")).replace('@', '-');
 }
  @Before
  public void setUp() throws Exception {
    File docRoot = new File("target/test-output/docroot/");
    docRoot.mkdirs();
    docRoot.deleteOnExit();

    System.setProperty("org.mortbay.jetty.util.DEBUG", "");
    _server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    _server.addConnector(connector);

    _handler = new TestHandler();
    _server.setHandler(_handler);

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    mBeanContainer.addBean(Log.getLog());

    _counter = _handler.getRequestCounter();
    mBeanContainer.addBean(_counter);

    _server.addBean(mBeanContainer);
    _server.getContainer().addEventListener(mBeanContainer);
    _server.start();

    startClient(null);

    _monitor = new JMXMonitor();

    int port = _server.getConnectors()[0].getLocalPort();
    _requestUrl = "http://localhost:" + port + "/";
  }
  /**
   * Register the JMX Bean.
   *
   * @param configuredFps the configured fps
   */
  public PixelControllerStatus(Collector col, int configuredFps) {
    LOG.log(Level.INFO, "Initialize the PixelControllerStatus JMX Bean");

    this.configuredFps = configuredFps;
    this.col = col;

    // initialize all buffers
    this.timeMeasureMapGlobal = new ConcurrentHashMap<TimeMeasureItemGlobal, CircularFifoBuffer>();
    for (TimeMeasureItemGlobal timeMeasureItem : TimeMeasureItemGlobal.values()) {
      this.timeMeasureMapGlobal.put(
          timeMeasureItem, new CircularFifoBuffer(this.configuredFps * SECONDS));
    }
    this.timeMeasureMapOutput =
        new ConcurrentHashMap<IOutput, Map<TimeMeasureItemOutput, CircularFifoBuffer>>();
    this.outputList = new ArrayList<IOutput>();

    startTime = System.currentTimeMillis();

    // register MBean
    try {
      MBeanServer server = ManagementFactory.getPlatformMBeanServer();
      ObjectName name = new ObjectName(JMX_BEAN_NAME);
      // check if the MBean is already registered
      if (!server.isRegistered(name)) {
        server.registerMBean(this, name);
      }
    } catch (JMException ex) {
      LOG.log(Level.WARNING, "Error while registering class as JMX Bean.", ex);
    }
  }
示例#12
0
  /**
   * Main function, starts the jetty server.
   *
   * @param args
   */
  public static void main(String[] args) {
    //		System.setProperty("wicket.configuration", "development");

    Server server = new Server();
    SocketConnector connector = new SocketConnector();

    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(1000 * 60 * 60);
    connector.setSoLingerTime(-1);
    connector.setPort(8080);
    server.setConnectors(new Connector[] {connector});

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");
    bb.setWar("src/main/webapp");

    server.setHandler(bb);

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    server.getContainer().addEventListener(mBeanContainer);

    try {
      mBeanContainer.start();
      server.start();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
示例#13
0
  @Override
  protected void registerMBeans() {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    try {
      server.registerMBean(this, new ObjectName(MBEAN_BOOTSTRAP_HOST));
    } catch (Exception e) {
      logger.error("Unable to register " + MBEAN_BOOTSTRAP_HOST + " mbean", e);
    }

    try {
      HierarchyDynamicMBean hdm = new HierarchyDynamicMBean();
      server.registerMBean(hdm, new ObjectName(MBEAN_LOG4J_HIERARCHY));

      // Add the root logger to the Hierarchy MBean
      hdm.addLoggerMBean(Logger.getRootLogger().getName());

      LoggerRepository r = LogManager.getLoggerRepository();

      @SuppressWarnings("rawtypes")
      Enumeration loggers = r.getCurrentLoggers();
      while (loggers.hasMoreElements()) {
        hdm.addLoggerMBean(((Logger) loggers.nextElement()).getName());
      }
    } catch (Exception e) {
      logger.error("Unable to register " + MBEAN_LOG4J_HIERARCHY + " mbean", e);
    }

    super.registerMBeans();
  }
  @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);
  }
示例#15
0
 /**
  * Cleanup after close: unregister the ScanManagerMXBean singleton.
  *
  * @throws java.io.IOException Cleanup failed for communication-related reasons.
  * @throws javax.management.JMException Cleanup failed for JMX-related reasons.
  */
 public void cleanup() throws IOException, JMException {
   try {
     ((NotificationEmitter) proxy).removeNotificationListener(listener, null, null);
   } finally {
     ManagementFactory.getPlatformMBeanServer().unregisterMBean(ScanManager.SCAN_MANAGER_NAME);
   }
 }
  @Test
  public void testResolveHelloBean() throws Exception {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    ObjectName objectName =
        new ObjectName("org.apache.camel:context=camel-2,type=context,name=\"camel-2\"");
    String methodSignature[] = {String.class.getName(), Object.class.getName()};
    Object methodParams[] = {"direct:start", null};

    // Get Camel to return the BeanManagers that are in use
    Map<String, BeanManager> beanMangers =
        (Map<String, BeanManager>)
            server.invoke(objectName, "requestBody", methodParams, methodSignature);

    BeanManager subModuleBeanManager = beanMangers.get("subModule");
    BeanManager camelBeanManager = beanMangers.get("camel");

    System.err.println(">>>>>> [Sub Module BeanManager] " + subModuleBeanManager);
    System.err.println(">>>>>> [Camel BeanManager] " + camelBeanManager);

    // Assert that the @Named HelloBean can be resolved
    Assert.assertTrue(
        "Sub module bean manager could not resolve helloBean",
        beanManagerCanResolveBean(subModuleBeanManager, "helloBean"));

    Assert.assertTrue(
        "Camel bean manager could not resolve helloBean",
        beanManagerCanResolveBean(camelBeanManager, "helloBean"));
  }
示例#17
0
  /** @param args the command line arguments */
  public static void main(String[] args) throws Exception {

    TestBean tb1 = new TestBean();
    tb1.setA(new Integer(42));
    tb1.setB(new Integer(-1));
    ObjectName tbName1 = new ObjectName("com.personal.JMXTestServer:name=TestBean1");

    TestBean tb2 = new TestBean();
    tb2.setA(new Integer(55));
    tb2.setB(new Integer(-99));
    ObjectName tbName2 = new ObjectName("com.personal.JMXTestServer:name=TestBean2");

    CarBean cb = new CarBean();
    ObjectName cbName = new ObjectName("org.jmxdatamart:name=CarBean");

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    mbs.registerMBean(tb1, tbName1);
    mbs.registerMBean(cb, cbName);
    mbs.registerMBean(tb2, tbName2);

    if (args.length == 0) {
      System.out.println("Press Enter to terminate...");
      System.in.read();
    } else { // a random argument will cause it to pause for 10s only
      Thread.sleep(10000);
    }

    mbs.unregisterMBean(tbName1);
    mbs.unregisterMBean(tbName2);
    mbs.unregisterMBean(cbName);
  }
  public static void main(String[] args) throws Exception {
    ServerOptions options = ServerOptions.parseCommandLine(args);
    if (options == null) return;
    info(options);

    ThrottlingController throttlingController = ThrottlingController.create();
    final Eventloop eventloop =
        Eventloop.create()
            .withThrottlingController(throttlingController)
            .withFatalErrorHandler(rethrowOnAnyError());

    final HttpThrottlingServer server = new HttpThrottlingServer(eventloop, options);

    MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
    DynamicMBeanFactory mBeanFactory = JmxMBeans.factory();
    mbeanServer.registerMBean(
        mBeanFactory.createFor(asList(eventloop), true),
        new ObjectName(Eventloop.class.getPackage().getName() + ":type=Eventloop"));
    mbeanServer.registerMBean(
        ByteBufPool.getStats(),
        new ObjectName(ByteBufPool.class.getPackage().getName() + ":type=ByteBufPool"));
    mbeanServer.registerMBean(
        mBeanFactory.createFor(asList(throttlingController), true),
        new ObjectName(
            ThrottlingController.class.getPackage().getName() + ":type=ThrottlingController"));
    server.start();

    eventloop.run();
  }
示例#19
0
  public void unregisterSystemEngine(StorageEngine<ByteArray, byte[], byte[]> engine) {
    String storeName = engine.getName();
    Store<ByteArray, byte[], byte[]> store = storeRepository.removeLocalStore(storeName);

    if (store != null) {
      if (voldemortConfig.isJmxEnabled()) {
        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

        if (voldemortConfig.isEnableRebalanceService()) {

          ObjectName name = null;
          if (this.voldemortConfig.isEnableJmxClusterName())
            name =
                JmxUtils.createObjectName(
                    metadata.getCluster().getName()
                        + "."
                        + JmxUtils.getPackageName(RedirectingStore.class),
                    store.getName());
          else
            name =
                JmxUtils.createObjectName(
                    JmxUtils.getPackageName(RedirectingStore.class), store.getName());

          synchronized (mbeanServer) {
            if (mbeanServer.isRegistered(name)) JmxUtils.unregisterMbean(mbeanServer, name);
          }
        }

        if (voldemortConfig.isStatTrackingEnabled()) {
          ObjectName name = null;
          if (this.voldemortConfig.isEnableJmxClusterName())
            name =
                JmxUtils.createObjectName(
                    metadata.getCluster().getName()
                        + "."
                        + JmxUtils.getPackageName(store.getClass()),
                    store.getName());
          else
            name =
                JmxUtils.createObjectName(
                    JmxUtils.getPackageName(store.getClass()), store.getName());

          synchronized (mbeanServer) {
            if (mbeanServer.isRegistered(name)) JmxUtils.unregisterMbean(mbeanServer, name);
          }
        }
      }
      if (voldemortConfig.isServerRoutingEnabled()) {
        this.storeRepository.removeRoutedStore(storeName);
        for (Node node : metadata.getCluster().getNodes())
          this.storeRepository.removeNodeStore(storeName, node.getId());
      }
    }

    storeRepository.removeStorageEngine(storeName);
    // engine.truncate(); why truncate here when unregister? Isn't close
    // good enough?
    engine.close();
  }
示例#20
0
文件: JMXUtil.java 项目: Juliens/red5
 public static void printMBeanInfo(ObjectName objectName, String className) {
   log.info("Retrieve the management information for the {}", className);
   log.info("MBean using the getMBeanInfo() method of the MBeanServer");
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   MBeanInfo info = null;
   try {
     info = mbs.getMBeanInfo(objectName);
   } catch (Exception e) {
     log.error("Could not get MBeanInfo object for {}", className, e);
     return;
   }
   log.info("CLASSNAME: \t" + info.getClassName());
   log.info("DESCRIPTION: \t" + info.getDescription());
   log.info("ATTRIBUTES");
   MBeanAttributeInfo[] attrInfo = info.getAttributes();
   if (attrInfo.length > 0) {
     for (int i = 0; i < attrInfo.length; i++) {
       log.info(" ** NAME: \t" + attrInfo[i].getName());
       log.info("    DESCR: \t" + attrInfo[i].getDescription());
       log.info(
           "    TYPE: \t"
               + attrInfo[i].getType()
               + "\tREAD: "
               + attrInfo[i].isReadable()
               + "\tWRITE: "
               + attrInfo[i].isWritable());
     }
   } else log.info(" ** No attributes **");
   log.info("CONSTRUCTORS");
   MBeanConstructorInfo[] constrInfo = info.getConstructors();
   for (int i = 0; i < constrInfo.length; i++) {
     log.info(" ** NAME: \t" + constrInfo[i].getName());
     log.info("    DESCR: \t" + constrInfo[i].getDescription());
     log.info("    PARAM: \t" + constrInfo[i].getSignature().length + " parameter(s)");
   }
   log.info("OPERATIONS");
   MBeanOperationInfo[] opInfo = info.getOperations();
   if (opInfo.length > 0) {
     for (int i = 0; i < opInfo.length; i++) {
       log.info(" ** NAME: \t" + opInfo[i].getName());
       log.info("    DESCR: \t" + opInfo[i].getDescription());
       log.info("    PARAM: \t" + opInfo[i].getSignature().length + " parameter(s)");
     }
   } else log.info(" ** No operations ** ");
   log.info("NOTIFICATIONS");
   MBeanNotificationInfo[] notifInfo = info.getNotifications();
   if (notifInfo.length > 0) {
     for (int i = 0; i < notifInfo.length; i++) {
       log.info(" ** NAME: \t" + notifInfo[i].getName());
       log.info("    DESCR: \t" + notifInfo[i].getDescription());
       String notifTypes[] = notifInfo[i].getNotifTypes();
       for (int j = 0; j < notifTypes.length; j++) {
         log.info("    TYPE: \t" + notifTypes[j]);
       }
     }
   } else {
     log.info(" ** No notifications **");
   }
 }
 protected void unregisterJMX() {
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   try {
     mbs.unregisterMBean(oName);
   } catch (Exception e) {
     log.warn("Exception unregistering", e);
   }
 }
示例#22
0
 public static void unregisterMBean(final ObjectName oname) {
   try {
     MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
     mbs.unregisterMBean(oname);
   } catch (JMException ex) {
     throw new RuntimeException(ex);
   }
 }
示例#23
0
 private void unregisterMBean(ObjectName objectName) {
   try {
     logger.debug("Unregister mbean: name={}", objectName);
     ManagementFactory.getPlatformMBeanServer().unregisterMBean(objectName);
   } catch (Exception e) {
     logger.warn("Failed to unregister mbean: name={}", objectName);
   }
 }
示例#24
0
  private void addWebServerJMXSupport(Server server) {
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.getContainer().addEventListener(mbContainer);
    server.addBean(mbContainer);

    // Register loggers as MBeans
    mbContainer.addBean(Log.getLog());
  }
 public MBeanRegisterSupport(final String objectNamePrefix, final MBeanServer mbeanServer) {
   this._mbeanServer =
       (null != mbeanServer) ? mbeanServer : ManagementFactory.getPlatformMBeanServer();
   this._objectNamePrefix = objectNamePrefix;
   if (null == this._objectNamePrefix) {
     LOG.warn("objectName prefix is null, registerMBean use suffix as full objectName.");
   }
 }
示例#26
0
  @Override
  public void postConstruct() {
    LazyMOMProvider.INSTANCE.initMOMForScope(LazyMOMProvider.Scope.GLASSFISH_NO_JMX);

    // Register listener for AMX DomainRoot loaded
    final AMXGlassfish amxg = AMXGlassfish.DEFAULT;
    amxg.listenForDomainRoot(ManagementFactory.getPlatformMBeanServer(), this);
  }
 @Test
 public void checkNotRegistered() throws MalformedObjectNameException {
   MBeanServer jolokiaServer = JolokiaMBeanServerUtil.getJolokiaMBeanServer();
   Assert.assertNotEquals(ManagementFactory.getPlatformMBeanServer(), jolokiaServer);
   for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {
     Assert.assertNotEquals(server, jolokiaServer);
   }
 }
  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
              + "\"");
    }
  }
  public static void main(String[] args) throws Exception {
    System.out.println("---RMIConnectorNullSubjectConnTest starting...");

    JMXConnectorServer connectorServer = null;
    JMXConnector connectorClient = null;

    try {
      MBeanServer mserver = ManagementFactory.getPlatformMBeanServer();
      JMXServiceURL serverURL = new JMXServiceURL("rmi", "localhost", 0);
      connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serverURL, null, mserver);
      connectorServer.start();

      JMXServiceURL serverAddr = connectorServer.getAddress();
      connectorClient = JMXConnectorFactory.connect(serverAddr, null);
      connectorClient.connect();

      Field nullSubjectConnField = RMIConnector.class.getDeclaredField("nullSubjectConnRef");
      nullSubjectConnField.setAccessible(true);

      WeakReference<MBeanServerConnection> weak =
          (WeakReference<MBeanServerConnection>) nullSubjectConnField.get(connectorClient);

      if (weak != null && weak.get() != null) {
        throw new RuntimeException("nullSubjectConnRef must be null at initial time.");
      }

      MBeanServerConnection conn1 = connectorClient.getMBeanServerConnection(null);
      MBeanServerConnection conn2 = connectorClient.getMBeanServerConnection(null);
      if (conn1 == null) {
        throw new RuntimeException("A connection with null subject should not be null.");
      } else if (conn1 != conn2) {
        throw new RuntimeException("The 2 connections with null subject are not equal.");
      }

      conn1 = null;
      conn2 = null;
      int i = 1;
      do {
        System.gc();
        Thread.sleep(100);
        weak = (WeakReference<MBeanServerConnection>) nullSubjectConnField.get(connectorClient);
      } while ((weak != null && weak.get() != null) && i++ < 60);

      System.out.println("---GC times: " + i);

      if (weak != null && weak.get() != null) {
        throw new RuntimeException("Failed to clean RMIConnector's nullSubjectConn");
      } else {
        System.out.println("---RMIConnectorNullSubjectConnTest: PASSED!");
      }
    } finally {
      try {
        connectorClient.close();
        connectorServer.stop();
      } catch (Exception e) {
      }
    }
  }
示例#30
0
 private void connectClient() throws IOException, TimeoutException {
   if (jmxUrl == null || ("localhost".equals(jmxUrl.getHost()) && jmxUrl.getPort() == 0)) {
     mbeanServerConnection = ManagementFactory.getPlatformMBeanServer();
   } else {
     jmxConnector = connectWithTimeout(jmxUrl, timeout);
     mbeanServerConnection = jmxConnector.getMBeanServerConnection();
   }
   this.connected = true;
 }