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);
  }
  @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);
  }
 private boolean valueTypeMatchesParameterType(Object value, MBeanParameterInfo paramInfo) {
   Class<? extends Object> valueClass = value.getClass();
   if (valueClass.getName().equals(paramInfo.getType())) {
     return true;
   } else {
     Class<?> primitiveType = ClassUtils.resolvePrimitiveType(valueClass);
     return primitiveType != null && primitiveType.getName().equals(paramInfo.getType());
   }
 }
 /**
  * Compare this MBeanParameterInfo to another.
  *
  * @param o the object to compare to.
  * @return true if and only if <code>o</code> is an MBeanParameterInfo such that its {@link
  *     #getName()}, {@link #getType()}, {@link #getDescriptor()}, and {@link #getDescription()}
  *     values are equal (not necessarily identical) to those of this MBeanParameterInfo.
  */
 public boolean equals(Object o) {
   if (o == this) return true;
   if (!(o instanceof MBeanParameterInfo)) return false;
   MBeanParameterInfo p = (MBeanParameterInfo) o;
   return (Objects.equals(p.getName(), getName())
       && Objects.equals(p.getType(), getType())
       && Objects.equals(p.getDescription(), getDescription())
       && Objects.equals(p.getDescriptor(), getDescriptor()));
 }
Exemplo n.º 5
0
  protected static boolean isSupported(MBeanOperationInfo operationInfo) {
    MBeanParameterInfo[] signature = operationInfo.getSignature();

    for (MBeanParameterInfo parameterInfo : signature) {
      if (!isArgumentSupported(parameterInfo.getType())) {
        return false;
      }
    }

    return true;
  }
Exemplo n.º 6
0
 public static String prettySignature(MBeanOperationInfo opInfo) {
   StringBuffer sig = new StringBuffer(opInfo.getName());
   MBeanParameterInfo[] params = opInfo.getSignature();
   sig.append('(');
   for (int i = 0; i < params.length; i++) {
     if (i > 0) {
       sig.append(", "); // $NON-NLS-1$
     }
     MBeanParameterInfo param = params[i];
     sig.append(StringUtils.toString(param.getType(), false));
   }
   sig.append(')');
   return sig.toString();
 }
Exemplo n.º 7
0
  /**
   * Description of the operation.
   *
   * @param operation the operation to describe
   * @return pretty-printed description
   */
  protected String describeOperation(MBeanOperationInfo operation) {
    StringBuilder buf = new StringBuilder();
    buf.append(operation.getReturnType()).append(" ").append(operation.getName()).append("(");

    MBeanParameterInfo[] params = operation.getSignature();
    for (int j = 0; j < params.length; j++) {
      MBeanParameterInfo param = params[j];
      if (j != 0) {
        buf.append(", ");
      }
      buf.append(param.getType()).append(" ").append(param.getName());
    }
    buf.append(")");
    return buf.toString();
  }
  /**
   * 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."));
      }
    }
  }
Exemplo n.º 9
0
  /**
   * {@inheritDoc}
   *
   * @see
   *     net.sourceforge.eclipsejetty.starter.console.AbstractCommand#help(net.sourceforge.eclipsejetty.starter.console.Process)
   */
  @Override
  public int help(Process process) throws Exception {
    String name = process.args.consumeString();

    if (name == null) {
      return super.help(process);
    }

    boolean hit = false;
    List<ObjectName> objectNames = findObjectNames(getLeft(name));
    String operationPattern = Utils.ensure(getRight(name), "*");

    for (ObjectName objectName : objectNames) {
      MBeanInfo info = getMBeanInfo(objectName);
      List<MBeanOperationInfo> operationInfos = findMBeanOperationInfos(info, operationPattern, -1);

      for (MBeanOperationInfo operationInfo : operationInfos) {
        StringBuilder builder = new StringBuilder(getNames()[0]);

        builder.append(" ").append(getName(objectName));
        builder.append(".").append(operationInfo.getName());

        MBeanParameterInfo[] parameterInfos = operationInfo.getSignature();

        for (MBeanParameterInfo parameterInfo : parameterInfos) {
          builder.append(" ").append(toParameter(toClass(parameterInfo.getType())));
        }

        process.out.println(builder);
        hit = true;
      }
    }

    if (!hit) {
      throw new ArgumentException(String.format("No bean operation matches %s", name));
    }

    return 0;
  }
Exemplo n.º 10
0
  public static final String getOperationName(MBeanOperationInfo info) {
    StringBuilder name = new StringBuilder(info.getName());
    name.append('(');

    MBeanParameterInfo[] parameterInfos = info.getSignature();

    if (parameterInfos != null) {

      int parameterCount = parameterInfos.length;
      for (int i = 0; i < parameterCount; i++) {
        MBeanParameterInfo parameterInfo = parameterInfos[i];
        String parameterType = getTypeName(parameterInfo.getType(), parameterInfo.getDescriptor());
        name.append(parameterType);

        if (i < parameterCount - 1) {
          name.append(", ");
        }
      }
    }

    name.append(')');
    return name.toString();
  }
  @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);
  }
 @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);
   }
 }
Exemplo n.º 13
0
 public static Object[] getParameters(String[] textParams, MBeanParameterInfo[] params)
     throws ClassNotFoundException {
   if (textParams == null || params == null) {
     return null;
   }
   Object[] ret = new Object[textParams.length];
   for (int i = 0; i < ret.length && i < params.length; i++) {
     MBeanParameterInfo param = params[i];
     String texti = textParams[i];
     if (texti.length() == 0) {
       ret[i] = null;
     } else if (param.getType().equals("byte")) { // $NON-NLS-1$
       ret[i] = new Byte(texti);
     } else if (param.getType().equals("short")) { // $NON-NLS-1$
       ret[i] = new Short(texti);
     } else if (param.getType().equals("java.lang.Short")) { // $NON-NLS-1$
       ret[i] = new Short(texti);
     } else if (param.getType().equals("int")) { // $NON-NLS-1$
       ret[i] = new Integer(texti);
     } else if (param.getType().equals("java.lang.Integer")) { // $NON-NLS-1$
       ret[i] = new Integer(texti);
     } else if (param.getType().equals("long")) { // $NON-NLS-1$
       ret[i] = new Long(texti);
     } else if (param.getType().equals("java.lang.Long")) { // $NON-NLS-1$
       ret[i] = new Long(texti);
     } else if (param.getType().equals("float")) { // $NON-NLS-1$
       ret[i] = new Float(texti);
     } else if (param.getType().equals("java.lang.Float")) { // $NON-NLS-1$
       ret[i] = new Float(texti);
     } else if (param.getType().equals("double")) { // $NON-NLS-1$
       ret[i] = new Double(texti);
     } else if (param.getType().equals("java.lang.Double")) { // $NON-NLS-1$
       ret[i] = new Double(texti);
     } else if (param.getType().equals("char")) { // $NON-NLS-1$
       ret[i] = new Character(texti.charAt(0));
     } else if (param.getType().equals("boolean")) { // $NON-NLS-1$
       ret[i] = new Boolean(texti);
     } else if (MBeanUtils.class
         .getClassLoader()
         .loadClass("java.lang.Number")
         .isAssignableFrom(
             MBeanUtils.class.getClassLoader().loadClass(param.getType()))) { // $NON-NLS-1$
       ret[i] = createNumber(texti);
     } else {
       ret[i] = texti;
     }
   }
   return ret;
 }