/**
   * Allows the MBean to perform any operations it needs before being registered in the MBean
   * server. If the name of the MBean is not specified, the MBean can provide a name for its
   * registration. If any exception is raised, the MBean will not be registered in the MBean server.
   *
   * @param server The MBean server in which the MBean will be registered.
   * @param name The object name of the MBean.
   * @return The name of the MBean registered.
   * @exception java.lang.Exception This exception should be caught by the MBean server and
   *     re-thrown as an {@link javax.management.MBeanRegistrationException}.
   */
  public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception {
    if (logger.finerOn()) {
      logger.finer("preRegister ", "object name   = " + name);
    }

    responderObjectName = name;

    // ----------------
    // Should we act as a spy ?
    // ----------------
    spy = (String) name.getKeyProperty(SPY);

    // ----------------
    // Should we Send event
    // ----------------
    noEvent = (String) name.getKeyProperty("PRIVATE_NO_EVENT");

    // ----------------
    // Initialise local pointer to the Core Management MBeanServer
    // ----------------
    this.cmf = server;

    // ----------------
    // Return part
    // ----------------
    return name;
  }
예제 #2
0
  /** Constructs a PrintGCStat object to monitor a remote JVM. */
  public PrintGCStat(MBeanServerConnection server) throws IOException {
    // Create the platform mxbean proxies
    this.rmbean = newPlatformMXBeanProxy(server, RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    this.mmbean = newPlatformMXBeanProxy(server, MEMORY_MXBEAN_NAME, MemoryMXBean.class);
    ObjectName poolName = null;
    ObjectName gcName = null;
    try {
      poolName = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",*");
      gcName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*");
    } catch (MalformedObjectNameException e) {
      // should not reach here
      assert (false);
    }

    Set<ObjectName> mbeans = server.queryNames(poolName, null);
    if (mbeans != null) {
      pools = new ArrayList<MemoryPoolMXBean>();
      for (ObjectName objName : mbeans) {
        MemoryPoolMXBean p =
            newPlatformMXBeanProxy(server, objName.getCanonicalName(), MemoryPoolMXBean.class);
        pools.add(p);
      }
    }

    mbeans = server.queryNames(gcName, null);
    if (mbeans != null) {
      gcmbeans = new ArrayList<GarbageCollectorMXBean>();
      for (ObjectName objName : mbeans) {
        GarbageCollectorMXBean gc =
            newPlatformMXBeanProxy(
                server, objName.getCanonicalName(), GarbageCollectorMXBean.class);
        gcmbeans.add(gc);
      }
    }
  }
예제 #3
0
  public synchronized Collection<GarbageCollectorMXBean> getGarbageCollectorMXBeans()
      throws IOException {

    // TODO: How to deal with changes to the list??
    if (garbageCollectorMBeans == null) {
      ObjectName gcName = null;
      try {
        gcName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*");
      } catch (MalformedObjectNameException e) {
        // should not reach here
        assert (false);
      }
      Set<ObjectName> mbeans = server.queryNames(gcName, null);
      if (mbeans != null) {
        garbageCollectorMBeans = new ArrayList<GarbageCollectorMXBean>();
        Iterator<ObjectName> iterator = mbeans.iterator();
        while (iterator.hasNext()) {
          ObjectName on = (ObjectName) iterator.next();
          String name = GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",name=" + on.getKeyProperty("name");

          GarbageCollectorMXBean mBean =
              newPlatformMXBeanProxy(server, name, GarbageCollectorMXBean.class);
          garbageCollectorMBeans.add(mBean);
        }
      }
    }
    return garbageCollectorMBeans;
  }
  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;
  }
예제 #5
0
 /**
  * Allows a named object to be created.
  *
  * @param objectName The object name of the object.
  * @param object A reference to the object.
  */
 public NamedObject(ObjectName objectName, Object object) {
   if (objectName.isPattern()) {
     throw new RuntimeOperationsException(
         new IllegalArgumentException("Invalid name->" + objectName.toString()));
   }
   this.name = objectName;
   this.object = object;
 }
