/**
  * @param objectName
  * @return artifact
  * @throws InstanceNotFoundException
  */
 public T getArtifact(final ObjectName objectName) throws InstanceNotFoundException {
   if (this.server.isRegistered(objectName)) {
     return JMX.newMXBeanProxy(this.server, objectName, this.artifactType);
   }
   throw new InstanceNotFoundException(
       String.format("Instance '%s' not found", objectName.getCanonicalName()));
 }
 @BeforeClass
 public static void beforeClass() throws Exception {
   runtimeType = RuntimeType.getRuntimeType(System.getProperty("target.container"));
   if (runtimeType == RuntimeType.KARAF) {
     String jmxServiceURL =
         "service:jmx:rmi://127.0.0.1:44444/jndi/rmi://127.0.0.1:1099/karaf-root";
     Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL);
     env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]});
     connector = ManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS);
   } else if (runtimeType == RuntimeType.TOMCAT) {
     String jmxServiceURL = "service:jmx:rmi:///jndi/rmi://127.0.0.1:8089/jmxrmi";
     Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL);
     env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]});
     connector = ManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS);
   } else if (runtimeType == RuntimeType.WILDFLY) {
     String jmxServiceURL = "service:jmx:http-remoting-jmx://127.0.0.1:9990";
     Map<String, Object> env = ManagementUtils.getDefaultEnvironment(jmxServiceURL);
     env.put(JMXConnector.CREDENTIALS, new String[] {credentials[0], credentials[1]});
     connector = WildFlyManagementUtils.getJMXConnector(jmxServiceURL, env, 10, TimeUnit.SECONDS);
   } else {
     throw new IllegalStateException("Usupported target container: " + runtimeType);
   }
   proxy =
       JMX.newMXBeanProxy(
           connector.getMBeanServerConnection(),
           ProfileManagement.OBJECT_NAME,
           ProfileManagement.class);
 }
 synchronized <T> T objectNameToMXBean(ObjectName name, Class<T> type) {
   WeakReference<Object> wr = objectNameToProxy.get(name);
   if (wr != null) {
     Object proxy = wr.get();
     if (type.isInstance(proxy)) return type.cast(proxy);
   }
   InvocationHandler handler = new MBeanServerInvocationHandler(mbsc, name);
   T proxy = JMX.newMXBeanProxy(mbsc, name, type);
   objectNameToProxy.put(name, new WeakReference<Object>(proxy));
   return proxy;
 }
