Пример #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);
    }
  }
  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();
    }
  }
Пример #4
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:type=Route@"
                    + 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);
      }
    }
Пример #5
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.");
    }
  }
  @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);
  }
Пример #7
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);
  }
    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");
              }
            }
          });
    }
Пример #10
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);
      }
    }
Пример #11
0
 public void run() {
   started = true;
   Thread.currentThread().setName("Q2-" + getInstanceId().toString());
   try {
     /*
      * The following code determines whether a MBeanServer exists
      * already. If so then the first one in the list is used.
      * I have not yet find a way to interrogate the server for
      * information other than MBeans so to pick a specific one
      * would be difficult.
      */
     ArrayList mbeanServerList = MBeanServerFactory.findMBeanServer(null);
     if (mbeanServerList.isEmpty()) {
       server = MBeanServerFactory.createMBeanServer(JMX_NAME);
     } else {
       server = (MBeanServer) mbeanServerList.get(0);
     }
     final ObjectName loaderName = new ObjectName(Q2_CLASS_LOADER);
     try {
       loader =
           (QClassLoader)
               java.security.AccessController.doPrivileged(
                   new java.security.PrivilegedAction() {
                     public Object run() {
                       return new QClassLoader(server, libDir, loaderName, mainClassLoader);
                     }
                   });
       server.registerMBean(loader, loaderName);
       loader = loader.scan(false);
     } catch (Throwable t) {
       if (log != null) log.error("initial-scan", t);
       else t.printStackTrace();
     }
     factory = new QFactory(loaderName, this);
     initSystemLogger();
     addShutdownHook();
     q2Thread = Thread.currentThread();
     q2Thread.setContextClassLoader(loader);
     if (cli != null) cli.start();
     initConfigDecorator();
     for (int i = 1; !shutdown; i++) {
       try {
         boolean forceNewClassLoader = scan();
         QClassLoader oldClassLoader = loader;
         loader = loader.scan(forceNewClassLoader);
         if (loader != oldClassLoader) {
           oldClassLoader = null; // We want't this to be null so it gets GCed.
           System.gc(); // force a GC
           log.info(
               "new classloader ["
                   + Integer.toString(loader.hashCode(), 16)
                   + "] has been created");
         }
         deploy();
         checkModified();
         relax(SCAN_INTERVAL);
         if (i % (3600000 / SCAN_INTERVAL) == 0) logVersion();
       } catch (Throwable t) {
         log.error("start", t);
         relax();
       }
     }
     undeploy();
     try {
       server.unregisterMBean(loaderName);
     } catch (InstanceNotFoundException e) {
       log.error(e);
     }
     if (decorator != null) {
       decorator.uninitialize();
     }
     if (exit && !shuttingDown) System.exit(0);
   } catch (Exception e) {
     if (log != null) log.error(e);
     else e.printStackTrace();
     System.exit(1);
   }
 }