예제 #6
0
 /**
  * Allows a named object to be created.
  *
  * @param objectName The string representation of the object name of the object.
  * @param object A reference to the object.
  * @exception MalformedObjectNameException The string passed does not have the format of a valid
  *     ObjectName
  */
 public NamedObject(String objectName, Object object) throws MalformedObjectNameException {
   ObjectName objName = new ObjectName(objectName);
   if (objName.isPattern()) {
     throw new RuntimeOperationsException(
         new IllegalArgumentException("Invalid name->" + objName.toString()));
   }
   this.name = objName;
   this.object = object;
 }
 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");
 }
 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());
     }
   }
 }
예제 #9
0
 /** @since Java DMK 1.5 */
 public String[] getDomains() {
   if (interceptor instanceof MBeanServerInterceptor) {
     return ((MBeanServerInterceptor) interceptor).getDomains();
   }
   final Set names = interceptor.queryNames(null, null);
   final Set tmpSet = new HashSet(1);
   for (final Iterator i = names.iterator(); i.hasNext(); ) {
     final ObjectName x = (ObjectName) i.next();
     final String domain = x.getDomain();
     if (tmpSet.contains(domain)) continue;
     tmpSet.add(domain);
   }
   final String[] result = new String[tmpSet.size()];
   return (String[]) tmpSet.toArray(result);
 }
예제 #10
0
  @Override
  public List<CamelProcessorMBean> getProcessors(String managementName) throws Exception {
    String id = managementName != null ? managementName : camelContextManagementName;

    ObjectName query =
        ObjectName.getInstance("org.apache.camel:context=" + id + ",type=processors,*");

    Set<ObjectInstance> names = queryNames(query, null);
    List<CamelProcessorMBean> answer = new ArrayList<CamelProcessorMBean>();
    for (ObjectInstance on : names) {
      CamelProcessorMBean processor;
      if (ManagedSendProcessor.class.getName().equals(on.getClassName())) {
        processor =
            (CamelProcessorMBean)
                newProxyInstance(on.getObjectName(), CamelSendProcessorMBean.class, true);
      } else if (ManagedDelayer.class.getName().equals(on.getClassName())) {
        processor =
            (CamelProcessorMBean)
                newProxyInstance(on.getObjectName(), CamelDelayProcessorMBean.class, true);
      } else if (ManagedThrottler.class.getName().equals(on.getClassName())) {
        processor =
            (CamelProcessorMBean)
                newProxyInstance(on.getObjectName(), CamelThrottleProcessorMBean.class, true);
      } else {
        processor =
            (CamelProcessorMBean)
                newProxyInstance(on.getObjectName(), CamelProcessorMBean.class, true);
      }
      answer.add(processor);
    }
    return answer;
  }
  protected Result describeMbean(
      @Nonnull MBeanServerConnection mbeanServer, @Nonnull ObjectName objectName)
      throws IntrospectionException, ReflectionException, InstanceNotFoundException, IOException {
    MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName);
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    out.println("# MBEAN");
    out.println(objectName.toString());
    out.println();
    out.println("## OPERATIONS");
    List<MBeanOperationInfo> operations = Arrays.asList(mbeanInfo.getOperations());
    Collections.sort(
        operations,
        new Comparator<MBeanOperationInfo>() {
          @Override
          public int compare(MBeanOperationInfo o1, MBeanOperationInfo o2) {
            return o1.getName().compareTo(o1.getName());
          }
        });

    for (MBeanOperationInfo opInfo : operations) {
      out.print("* " + opInfo.getName() + "(");
      MBeanParameterInfo[] signature = opInfo.getSignature();
      for (int i = 0; i < signature.length; i++) {
        MBeanParameterInfo paramInfo = signature[i];
        out.print(paramInfo.getType() + " " + paramInfo.getName());
        if (i < signature.length - 1) {
          out.print(", ");
        }
      }

      out.print("):" + opInfo.getReturnType() /* + " - " + opInfo.getDescription() */);
      out.println();
    }
    out.println();
    out.println("## ATTRIBUTES");
    List<MBeanAttributeInfo> attributes = Arrays.asList(mbeanInfo.getAttributes());
    Collections.sort(
        attributes,
        new Comparator<MBeanAttributeInfo>() {
          @Override
          public int compare(MBeanAttributeInfo o1, MBeanAttributeInfo o2) {
            return o1.getName().compareTo(o2.getName());
          }
        });
    for (MBeanAttributeInfo attrInfo : attributes) {
      out.println(
          "* "
              + attrInfo.getName()
              + ": "
              + attrInfo.getType()
              + " - "
              + (attrInfo.isReadable() ? "r" : "")
              + (attrInfo.isWritable() ? "w" : "") /* + " - " +
                    attrInfo.getDescription() */);
    }

    String description = sw.getBuffer().toString();
    return new Result(objectName, description, description);
  }
