@Test
  public void testBeanInfoEmpty() {
    ManagedBeanDefinition definition = new ManagedBeanDefinition();
    MBeanInfo info = definition.createMBeanInfo();

    Assert.assertEquals(info.getClassName(), "com.consol.citrus.CitrusMBean");
  }
Exemple #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);
     }
   }
 }
  @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);
  }
  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;
  }
  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);
  }
 public void testRegisterAttributes() throws Exception {
   IJmxTestBean bean = getBean();
   MBeanInfo inf = getMBeanInfo();
   assertEquals(
       "Incorrect number of attributes registered",
       getExpectedAttributeCount(),
       inf.getAttributes().length);
 }
 public void testRegisterOperations() throws Exception {
   IJmxTestBean bean = getBean();
   MBeanInfo inf = getMBeanInfo();
   assertEquals(
       "Incorrect number of operations registered",
       getExpectedOperationCount(),
       inf.getOperations().length);
 }
  public void testMBeanInfoIsDeterminedIfKeyIsString() {
    final ComponentAdapter componentAdapter =
        pico.addComponent("JUnit", Person.class).getComponentAdapter("JUnit");
    pico.addComponent("JUnitMBeanInfo", Person.createMBeanInfo());

    final MBeanInfo info = mBeanProvider.provide(pico, componentAdapter);
    assertNotNull(info);
    assertEquals(Person.createMBeanInfo().getDescription(), info.getDescription());
  }
  public void testMBeanInfoIsDeterminedIfKeyIsManagementInterface() {
    final ComponentAdapter componentAdapter =
        pico.addComponent(PersonMBean.class, Person.class)
            .getComponentAdapter(PersonMBean.class, null);
    pico.addComponent(PersonMBean.class.getName() + "Info", Person.createMBeanInfo());

    final MBeanInfo info = mBeanProvider.provide(pico, componentAdapter);
    assertNotNull(info);
    assertEquals(Person.createMBeanInfo().getDescription(), info.getDescription());
  }
 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());
     }
   }
 }
