Example #1
0
  private static boolean test(String proto, MBeanServer mbs) throws Exception {
    System.out.println("Testing for proto " + proto);

    JMXConnectorServer cs;
    JMXServiceURL url = new JMXServiceURL(proto, null, 0);
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    } catch (MalformedURLException e) {
      System.out.println("System does not recognize URL: " + url + "; ignoring");
      return true;
    }
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXServiceURL rmiurl = new JMXServiceURL("rmi", null, 0);
    JMXConnector client = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = client.getMBeanServerConnection();
    ObjectName on = new ObjectName("x:proto=" + proto + ",ok=yes");
    mbsc.createMBean(
        RMIConnectorServer.class.getName(),
        on,
        mletName,
        new Object[] {rmiurl, null},
        new String[] {JMXServiceURL.class.getName(), Map.class.getName()});
    System.out.println("Successfully deserialized with " + proto);
    mbsc.unregisterMBean(on);

    client.close();
    cs.stop();
    return true;
  }
Example #2
0
 /** List all MBeans and their attributes. */
 public static void listMBeans(MBeanServerConnection server) throws IOException {
   final Set names = server.queryNames(null, null);
   for (final Iterator i = names.iterator(); i.hasNext(); ) {
     ObjectName name = (ObjectName) i.next();
     System.out.println("Got MBean: " + name);
     try {
       MBeanInfo info = server.getMBeanInfo((ObjectName) name);
       MBeanAttributeInfo[] attrs = info.getAttributes();
       if (attrs == null) continue;
       for (int j = 0; j < attrs.length; j++) {
         if (attrs[j].isReadable()) {
           try {
             Object o = server.getAttribute(name, attrs[j].getName());
             System.out.println("\t\t" + attrs[j].getName() + " = " + o);
           } catch (Exception x) {
             System.err.println("JmxClient failed to get " + attrs[j].getName());
             x.printStackTrace(System.err);
           }
         }
       }
     } catch (Exception x) {
       System.err.println("JmxClient failed to get MBeanInfo: " + x);
       x.printStackTrace(System.err);
     }
   }
 }
  /** 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);
      }
    }
  }
Example #4
0
  private static void test(String proto) throws Exception {
    System.out.println(">>> Test for protocol " + proto);

    JMXServiceURL u = null;
    JMXConnectorServer server = null;

    HashMap env = new HashMap(2);
    // server will close a client connection after 1 second
    env.put("jmx.remote.x.server.connection.timeout", "1000");

    // disable the client ping
    env.put("jmx.remote.x.client.connection.check.period", "0");

    try {
      u = new JMXServiceURL(proto, null, 0);
      server = JMXConnectorServerFactory.newJMXConnectorServer(u, env, mbs);
    } catch (MalformedURLException e) {
      System.out.println(">>> Skipping unsupported URL " + proto);
    }

    server.start();

    JMXServiceURL addr = server.getAddress();

    long st = 2000;
    MyListener myListener;

    // a cycle to make sure that we test the blocking problem.
    do {
      JMXConnector client = JMXConnectorFactory.connect(addr, env);
      MBeanServerConnection conn = client.getMBeanServerConnection();
      myListener = new MyListener(conn);
      client.addConnectionNotificationListener(myListener, null, null);

      // wait the server to close the client connection
      Thread.sleep(st);

      // makes the listener to do a remote request via the connection
      // which should be closed by the server.
      conn.getDefaultDomain();

      // allow the listner to have time to work
      Thread.sleep(100);

      // get a closed notif, should no block.
      client.close();
      Thread.sleep(100);

      st += 2000;

    } while (!myListener.isDone());

    server.stop();
  }
 /**
  * Get the string representation of an attribute
  *
  * @param pMbeanServers set of MBeanServers to query. The first one wins.
  * @param pMBean name of MBean to lookup
  * @param pAttribute attribute to lookup
  * @return string value of attribute or <code>null</code> if the attribute could not be fetched
  */
 protected String getAttributeValue(
     Set<? extends MBeanServerConnection> pMbeanServers, ObjectName pMBean, String pAttribute) {
   try {
     for (MBeanServerConnection s : pMbeanServers) {
       Object attr = s.getAttribute(pMBean, pAttribute);
       if (attr != null) {
         return attr.toString();
       }
     }
     return null;
   } catch (JMException e) {
     return null;
   } catch (IOException e) {
     return null;
   }
 }
  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);
  }
 /**
  * Check for the existence of a certain MBean. All known MBeanServers are queried
  *
  * @param pMbeanServers mbean servers to query for
  * @param pMbeanPattern MBean name pattern for MBeans to check for
  * @return set of {@link ObjectName}s if the pattern matches, null if no match was found
  */
 protected Set<ObjectName> searchMBeans(
     Set<? extends MBeanServerConnection> pMbeanServers, String pMbeanPattern) {
   try {
     ObjectName oName = new ObjectName(pMbeanPattern);
     for (MBeanServerConnection s : pMbeanServers) {
       Set<ObjectName> names = s.queryNames(oName, null);
       if (names != null && names.size() > 0) {
         return names;
       }
     }
     return null;
   } catch (MalformedObjectNameException e) {
     return null;
   } catch (IOException e) {
     return null;
   }
 }