예제 #12
0
파일: Router.java 프로젝트: unbounce/yoke
    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);
      }
    }
예제 #13
0
  @Override
  public List<CamelEndpointMBean> getEndpoints(String managementName) throws Exception {
    String id = managementName != null ? managementName : camelContextManagementName;

    ObjectName query =
        ObjectName.getInstance("org.apache.camel:context=" + id + ",type=endpoints,*");

    Set<ObjectInstance> names = queryNames(query, null);
    List<CamelEndpointMBean> answer = new ArrayList<CamelEndpointMBean>();
    for (ObjectInstance on : names) {
      CamelEndpointMBean endpoint;
      if (ManagedBrowsableEndpoint.class.getName().equals(on.getClassName())
          || SedaEndpoint.class.getName().equals(on.getClassName())) {
        endpoint =
            (CamelEndpointMBean)
                newProxyInstance(on.getObjectName(), CamelBrowsableEndpointMBean.class, true);
      } else if (on.getClassName().startsWith("org.apache.camel.component.jms")) {
        // special for JMS endpoints as they are browsable as well
        endpoint =
            (CamelEndpointMBean)
                newProxyInstance(on.getObjectName(), CamelBrowsableEndpointMBean.class, true);
      } else {
        endpoint =
            (CamelEndpointMBean)
                newProxyInstance(on.getObjectName(), CamelEndpointMBean.class, true);
      }
      answer.add(endpoint);
    }
    return answer;
  }
예제 #14
0
 /**
  * Compares the current object name with another object name.
  *
  * @param object The Named Object that the current object name is to be compared with.
  * @return True if the two named objects are equal, otherwise false.
  */
 public boolean equals(Object object) {
   if (this == object) return true;
   if (object == null) return false;
   if (!(object instanceof NamedObject)) return false;
   NamedObject no = (NamedObject) object;
   return name.equals(no.getName());
 }
예제 #15
0
 @SuppressWarnings("unchecked")
 protected Object newProxyInstance(
     ObjectName objectName, Class interfaceClass, boolean notificationBroadcaster)
     throws Exception {
   Object jmx_proxy =
       MBeanServerInvocationHandler.newProxyInstance(
           getMBeanServerConnection(), objectName, interfaceClass, notificationBroadcaster);
   return addGetId(interfaceClass, jmx_proxy, objectName.getCanonicalName());
 }
    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");
              }
            }
          });
    }
예제 #17
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);
    }
  }
