Пример #1
0
    public QClassLoader scan (boolean forceNewClassLoader) 
        throws InstanceAlreadyExistsException,
               InstanceNotFoundException,
               NotCompliantMBeanException,
               MalformedURLException,
               MBeanRegistrationException
    
    {
        if ((!isModified () && !forceNewClassLoader) || !libDir.canRead())
            return this;
        QClassLoader loader;
        if (server.isRegistered (loaderName)) {
            server.unregisterMBean (loaderName);
            loader = new QClassLoader (server, libDir, loaderName, getParent());
        } else
            loader = this;

        File file[] = libDir.listFiles (this);
        for (int i=0; i<file.length; i++) {
            try {
                loader.addURL (file[i].toURL ());
            } catch (MalformedURLException e) {
                e.printStackTrace ();
            }
        }
        loader.lastModified = libDir.lastModified ();
        server.registerMBean (loader, loaderName);
        return loader;
    }
  public void attemptManageC3P0Registry() {
    try {
      ObjectName name = new ObjectName(regName);
      C3P0RegistryManager mbean = new C3P0RegistryManager();

      if (mbs.isRegistered(name)) {
        if (logger.isLoggable(MLevel.WARNING)) {
          logger.warning(
              "A C3P0Registry mbean is already registered. "
                  + "This probably means that an application using c3p0 was undeployed, "
                  + "but not all PooledDataSources were closed prior to undeployment. "
                  + "This may lead to resource leaks over time. Please take care to close "
                  + "all PooledDataSources.");
        }
        mbs.unregisterMBean(name);
      }
      mbs.registerMBean(mbean, name);
    } catch (Exception e) {
      if (logger.isLoggable(MLevel.WARNING))
        logger.log(
            MLevel.WARNING,
            "Failed to set up C3P0RegistryManager mBean. "
                + "[c3p0 will still function normally, but management via JMX may not be possible.]",
            e);
    }
  }
Пример #3
0
  private static void checkThreadInfo() throws Exception {
    // assume all threads stay alive
    long[] ids = (long[]) server.getAttribute(thread, "AllThreadIds");
    Object result = server.invoke(thread, "getThreadInfo", new Object[] {ids}, new String[] {"[J"});
    for (CompositeData cd : (CompositeData[]) result) {
      printThreadInfo(cd);
    }

    result =
        server.invoke(
            thread,
            "getThreadInfo",
            new Object[] {ids, new Integer(2)},
            new String[] {"[J", "int"});
    for (CompositeData cd : (CompositeData[]) result) {
      printThreadInfo(cd);
    }

    long id = Thread.currentThread().getId();
    result =
        server.invoke(thread, "getThreadInfo", new Object[] {new Long(id)}, new String[] {"long"});
    printThreadInfo((CompositeData) result);

    result =
        server.invoke(
            thread,
            "getThreadInfo",
            new Object[] {new Long(id), new Integer(2)},
            new String[] {"long", "int"});
    printThreadInfo((CompositeData) result);
  }
  public void export() {
    try {
      // 创建一个MBeanServer
      MBeanServer mbs = MBeanServerFactory.createMBeanServer(DOMAIN);
      // MBeanServer mbs = MBeanServerFactory.createMBeanServer();//不能在jconsole中使用
      // MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();//可在jconsole中使用
      // 用MBeanServer注册LoginStatsMBean
      // MBeanServer.registerMBean(Object,ObjectName)方法使用的参数有两个:一个是MBean实现的一个实例;另一个是类型ObjectName的一个对象-它用于唯一地标识该MBean
      mbs.registerMBean(new Status(), new ObjectName(MBeanName));

      // 存取该JMX服务的URL:
      JMXServiceURL url =
          new JMXServiceURL("rmi", HOST, JMX_PORT, "/jndi/rmi://" + HOST + ":" + 1099 + "/app");
      // start()和stop()来启动和停止 JMXConnectorServer
      JMXConnectorServer jmxServer =
          JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
      serviceUrl = url.toString();
      // 在RMI上注册
      LocateRegistry.createRegistry(JMX_PORT);
      jmxServer.start();

      // 创建适配器,用于能够通过浏览器访问MBean
      //            HtmlAdaptorServer adapter = new HtmlAdaptorServer();
      //            adapter.setPort(9797);
      //            mbs.registerMBean(adapter, new ObjectName(
      //                    "MyappMBean:name=htmladapter,port=9797"));
      //            adapter.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  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;
  }
 /**
  * Returns a string array containing the default JMX domains of all available MBeanServers in this
  * JVM.
  *
  * @return a string array of JMX default domains
  */
 public static String[] getMBeanServerDomains() {
   Set<String> domains = new HashSet<String>();
   for (MBeanServer mbs : MBeanServerFactory.findMBeanServer(null)) {
     String domain = mbs.getDefaultDomain();
     if (domain == null) domain = "DefaultDomain";
     domains.add(domain);
   }
   return domains.toArray(new String[domains.size()]);
 }
 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");
 }