Example #8
0
 public void setProperty(String property, Object value) {
   try {
     server.setAttribute(name, new Attribute(property, value));
   } catch (MBeanException e) {
     throwExceptionWithTarget("Could not set property: " + property + ". Reason: ", e);
   } catch (Exception e) {
     throwException("Could not set property: " + property + ". Reason: ", e);
   }
 }
Example #9
0
 public Object getProperty(String property) {
   try {
     return server.getAttribute(name, property);
   } catch (MBeanException e) {
     throwExceptionWithTarget("Could not access property: " + property + ". Reason: ", e);
   } catch (Exception e) {
     if (!ignoreErrors) throwException("Could not access property: " + property + ". Reason: ", e);
   }
   return null;
 }
Example #10
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());
      }
    }
  }
Example #11
0
 private Object getAttribute(ObjectName objName, String attrName)
     throws MBeanException, InstanceNotFoundException, AttributeNotFoundException,
         ReflectionException, IOException {
   final NameValueMap values = getCachedAttributes(objName, Collections.singleton(attrName));
   Object value = values.get(attrName);
   if (value != null || values.containsKey(attrName)) {
     return value;
   }
   // Not in cache, presumably because it was omitted from the
   // getAttributes result because of an exception.  Following
   // call will probably provoke the same exception.
   return conn.getAttribute(objName, attrName);
 }
  /**
   * Finds all CamelContext's registered on a certain JMX-Server or, if a JMX-BrokerName has been
   * set, the broker with that name.
   *
   * @param connection not <code>null</code>
   * @param managementName to find a specific context by its management name
   * @return Set with ObjectName-elements
   */
  protected Set<ObjectName> findCamelContexts(
      MBeanServerConnection connection, String managementName) throws Exception {
    String id = managementName != null ? managementName : camelContextManagementName;

    ObjectName name;
    if (id != null) {
      name = new ObjectName("org.apache.camel:context=" + managementName + ",type=context,*");
    } else {
      name = new ObjectName("org.apache.camel:context=*,type=context,*");
    }
    Set<ObjectName> camels = connection.queryNames(name, null);
    return camels;
  }
Example #13
0
  public GroovyMBean(MBeanServerConnection server, ObjectName name, boolean ignoreErrors)
      throws JMException, IOException {
    this.server = server;
    this.name = name;
    this.ignoreErrors = ignoreErrors;
    this.beanInfo = server.getMBeanInfo(name);

    MBeanOperationInfo[] operationInfos = beanInfo.getOperations();
    for (MBeanOperationInfo info : operationInfos) {
      String signature[] = createSignature(info);
      // Construct a simplistic key to support overloaded operations on the MBean.
      String operationKey = createOperationKey(info.getName(), signature.length);
      operations.put(operationKey, signature);
    }
  }
Example #14
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);
  }