Beispiel #4
0
 public static <T> T getRemoteBean(
     Class<T> clazz, String mbeanName, IConfiguration config, boolean mxbean) {
   try {
     if (mxbean)
       return ManagementFactory.newPlatformMXBeanProxy(
           JMXNodeTool.instance(config).mbeanServerConn, mbeanName, clazz);
     else
       return JMX.newMBeanProxy(
           JMXNodeTool.instance(config).mbeanServerConn, new ObjectName(mbeanName), clazz);
   } catch (Exception e) {
     logger.error(e.getMessage(), e);
   }
   return null;
 }
 public void testIiopWorksOnStandard() throws Exception {
   try {
     deployFailOnError("jbpapp6469.jar");
     String objectNameString = "jboss:service=CorbaNaming";
     MBeanServerConnection mbeanServerConnection = getRMIServer(null);
     ObjectName objectName = new ObjectName(objectNameString);
     CorbaNamingServiceMBean mbean =
         JMX.newMBeanProxy(mbeanServerConnection, objectName, CorbaNamingServiceMBean.class);
     String listing = mbean.list();
     String[] deployments = listing.split("\n");
     for (String deployment : deployments) {
       if (deployment.equals("HelloSessionBean/")) return;
     }
     fail("Did not find IIOP EJB");
   } finally {
     undeployFailOnError("jbpapp6469.jar");
   }
 }
 private boolean isEndpointRegistered(String applicationName, EndpointClassNamePathPair endpoint) {
   MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
   String fullMxBeanName = "org.glassfish.tyrus:type=" + applicationName;
   ApplicationMXBean proxy;
   try {
     proxy =
         JMX.newMXBeanProxy(mBeanServer, new ObjectName(fullMxBeanName), ApplicationMXBean.class);
     List<EndpointClassNamePathPair> registeredEndpoints = proxy.getEndpoints();
     for (EndpointClassNamePathPair registeredEndpoint : registeredEndpoints) {
       if (registeredEndpoint.getEndpointPath().equals(endpoint.getEndpointPath())
           && registeredEndpoint.getEndpointClassName().equals(endpoint.getEndpointClassName())) {
         return true;
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return false;
 }
  @Override
  public ProgressNotification getTotalProgress() {

    ObjectName crossbowNotificationObjectName = null;
    try {
      crossbowNotificationObjectName = ObjectName.getInstance("Crossbow:type=CrossbowNotification");

    } catch (Exception e) {
      log.error("Exception while creating workerProgress ObjectName", e);
      e.printStackTrace();
    }

    int total = totalTasks;
    int realised = 0;
    try {

      for (String url : delegate.scGetAllMBeanServers()) {

        try {

          MBeanServerConnection mbsc =
              JMXConnectorFactory.connect(new JMXServiceURL(url)).getMBeanServerConnection();

          CrossbowNotificationMBean crossbowNotification =
              JMX.newMBeanProxy(
                  mbsc, crossbowNotificationObjectName, CrossbowNotificationMBean.class);

          ProgressNotification progress = crossbowNotification.getProgress();
          realised += progress.getCurrent();

        } catch (Exception ex) {
          log.error("Error while querying MBean server (url: " + url + ")", ex);
        }
      }

      progressNotification = new ProgressNotification(realised, total, null);

    } catch (RemoteException ex) {
      log.error("Error while getting MBean servers list.", ex);
    }

    return progressNotification;
  }
Beispiel #8
0
 /**
  * Returns the LoaderMBean.
  *
  * @return LoadeerMBean
  */
 @SuppressWarnings("cast")
 public LoaderMXBean getLoader() {
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   // proxy class
   LoaderMXBean proxy = null;
   ObjectName oName;
   try {
     oName = new ObjectName("org.red5.server:type=TomcatLoader");
     if (mbs.isRegistered(oName)) {
       proxy = JMX.newMXBeanProxy(mbs, oName, LoaderMXBean.class, true);
       log.debug("Loader was found");
     } else {
       log.warn("Loader not found");
     }
   } catch (Exception e) {
     log.error("Exception getting loader", e);
   }
   return proxy;
 }
Beispiel #9
0
  /**
   * Returns a proxy for a platform MXBean interface of a given <a href="#MXBeanNames">MXBean
   * name</a> that forwards its method calls through the given <tt>MBeanServerConnection</tt>.
   *
   * <p>This method is equivalent to:
   *
   * <blockquote>
   *
   * {@link java.lang.reflect.Proxy#newProxyInstance
   * Proxy.newProxyInstance}<tt>(mxbeanInterface.getClassLoader(), new Class[] { mxbeanInterface },
   * handler)</tt>
   *
   * </blockquote>
   *
   * where <tt>handler</tt> is an {@link java.lang.reflect.InvocationHandler InvocationHandler} to
   * which method invocations to the MXBean interface are dispatched. This <tt>handler</tt> converts
   * an input parameter from an MXBean data type to its mapped open type before forwarding to the
   * <tt>MBeanServer</tt> and converts a return value from an MXBean method call through the
   * <tt>MBeanServer</tt> from an open type to the corresponding return type declared in the MXBean
   * interface.
   *
   * <p>If the MXBean is a notification emitter (i.e., it implements {@link
   * javax.management.NotificationEmitter NotificationEmitter}), both the <tt>mxbeanInterface</tt>
   * and <tt>NotificationEmitter</tt> will be implemented by this proxy.
   *
   * <p><b>Notes:</b>
   *
   * <ol>
   *   <li>Using an MXBean proxy is a convenience remote access to a platform MXBean of a running
   *       virtual machine. All method calls to the MXBean proxy are forwarded to an
   *       <tt>MBeanServerConnection</tt> where {@link java.io.IOException IOException} may be
   *       thrown when the communication problem occurs with the connector server. An application
   *       remotely accesses the platform MXBeans using proxy should prepare to catch
   *       <tt>IOException</tt> as if accessing with the <tt>MBeanServerConnector</tt> interface.
   *   <li>When a client application is designed to remotely access MXBeans for a running virtual
   *       machine whose version is different than the version on which the application is running,
   *       it should prepare to catch {@link java.io.InvalidObjectException InvalidObjectException}
   *       which is thrown when an MXBean proxy receives a name of an enum constant which is missing
   *       in the enum class loaded in the client application.
   *   <li>{@link javax.management.MBeanServerInvocationHandler MBeanServerInvocationHandler} or its
   *       {@link javax.management.MBeanServerInvocationHandler#newProxyInstance newProxyInstance}
   *       method cannot be used to create a proxy for a platform MXBean. The proxy object created
   *       by <tt>MBeanServerInvocationHandler</tt> does not handle the properties of the platform
   *       MXBeans described in the <a href="#MXBean">class specification</a>.
   * </ol>
   *
   * @param connection the <tt>MBeanServerConnection</tt> to forward to.
   * @param mxbeanName the name of a platform MXBean within <tt>connection</tt> to forward to.
   *     <tt>mxbeanName</tt> must be in the format of {@link ObjectName ObjectName}.
   * @param mxbeanInterface the MXBean interface to be implemented by the proxy.
   * @throws IllegalArgumentException if
   *     <ul>
   *       <li><tt>mxbeanName</tt> is not with a valid {@link ObjectName ObjectName} format, or
   *       <li>the named MXBean in the <tt>connection</tt> is not a MXBean provided by the platform,
   *           or
   *       <li>the named MXBean is not registered in the <tt>MBeanServerConnection</tt>, or
   *       <li>the named MXBean is not an instance of the given <tt>mxbeanInterface</tt>
   *     </ul>
   *
   * @throws java.io.IOException if a communication problem occurred when accessing the
   *     <tt>MBeanServerConnection</tt>.
   */
  public static <T> T newPlatformMXBeanProxy(
      MBeanServerConnection connection, String mxbeanName, Class<T> mxbeanInterface)
      throws java.io.IOException {

    final Class interfaceClass = mxbeanInterface;
    // Only allow MXBean interfaces from rt.jar loaded by the
    // bootstrap class loader
    final ClassLoader loader =
        AccessController.doPrivileged(
            new PrivilegedAction<ClassLoader>() {
              public ClassLoader run() {
                return interfaceClass.getClassLoader();
              }
            });
    if (loader != null) {
      throw new IllegalArgumentException(mxbeanName + " is not a platform MXBean");
    }

    try {
      final ObjectName objName = new ObjectName(mxbeanName);
      if (!connection.isInstanceOf(objName, interfaceClass.getName())) {
        throw new IllegalArgumentException(mxbeanName + " is not an instance of " + interfaceClass);
      }

      final Class[] interfaces;
      // check if the registered MBean is a notification emitter
      boolean emitter = connection.isInstanceOf(objName, NOTIF_EMITTER);

      // create an MXBean proxy
      return JMX.newMXBeanProxy(connection, objName, mxbeanInterface, emitter);
    } catch (InstanceNotFoundException e) {
      final IllegalArgumentException iae =
          new IllegalArgumentException(mxbeanName + " not found in the connection.");
      iae.initCause(e);
      throw iae;
    } catch (MalformedObjectNameException e) {
      final IllegalArgumentException iae =
          new IllegalArgumentException(mxbeanName + " is not a valid ObjectName format.");
      iae.initCause(e);
      throw iae;
    }
  }
  public String getTotalNewLogs() {

    StringBuilder stringBuilder = new StringBuilder();
    ObjectName crossbowNotificationObjectName = null;
    try {
      crossbowNotificationObjectName = ObjectName.getInstance("Crossbow:type=CrossbowNotification");

    } catch (Exception e) {
      log.error("Exception while creating workerProgress ObjectName", e);
      e.printStackTrace();
    }

    try {

      for (String url : delegate.scGetAllMBeanServers()) {

        try {

          MBeanServerConnection mbsc =
              JMXConnectorFactory.connect(new JMXServiceURL(url)).getMBeanServerConnection();

          CrossbowNotificationMBean crossbowNotification =
              JMX.newMBeanProxy(
                  mbsc, crossbowNotificationObjectName, CrossbowNotificationMBean.class);

          String logs = crossbowNotification.getNewLogs();
          if (logs != null && !logs.equals("")) {
            stringBuilder.append(crossbowNotification.getNewLogs());
            stringBuilder.append("\n");
          }

        } catch (Exception ex) {
          log.error("Error while querying MBean server (url: " + url + ")", ex);
        }
      }

    } catch (RemoteException ex) {
      log.error("Error while getting MBean servers list.", ex);
    }

    return stringBuilder.toString();
  }
 private void awaitActive(String type, String name, String version) {
     try {
         ObjectName objectName = new ObjectName("org.eclipse.virgo.kernel:type=Model,artifact-type=" + type + ",name=" + name + ",version=" + version);
         ManageableArtifact artifact = JMX.newMXBeanProxy(this.mBeanServer, objectName, ManageableArtifact.class);
         
         long startTime = System.currentTimeMillis();
         
         while (!"ACTIVE".equals(artifact.getState())) {
             if (System.currentTimeMillis() - startTime > TIMEOUT) {
                 fail("Artifact " + type + " " + name + " " + version + " was not active within " + TIMEOUT + "ms.");
             }
             try {
                 Thread.sleep(50);
             } catch (InterruptedException _) {
             }
         }
     } catch (JMException jme) {
         fail(jme.getMessage());
     }
 }
 public void use() {
   JMXConnector jmxc = null;
   try {
     JMXServiceURL serviceURL = new JMXServiceURL(this.serviceUrl);
     jmxc = JMXConnectorFactory.connect(serviceURL, null);
     MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
     ObjectName mbeanName = new ObjectName(MBeanName);
     StatusMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, StatusMBean.class, true);
     System.out.println(mbeanProxy.getName());
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (jmxc != null) {
       try {
         jmxc.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
 @Test
 @Ignore
 public void reconnect() throws Exception {
   MarketDataRequest request = MarketDataRequestBuilder.newRequest().withSymbols("GOOG").create();
   final DataFlowID flowID =
       moduleManager.createDataFlow(
           new DataRequest[] {new DataRequest(getInstanceURN(), request)});
   // wait until some arbitrary number of ticks have been received
   AbstractMarketDataFeedTest.wait(
       new Callable<Boolean>() {
         @Override
         public Boolean call() throws Exception {
           return dataSink.getData(flowID).size() > 20;
         }
       });
   // reconnect and wait for more data
   // TODO - need to figure out how to make this magic incantation work
   ObjectName objectName = getInstanceURN().toObjectName();
   MBeanServerConnection mMBeanServer = null;
   AbstractMarketDataModuleMXBean mMBeanProxy =
       JMX.newMXBeanProxy(mMBeanServer, objectName, AbstractMarketDataModuleMXBean.class, true);
 }
 /**
  * Initialization.
  *
  * @throws ServletException
  */
 @SuppressWarnings("cast")
 @Override
 public void start() throws ServletException {
   log.info("Loading tomcat virtual host");
   if (webappFolder != null) {
     // check for match with base webapp root
     if (webappFolder.equals(webappRoot)) {
       log.error("Web application root cannot be the same as base");
       return;
     }
   }
   ClassLoader classloader = Thread.currentThread().getContextClassLoader();
   // ensure we have a host
   if (host == null) {
     host = createHost();
   }
   host.setParentClassLoader(classloader);
   String propertyPrefix = name;
   if (domain != null) {
     propertyPrefix += '_' + domain.replace('.', '_');
   }
   log.debug("Generating name (for props) {}", propertyPrefix);
   System.setProperty(propertyPrefix + ".webapp.root", webappRoot);
   log.info("Virtual host root: {}", webappRoot);
   log.info("Virtual host context id: {}", defaultApplicationContextId);
   // Root applications directory
   File appDirBase = new File(webappRoot);
   // Subdirs of root apps dir
   File[] dirs = appDirBase.listFiles(new TomcatLoader.DirectoryFilter());
   // Search for additional context files
   for (File dir : dirs) {
     String dirName = '/' + dir.getName();
     // check to see if the directory is already mapped
     if (null == host.findChild(dirName)) {
       String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName);
       Context ctx = null;
       if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
         log.debug("Adding ROOT context");
         ctx = addContext("/", webappContextDir);
       } else {
         log.debug("Adding context from directory scan: {}", dirName);
         ctx = addContext(dirName, webappContextDir);
       }
       log.debug("Context: {}", ctx);
       webappContextDir = null;
     }
   }
   appDirBase = null;
   dirs = null;
   // Dump context list
   if (log.isDebugEnabled()) {
     for (Container cont : host.findChildren()) {
       log.debug("Context child name: {}", cont.getName());
     }
   }
   engine.addChild(host);
   // Start server
   try {
     log.info("Starting Tomcat virtual host");
     // may not have to do this step for every host
     LoaderBase.setApplicationLoader(
         new TomcatApplicationLoader(embedded, host, applicationContext));
     for (Container cont : host.findChildren()) {
       if (cont instanceof StandardContext) {
         StandardContext ctx = (StandardContext) cont;
         ServletContext servletContext = ctx.getServletContext();
         log.debug("Context initialized: {}", servletContext.getContextPath());
         // set the hosts id
         servletContext.setAttribute("red5.host.id", getHostId());
         String prefix = servletContext.getRealPath("/");
         log.debug("Path: {}", prefix);
         try {
           Loader cldr = ctx.getLoader();
           log.debug("Loader type: {}", cldr.getClass().getName());
           ClassLoader webClassLoader = cldr.getClassLoader();
           log.debug("Webapp classloader: {}", webClassLoader);
           // create a spring web application context
           XmlWebApplicationContext appctx = new XmlWebApplicationContext();
           appctx.setClassLoader(webClassLoader);
           appctx.setConfigLocations(new String[] {"/WEB-INF/red5-*.xml"});
           // check for red5 context bean
           if (applicationContext.containsBean(defaultApplicationContextId)) {
             appctx.setParent(
                 (ApplicationContext) applicationContext.getBean(defaultApplicationContextId));
           } else {
             log.warn(
                 "{} bean was not found in context: {}",
                 defaultApplicationContextId,
                 applicationContext.getDisplayName());
             // lookup context loader and attempt to get what we need from it
             if (applicationContext.containsBean("context.loader")) {
               ContextLoader contextLoader =
                   (ContextLoader) applicationContext.getBean("context.loader");
               appctx.setParent(contextLoader.getContext(defaultApplicationContextId));
             } else {
               log.debug("Context loader was not found, trying JMX");
               MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
               // get the ContextLoader from jmx
               ContextLoaderMXBean proxy = null;
               ObjectName oName = null;
               try {
                 oName = new ObjectName("org.red5.server:name=contextLoader,type=ContextLoader");
                 if (mbs.isRegistered(oName)) {
                   proxy = JMX.newMXBeanProxy(mbs, oName, ContextLoaderMXBean.class, true);
                   log.debug("Context loader was found");
                   proxy.setParentContext(defaultApplicationContextId, appctx.getId());
                 } else {
                   log.warn("Context loader was not found");
                 }
               } catch (Exception e) {
                 log.warn("Exception looking up ContextLoader", e);
               }
             }
           }
           if (log.isDebugEnabled()) {
             if (appctx.getParent() != null) {
               log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
             }
           }
           //
           appctx.setServletContext(servletContext);
           // set the root webapp ctx attr on the each servlet context so spring can find it later
           servletContext.setAttribute(
               WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
           appctx.refresh();
         } catch (Throwable t) {
           log.error("Error setting up context: {}", servletContext.getContextPath(), t);
           if (log.isDebugEnabled()) {
             t.printStackTrace();
           }
         }
       }
     }
   } catch (Exception e) {
     log.error("Error loading Tomcat virtual host", e);
   }
 }
  /**
   * Starts a web application and its red5 (spring) component. This is basically a stripped down
   * version of init().
   *
   * @return true on success
   * @throws ServletException
   */
  @SuppressWarnings("cast")
  public boolean startWebApplication(String applicationName) throws ServletException {
    boolean result = false;
    log.info("Starting Tomcat virtual host - Web application");
    log.info("Virtual host root: {}", webappRoot);
    log.info("Virtual host context id: {}", defaultApplicationContextId);
    // application directory
    String contextName = '/' + applicationName;
    Container cont = null;
    // check if the context already exists for the host
    if ((cont = host.findChild(contextName)) == null) {
      log.debug("Context did not exist in host");
      String webappContextDir = FileUtil.formatPath(webappRoot, applicationName);
      // prepend slash
      Context ctx = addContext(contextName, webappContextDir);
      // set the newly created context as the current container
      cont = ctx;
    } else {
      log.debug("Context already exists in host");
    }
    try {
      ServletContext servletContext = ((Context) cont).getServletContext();
      log.debug("Context initialized: {}", servletContext.getContextPath());
      String prefix = servletContext.getRealPath("/");
      log.debug("Path: {}", prefix);
      Loader cldr = ((Context) cont).getLoader();
      log.debug("Loader type: {}", cldr.getClass().getName());
      ClassLoader webClassLoader = cldr.getClassLoader();
      log.debug("Webapp classloader: {}", webClassLoader);
      // create a spring web application context
      XmlWebApplicationContext appctx = new XmlWebApplicationContext();
      appctx.setClassLoader(webClassLoader);
      appctx.setConfigLocations(new String[] {"/WEB-INF/red5-*.xml"});
      // check for red5 context bean
      if (applicationContext.containsBean(defaultApplicationContextId)) {
        appctx.setParent(
            (ApplicationContext) applicationContext.getBean(defaultApplicationContextId));
      } else {
        log.warn(
            "{} bean was not found in context: {}",
            defaultApplicationContextId,
            applicationContext.getDisplayName());
        // lookup context loader and attempt to get what we need from it
        if (applicationContext.containsBean("context.loader")) {
          ContextLoader contextLoader =
              (ContextLoader) applicationContext.getBean("context.loader");
          appctx.setParent(contextLoader.getContext(defaultApplicationContextId));
        } else {
          log.debug("Context loader was not found, trying JMX");
          MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
          // get the ContextLoader from jmx
          ContextLoaderMXBean proxy = null;
          ObjectName oName = null;
          try {
            oName = new ObjectName("org.red5.server:name=contextLoader,type=ContextLoader");
            if (mbs.isRegistered(oName)) {
              proxy = JMX.newMXBeanProxy(mbs, oName, ContextLoaderMXBean.class, true);
              log.debug("Context loader was found");
              proxy.setParentContext(defaultApplicationContextId, appctx.getId());
            } else {
              log.warn("Context loader was not found");
            }
          } catch (Exception e) {
            log.warn("Exception looking up ContextLoader", e);
          }
        }
      }
      if (log.isDebugEnabled()) {
        if (appctx.getParent() != null) {
          log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
        }
      }
      //
      appctx.setServletContext(servletContext);
      // set the root webapp ctx attr on the each servlet context so spring can find it later
      servletContext.setAttribute(
          WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
      appctx.refresh();
      result = true;
    } catch (Throwable t) {
      log.error("Error setting up context: {}", applicationName, t);
      if (log.isDebugEnabled()) {
        t.printStackTrace();
      }
    }

    return result;
  }
Beispiel #16
0
  private void test(boolean monitorOnSessionLevel) {
    Server server = null;
    try {
      setContextPath("/monitoringBroadcastApp");

      ApplicationMonitor applicationMonitor;
      if (monitorOnSessionLevel) {
        applicationMonitor = new SessionAwareApplicationMonitor();
      } else {
        applicationMonitor = new SessionlessApplicationMonitor();
      }

      int sessionsCount = 3;

      // each sessions gets 3 messages - 2 text messages and 1 binary
      CountDownLatch sentMessagesLatch = new CountDownLatch(sessionsCount * 3);

      ApplicationEventListener applicationEventListener =
          new TestApplicationEventListener(
              applicationMonitor, null, null, sentMessagesLatch, null, null);
      getServerProperties()
          .put(ApplicationEventListener.APPLICATION_EVENT_LISTENER, applicationEventListener);
      server = startServer(AnnotatedServerEndpoint.class);

      ClientManager client = createClient();
      Session session = null;
      for (int i = 0; i < sessionsCount; i++) {
        session =
            client.connectToServer(
                AnnotatedClientEndpoint.class, getURI(AnnotatedServerEndpoint.class));
      }

      // send different number of messages of each type so that it can be verified that a correct
      // MXBean is
      // accessed
      session.getBasicRemote().sendText("Broadcast request");

      assertTrue(sentMessagesLatch.await(5, TimeUnit.SECONDS));

      String applicationMxBeanName = "org.glassfish.tyrus:type=/monitoringBroadcastApp";
      MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
      ApplicationMXBean applicationMXBean =
          JMX.newMXBeanProxy(
              mBeanServer, new ObjectName(applicationMxBeanName), ApplicationMXBean.class);

      assertEquals(9, applicationMXBean.getSentMessagesCount());
      assertEquals(3, applicationMXBean.getBinaryMessageStatisticsMXBean().getSentMessagesCount());
      assertEquals(6, applicationMXBean.getTextMessageStatisticsMXBean().getSentMessagesCount());

      // check message sizes get monitored properly
      assertEquals(
          (TEXT_MESSAGE_1.length() + TEXT_MESSAGE_2.length()) / 2,
          applicationMXBean.getTextMessageStatisticsMXBean().getAverageSentMessageSize());
      assertEquals(
          BINARY_MESSAGE.limit(),
          applicationMXBean.getBinaryMessageStatisticsMXBean().getAverageSentMessageSize());

      List<EndpointMXBean> endpointMXBeans = applicationMXBean.getEndpointMXBeans();
      assertEquals(1, endpointMXBeans.size());

      EndpointMXBean endpointMXBean = endpointMXBeans.get(0);

      assertEquals(9, endpointMXBean.getSentMessagesCount());
      assertEquals(3, endpointMXBean.getBinaryMessageStatisticsMXBean().getSentMessagesCount());
      assertEquals(6, endpointMXBean.getTextMessageStatisticsMXBean().getSentMessagesCount());

      assertEquals(
          (TEXT_MESSAGE_1.length() + TEXT_MESSAGE_2.length()) / 2,
          endpointMXBean.getTextMessageStatisticsMXBean().getAverageSentMessageSize());
      assertEquals(
          BINARY_MESSAGE.limit(),
          endpointMXBean.getBinaryMessageStatisticsMXBean().getAverageSentMessageSize());

      List<SessionMXBean> sessionMXBeans = endpointMXBean.getSessionMXBeans();
      if (!monitorOnSessionLevel) {
        assertTrue(sessionMXBeans.isEmpty());
        return;
      }

      assertEquals(3, sessionMXBeans.size());
      for (BaseMXBean sessionMXBean : sessionMXBeans) {
        assertEquals(3, sessionMXBean.getSentMessagesCount());
        assertEquals(1, sessionMXBean.getBinaryMessageStatisticsMXBean().getSentMessagesCount());
        assertEquals(2, sessionMXBean.getTextMessageStatisticsMXBean().getSentMessagesCount());

        assertEquals(
            (TEXT_MESSAGE_1.length() + TEXT_MESSAGE_2.length()) / 2,
            sessionMXBean.getTextMessageStatisticsMXBean().getAverageSentMessageSize());
        assertEquals(
            BINARY_MESSAGE.limit(),
            sessionMXBean.getBinaryMessageStatisticsMXBean().getAverageSentMessageSize());
      }

    } catch (Exception e) {
      e.printStackTrace();
      fail();
    } finally {
      stopServer(server);
    }
  }
 private void initMbean(MBeanServerConnection mbsc)
     throws IOException, MalformedObjectNameException {
   this.mbean = JMX.newMBeanProxy(mbsc, new ObjectName(MBEAN_NAME), DbManagerMBean.class);
 }
 /**
  * Returns an <code>MXBean</code> Proxy for the market data module being tested.
  *
  * @return an <code>AbstractMarketDataModuleMXBean</code> value
  * @throws Exception if an error occurs
  */
 protected final AbstractMarketDataModuleMXBean getMXBeanProxy() throws Exception {
   ObjectName objectName = getInstanceURN().toObjectName();
   MBeanServerConnection mMBeanServer = ModuleTestBase.getMBeanServer();
   return JMX.newMXBeanProxy(mMBeanServer, objectName, AbstractMarketDataModuleMXBean.class, true);
 }
  private void registerNotificationListener() {

    log.debug("Reseting and registering at all WorkerProgressMBeans as listener");

    ObjectName workerProgressObjectName = null;
    ObjectName crossbowNotificationObjectName = null;
    try {
      crossbowNotificationObjectName = ObjectName.getInstance("Crossbow:type=CrossbowNotification");
      workerProgressObjectName = ObjectName.getInstance("Crossbow:type=WorkerProgress");

    } catch (Exception e) {
      log.error("Exception while creating workerProgress ObjectName", e);
      e.printStackTrace();
    }

    MBeanServer server = JimsMBeanServer.findJimsMBeanServer();

    try {

      for (String url : delegate.scGetAllMBeanServers()) {

        try {

          MBeanServerConnection mbsc =
              JMXConnectorFactory.connect(new JMXServiceURL(url)).getMBeanServerConnection();

          CrossbowNotificationMBean crossbowNotification =
              JMX.newMBeanProxy(
                  mbsc, crossbowNotificationObjectName, CrossbowNotificationMBean.class);

          crossbowNotification.reset();

          try {
            mbsc.removeNotificationListener(
                workerProgressObjectName, crossbowNotificationObjectName);
          } catch (Exception e) {
            log.error(
                "Exception while removing notification listener from MBean server (url: "
                    + url
                    + ")",
                e);
          }
          mbsc.addNotificationListener(
              workerProgressObjectName, crossbowNotificationObjectName, null, null);

          log.info(
              "CrosbowNotification successfully registered lestener at WorkerProgressMBean (url: "
                  + url
                  + ")");

        } catch (Exception ex) {
          log.error("Error while querying MBean server (url: " + url + ")", ex);
        }
      }

      progressNotification = new ProgressNotification(0, totalTasks, WorkerProgress.getIpAddress());

    } catch (RemoteException ex) {
      log.error("Error while getting MBean servers list.", ex);
    }
  }