Пример #8
0
  private static void checkEnum() throws Exception {
    String type = (String) server.getAttribute(heapPool, "Type");
    if (!type.equals("HEAP")) {
      throw new RuntimeException("TEST FAILED: " + " incorrect memory type for " + heapPool);
    }

    type = (String) server.getAttribute(nonHeapPool, "Type");
    if (!type.equals("NON_HEAP")) {
      throw new RuntimeException("TEST FAILED: " + " incorrect memory type for " + nonHeapPool);
    }
  }
Пример #9
0
  public static void main(String[] args) throws Exception {
    System.out.println(
        ">>> Test how for the MBeanServerInvocationHandler to "
            + "unwrap a user specific exception.");

    final MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    final ObjectName name = new ObjectName("a:b=c");
    mbs.registerMBean(new Test(), name);
    TestMBean proxy =
        (TestMBean)
            MBeanServerInvocationHandler.newProxyInstance(mbs, name, TestMBean.class, false);

    // test the method "getter"
    System.out.println(">>> Test the method getter to get an IOException.");
    try {
      proxy.getIOException();
    } catch (IOException e) {
      System.out.println(">>> Test passed: got expected exception:");
      // e.printStackTrace(System.out);
    } catch (Throwable t) {
      System.out.println(">>> Test failed: got wrong exception:");
      t.printStackTrace(System.out);

      throw new RuntimeException("Did not get an expected IOException.");
    }

    // test the method "setter"
    System.out.println(">>> Test the method setter to get a RuntimeException.");
    try {
      proxy.setRuntimeException("coucou");
    } catch (UnsupportedOperationException ue) {
      System.out.println(">>> Test passed: got expected exception:");
      // ue.printStackTrace(System.out);
    } catch (Throwable t) {
      System.out.println(">>> Test failed: got wrong exception:");
      t.printStackTrace(System.out);

      throw new RuntimeException("Did not get an expected Runtimeexception.");
    }

    // test the method "invoke"
    System.out.println(">>> Test the method invoke to get an Error.");
    try {
      proxy.invokeError();
    } catch (AssertionError ae) {
      System.out.println(">>> Test passed: got expected exception:");
      // ue.printStackTrace(System.out);
    } catch (Throwable t) {
      System.out.println(">>> Test failed: got wrong exception:");
      t.printStackTrace(System.out);

      throw new RuntimeException("Did not get an expected Error.");
    }
  }
 private static void checkPlatformMBeans() throws Exception {
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   Set<ObjectName> mbeanNames = mbs.queryNames(null, null);
   for (ObjectName name : mbeanNames) {
     if (!mbs.isInstanceOf(name, NotificationBroadcaster.class.getName())) {
       System.out.println(name + ": not a NotificationBroadcaster");
     } else {
       MBeanInfo mbi = mbs.getMBeanInfo(name);
       check(name.toString(), mbi.getNotifications());
     }
   }
 }
  @Test
  public void registerMBean()
      throws MalformedObjectNameException, NotCompliantMBeanException,
          InstanceAlreadyExistsException, MBeanRegistrationException, InstanceNotFoundException {
    MBeanServer jolokiaServer = JolokiaMBeanServerUtil.getJolokiaMBeanServer();

    Dummy test = new Dummy();
    ObjectName name = new ObjectName("jolokia.test:name=test");
    JolokiaMBeanServerUtil.registerMBean(test, name);
    assertTrue(jolokiaServer.isRegistered(name));
    JolokiaMBeanServerUtil.unregisterMBean(name);
    Assert.assertFalse(jolokiaServer.isRegistered(name));
  }
  @Test(expectedExceptions = IllegalStateException.class)
  void registerMBeanFailed()
      throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanException,
          MalformedObjectNameException, AttributeNotFoundException, ReflectionException,
          InstanceNotFoundException {
    MBeanServer server = EasyMock.createMock(MBeanServer.class);
    ObjectName oName = new ObjectName(JolokiaMBeanServerHolderMBean.OBJECT_NAME);
    EasyMock.expect(server.registerMBean(EasyMock.anyObject(), EasyMock.eq(oName)))
        .andThrow(new MBeanRegistrationException(new Exception()));
    EasyMock.replay(server);

    MBeanServer m = JolokiaMBeanServerUtil.registerJolokiaMBeanServerHolderMBean(server);
  }