Example #15
0
 private synchronized NameValueMap getCachedAttributes(ObjectName objName, Set<String> attrNames)
     throws InstanceNotFoundException, ReflectionException, IOException {
   NameValueMap values = cachedValues.get(objName);
   if (values != null && values.keySet().containsAll(attrNames)) {
     return values;
   }
   attrNames = new TreeSet<String>(attrNames);
   Set<String> oldNames = cachedNames.get(objName);
   if (oldNames != null) {
     attrNames.addAll(oldNames);
   }
   values = new NameValueMap();
   final AttributeList attrs =
       conn.getAttributes(objName, attrNames.toArray(new String[attrNames.size()]));
   for (Attribute attr : attrs.asList()) {
     values.put(attr.getName(), attr.getValue());
   }
   cachedValues.put(objName, values);
   cachedNames.put(objName, attrNames);
   return values;
 }
Example #16
0
  public Object invokeMethod(String method, Object arguments) {
    Object[] argArray;
    if (arguments instanceof Object[]) {
      argArray = (Object[]) arguments;
    } else {
      argArray = new Object[] {arguments};
    }
    // Locate the specific method based on the name and number of parameters
    String operationKey = createOperationKey(method, argArray.length);
    String[] signature = operations.get(operationKey);

    if (signature != null) {
      try {
        return server.invoke(name, method, argArray, signature);
      } catch (MBeanException e) {
        throwExceptionWithTarget("Could not invoke method: " + method + ". Reason: ", e);
      } catch (Exception e) {
        throwException("Could not invoke method: " + method + ". Reason: ", e);
      }
      return null;
    } else {
      return super.invokeMethod(method, arguments);
    }
  }
  @Nullable
  public Result invokeOperation(
      @Nonnull MBeanServerConnection mBeanServer,
      @Nonnull ObjectName on,
      @Nonnull String operationName,
      @Nonnull String... arguments)
      throws JMException, IOException {

    logger.debug("invokeOperation({},{}, {}, {})...", on, operationName, Arrays.asList(arguments));
    MBeanInfo mbeanInfo = mBeanServer.getMBeanInfo(on);

    List<MBeanOperationInfo> candidates = new ArrayList<MBeanOperationInfo>();
    for (MBeanOperationInfo mbeanOperationInfo : mbeanInfo.getOperations()) {
      if (mbeanOperationInfo.getName().equals(operationName)
          && mbeanOperationInfo.getSignature().length == arguments.length) {
        candidates.add(mbeanOperationInfo);
        logger.debug("Select matching operation {}", mbeanOperationInfo);
      } else {
        logger.trace("Ignore non matching operation {}", mbeanOperationInfo);
      }
    }
    if (candidates.isEmpty()) {
      throw new IllegalArgumentException(
          "Operation '"
              + operationName
              + "("
              + Strings2.join(arguments, ", ")
              + ")' NOT found on "
              + on);
    } else if (candidates.size() > 1) {
      throw new IllegalArgumentException(
          "More than 1 ("
              + candidates.size()
              + ") operation '"
              + operationName
              + "("
              + Strings2.join(arguments, ", ")
              + ")' found on '"
              + on
              + "': "
              + candidates);
    }
    MBeanOperationInfo beanOperationInfo = candidates.get(0);

    MBeanParameterInfo[] mbeanParameterInfos = beanOperationInfo.getSignature();

    List<String> signature = new ArrayList<String>();
    for (MBeanParameterInfo mbeanParameterInfo : mbeanParameterInfos) {
      signature.add(mbeanParameterInfo.getType());
    }

    Object[] convertedArguments = convertValues(arguments, signature);

    logger.debug("Invoke {}:{}({}) ...", on, operationName, Arrays.asList(convertedArguments));

    Object result =
        mBeanServer.invoke(on, operationName, convertedArguments, signature.toArray(new String[0]));

    if ("void".equals(beanOperationInfo.getReturnType()) && result == null) {
      result = "void";
    }

    logger.info(
        "Invoke {}:{}({}): {}", on, operationName, Arrays.asList(convertedArguments), result);

    String description =
        "Invoke operation "
            + on
            + ":"
            + operationName
            + "("
            + Strings2.join(convertedArguments, ", ")
            + "): "
            + Strings2.toString(result);
    return new Result(on, result, description);
  }