Exemple #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;
  }
  /**
   * Exports all the numeric attributes of beans matching the supplied MXBean name pattern. Also,
   * discovers the numeric properties of the attributes of type CompositeData and registers them as
   * well.
   *
   * @param beanNamePattern the bean name pattern used to discover the beans.
   * @see javax.management.ObjectName for bean name pattern syntax
   * @see java.lang.management for the list of java platform mbeans
   * @throws JMException if there are errors querying MBeans or information on them
   */
  public void exportNumericAttributes(ObjectName beanNamePattern) throws JMException {
    MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> beanNames = beanServer.queryNames(beanNamePattern, null);

    // Iterate through all beans and register their numeric properties with Stats
    for (ObjectName beanName : beanNames) {
      MBeanInfo beanInfo = beanServer.getMBeanInfo(beanName);

      // Iterate through all bean attributes
      for (MBeanAttributeInfo attributeInfo : beanInfo.getAttributes()) {
        if (attributeInfo.isReadable()) {
          // Figure out the open type for the attribute
          OpenType<?> openType = null;
          if (attributeInfo instanceof OpenMBeanAttributeInfo) {
            openType = ((OpenMBeanAttributeInfo) attributeInfo).getOpenType();
          } else {
            // Sometimes the open mbean info is available in the descriptor
            Object obj = attributeInfo.getDescriptor().getFieldValue("openType");
            if (obj != null && obj instanceof OpenType) {
              openType = (OpenType) obj;
            }
          }
          // once the open type is found, figure out if it's a numeric or composite type
          if (openType != null) {
            if (NUMERIC_TYPES.contains(openType)) {
              // numeric attribute types are registered with callbacks that simply
              // return their value
              addStatIfMatches(
                  getStatName(beanName, attributeInfo.getName()),
                  new MBeanLongAttributeFetcher(beanServer, beanName, attributeInfo.getName()));
            } else if (openType instanceof CompositeType) {
              // for composite types, we figure out which properties of the composite type
              // are numeric and register callbacks to fetch those composite type attributes
              CompositeType compositeType = (CompositeType) openType;

              for (String key : compositeType.keySet()) {
                if (NUMERIC_TYPES.contains(compositeType.getType(key))) {
                  addStatIfMatches(
                      getStatName(beanName, attributeInfo.getName(), key),
                      new MBeanLongCompositeValueFetcher(
                          beanServer, beanName, attributeInfo.getName(), key));
                }
              }
            }
          }
        }
      }
    }
  }
 void addMBean(ObjectName beanName) {
   try {
     MBeanInfo info = _server.getMBeanInfo(beanName);
     MBeanAttributeInfo[] infos = info.getAttributes();
     _beanValueMap.put(beanName.toString(), new HashMap<String, Object>());
     for (MBeanAttributeInfo infoItem : infos) {
       Object val = _server.getAttribute(beanName, infoItem.getName());
       // System.out.println("         " + infoItem.getName() + " : " +
       // _server.getAttribute(beanName, infoItem.getName()) + " type : " + infoItem.getType());
       _beanValueMap.get(beanName.toString()).put(infoItem.getName(), val);
     }
   } catch (Exception e) {
     _logger.error("Error getting bean info, domain=" + _domain, e);
   }
 }
  /**
   * 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);
    }
  }
 protected MBeanAttributeInfo getAttributeInfo(MBeanInfo info, String attributeName) {
   for (MBeanAttributeInfo attributeInfo : info.getAttributes()) {
     if (attributeInfo.getName().equals(attributeName)) {
       return attributeInfo;
     }
   }
   return null;
 }
  public void testMBeanInfoIsDeterminedIfKeyIsType() {
    final PersonMBean person = new OtherPerson();

    final Mock mockComponentAdapter = mock(ComponentAdapter.class);
    mockComponentAdapter.stubs().method("getComponentKey").will(returnValue(Person.class));
    mockComponentAdapter
        .stubs()
        .method("getComponentImplementation")
        .will(returnValue(person.getClass()));

    pico.addAdapter((ComponentAdapter) mockComponentAdapter.proxy());
    pico.addComponent(Person.class.getName() + "MBeanInfo", Person.createMBeanInfo());

    final MBeanInfo info =
        mBeanProvider.provide(pico, (ComponentAdapter) mockComponentAdapter.proxy());
    assertNotNull(info);
    assertEquals(Person.createMBeanInfo().getDescription(), info.getDescription());
  }
Exemple #17
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 **");
   }
 }
  /**
   * Refreshes the content provider.
   *
   * @param jvm The active JVM
   */
  public void refresh(IActiveJvm jvm) {
    domains = new HashMap<String, MBeanDomain>();

    // add or update elements
    for (ObjectName objectName : getObjectNames(jvm)) {
      MBeanInfo mBeanInfo = getMBeanInfo(jvm, objectName);
      if (mBeanInfo == null) {
        continue;
      }

      List<AttributeNode> mBeanAttributes = new ArrayList<AttributeNode>();
      for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {
        String attributeName = attributeInfo.getName();

        Object value = getContents(jvm, objectName, attributeName);
        addAttributeRoots(
            mBeanAttributes, new AttributeNode(attributeName, null, objectName), value);
      }

      for (AttributeNode node : mBeanAttributes.toArray(new AttributeNode[0])) {
        validateAttributes(node);
        if (node.getChildren().size() == 0 && !node.isValidLeaf()) {
          mBeanAttributes.remove(node);
        }
      }
      if (mBeanAttributes.size() == 0) {
        continue;
      }

      attributes.put(objectName, mBeanAttributes);

      String domainName = objectName.getDomain();
      MBeanDomain domain;
      if (domains.containsKey(domainName)) {
        domain = domains.get(domainName);
      } else {
        domain = new MBeanDomain(domainName);
      }
      domain.refresh(objectName, jvm);
      domains.put(domainName, domain);
    }
  }
Exemple #19
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;
 }
Exemple #20
0
 /**
  * List of string representations of all of the attributes on the MBean.
  *
  * @return list of descriptions of each attribute on the mbean
  */
 public Collection<String> listAttributeDescriptions() {
   List<String> list = new ArrayList<String>();
   try {
     MBeanAttributeInfo[] attrs = beanInfo.getAttributes();
     for (MBeanAttributeInfo attr : attrs) {
       list.add(describeAttribute(attr));
     }
   } catch (Exception e) {
     throwException("Could not list attribute descriptions. Reason: ", e);
   }
   return list;
 }
Exemple #21
0
 @SuppressWarnings("unchecked")
 private void listAll()
     throws IOException, InstanceNotFoundException, IntrospectionException, ReflectionException {
   Set<ObjectName> mbeans = connection.queryNames(null, null);
   for (ObjectName name : mbeans) {
     MBeanInfo info = connection.getMBeanInfo(name);
     MBeanAttributeInfo[] attrs = info.getAttributes();
     String[] attrNames = new String[attrs.length];
     for (int i = 0; i < attrs.length; i++) {
       attrNames[i] = attrs[i].getName();
     }
     try {
       List<Attribute> attributes = connection.getAttributes(name, attrNames).asList();
       for (Attribute attribute : attributes) {
         output(name.getCanonicalName() + "%" + attribute.getName(), attribute.getValue());
       }
     } catch (Exception e) {
       System.err.println("error getting " + name + ":" + e.getMessage());
     }
   }
 }