예제 #18
0
  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    if (args.length != 4) {
      System.err.println("Please provide process id zabbix-host zabbix-port host-guid");
      System.exit(-1);
    }
    String processPid = args[0];
    String zabbixHost = args[1];
    String zabbixPort = args[2];
    String hostGuid = args[3];

    VirtualMachine vm = VirtualMachine.attach(processPid);
    String connectorAddr =
        vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    if (connectorAddr == null) {
      String agent =
          vm.getSystemProperties().getProperty("java.home")
              + File.separator
              + "lib"
              + File.separator
              + "management-agent.jar";
      vm.loadAgent(agent);
      connectorAddr =
          vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    }
    JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr);
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();
    ObjectName objName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
    Set<ObjectName> mbeans = mbsc.queryNames(objName, null);
    for (ObjectName name : mbeans) {
      ThreadMXBean threadBean;
      threadBean =
          ManagementFactory.newPlatformMXBeanProxy(mbsc, name.toString(), ThreadMXBean.class);
      long threadIds[] = threadBean.getAllThreadIds();
      for (long threadId : threadIds) {
        ThreadInfo threadInfo = threadBean.getThreadInfo(threadId);
        System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState());
      }
    }
  }
예제 #19
0
  @Test
  public void testObjectName() {
    ManagedBeanDefinition definition = new ManagedBeanDefinition();
    definition.setType(HelloBean.class);
    ObjectName objectName = definition.createObjectName();

    Assert.assertEquals(objectName.toString(), "com.consol.citrus.jmx.mbean:type=HelloBean");

    definition = new ManagedBeanDefinition();
    definition.setObjectDomain(HelloBean.class.getPackage().getName());
    definition.setObjectName("type=HelloBean,name=Hello");
    objectName = definition.createObjectName();

    Assert.assertEquals(
        objectName.toString(), "com.consol.citrus.jmx.mbean:type=HelloBean,name=Hello");

    definition = new ManagedBeanDefinition();
    definition.setObjectDomain(HelloBean.class.getPackage().getName());
    definition.setName(HelloBean.class.getSimpleName());
    objectName = definition.createObjectName();

    Assert.assertEquals(objectName.toString(), "com.consol.citrus.jmx.mbean:name=HelloBean");
  }
예제 #20
0
 /**
  * Allows the MBean to perform any operations it needs before being registered in the MBean
  * server. If the name of the MBean is not specified, the MBean can provide a name for its
  * registration. If any exception is raised, the MBean will not be registered in the MBean server.
  *
  * @param server The MBean server in which the MBean will be registered.
  * @param name The object name of the MBean. This name is null if the name parameter to one of the
  *     createMBean or registerMBean methods in the MBeanServer interface is null. In that case,
  *     this method will try to guess its MBean name by examining its configuration data. If its
  *     configuration data is null (nothing was provided in the constructor) or doesn't contain a
  *     name, this method returns {@code null}, and registration will fail.
  *     <p>Otherwise, if {@code name} wasn't {@code null} or if a default name could be
  *     constructed, the name of the configuration will be set to the value of the ObjectName's
  *     {@code name=} key, and the configuration data will always be renamed to reflect this
  *     change.
  * @return The name under which the MBean is to be registered.
  * @throws Exception This exception will be caught by the MBean server and re-thrown as an
  *     MBeanRegistrationException.
  */
 public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
   if (name == null) {
     if (config == null) return null;
     if (config.getName() == null) return null;
     name = ScanManager.makeMBeanName(ScanDirConfigMXBean.class, config.getName());
   }
   objectName = name;
   mbeanServer = server;
   synchronized (this) {
     configname = name.getKeyProperty("name");
     if (config == null) config = new ScanManagerConfig(configname);
     else config = config.copy(configname);
   }
   return name;
 }