Example #18
0
  /**
   * Program Main
   *
   * <p>Lookup all JMX agents in the Jini Lookup Service and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Djini.lookup.url=&lt;jini-url&gt;</code>: the Jini Lookup Service URL (default is
   *       "jini://localhost"), see {@link #getRegistrar()}.
   *   <li><code>-Ddebug="true|false"</code>: switch the Client debug flag on/off (default is
   *       "false").
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Jini requires a security manager.
      //
      if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager());

      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get AgentName to lookup. If not defined, all agents
      // are looked up.
      //
      final String agentName = System.getProperty("agent.name");

      // Get a pointer to the Jini Lookup Service.
      //
      final ServiceRegistrar registrar = getRegistrar();
      debug("registrar is: " + registrar);

      // Lookup all matching agents in the Jini Lookup Service.
      //
      List l = lookup(registrar, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          try {
            c1.connect(null);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            if (debug) x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            if (debug) x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            if (debug) x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }
  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;
  }
  /**
   * @param mbeanServer
   * @param objectName
   * @param attributeName
   * @param attributeValue if <code>null</code>, this is a read access.
   * @return if this is a read access, the returned value (may be null); if it is a write access,
   *     return <code>void.class</code>.
   * @throws IOException
   * @throws JMException
   */
  public Result invokeAttribute(
      @Nonnull MBeanServerConnection mbeanServer,
      @Nonnull ObjectName objectName,
      @Nonnull String attributeName,
      @Nullable String attributeValue)
      throws IOException, JMException {
    MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName);
    MBeanAttributeInfo attributeInfo = null;
    for (MBeanAttributeInfo mai : mbeanInfo.getAttributes()) {
      if (mai.getName().equals(attributeName)) {
        attributeInfo = mai;
        break;
      }
    }
    if (attributeInfo == null) {
      throw new IllegalArgumentException(
          "No attribute '"
              + attributeName
              + "' found on '"
              + objectName
              + "'. Existing attributes: "
              + Arrays.asList(mbeanInfo.getAttributes()));
    }

    String description;
    Object resultValue;

    if (attributeValue == null) {
      if (attributeInfo.isReadable()) {
        Object attribute = mbeanServer.getAttribute(objectName, attributeName);
        logger.info("get attribute value {}:{}:{}", objectName, attributeName, attribute);
        resultValue = attribute;
        description =
            "Get attribute value " + objectName + ":" + attributeName + ": " + resultValue;
      } else {
        throw new IllegalArgumentException(
            "Attribute '"
                + attributeName
                + "' is not readable on '"
                + objectName
                + "': "
                + attributeInfo);
      }
    } else {
      if (attributeInfo.isWritable()) {
        Object value = convertValue(attributeValue, attributeInfo.getType());
        mbeanServer.setAttribute(objectName, new Attribute(attributeName, value));
        logger.info("set attribute value {}:{}:{}", objectName, attributeName, value);

        description = "Set attribute value " + objectName + ":" + attributeName + ": " + value;
        resultValue = void.class;
      } else {
        throw new IllegalArgumentException(
            "Attribute '"
                + attributeName
                + "' is not writable on '"
                + objectName
                + "': "
                + attributeInfo);
      }
    }

    return new Result(objectName, resultValue, description);
  }