Пример #13
0
  public static void main(String[] args) throws Exception {
    Class thisClass = MethodResultTest.class;
    Class exoticClass = Exotic.class;
    String exoticClassName = Exotic.class.getName();
    ClassLoader testClassLoader = thisClass.getClassLoader();
    if (!(testClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader);
      System.exit(1);
    }

    URLClassLoader tcl = (URLClassLoader) testClassLoader;
    URL[] urls = tcl.getURLs();
    ClassLoader shadowLoader =
        new ShadowLoader(
            urls,
            testClassLoader,
            new String[] {
              exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName()
            });
    Class cl = shadowLoader.loadClass(exoticClassName);
    if (cl == exoticClass) {
      System.out.println(
          "TEST INVALID: Shadow class loader loaded " + "same class as test class loader");
      System.exit(1);
    }
    Thread.currentThread().setContextClassLoader(shadowLoader);

    ObjectName on = new ObjectName("a:b=c");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.createMBean(Thing.class.getName(), on);

    final String[] protos = {"rmi", "iiop", "jmxmp"};

    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs, on);
        System.out.println();
      } catch (Exception e) {
        System.out.println("TEST FAILED WITH EXCEPTION:");
        e.printStackTrace(System.out);
        ok = false;
      }
    }

    if (ok) System.out.println("Test passed");
    else {
      System.out.println("TEST FAILED");
      System.exit(1);
    }
  }
Пример #14
0
    private PatternBinding(
        int hasCode,
        @NotNull String verb,
        @Nullable String route,
        @NotNull Pattern pattern,
        @Nullable Set<String> paramNames,
        @NotNull Middleware[] middleware) {
      this.route = route;
      this.pattern = pattern;
      this.paramNames = paramNames;
      Collections.addAll(this.middleware, middleware);

      // register on JMX
      try {
        objectName =
            new ObjectName(
                "com.jetdrone.yoke:[email protected]"
                    + hasCode
                    + ",method="
                    + verb
                    + ",path="
                    + ObjectName.quote(route));
      } catch (MalformedObjectNameException e) {
        throw new RuntimeException(e);
      }

      try {
        mbs.registerMBean(new RouteMBean(this.middleware), objectName);
      } catch (InstanceAlreadyExistsException e) {
        // ignore
      } catch (MBeanRegistrationException | NotCompliantMBeanException e) {
        throw new RuntimeException(e);
      }
    }
  /* ------------------------------------------------------------ */
  public synchronized ObjectName uniqueObjectName(
      MBeanServer server, Object object, String objectName) {
    if (!objectName.endsWith("=")) {
      String className = object.getClass().getName();
      if (className.indexOf(".") > 0)
        className = className.substring(className.lastIndexOf(".") + 1);
      if (className.endsWith("MBean")) className = className.substring(0, className.length() - 5);
      if (!objectName.endsWith(":")) objectName += ",";
      objectName += className + "=";
    }

    ObjectName oName = null;
    try {
      while (true) {
        Integer id = (Integer) __objectId.get(objectName);
        if (id == null) id = new Integer(0);
        oName = new ObjectName(objectName + id);
        id = new Integer(id.intValue() + 1);
        __objectId.put(objectName, id);

        // If no server, this must be unique
        if (server == null) break;

        // Otherwise let's check it is unique
        // if not found then it is unique
        if (!server.isRegistered(oName)) break;
      }
    } catch (Exception e) {
      log.warn(LogSupport.EXCEPTION, e);
    }

    return oName;
  }
 public void attemptUnmanageC3P0Registry() {
   try {
     ObjectName name = new ObjectName(regName);
     if (mbs.isRegistered(name)) {
       mbs.unregisterMBean(name);
       if (logger.isLoggable(MLevel.FINER))
         logger.log(MLevel.FINER, "C3P0Registry mbean unregistered.");
     } else if (logger.isLoggable(MLevel.FINE))
       logger.fine(
           "The C3P0Registry mbean was not found in the registry, so could not be unregistered.");
   } catch (Exception e) {
     if (logger.isLoggable(MLevel.WARNING))
       logger.log(
           MLevel.WARNING,
           "An Exception occurred while trying to unregister the C3P0RegistryManager mBean." + e);
   }
 }
  @Test
  public void testJmxRuleUnregistration()
      throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException,
          ReflectionException {

    rulesEngine.unregisterJmxRule(rule);

    // assert that the rule has been successfully unregistered form the JMX registry
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName name =
        new ObjectName(
            "org.easyrules.core.jmx:type="
                + rule.getClass().getSimpleName()
                + ",name="
                + rule.getName());
    assertThat(mBeanServer.isRegistered(name)).isFalse();
  }