예제 #21
0
  public void init() throws Exception {

    super.init();

    url = getParameter(URL);

    if (url == null) {
      protocol = getParameter(PROTOCOL);
      host = getParameter(HOST);
      port = Integer.parseInt(getParameter(PORT));
      transportPort = Integer.parseInt(getParameter(TRANSPORT_PORT));

      url = "service:jmx:" + protocol + "://" + host;
      if (transportPort != DEFAULT_TRANSPORT_PORT) url += ":" + transportPort;

      url += "/jndi/" + protocol + "://" + host;
      if (port != DEFAULT_PORT) url += ":" + port;

      url += "/penrose";

      // url =
      // "service:jmx:rmi://localhost:rmiTransportProtocol/jndi/rmi://localhost:rmiProtocol/penrose";
    }

    bindDn = getParameter(BIND_DN);
    log.debug("Bind DN: " + bindDn);

    bindPassword = getParameter(BIND_PASSWORD);
    log.debug("Password: "******"java.lang:type=Memory");

    Hashtable<String, Object> parameters = new Hashtable<String, Object>();

    if (bindDn != null && bindPassword != null) {
      log.debug("Binding as " + bindDn + ".");

      String[] credentials = new String[] {bindDn, bindPassword};

      parameters.put(JMXConnector.CREDENTIALS, credentials);
    }

    JMXServiceURL serviceURL = new JMXServiceURL(url);
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, parameters);

    connection = connector.getMBeanServerConnection();
    connection.addNotificationListener(memoryMBean, this, null, null);
  }
예제 #22
0
  @Override
  public List<CamelThreadPoolMBean> getThreadPools(String managementName) throws Exception {
    String id = managementName != null ? managementName : camelContextManagementName;

    ObjectName query =
        ObjectName.getInstance("org.apache.camel:context=" + id + ",type=threadpools,*");

    Set<ObjectInstance> names = queryNames(query, null);
    List<CamelThreadPoolMBean> answer = new ArrayList<CamelThreadPoolMBean>();
    for (ObjectInstance on : names) {
      CamelThreadPoolMBean pool =
          (CamelThreadPoolMBean)
              newProxyInstance(on.getObjectName(), CamelThreadPoolMBean.class, true);
      answer.add(pool);
    }
    return answer;
  }
예제 #23
0
 /**
  * Return an end user readable representation of the underlying MBean
  *
  * @return the user readable description
  */
 public String toString() {
   StringBuilder buf = new StringBuilder();
   buf.append("MBean Name:").append("\n  ").append(name.getCanonicalName()).append("\n  ");
   if (!listAttributeDescriptions().isEmpty()) {
     buf.append("\nAttributes:");
     for (String attrDesc : listAttributeDescriptions()) {
       buf.append("\n  ").append(attrDesc);
     }
   }
   if (!listOperationDescriptions().isEmpty()) {
     buf.append("\nOperations:");
     for (String attrDesc : listOperationDescriptions()) {
       buf.append("\n  ").append(attrDesc);
     }
   }
   return buf.toString();
 }
예제 #24
0
  @Override
  public ManagedBacklogTracerMBean getCamelTracer(String managementName) throws Exception {
    String id = managementName != null ? managementName : camelContextManagementName;

    ObjectName query = ObjectName.getInstance("org.apache.camel:context=" + id + ",type=tracer,*");

    Set<ObjectInstance> names = queryNames(query, null);
    for (ObjectInstance on : names) {
      if (on.getClassName().equals("org.apache.camel.management.mbean.ManagedBacklogTracer")) {
        ManagedBacklogTracerMBean tracer =
            (ManagedBacklogTracerMBean)
                newProxyInstance(on.getObjectName(), ManagedBacklogTracerMBean.class, true);
        return tracer;
      }
    }

    // tracer not found
    return null;
  }
예제 #25
0
  @Override
  public List<CamelRouteMBean> getRoutes(String managementName) throws Exception {
    String id = managementName != null ? managementName : camelContextManagementName;

    ObjectName query = ObjectName.getInstance("org.apache.camel:context=" + id + ",type=routes,*");

    Set<ObjectInstance> names = queryNames(query, null);
    List<CamelRouteMBean> answer = new ArrayList<CamelRouteMBean>();
    for (ObjectInstance on : names) {
      CamelRouteMBean route;
      if (ManagedSuspendableRoute.class.getName().equals(on.getClassName())) {
        route =
            (CamelRouteMBean)
                newProxyInstance(on.getObjectName(), CamelSuspendableRouteMBean.class, true);
      } else {
        route = (CamelRouteMBean) newProxyInstance(on.getObjectName(), CamelRouteMBean.class, true);
      }
      answer.add(route);
    }
    return answer;
  }