Example #21
0
  private static boolean test(String proto, MBeanServer mbs, ObjectName on) throws Exception {
    System.out.println("Testing for protocol " + proto);

    JMXConnectorServer cs;
    JMXServiceURL url = new JMXServiceURL(proto, null, 0);
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    } catch (MalformedURLException e) {
      System.out.println("System does not recognize URL: " + url + "; ignoring");
      return true;
    }
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector client = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = client.getMBeanServerConnection();
    Object getAttributeExotic = mbsc.getAttribute(on, "Exotic");
    AttributeList getAttrs = mbsc.getAttributes(on, new String[] {"Exotic"});
    AttributeList setAttrs = new AttributeList();
    setAttrs.add(new Attribute("Exotic", new Exotic()));
    setAttrs = mbsc.setAttributes(on, setAttrs);
    Object invokeExotic = mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {});
    MBeanInfo exoticMBI = mbsc.getMBeanInfo(on);

    mbsc.setAttribute(on, new Attribute("Exception", Boolean.TRUE));
    Exception getAttributeException, setAttributeException, invokeException;
    try {
      try {
        mbsc.getAttribute(on, "Exotic");
        throw noException("getAttribute");
      } catch (Exception e) {
        getAttributeException = e;
      }
      try {
        mbsc.setAttribute(on, new Attribute("Exotic", new Exotic()));
        throw noException("setAttribute");
      } catch (Exception e) {
        setAttributeException = e;
      }
      try {
        mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {});
        throw noException("invoke");
      } catch (Exception e) {
        invokeException = e;
      }
    } finally {
      mbsc.setAttribute(on, new Attribute("Exception", Boolean.FALSE));
    }
    client.close();
    cs.stop();

    boolean ok = true;

    ok &= checkAttrs("getAttributes", getAttrs);
    ok &= checkAttrs("setAttributes", setAttrs);

    ok &= checkType("getAttribute", getAttributeExotic, Exotic.class);
    ok &= checkType("getAttributes", attrValue(getAttrs), Exotic.class);
    ok &= checkType("setAttributes", attrValue(setAttrs), Exotic.class);
    ok &= checkType("invoke", invokeExotic, Exotic.class);
    ok &= checkType("getMBeanInfo", exoticMBI, ExoticMBeanInfo.class);

    ok &= checkExceptionType("getAttribute", getAttributeException, ExoticException.class);
    ok &= checkExceptionType("setAttribute", setAttributeException, ExoticException.class);
    ok &= checkExceptionType("invoke", invokeException, ExoticException.class);

    if (ok) System.out.println("Test passes for protocol " + proto);
    return ok;
  }
Example #22
0
  /**
   * Program Main.
   *
   * <p>Lookup all JMX agents in the LDAP Directory and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Dprotocol=&lt;ProtocolType&gt;</code>: restrains the client to lookup for a
   *       specific protocol type (default is null, meaning any type).
   *   <li><code>-Djava.naming.factory.initial=&lt;initial-context-factory&gt;
   *     </code>: The initial context factory to use for accessing the LDAP directory (see {@link
   *       Context#INITIAL_CONTEXT_FACTORY Context.INITIAL_CONTEXT_FACTORY}) - default is <code>
   *       "com.sun.jndi.ldap.LdapCtxFactory"</code>.
   *   <li><code>-Djava.naming.provider.url=&lt;provider-url&gt;</code>: The LDAP Provider URL (see
   *       {@link Context#PROVIDER_URL Context.PROVIDER_URL}).
   *   <li><code>-Djava.naming.security.principal=&lt;ldap-principal&gt;
   *     </code>: The security principal (login) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_PRINCIPAL Context.SECURITY_PRINCIPAL} - default is <code>
   *       "cn=Directory Manager"</code>.
   *   <li><code>-Djava.naming.security.credentials=&lt;ldap-credentials&gt;
   *     </code>: The security credentials (password) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_CREDENTIALS Context.SECURITY_CREDENTIALS}).
   *   <li><code>-Ddebug="true|false"</code>: switch the Server debug flag on/off (default is
   *       "false")
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get a pointer to the LDAP Directory.
      //
      final DirContext root = getRootContext();
      debug("root is: " + root.getNameInNamespace());

      final String protocolType = System.getProperty("protocol");
      final String agentName = System.getProperty("agent.name");

      // Lookup all matching agents in the LDAP Directory.
      //
      List l = lookup(root, protocolType, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          // Prepare the environment Map
          //
          final HashMap env = new HashMap();
          final String factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
          final String ldapServerUrl = System.getProperty(Context.PROVIDER_URL);
          final String ldapUser = System.getProperty(Context.SECURITY_PRINCIPAL);
          final String ldapPasswd = System.getProperty(Context.SECURITY_CREDENTIALS);

          // Transfer some system properties to the Map
          //
          if (factory != null) // this should not be needed
          env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
          if (ldapServerUrl != null) // this should not be needed
          env.put(Context.PROVIDER_URL, ldapServerUrl);
          if (ldapUser != null) // this is needed when LDAP is used
          env.put(Context.SECURITY_PRINCIPAL, ldapUser);
          if (ldapPasswd != null) // this is needed when LDAP is used
          env.put(Context.SECURITY_CREDENTIALS, ldapPasswd);

          try {
            c1.connect(env);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }