@Test
  public void testBeanInfoFromImpl() {
    ManagedBeanDefinition definition = new ManagedBeanDefinition();
    definition.setType(HelloBeanImpl.class);
    MBeanInfo info = definition.createMBeanInfo();

    Assert.assertEquals(info.getClassName(), "com.consol.citrus.jmx.mbean.HelloBeanImpl");
    Assert.assertEquals(info.getAttributes().length, 1);
    Assert.assertEquals(info.getAttributes()[0].getType(), String.class.getName());
    Assert.assertEquals(info.getAttributes()[0].getName(), "helloMessage");
    Assert.assertEquals(info.getOperations().length, 1);
    Assert.assertEquals(info.getOperations()[0].getName(), "hello");
    Assert.assertEquals(info.getOperations()[0].getSignature().length, 1);
    Assert.assertEquals(
        info.getOperations()[0].getSignature()[0].getType(), String.class.getName());
    Assert.assertEquals(info.getOperations()[0].getSignature()[0].getName(), "p1");
    Assert.assertEquals(info.getOperations()[0].getReturnType(), String.class.getName());

    definition.setType(NewsBeanImpl.class);
    info = definition.createMBeanInfo();

    Assert.assertEquals(info.getClassName(), "com.consol.citrus.jmx.mbean.NewsBeanImpl");
    Assert.assertEquals(info.getAttributes().length, 1);
    Assert.assertEquals(info.getAttributes()[0].getType(), String.class.getName());
    Assert.assertEquals(info.getAttributes()[0].getName(), "news");
    Assert.assertEquals(info.getOperations().length, 0);
  }
Esempio n. 2
0
  private static void test(Object child, String name, boolean mxbean) throws Exception {
    final ObjectName childName = new ObjectName("test:type=Child,name=" + name);
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    server.registerMBean(child, childName);
    try {
      final MBeanInfo info = server.getMBeanInfo(childName);
      System.out.println(name + ": " + info.getDescriptor());
      final int len = info.getOperations().length;
      if (len == OPCOUNT) {
        System.out.println(name + ": OK, only " + OPCOUNT + " operations here...");
      } else {
        final String qual = (len > OPCOUNT) ? "many" : "few";
        System.err.println(
            name + ": Too " + qual + " foos! Found " + len + ", expected " + OPCOUNT);
        for (MBeanOperationInfo op : info.getOperations()) {
          System.err.println("public " + op.getReturnType() + " " + op.getName() + "();");
        }
        throw new RuntimeException("Too " + qual + " foos for " + name);
      }

      final Descriptor d = info.getDescriptor();
      final String mxstr = String.valueOf(d.getFieldValue("mxbean"));
      final boolean mxb = (mxstr == null) ? false : Boolean.valueOf(mxstr).booleanValue();
      System.out.println(name + ": mxbean=" + mxb);
      if (mxbean && !mxb) throw new AssertionError("MXBean is not OpenMBean?");

      for (MBeanOperationInfo mboi : info.getOperations()) {

        // Sanity check
        if (mxbean && !mboi.getName().equals("foo")) {
          // The spec doesn't guarantee that the MBeanOperationInfo
          // of an MXBean will be an OpenMBeanOperationInfo, and in
          // some circumstances in our implementation it will not.
          // However, in thsi tests, for all methods but foo(),
          // it should.
          //
          if (!(mboi instanceof OpenMBeanOperationInfo))
            throw new AssertionError("Operation " + mboi.getName() + "() is not Open?");
        }

        final String exp = EXPECTED_TYPES.get(mboi.getName());

        // For MXBeans, we need to compare 'exp' with the original
        // type - because mboi.getReturnType() returns the OpenType
        //
        String type = (String) mboi.getDescriptor().getFieldValue("originalType");
        if (type == null) type = mboi.getReturnType();
        if (type.equals(exp)) continue;
        System.err.println(
            "Bad return type for " + mboi.getName() + "! Found " + type + ", expected " + exp);
        throw new RuntimeException("Bad return type for " + mboi.getName());
      }
    } finally {
      server.unregisterMBean(childName);
    }
  }
  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);
  }
  protected MBeanOperationInfo findClosestOperation(String name, Object[] args) throws Exception {
    MBeanInfo info = getMbean_info();

    if (info == null) return null;

    MBeanOperationInfo[] ops = info.getOperations();

    MBeanOperationInfo bestOp = null;
    long bestCost = Long.MAX_VALUE;

    for (int i = 0; i < ops.length; i++) {
      MBeanOperationInfo op = ops[i];

      if (!name.equals(op.getName())) continue;

      if (op.getSignature().length == args.length) {
        long cost = calculateCost(op.getSignature(), args);

        if (cost < bestCost) {
          bestCost = cost;
          bestOp = op;
        }
      }
    }

    return bestOp;
  }
  @Test
  public void testMBeanBySuffix() throws Exception {
    Registry registry = RegistryUtil.getRegistry();

    MBeanServer mBeanServer = registry.getService(MBeanServer.class);

    ObjectName objectName = new ObjectName(JMXWhiteboardByInterfaceMBean.OBJECT_NAME);

    MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objectName);

    Assert.assertNotNull(mBeanInfo);

    MBeanOperationInfo[] operations = mBeanInfo.getOperations();

    MBeanOperationInfo mBeanOperationInfo = operations[0];

    MBeanParameterInfo[] signatureParameters = mBeanOperationInfo.getSignature();

    String[] sinature = new String[signatureParameters.length];

    for (int i = 0; i < signatureParameters.length; i++) {
      MBeanParameterInfo mBeanParameterInfo = signatureParameters[i];

      sinature[i] = mBeanParameterInfo.getType();
    }

    Object result =
        mBeanServer.invoke(
            objectName, mBeanOperationInfo.getName(), new Object[] {"Hello!"}, sinature);

    Assert.assertEquals("{Hello!}", result);
  }