예제 #26
0
  @Override
  public List<CamelConsumerMBean> getConsumers(String managementName) throws Exception {
    String id = managementName != null ? managementName : camelContextManagementName;

    ObjectName query =
        ObjectName.getInstance("org.apache.camel:context=" + id + ",type=consumers,*");

    Set<ObjectInstance> names = queryNames(query, null);
    List<CamelConsumerMBean> answer = new ArrayList<CamelConsumerMBean>();
    for (ObjectInstance on : names) {
      CamelConsumerMBean consumer;
      if (ManagedScheduledPollConsumer.class.getName().equals(on.getClassName())) {
        consumer =
            (CamelConsumerMBean)
                newProxyInstance(on.getObjectName(), CamelScheduledPollConsumerMBean.class, true);
      } else {
        consumer =
            (CamelConsumerMBean)
                newProxyInstance(on.getObjectName(), CamelConsumerMBean.class, true);
      }
      answer.add(consumer);
    }
    return answer;
  }
예제 #27
0
 /** Returns a hash code for this named object. */
 public int hashCode() {
   return name.hashCode();
 }
  public Map<ObjectName, Result> process(JmxInvokerArguments arguments) throws IOException {

    String pid =
        (arguments.pid == null) ? Files2.readFile(arguments.pidFile, "US-ASCII") : arguments.pid;
    pid = pid.replace("\n", "").trim();

    ObjectName on = arguments.objectName;

    String[] op = arguments.operation;

    String operationName = op == null || op.length == 0 ? null : op[0];
    String[] operationArguments =
        op == null || op.length < 2 ? new String[0] : Arrays.copyOfRange(op, 1, op.length);

    String[] attr = arguments.attribute;
    String attributeName = attr == null || attr.length == 0 ? null : attr[0];
    String attributeValue = attr == null || attr.length < 2 ? null : attr[1];

    MBeanServerConnection mbeanServer = connectToMbeanServer(pid);

    Map<ObjectName, Result> results = new TreeMap<ObjectName, Result>();

    Set<ObjectName> objectNames = mbeanServer.queryNames(on, null);
    if (objectNames.isEmpty()) {
      logger.warn("No mbean found for ObjectName {}", on);
    }

    for (ObjectName objectName : objectNames) {
      Result result;
      try {
        if (operationName != null) {
          result = invokeOperation(mbeanServer, objectName, operationName, operationArguments);
        } else if (attributeName != null) {
          result = invokeAttribute(mbeanServer, objectName, attributeName, attributeValue);
        } else if (arguments.describeMbeans) {
          result = describeMbean(mbeanServer, objectName);
        } else if (arguments.listMbeans) {
          result = new Result(objectName, objectName.toString(), objectName.toString());
        } else {
          throw new CmdLineException(
              arguments.cmdLineParser, "NO SEARCH_MBEANS OR OPERATION OR ATTRIBUTE DEFINED");
        }
      } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String msg = "## EXCEPTION ##\n" + sw.toString();
        result = new Result(objectName, msg, msg);
      }

      results.put(objectName, result);
    }

    logger.info("INVOCATION RESULT");
    logger.info("#################");
    logger.info("JVM pid: {}", pid);
    logger.info("Searched object-name: {}", on);
    if (operationName != null) {
      logger.info("Invoke operation {}{}", operationName, Arrays.asList(operationArguments));
    } else if (attributeValue == null) {
      logger.info("Get attribute {}", attributeName);
    } else {
      logger.info("Set attribute {}: {}", attributeName, attributeValue);
    }
    for (Map.Entry<ObjectName, Result> entry : results.entrySet()) {
      logger.info("{}", entry.getKey());
      logger.info("\t{}", entry.getValue());
    }

    return results;
  }
예제 #29
0
 public <T> T getMXBean(ObjectName objName, Class<T> interfaceClass) throws IOException {
   return newPlatformMXBeanProxy(server, objName.toString(), interfaceClass);
 }