Exemple #22
0
  public void walkTree(MBeanServerConnection connection, Server server) throws Exception {

    // key here is null, null returns everything!
    Set<ObjectName> mbeans = connection.queryNames(null, null);

    Map<String, String> output = newHashMap();

    for (ObjectName name : mbeans) {
      MBeanInfo info = connection.getMBeanInfo(name);
      MBeanAttributeInfo[] attrs = info.getAttributes();

      Query.Builder queryBuilder = Query.builder().setObj(name.getCanonicalName());
      ResultCapture resultCapture = new ResultCapture();
      queryBuilder.addOutputWriter(resultCapture);

      for (MBeanAttributeInfo attrInfo : attrs) {
        queryBuilder.addAttr(attrInfo.getName());
      }

      Query query = queryBuilder.build();

      try {
        Iterable<Result> results = server.execute(query);
        query.runOutputWritersForQuery(server, results);
      } catch (AttributeNotFoundException anfe) {
        log.error("Error", anfe);
      }

      for (Result result : resultCapture.results) {
        output.put(result.getTypeName(), query.getAttr().toString());
      }
    }

    for (Entry<String, String> entry : output.entrySet()) {
      log.debug(entry.getKey());
      log.debug(entry.getValue());
      log.debug("-----------------------------------------");
    }
  }
Exemple #23
0
 /**
  * Description of the specified attribute name.
  *
  * @param attributeName - stringified name of the attribute
  * @return the description
  */
 public String describeAttribute(String attributeName) {
   String ret = "Attribute not found";
   try {
     MBeanAttributeInfo[] attributes = beanInfo.getAttributes();
     for (MBeanAttributeInfo attribute : attributes) {
       if (attribute.getName().equals(attributeName)) {
         return describeAttribute(attribute);
       }
     }
   } catch (Exception e) {
     throwException("Could not describe attribute '" + attributeName + "'. Reason: ", e);
   }
   return ret;
 }
 public ExoticMBeanInfo(MBeanInfo mbi) {
   super(
       mbi.getClassName(),
       mbi.getDescription(),
       mbi.getAttributes(),
       mbi.getConstructors(),
       mbi.getOperations(),
       mbi.getNotifications());
 }
Exemple #25
0
  /**
   * Query the mbean connection and add all metrics that satisfy the filter to the list {@code
   * metrics}.
   */
  private void getMetrics(
      MBeanServerConnection con, MetricFilter filter, List<Metric> metrics, ObjectName name)
      throws JMException, IOException {
    // Create tags from the object name
    TagList tags = createTagList(name);
    MBeanInfo info = con.getMBeanInfo(name);
    MBeanAttributeInfo[] attrInfos = info.getAttributes();

    // Restrict to attributes that match the filter
    List<String> matchingNames = Lists.newArrayList();
    for (MBeanAttributeInfo attrInfo : attrInfos) {
      String attrName = attrInfo.getName();
      if (filter.matches(new MonitorConfig.Builder(attrName).withTags(tags).build())) {
        matchingNames.add(attrName);
      }
    }
    List<Attribute> attributeList = safelyLoadAttributes(con, name, matchingNames);

    for (Attribute attr : attributeList) {
      String attrName = attr.getName();
      Object obj = attr.getValue();
      if (obj instanceof CompositeData) {
        Map<String, Object> values = Maps.newHashMap();
        extractValues(null, values, (CompositeData) obj);
        for (Map.Entry<String, Object> e : values.entrySet()) {
          String key = e.getKey();
          TagList newTags =
              SortedTagList.builder().withTags(tags).withTag(COMPOSITE_PATH_KEY, key).build();
          if (filter.matches(MonitorConfig.builder(attrName).withTags(newTags).build())) {
            addMetric(metrics, attrName, newTags, e.getValue());
          }
        }
      } else {
        addMetric(metrics, attrName, tags, obj);
      }
    }
  }
Exemple #26
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;
 }
  @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());
  }
  protected List<MBeanAttributeInfo> findMBeanAttributeInfos(
      MBeanInfo info, String attributePattern) {
    List<MBeanAttributeInfo> results = new ArrayList<MBeanAttributeInfo>();

    if (attributePattern != null) {
      for (MBeanAttributeInfo attributeInfo : info.getAttributes()) {
        if (WildcardUtils.match(
            attributeInfo.getName().toLowerCase(), attributePattern.toLowerCase())) {
          results.add(attributeInfo);
        }
      }
    }

    return results;
  }
Exemple #29
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);
    }
  }
Exemple #30
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);
    }
  }