Esempio n. 6
0
 public static void printMBeanInfo(ObjectName objectName, String className) {
   log.info("Retrieve the management information for the {}", className);
   log.info("MBean using the getMBeanInfo() method of the MBeanServer");
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   MBeanInfo info = null;
   try {
     info = mbs.getMBeanInfo(objectName);
   } catch (Exception e) {
     log.error("Could not get MBeanInfo object for {}", className, e);
     return;
   }
   log.info("CLASSNAME: \t" + info.getClassName());
   log.info("DESCRIPTION: \t" + info.getDescription());
   log.info("ATTRIBUTES");
   MBeanAttributeInfo[] attrInfo = info.getAttributes();
   if (attrInfo.length > 0) {
     for (int i = 0; i < attrInfo.length; i++) {
       log.info(" ** NAME: \t" + attrInfo[i].getName());
       log.info("    DESCR: \t" + attrInfo[i].getDescription());
       log.info(
           "    TYPE: \t"
               + attrInfo[i].getType()
               + "\tREAD: "
               + attrInfo[i].isReadable()
               + "\tWRITE: "
               + attrInfo[i].isWritable());
     }
   } else log.info(" ** No attributes **");
   log.info("CONSTRUCTORS");
   MBeanConstructorInfo[] constrInfo = info.getConstructors();
   for (int i = 0; i < constrInfo.length; i++) {
     log.info(" ** NAME: \t" + constrInfo[i].getName());
     log.info("    DESCR: \t" + constrInfo[i].getDescription());
     log.info("    PARAM: \t" + constrInfo[i].getSignature().length + " parameter(s)");
   }
   log.info("OPERATIONS");
   MBeanOperationInfo[] opInfo = info.getOperations();
   if (opInfo.length > 0) {
     for (int i = 0; i < opInfo.length; i++) {
       log.info(" ** NAME: \t" + opInfo[i].getName());
       log.info("    DESCR: \t" + opInfo[i].getDescription());
       log.info("    PARAM: \t" + opInfo[i].getSignature().length + " parameter(s)");
     }
   } else log.info(" ** No operations ** ");
   log.info("NOTIFICATIONS");
   MBeanNotificationInfo[] notifInfo = info.getNotifications();
   if (notifInfo.length > 0) {
     for (int i = 0; i < notifInfo.length; i++) {
       log.info(" ** NAME: \t" + notifInfo[i].getName());
       log.info("    DESCR: \t" + notifInfo[i].getDescription());
       String notifTypes[] = notifInfo[i].getNotifTypes();
       for (int j = 0; j < notifTypes.length; j++) {
         log.info("    TYPE: \t" + notifTypes[j]);
       }
     }
   } else {
     log.info(" ** No notifications **");
   }
 }
 public void testRegisterOperations() throws Exception {
   IJmxTestBean bean = getBean();
   MBeanInfo inf = getMBeanInfo();
   assertEquals(
       "Incorrect number of operations registered",
       getExpectedOperationCount(),
       inf.getOperations().length);
 }