Пример #18
0
  public static void main(String[] args) throws Exception {
    System.out.println(
        "Test that target MBean class loader is used " + "before JMX Remote API class loader");

    ClassLoader jmxRemoteClassLoader = JMXServiceURL.class.getClassLoader();
    if (jmxRemoteClassLoader == null) {
      System.out.println(
          "JMX Remote API loaded by bootstrap " + "class loader, this test is irrelevant");
      return;
    }
    if (!(jmxRemoteClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: JMX Remote API not loaded by " + "URLClassLoader");
      System.exit(1);
    }

    URLClassLoader jrcl = (URLClassLoader) jmxRemoteClassLoader;
    URL[] urls = jrcl.getURLs();
    PrivateMLet mlet = new PrivateMLet(urls, null, false);
    Class shadowClass = mlet.loadClass(JMXServiceURL.class.getName());
    if (shadowClass == JMXServiceURL.class) {
      System.out.println("TEST INVALID: MLet got original " + "JMXServiceURL not shadow");
      System.exit(1);
    }

    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.registerMBean(mlet, mletName);

    final String[] protos = {"rmi", "iiop", "jmxmp"};
    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs);
      } catch (Exception e) {
        System.out.println("TEST FAILED WITH EXCEPTION:");
        e.printStackTrace(System.out);
        ok = false;
      }
    }

    if (ok) System.out.println("Test passed");
    else {
      System.out.println("TEST FAILED");
      System.exit(1);
    }
  }
  @Test
  void registerMBean2()
      throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanException,
          MalformedObjectNameException, AttributeNotFoundException, ReflectionException,
          InstanceNotFoundException {
    MBeanServer server = EasyMock.createMock(MBeanServer.class);
    MBeanServer ret = MBeanServerFactory.newMBeanServer();
    ObjectName oName = new ObjectName(JolokiaMBeanServerHolderMBean.OBJECT_NAME);
    EasyMock.expect(server.registerMBean(EasyMock.anyObject(), EasyMock.eq(oName)))
        .andThrow(new InstanceAlreadyExistsException());
    EasyMock.expect(
            server.getAttribute(
                EasyMock.eq(oName), eq(JolokiaMBeanServerUtil.JOLOKIA_MBEAN_SERVER_ATTRIBUTE)))
        .andReturn(ret);
    EasyMock.replay(server);

    MBeanServer m = JolokiaMBeanServerUtil.registerJolokiaMBeanServerHolderMBean(server);
    Assert.assertEquals(ret, m);
  }
Пример #20
0
  static void MonitorGC(long h) {

    handle = h;
    List<GarbageCollectorMXBean> gcbeans =
        java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    try {
      ObjectName gcName =
          new ObjectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*");
      for (ObjectName name : server.queryNames(gcName, null)) {
        GarbageCollectorMXBean gc =
            ManagementFactory.newPlatformMXBeanProxy(
                server, name.getCanonicalName(), GarbageCollectorMXBean.class);
        gcbeans.add(gc);

        NotificationEmitter emitter = (NotificationEmitter) gc;
        NotificationListener listener =
            new NotificationListener() {
              @Override
              public void handleNotification(Notification notification, Object handback) {
                if (notification
                    .getType()
                    .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                  CompositeData ndata = (CompositeData) notification.getUserData();
                  GarbageCollectionNotificationInfo info =
                      GarbageCollectionNotificationInfo.from(ndata);
                  boolean major = "end of major GC".equals(info.getGcAction());
                  long free = Runtime.getRuntime().freeMemory();
                  long total = Runtime.getRuntime().totalMemory();
                  long qty = (15 * total) - (free * 100);
                  if (qty > 0) {
                    NotifyOSv(handle, qty);
                  }
                }
              }
            };
        emitter.addNotificationListener(listener, null, null);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Пример #21
0
 private int getState(ObjectName name) {
   int status = -1;
   if (name != null) {
     try {
       status = (Integer) server.getAttribute(name, "State");
     } catch (Exception e) {
       log.warn("getState", e);
     }
   }
   return status;
 }
  /**
   * Applies the QualifiedAttributeValueExp to an MBean.
   *
   * @param name The name of the MBean on which the QualifiedAttributeValueExp will be applied.
   * @return The ValueExp.
   * @exception BadStringOperationException
   * @exception BadBinaryOpValueExpException
   * @exception BadAttributeValueExpException
   * @exception InvalidApplicationException
   */
  public ValueExp apply(ObjectName name)
      throws BadStringOperationException, BadBinaryOpValueExpException,
          BadAttributeValueExpException, InvalidApplicationException {
    try {
      MBeanServer server = QueryEval.getMBeanServer();
      String v = server.getObjectInstance(name).getClassName();

      if (v.equals(className)) {
        return super.apply(name);
      }
      throw new InvalidApplicationException("Class name is " + v + ", should be " + className);

    } catch (Exception e) {
      throw new InvalidApplicationException("Qualified attribute: " + e);
      /* Can happen if MBean disappears between the time we
      construct the list of MBeans to query and the time we
      evaluate the query on this MBean, or if
      getObjectInstance throws SecurityException.  */
    }
  }
Пример #23
0
 private boolean isModified(ObjectName name) {
   boolean modified = false;
   if (name != null) {
     try {
       modified = (Boolean) server.getAttribute(name, "Modified");
     } catch (Exception e) {
       // Okay to fail
     }
   }
   return modified;
 }
Пример #24
0
 public void attemptUnmanagePooledDataSource(PooledDataSource pds) {
   String nameStr = getPdsObjectNameStr(pds);
   try {
     ObjectName name = new ObjectName(nameStr);
     if (mbs.isRegistered(name)) {
       mbs.unregisterMBean(name);
       if (logger.isLoggable(MLevel.FINER))
         logger.log(MLevel.FINER, "MBean: " + nameStr + " unregistered.");
     } else if (logger.isLoggable(MLevel.FINE))
       logger.fine(
           "The mbean "
               + nameStr
               + " was not found in the registry, so could not be unregistered.");
   } catch (Exception e) {
     if (logger.isLoggable(MLevel.WARNING))
       logger.log(
           MLevel.WARNING,
           "An Exception occurred while unregistering mBean. [" + nameStr + "] " + e);
   }
 }
Пример #25
0
    private void addMiddleware(@NotNull Middleware[] middleware) {
      Collections.addAll(this.middleware, middleware);

      // un register if present
      try {
        mbs.unregisterMBean(objectName);
      } catch (InstanceNotFoundException e) {
        // ignore
      } catch (MBeanRegistrationException e) {
        throw new RuntimeException(e);
      }

      // re register if present
      try {
        mbs.registerMBean(new RouteMBean(this.middleware), objectName);
      } catch (InstanceAlreadyExistsException e) {
        // ignore
      } catch (MBeanRegistrationException | NotCompliantMBeanException e) {
        throw new RuntimeException(e);
      }
    }
Пример #26
0
 private static void checkSunGC() throws Exception {
   // Test com.sun.management proxy
   List<GarbageCollectorMXBean> gcs = getGarbageCollectorMXBeans();
   for (GarbageCollectorMXBean gc : gcs) {
     ObjectName sunGc =
         new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",name=" + gc.getName());
     CompositeData cd = (CompositeData) server.getAttribute(sunGc, "LastGcInfo");
     if (cd != null) {
       System.out.println("GC statistic for : " + gc.getName());
       printGcInfo(cd);
     }
   }
 }
Пример #27
0
  public static void main(String[] argv) throws Exception {
    memory = new ObjectName(MEMORY_MXBEAN_NAME);
    runtime = new ObjectName(RUNTIME_MXBEAN_NAME);
    thread = new ObjectName(THREAD_MXBEAN_NAME);
    os = new ObjectName(OPERATING_SYSTEM_MXBEAN_NAME);

    List<MemoryPoolMXBean> pools = getMemoryPoolMXBeans();
    for (MemoryPoolMXBean p : pools) {
      if (heapPool == null
          && p.getType() == MemoryType.HEAP
          && p.isUsageThresholdSupported()
          && p.isCollectionUsageThresholdSupported()) {
        heapPool = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",name=" + p.getName());
      }
      if (nonHeapPool == null
          && p.getType() == MemoryType.NON_HEAP
          && p.isUsageThresholdSupported()) {
        nonHeapPool = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",name=" + p.getName());
      }
    }

    // Check notification emitters
    MyListener listener = new MyListener();
    server.addNotificationListener(memory, listener, null, null);
    server.removeNotificationListener(memory, listener);

    checkEnum();
    checkList();
    checkMap();
    checkMemoryUsage();
    checkThreadInfo();

    checkOS();
    checkSunGC();

    System.out.println("Test passed.");
  }