Esempio n. 8
0
 public ExoticMBeanInfo(MBeanInfo mbi) {
   super(
       mbi.getClassName(),
       mbi.getDescription(),
       mbi.getAttributes(),
       mbi.getConstructors(),
       mbi.getOperations(),
       mbi.getNotifications());
 }
  /**
   * Tests correct MBean interface.
   *
   * @throws Exception Thrown if test fails.
   */
  public void testCorrectMBeanInfo() throws Exception {
    StandardMBean mbean =
        new IgniteStandardMXBean(new GridMBeanImplementation(), GridMBeanInterface.class);

    MBeanInfo info = mbean.getMBeanInfo();

    assert info.getDescription().equals("MBeanDescription.") == true;

    assert info.getOperations().length == 2;

    for (MBeanOperationInfo opInfo : info.getOperations()) {
      if (opInfo.getDescription().equals("MBeanOperation."))
        assert opInfo.getSignature().length == 2;
      else {
        assert opInfo.getDescription().equals("MBeanSuperOperation.") == true;
        assert opInfo.getSignature().length == 1;
      }
    }

    for (MBeanParameterInfo paramInfo : info.getOperations()[0].getSignature()) {
      if (paramInfo.getName().equals("ignored"))
        assert paramInfo.getDescription().equals("MBeanOperationParameter1.") == true;
      else {
        assert paramInfo.getName().equals("someData") == true;
        assert paramInfo.getDescription().equals("MBeanOperationParameter2.") == true;
      }
    }

    assert info.getAttributes().length == 4
        : "Expected 4 attributes but got " + info.getAttributes().length;

    for (MBeanAttributeInfo attrInfo : info.getAttributes()) {
      if (attrInfo.isWritable() == false) {
        assert (attrInfo.getDescription().equals("MBeanReadonlyGetter.") == true
            || attrInfo.getDescription().equals("MBeanROGetter."));
      } else {
        assert (attrInfo.getDescription().equals("MBeanWritableGetter.") == true
            || attrInfo.getDescription().equals("MBeanWritableIsGetter."));
      }
    }
  }
Esempio n. 10
0
 /**
  * Description of all of the operations available on the MBean.
  *
  * @return full description of each operation on the MBean
  */
 public Collection<String> listOperationDescriptions() {
   List<String> list = new ArrayList<String>();
   try {
     MBeanOperationInfo[] operations = beanInfo.getOperations();
     for (MBeanOperationInfo operation : operations) {
       list.add(describeOperation(operation));
     }
   } catch (Exception e) {
     throwException("Could not list operation descriptions. Reason: ", e);
   }
   return list;
 }