Пример #28
0
 private static void checkList() throws Exception {
   String[] args = (String[]) server.getAttribute(runtime, "InputArguments");
   if (args.length < 1) {
     throw new RuntimeException("TEST FAILED: " + " empty input arguments");
   }
   // check if -verbose:gc exists
   boolean found = false;
   for (String option : args) {
     if (option.equals(OPTION)) {
       found = true;
       break;
     }
   }
   if (!found) {
     throw new RuntimeException("TEST FAILED: " + "VM option " + OPTION + " not found");
   }
 }
    public void registerCircuitBreaker(final CircuitBreaker circuitBreaker, final String name)
        throws JMException {
      ObjectName mbeanObjectName = null;

      ObjectName serviceName = Qi4jMBeans.findServiceName(server, application.name(), name);
      if (serviceName != null) {
        mbeanObjectName = new ObjectName(serviceName.toString() + ",name=Circuit breaker");
      } else {
        try {
          mbeanObjectName = new ObjectName("CircuitBreaker:name=" + name);
        } catch (MalformedObjectNameException e) {
          throw new IllegalArgumentException("Illegal name:" + name);
        }
      }

      CircuitBreakerJMX bean = new CircuitBreakerJMX(circuitBreaker, mbeanObjectName);

      try {
        server.registerMBean(bean, mbeanObjectName);
        registeredCircuitBreakers.put(circuitBreaker, mbeanObjectName);
      } catch (InstanceAlreadyExistsException e) {
        e.printStackTrace();
      } catch (MBeanRegistrationException e) {
        e.printStackTrace();
      } catch (NotCompliantMBeanException e) {
        e.printStackTrace();
      }

      // Add logger
      circuitBreaker.addPropertyChangeListener(
          new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
              if (evt.getPropertyName().equals("status")) {
                if (evt.getNewValue().equals(CircuitBreaker.Status.on))
                  LoggerFactory.getLogger(CircuitBreakerManagement.class)
                      .info("Circuit breaker " + name + " is now on");
                else
                  LoggerFactory.getLogger(CircuitBreakerManagement.class)
                      .error("Circuit breaker " + name + " is now off");
              }
            }
          });
    }
Пример #30
0
 private long persist(File f, ObjectName name) {
   long deployed = f.lastModified();
   try {
     Element e = (Element) server.getAttribute(name, "Persist");
     if (e != null) {
       XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
       Document doc = new Document();
       e.detach();
       doc.setRootElement(e);
       File tmp = new File(f.getAbsolutePath() + ".tmp");
       FileWriter writer = new FileWriter(tmp);
       out.output(doc, writer);
       writer.close();
       f.delete();
       tmp.renameTo(f);
       deployed = f.lastModified();
     }
   } catch (Exception ex) {
     log.warn("persist", ex);
   }
   return deployed;
 }