Esempio n. 11
0
  static String getJobGraph(ObjectName jobObjName) {
    Set<ObjectInstance> jobInstances = mBeanServer.queryMBeans(jobObjName, null);
    Iterator<ObjectInstance> jobIterator = jobInstances.iterator();
    ObjectInstance jobInstance = null;

    if (jobIterator.hasNext()) {
      jobInstance = jobIterator.next();
    }
    String gSnapshot = "";
    if (jobInstance != null) {
      ObjectName jobObjectName = jobInstance.getObjectName();
      MBeanInfo mBeanInfo = null;
      try {
        mBeanInfo = mBeanServer.getMBeanInfo(jobObjectName);
      } catch (IntrospectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (InstanceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ReflectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      /*
       * Now get the graph for the job
       */
      Set<String> operations = new HashSet<String>();
      for (MBeanOperationInfo operationInfo : mBeanInfo.getOperations()) {
        operations.add(operationInfo.getName());
        if (operationInfo.getName().equals("graphSnapshot")) {
          try {
            gSnapshot = (String) mBeanServer.invoke(jobObjectName, "graphSnapshot", null, null);
            // System.out.println(gSnapshot);
          } catch (InstanceNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (ReflectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (MBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }
    }
    return gSnapshot;
  }
  @Test
  public void testBeanInfoFromGenericInfo() {
    ManagedBeanDefinition definition = new ManagedBeanDefinition();
    definition.setName("GenericBean");
    ManagedBeanInvocation.Attribute att1 = new ManagedBeanInvocation.Attribute();
    att1.setType(String.class.getName());
    att1.setName("message");
    ManagedBeanInvocation.Attribute att2 = new ManagedBeanInvocation.Attribute();
    att2.setType(Boolean.class.getName());
    att2.setName("standard");
    definition.setAttributes(Arrays.asList(att1, att2));

    ManagedBeanInvocation.Operation op1 = new ManagedBeanInvocation.Operation();
    op1.setName("operation");
    op1.setParameter(new ManagedBeanInvocation.Parameter());
    OperationParam p1 = new OperationParam();
    p1.setType(Integer.class.getName());
    op1.getParameter().getParameter().add(p1);
    definition.setOperations(Arrays.asList(op1));

    MBeanInfo info = definition.createMBeanInfo();

    Assert.assertEquals(info.getClassName(), "GenericBean");
    Assert.assertEquals(info.getAttributes().length, 2);
    Assert.assertEquals(info.getAttributes()[0].getType(), String.class.getName());
    Assert.assertEquals(info.getAttributes()[0].getName(), "message");
    Assert.assertEquals(info.getAttributes()[1].getType(), Boolean.class.getName());
    Assert.assertEquals(info.getAttributes()[1].getName(), "standard");
    Assert.assertEquals(info.getOperations().length, 1);
    Assert.assertEquals(info.getOperations()[0].getName(), "operation");
    Assert.assertEquals(info.getOperations()[0].getSignature().length, 1);
    Assert.assertEquals(
        info.getOperations()[0].getSignature()[0].getType(), Integer.class.getName());
    Assert.assertEquals(info.getOperations()[0].getSignature()[0].getName(), "p1");
    Assert.assertNull(info.getOperations()[0].getReturnType());
  }
Esempio n. 13
0
 /**
  * Get the description of the specified operation. This returns a Collection since operations can
  * be overloaded and one operationName can have multiple forms.
  *
  * @param operationName the name of the operation to describe
  * @return Collection of operation description
  */
 public List<String> describeOperation(String operationName) {
   List<String> list = new ArrayList<String>();
   try {
     MBeanOperationInfo[] operations = beanInfo.getOperations();
     for (MBeanOperationInfo operation : operations) {
       if (operation.getName().equals(operationName)) {
         list.add(describeOperation(operation));
       }
     }
   } catch (Exception e) {
     throwException(
         "Could not describe operations matching name '" + operationName + "'. Reason: ", e);
   }
   return list;
 }
Esempio n. 14
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);
    }
  }
  /**
   * Loads the management interface info for the configured MBean into the caches. This information
   * is used by the proxy when determining whether an invocation matches a valid operation or
   * attribute on the management interface of the managed resource.
   */
  private void retrieveMBeanInfo()
      throws MBeanServerNotFoundException, MBeanInfoRetrievalException {
    try {
      MBeanInfo info = this.server.getMBeanInfo(this.objectName);

      // get attributes
      MBeanAttributeInfo[] attributeInfo = info.getAttributes();
      this.allowedAttributes = new HashMap(attributeInfo.length);

      for (int x = 0; x < attributeInfo.length; x++) {
        this.allowedAttributes.put(attributeInfo[x].getName(), attributeInfo[x]);
      }

      // get operations
      MBeanOperationInfo[] operationInfo = info.getOperations();
      this.allowedOperations = new HashMap(operationInfo.length);

      for (int x = 0; x < operationInfo.length; x++) {
        MBeanOperationInfo opInfo = operationInfo[x];
        this.allowedOperations.put(
            new MethodCacheKey(
                opInfo.getName(), JmxUtils.parameterInfoToTypes(opInfo.getSignature())),
            opInfo);
      }
    } catch (ClassNotFoundException ex) {
      throw new MBeanInfoRetrievalException(
          "Unable to locate class specified in method signature", ex);
    } catch (IntrospectionException ex) {
      throw new MBeanInfoRetrievalException(
          "Unable to obtain MBean info for bean [" + this.objectName + "]", ex);
    } catch (InstanceNotFoundException ex) {
      // if we are this far this shouldn't happen, but...
      throw new MBeanInfoRetrievalException(
          "Unable to obtain MBean info for bean ["
              + this.objectName
              + "]: it is likely that this bean was unregistered during the proxy creation process",
          ex);
    } catch (ReflectionException ex) {
      throw new MBeanInfoRetrievalException(
          "Unable to read MBean info for bean [ " + this.objectName + "]", ex);
    } catch (IOException ex) {
      throw new MBeanInfoRetrievalException(
          "An IOException occurred when communicating with the MBeanServer. "
              + "It is likely that you are communicating with a remote MBeanServer. "
              + "Check the inner exception for exact details.",
          ex);
    }
  }
Esempio n. 16
0
  protected List<MBeanOperationInfo> findMBeanOperationInfos(
      MBeanInfo info, String operationPattern, int signatureLength) {
    List<MBeanOperationInfo> results = new ArrayList<MBeanOperationInfo>();

    if (operationPattern != null) {
      for (MBeanOperationInfo operationInfo : info.getOperations()) {
        if (!isSupported(operationInfo)) {
          continue;
        }

        if ((signatureLength >= 0) && (operationInfo.getSignature().length != signatureLength)) {
          continue;
        }

        if (WildcardUtils.match(
            operationInfo.getName().toLowerCase(), operationPattern.toLowerCase())) {
          results.add(operationInfo);
        }
      }
    }

    return results;
  }
Esempio n. 17
0
  public static OperationParams getOperationParams(MBeanInfo info, String method, Object args[])
      throws PluginException {

    boolean isDebug = log.isDebugEnabled();
    MBeanOperationInfo[] ops = info.getOperations();
    MBeanParameterInfo[] pinfo = null;
    HashMap sigs = new HashMap();
    String methodSignature = null;

    if (args.length != 0) {
      String arg = (String) args[0];
      if (arg.startsWith("@(") && arg.endsWith(")")) {
        methodSignature = arg.substring(1);
        String[] dst = new String[args.length - 1];
        System.arraycopy(args, 1, dst, 0, dst.length);
        args = dst;
      }
    }

    if (isDebug) {
      String msg = "Converting params for: " + method + Arrays.asList(args);
      if (methodSignature != null) {
        msg += ", using provided signature: " + methodSignature;
      }
      log.debug(msg);
    }

    for (int i = 0; i < ops.length; i++) {
      if (ops[i].getName().equals(method)) {
        pinfo = ops[i].getSignature();
        StringBuffer sig = new StringBuffer();
        sig.append("(");
        for (int j = 0; j < pinfo.length; j++) {
          sig.append(pinfo[j].getType());
          if (j + 1 != pinfo.length) {
            sig.append(';');
          }
        }
        sig.append(')');
        log.debug("Found operation: " + method + sig);
        sigs.put(sig.toString(), pinfo);
        sigs.put(new Integer(pinfo.length), pinfo);
        // XXX might have more than 1 method w/ same
        // number of args but different signature
      }
    }

    if (sigs.size() == 0) {
      OperationParams op = getAttributeParams(info, method, args);
      if (op != null) {
        return op;
      }
      String msg = "No MBean Operation or Attribute Info found for: " + method;
      throw new PluginException(msg);
    } else if (sigs.size() > 1) {
      if (methodSignature == null) {
        // try exact match, else last one wins.
        Object o = sigs.get(new Integer(args.length));
        if (o != null) {
          pinfo = (MBeanParameterInfo[]) o;
          if (log.isDebugEnabled()) {
            log.debug("Using default sig: " + toString(pinfo));
          }
        }
      } else {
        pinfo = (MBeanParameterInfo[]) sigs.get(methodSignature);
        if (pinfo == null) {
          String msg = "No matching Operation signature found for: " + method + methodSignature;
          throw new PluginException(msg);
        } else if (log.isDebugEnabled()) {
          log.debug("Using matched sig: " + toString(pinfo));
        }
      }
    }

    int len = pinfo.length;
    int nargs = args.length;
    int consumed;
    String[] signature = new String[len];
    List arguments = new ArrayList();

    for (int i = 0, j = 0; i < len; i++, j += consumed) {
      consumed = 1;
      String sig = pinfo[i].getType();
      signature[i] = sig;

      if (!hasConverter(sig)) {
        String msg = "Cannot convert String argument to " + sig;
        throw new PluginException(msg);
      }

      if (j >= args.length) {
        throw invalidParams(method, sigs, args);
      }

      if (isListType(sig)) {
        String[] listArgs;
        if (len == 1) {
          listArgs = (String[]) args;
        } else {
          int remain = (len - 1) - j;
          consumed = args.length - j - remain;

          listArgs = new String[consumed];
          System.arraycopy(args, j, listArgs, 0, consumed);
        }

        nargs -= listArgs.length;
        try {
          arguments.add(convert(sig, listArgs));
        } catch (Exception e) {
          String msg =
              "Exception converting " + Arrays.asList(listArgs) + "' to type '" + sig + "'";
          throw new PluginException(msg + ": " + e);
        }
      } else {
        nargs--;
        try {
          arguments.add(convert(sig, (String) args[j]));
        } catch (Exception e) {
          String msg =
              "Exception converting param[" + j + "] '" + args[j] + "' to type '" + sig + "'";
          throw new PluginException(msg + ": " + e);
        }
      }

      if (isDebug) {
        Object arg = arguments.get(i);
        if (arg.getClass().isArray()) {
          if ((arg = asObjectArray(arg)) == null) {
            arg = arguments.get(i).toString();
          } else {
            arg = Arrays.asList((Object[]) arg).toString();
          }
        }
        log.debug(method + "() arg " + i + "=" + arg + ", type=" + sig);
      }
    }

    if (nargs != 0) {
      throw invalidParams(method, sigs, args);
    }

    OperationParams params = new OperationParams();
    params.signature = signature;
    params.arguments = arguments.toArray();
    return params;
  }
Esempio n. 18
0
  private static String invokeJmx(
      String ip,
      String port,
      String newPort,
      String objectName,
      String methodName,
      String[] arguments)
      throws MalformedURLException, IOException, MalformedObjectNameException,
          InstanceNotFoundException, IntrospectionException, ReflectionException, MBeanException {

    try {
      if ("other".equals(port)) {
        port = newPort;
      }

      JMXServiceURL address =
          new JMXServiceURL(
              "service:jmx:rmi://" + ip + "/jndi/rmi://" + ip + ":" + port + "/defaultConnector");
      JMXConnector connector = JMXConnectorFactory.connect(address);
      MBeanServerConnection mbs = connector.getMBeanServerConnection();

      ObjectName mxbeanName =
          new ObjectName(objectName); // com.taobao.wlb:id=testJmxMBean,type=mywlb

      MBeanInfo mbeanInfo = mbs.getMBeanInfo(mxbeanName);
      MBeanOperationInfo[] opeInfos = mbeanInfo.getOperations();
      for (MBeanOperationInfo o : opeInfos) {
        if (o.getName().equals(methodName)) {
          int length = o.getSignature().length;
          Object[] params = new Object[length];
          String[] typeNames = new String[length];
          for (int i = 0; i < length; i++) {
            if ("boolean".equals(o.getSignature()[i].getType())) {
              params[i] = Boolean.valueOf(arguments[i]);
            } else if ("int".equals(o.getSignature()[i].getType())) {
              params[i] = Integer.valueOf(arguments[i]);
            } else if ("java.lang.Integer".equals(o.getSignature()[i].getType())) {
              params[i] = Integer.valueOf(arguments[i]);
            } else if ("long".equals(o.getSignature()[i].getType())) {
              params[i] = Long.valueOf(arguments[i]);
            } else if ("java.lang.Long".equals(o.getSignature()[i].getType())) {
              params[i] = Long.valueOf(arguments[i]);
            } else if ("double".equals(o.getSignature()[i].getType())) {
              params[i] = Double.valueOf(arguments[i]);
            } else if ("java.lang.Double".equals(o.getSignature()[i].getType())) {
              params[i] = Double.valueOf(arguments[i]);
            } else {
              params[i] = arguments[i];
            }
            typeNames[i] = o.getSignature()[i].getType();
          }

          Object result = mbs.invoke(mxbeanName, methodName, params, typeNames);
          if (result == null) return null;
          return result.toString();
        }
      }

      return "Jmx对象中没有该方法";
    } catch (Exception e) {
      e.printStackTrace();

      return "执行JMX异常:" + e.getMessage();
    }
  }
  private void renderJsonDomain(
      final PrintWriter pw,
      final ObjectName objectName,
      final MBeanInfo mBeanInfo,
      boolean renderDetails)
      throws IOException, AttributeNotFoundException, InstanceNotFoundException {
    pw.write("{");
    jsonKey(pw, "mbean");
    // using toString to make shure that type is set before any other
    // property
    String canonicalName = objectName.toString();
    String[] split = canonicalName.split(":");
    jsonValue(pw, split[1]);

    if (renderDetails) {
      pw.write(',');
      jsonKey(pw, "attributes");
      pw.write("[{");

      final MBeanAttributeInfo[] attrs = mBeanInfo.getAttributes();
      for (int i = 0; i < attrs.length; i++) {
        final MBeanAttributeInfo attr = attrs[i];
        if (!attr.isReadable()) continue; // skip non readable properties
        // jsonValue(pw, attr.getName() + ":writable=" +
        // attr.isWritable());
        jsonKey(pw, attr.getName());
        pw.write("[");
        jsonValue(pw, "writable=" + attr.isWritable());
        Object value = null;
        try {
          // Descriptor descriptor = attr.getDescriptor();
          // descriptor.get
          value = (mBeanServer.getAttribute(objectName, attr.getName()));
        } catch (ReflectionException e) {
          // Munch skip this attribute then
        } catch (MBeanException e) {
          // Munch skip this attribute then
        } catch (RuntimeMBeanException e) {
          // Munch skip this attribute then
        }
        if (value != null) {
          pw.write(",");
          if (!value.getClass().isArray()) {
            jsonValue(pw, "value=" + value.toString());
          } else {
            jsonValue(pw, "value=" + Arrays.toString((Object[]) value));
          }
        }
        pw.write("]");
        if (i < attrs.length) {
          pw.write(',');
        }
      }
      pw.write("}]");
      pw.write(',');
      jsonKey(pw, "operations");
      pw.write("[");
      final MBeanOperationInfo[] ops = mBeanInfo.getOperations();
      for (int i = 0; i < ops.length; i++) {
        final MBeanOperationInfo op = ops[i];
        // jsonValue(pw, op.getDescription() + ": " + op.getName() +
        // " - "
        // + op.getReturnType());
        jsonValue(pw, op.getName());
        if (i < ops.length) {
          pw.write(',');
        }
      }
      pw.write("]");
    }
    pw.write("},");
  }
 @Override
 protected Object handleRequestMessage(Message<?> requestMessage) {
   ObjectName objectName = this.resolveObjectName(requestMessage);
   String operationName = this.resolveOperationName(requestMessage);
   Map<String, Object> paramsFromMessage = this.resolveParameters(requestMessage);
   try {
     MBeanInfo mbeanInfo = this.server.getMBeanInfo(objectName);
     MBeanOperationInfo[] opInfoArray = mbeanInfo.getOperations();
     boolean hasNoArgOption = false;
     for (MBeanOperationInfo opInfo : opInfoArray) {
       if (operationName.equals(opInfo.getName())) {
         MBeanParameterInfo[] paramInfoArray = opInfo.getSignature();
         if (paramInfoArray.length == 0) {
           hasNoArgOption = true;
         }
         if (paramInfoArray.length == paramsFromMessage.size()) {
           int index = 0;
           Object values[] = new Object[paramInfoArray.length];
           String signature[] = new String[paramInfoArray.length];
           for (MBeanParameterInfo paramInfo : paramInfoArray) {
             Object value = paramsFromMessage.get(paramInfo.getName());
             if (value == null) {
               /*
                * With Spring 3.2.3 and greater, the parameter names are
                * registered instead of the JVM's default p1, p2 etc.
                * Fall back to that naming style if not found.
                */
               value = paramsFromMessage.get("p" + (index + 1));
             }
             if (value != null && valueTypeMatchesParameterType(value, paramInfo)) {
               values[index] = value;
               signature[index] = paramInfo.getType();
               index++;
             }
           }
           if (index == paramInfoArray.length) {
             return this.server.invoke(objectName, operationName, values, signature);
           }
         }
       }
     }
     if (hasNoArgOption) {
       return this.server.invoke(objectName, operationName, null, null);
     }
     throw new MessagingException(
         requestMessage,
         "failed to find JMX operation '"
             + operationName
             + "' on MBean ["
             + objectName
             + "] of type ["
             + mbeanInfo.getClassName()
             + "] with "
             + paramsFromMessage.size()
             + " parameters: "
             + paramsFromMessage);
   } catch (JMException e) {
     throw new MessageHandlingException(
         requestMessage,
         "failed to invoke JMX operation '"
             + operationName
             + "' on MBean ["
             + objectName
             + "]"
             + " with "
             + paramsFromMessage.size()
             + " parameters: "
             + paramsFromMessage,
         e);
   } catch (IOException e) {
     throw new MessageHandlingException(requestMessage, "IOException on MBeanServerConnection", e);
   }
 }
  @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);
  }