private Object invokeAttribute(PropertyDescriptor pd, MethodInvocation invocation)
      throws JMException, IOException {

    String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing);
    MBeanAttributeInfo inf = (MBeanAttributeInfo) this.allowedAttributes.get(attributeName);

    // If no attribute is returned, we know that it is not defined in the
    // management interface.
    if (inf == null) {
      throw new InvalidInvocationException(
          "Attribute '" + pd.getName() + "' is not exposed on the management interface");
    }
    if (invocation.getMethod().equals(pd.getReadMethod())) {
      if (inf.isReadable()) {
        return this.server.getAttribute(this.objectName, attributeName);
      } else {
        throw new InvalidInvocationException("Attribute '" + attributeName + "' is not readable");
      }
    } else if (invocation.getMethod().equals(pd.getWriteMethod())) {
      if (inf.isWritable()) {
        server.setAttribute(
            this.objectName, new Attribute(attributeName, invocation.getArguments()[0]));
        return null;
      } else {
        throw new InvalidInvocationException("Attribute '" + attributeName + "' is not writable");
      }
    } else {
      throw new IllegalStateException(
          "Method [" + invocation.getMethod() + "] is neither a bean property getter nor a setter");
    }
  }
  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);
  }
  /**
   * Writes this attribute value to the MBEan server.
   *
   * @param connectionConfiguration the connection context.
   * @param objectName the ObjectName of the specified MBean
   * @param attributeInfo the AtributeInfo object.
   * @param attributeValue the new Value
   */
  public void writeAttributeValue(
      IConnectionConfiguration connectionConfiguration,
      ObjectName objectName,
      MBeanAttributeInfo attributeInfo,
      String attributeValue) {
    // convert
    Object value = convertStringValueToObjectValue(attributeInfo.getType(), attributeValue);
    Attribute attribute = new Attribute(attributeInfo.getName(), value);
    JMXExplorerEvent event;
    try {
      mBeanServerConnection.setAttribute(objectName, attribute);

      event =
          new JMXExplorerEvent(
              connectionConfiguration,
              JMXExplorerEvent.ATTRIBUTE_VALUE_CHANGED,
              objectName,
              attribute,
              attributeInfo);
    } catch (Exception t) {
      // we fould exception, no mather what, the attribute value was not
      // set
      Activator.getDefault().error("writeAttributeValue failed", t);
      event =
          new JMXExplorerEvent(
              connectionConfiguration,
              JMXExplorerEvent.CHANGE_ATTRIBUTE_VALUE_ERROR,
              objectName,
              t,
              attributeInfo);
      return;
    }
    jmxExplorerMediator.notifyObserversWithJMXEvent(event);
  }
 protected MBeanAttributeInfo getAttributeInfo(MBeanInfo info, String attributeName) {
   for (MBeanAttributeInfo attributeInfo : info.getAttributes()) {
     if (attributeInfo.getName().equals(attributeName)) {
       return attributeInfo;
     }
   }
   return null;
 }
  /* Check that all descriptors have been returned */
  private static void checkDescriptors(
      ModelMBeanInfo modelMBeanInfo, Descriptor[] descriptors, String string) {
    int errCount = 0;
    final ArrayList<Descriptor> list = new ArrayList<Descriptor>(descriptors.length);
    list.addAll(Arrays.asList(descriptors));
    System.out.println("Got " + list.size() + " descriptors for " + string);

    // checks that MBean's descriptor is returned.
    //
    final Descriptor mbd = ((MBeanInfo) modelMBeanInfo).getDescriptor();
    if (!mbd.equals(remove(list, mbd))) {
      System.err.println("modelMBeanInfo.getDescriptor(): not found");
      errCount++;
    }

    // checks that MBean's attributes descriptors are returned.
    //
    final MBeanAttributeInfo[] attrs = modelMBeanInfo.getAttributes();
    for (MBeanAttributeInfo att : attrs) {
      final Descriptor ad = att.getDescriptor();
      final String name = att.getName();
      if (!ad.equals(remove(list, ad))) {
        System.err.println("attInfo.getDescriptor(): not found for " + name);
        errCount++;
      }
    }

    // checks that MBean's operations descriptors are returned.
    //
    final MBeanOperationInfo[] ops = modelMBeanInfo.getOperations();
    for (MBeanOperationInfo op : ops) {
      final Descriptor od = op.getDescriptor();
      final String name = op.getName();
      if (!od.equals(remove(list, od))) {
        System.err.println("opInfo.getDescriptor(): not found for " + name);
        errCount++;
      }
    }

    // checks that MBean's notifications descriptors are returned.
    //
    final MBeanNotificationInfo[] ntfs = modelMBeanInfo.getNotifications();
    for (MBeanNotificationInfo ntf : ntfs) {
      final Descriptor nd = ntf.getDescriptor();
      final String name = ntf.getName();
      if (!nd.equals(remove(list, nd))) {
        System.err.println("notifInfo.getDescriptor(): not found for " + name);
        errCount++;
      }
    }
    if (errCount > 0) {
      throw new RuntimeException(string + ": failed with " + errCount + " errors");
    } else if (list.size() != 0) {
      // Check that there are no additional descriptors
      //
      throw new RuntimeException(string + ": Unexpected remaining descriptors: " + list);
    } else System.out.println(string + ": PASSED");
  }
Esempio n. 6
0
 /**
  * List of the names of each of the attributes on the MBean
  *
  * @return list of attribute names
  */
 public Collection<String> listAttributeNames() {
   List<String> list = new ArrayList<String>();
   try {
     MBeanAttributeInfo[] attrs = beanInfo.getAttributes();
     for (MBeanAttributeInfo attr : attrs) {
       list.add(attr.getName());
     }
   } catch (Exception e) {
     throwException("Could not list attribute names. Reason: ", e);
   }
   return list;
 }
Esempio n. 7
0
 /**
  * Description of the specified attribute name.
  *
  * @param attr - the attribute
  * @return String the description
  */
 protected String describeAttribute(MBeanAttributeInfo attr) {
   StringBuilder buf = new StringBuilder();
   buf.append("(");
   if (attr.isReadable()) {
     buf.append("r");
   }
   if (attr.isWritable()) {
     buf.append("w");
   }
   buf.append(") ").append(attr.getType()).append(" ").append(attr.getName());
   return buf.toString();
 }
Esempio n. 8
0
 /**
  * @see com.ixora.rms.agents.impl.jmx.JMXAbstractAgent#acceptCounter(javax.management.ObjectName,
  *     javax.management.MBeanAttributeInfo)
  */
 protected boolean acceptCounter(ObjectName oname, MBeanAttributeInfo ainfo) {
   if (ainfo.getName().equals("Name")) {
     return false;
   }
   String soname = oname.toString();
   if (soname.startsWith("java.lang:type=MemoryPool,name=")) {
     if (ainfo.getName().indexOf("Threshold") >= 0) {
       return false;
     }
   }
   return true;
 }
Esempio n. 9
0
 private String getType(String attName, boolean read, boolean write) {
   boolean allowed = true;
   if (attributes.containsKey(attName)) {
     MBeanAttributeInfo temp = (MBeanAttributeInfo) attributes.get(attName);
     if (read) {
       if (!temp.isReadable()) allowed = false;
     }
     if (write) {
       if (!temp.isWritable()) allowed = false;
     }
     if (!allowed) return null;
     else return temp.getType();
   } else return null;
 }
Esempio n. 10
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;
 }
 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);
   }
 }
Esempio n. 12
0
  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;
  }
Esempio n. 13
0
  private int attr(
      Process process, ObjectName objectName, List<MBeanAttributeInfo> attributeInfos) {
    for (MBeanAttributeInfo attributeInfo : attributeInfos) {
      Object value;

      try {
        value = server.getAttribute(objectName, attributeInfo.getName());
      } catch (Exception e) {
        value = String.format("<%s: %s>", e.getClass().getName(), e.getMessage());
      }

      process.out.println(
          String.format(
              "%s.%s = %s", getName(objectName), attributeInfo.getName(), toString(value)));
    }

    return 0;
  }
  /**
   * 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);
    }
  }
  public Object getValue(ServiceValueContext valueContext) throws Exception {
    MBeanAttributeInfo attributeInfo = valueContext.getAttributeInfo();
    ClassLoader cl = valueContext.getClassloader();

    String typeName = attributeInfo.getType();
    if (typeName == null)
      throw new DeploymentException(
          "AttributeInfo for " + attributeInfo.getName() + " has no type");

    // see if it is a primitive type first
    Class typeClass = Classes.getPrimitiveTypeForName(typeName);
    if (typeClass == null) {
      // nope try look up
      try {
        typeClass = cl.loadClass(typeName);
      } catch (ClassNotFoundException e) {
        throw new DeploymentException(
            "Class not found for attribute: " + attributeInfo.getName(), e);
      }
    }

    PropertyEditor editor = PropertyEditorFinder.getInstance().find(typeClass);
    if (editor == null)
      throw new DeploymentException(
          "No property editor for attribute: "
              + attributeInfo.getName()
              + "; type="
              + typeClass.getName());

    // JBAS-1709, temporarily switch the TCL so that property
    // editors have access to the actual deployment ClassLoader.
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(cl);
    try {
      editor.setAsText(text);
      return editor.getValue();
    } finally {
      Thread.currentThread().setContextClassLoader(tcl);
    }
  }
Esempio n. 16
0
  public static OperationParams getAttributeParams(MBeanInfo info, String method, Object args[])
      throws PluginException {

    if (method.startsWith("set") || method.startsWith("get")) {
      method = method.substring(3);
    }

    MBeanAttributeInfo[] attrs = info.getAttributes();
    for (int i = 0; i < attrs.length; i++) {
      MBeanAttributeInfo attr = attrs[i];
      if (!attr.getName().equals(method)) {
        continue;
      }

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

      OperationParams params = new OperationParams();
      Object value = null;
      try {
        if (args.length > 0) {
          value = convert(sig, (String) args[0]);
        }
      } catch (Exception e) {
        String msg = "Exception converting param '" + args[0] + "' to type '" + sig + "'";
        throw new PluginException(msg + ": " + e);
      }
      if (value != null) {
        params.arguments = new Object[] {value};
      }
      params.isAttribute = true;
      return params;
    }

    return null;
  }
Esempio n. 17
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("-----------------------------------------");
    }
  }
Esempio n. 18
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);
      }
    }
  }
  public Object getPropertyValue(Object id) {
    if ("name".equals(id)) { // $NON-NLS-1$
      return attrInfo.getName();
    }
    if ("description".equals(id)) { // $NON-NLS-1$
      return attrInfo.getDescription();
    }
    if ("type".equals(id)) { // $NON-NLS-1$
      Object obj = attrInfo.getType();
      if (obj instanceof Object[]) {
        return Arrays.asList((Object[]) obj).toString();
      }
      return obj;
    }
    if ("readable".equals(id)) { // $NON-NLS-1$
      return Boolean.valueOf(attrInfo.isReadable());
    }
    if ("writable".equals(id)) { // $NON-NLS-1$
      return Boolean.valueOf(attrInfo.isWritable());
    }
    if ("value".equals(id)) { // $NON-NLS-1$
      try {
        if (mbsc != null) {
          Object obj = mbsc.getAttribute(on, attrInfo.getName());
          if (obj instanceof Object[]) {
            return Arrays.asList((Object[]) obj).toString();
          }
          return obj;
        } else {
          conn.run(
              new IJMXRunnable() {
                final Object[] ret = new Object[1];

                @Override
                public void run(MBeanServerConnection connection) throws Exception {
                  Object obj = connection.getAttribute(on, attrInfo.getName());
                  if (obj instanceof Object[]) {
                    ret[0] = Arrays.asList((Object[]) obj).toString();
                  }
                  ret[0] = obj;
                }
              });
        }
      } catch (Exception e) {
        JMXUIActivator.log(
            IStatus.WARNING, NLS.bind(Messages.MBeanAttributeValue_Warning, attrInfo.getName()), e);
        return null;
      }
    }
    return null;
  }
Esempio n. 20
0
  /**
   * 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));
                }
              }
            }
          }
        }
      }
    }
  }
  /**
   * 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."));
      }
    }
  }
  @Test(dataProvider = "fixtures")
  public void testGetterAttributeInfo(
      String attribute, boolean isIs, Object[] values, Class<?> clazz) throws Exception {
    String methodName = "set" + attribute.replace(".", "");
    for (T t : objects) {
      String attributeName = toFeatureName(attribute, t);
      SimpleInterface simpleInterface = toSimpleInterface(t);
      Method setter = getMethod(simpleInterface.getClass(), methodName, clazz);

      MBeanInfo info = getMBeanInfo(t);
      MBeanAttributeInfo attributeInfo = getAttributeInfo(info, attributeName);
      assertNotNull(attributeInfo, "AttributeInfo for " + attributeName);
      assertEquals(attributeInfo.getName(), attributeName, "Attribute Name for " + attributeName);
      assertEquals(
          attributeInfo.getType(),
          setter.getParameterTypes()[0].getName(),
          "Attribute type for " + attributeName);
      assertEquals(attributeInfo.isIs(), isIs, "Attribute isIs for " + attributeName);
      assertTrue(attributeInfo.isReadable(), "Attribute Readable for " + attributeName);
      assertFalse(attributeInfo.isWritable(), "Attribute Writable for " + attributeName);
    }
  }
Esempio n. 23
0
 /**
  * @see
  *     com.ixora.rms.agents.impl.jmx.JMXAbstractAgent#getCounterNameAndDescription(javax.management.ObjectName,
  *     javax.management.MBeanAttributeInfo)
  */
 protected String[] getCounterNameAndDescription(ObjectName oname, MBeanAttributeInfo ainfo) {
   String soname = oname.toString();
   if (soname.equals("java.lang:type=Compilation")) {
     return new String[] {
       "Compilation." + ainfo.getName(), "Compilation." + ainfo.getName() + ".desc"
     };
   }
   if (soname.equals("java.lang:type=MemoryManager,name=CodeCacheManager")) {
     return new String[] {
       "CodeCacheManager." + ainfo.getName(), "CodeCacheManager." + ainfo.getName() + ".desc"
     };
   }
   if (soname.startsWith("java.lang:type=GarbageCollector,name=")) {
     return new String[] {
       "GarbageCollector." + ainfo.getName(), "GarbageCollector." + ainfo.getName() + ".desc"
     };
   }
   if (soname.startsWith("java.lang:type=Runtime")) {
     return new String[] {"Runtime." + ainfo.getName(), "Runtime." + ainfo.getName() + ".desc"};
   }
   if (soname.startsWith("java.lang:type=ClassLoading")) {
     return new String[] {
       "ClassLoading." + ainfo.getName(), "ClassLoading." + ainfo.getName() + ".desc"
     };
   }
   if (soname.startsWith("java.lang:type=Threading")) {
     return new String[] {
       "Threading." + ainfo.getName(), "Threading." + ainfo.getName() + ".desc"
     };
   }
   if (soname.startsWith("java.lang:type=OperatingSystem")) {
     return new String[] {
       "OperatingSystem." + ainfo.getName(), "OperatingSystem." + ainfo.getName() + ".desc"
     };
   }
   if (soname.startsWith("java.lang:type=Memory")) {
     return new String[] {"Memory." + ainfo.getName(), "Memory." + ainfo.getName() + ".desc"};
   }
   return super.getCounterNameAndDescription(oname, ainfo);
 }
Esempio n. 24
0
  static String getJobsInfo(ObjectName jobObjName) {
    Set<ObjectInstance> jobInstances = mBeanServer.queryMBeans(jobObjName, null);

    Iterator<ObjectInstance> jobIterator = jobInstances.iterator();
    StringBuffer json = new StringBuffer("[");
    int counter = 0;
    while (jobIterator.hasNext()) {
      if (counter > 0) {
        json.append(",");
      }
      ObjectInstance jobInstance = jobIterator.next();
      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();
      }

      /*
       * Get the names of all the attributes
       */

      Set<String> names = new HashSet<String>();
      for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {
        names.add(attributeInfo.getName());
      }
      // now construct the job json and add it to the string buffer
      StringBuffer s = new StringBuffer();
      s.append("{\"");
      Iterator<String> it = names.iterator();
      while (it.hasNext()) {
        String attr = it.next();
        s.append(attr);
        s.append("\":\"");
        try {
          s.append((String) mBeanServer.getAttribute(jobObjectName, attr));
        } catch (AttributeNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (InstanceNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (MBeanException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (ReflectionException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        s.append("\",\"");
      }
      // remove the trailing ,\
      s.deleteCharAt(s.length() - 1);
      s.deleteCharAt(s.length() - 1);
      json.append(s.toString() + "}");
      counter++;
    }
    json.append("]");
    String jsonString = json.toString();

    return jsonString;
  }
Esempio n. 25
0
  public void testCacheService() throws Exception {
    assertNotNull(service_.getAllCacheInstances());
    int size = service_.getAllCacheInstances().size();

    // -----nocache info is retrived from test-configuration(nocache 0bject)
    ExoCache<String, Object> nocache = service_.getCacheInstance("nocache");
    assertTrue("expect find nocache configuaration", nocache instanceof SimpleExoCache);
    assertEquals("expect 'maxsize' of nocache is", 5, nocache.getMaxSize());
    assertEquals("expect 'liveTime' of nocache' is", 0, nocache.getLiveTime());
    nocache.put("key1", "object 1");
    assertEquals("expect 'nocache' is not lived(LiveTime=0)", 0, nocache.getCacheSize());
    // -----cacheLiveTime2s's info is retrived from test-configuration
    // (cacheLiveTime2s object)
    ExoCache<String, Object> cacheLiveTime2s = service_.getCacheInstance("cacheLiveTime2s");
    assertTrue(
        "expect find cacheLiveTime2s configuaration", cacheLiveTime2s instanceof SimpleExoCache);
    assertEquals("expect 'maxsize' of this cache is", 5, cacheLiveTime2s.getMaxSize());
    assertEquals("expect 'liveTime' of nocache' is", 2, cacheLiveTime2s.getLiveTime());
    cacheLiveTime2s.put("key", "object2s");
    String obj2s = (String) cacheLiveTime2s.get("key");
    assertTrue("expect found 'object' in cache", obj2s != null && obj2s.equals("object2s"));
    assertEquals("expect found object in this cache", 1, cacheLiveTime2s.getCacheSize());
    Thread.sleep(2500);
    assertTrue("expect no found 'object' in this cache", cacheLiveTime2s.get("key") == null);
    assertEquals("expect cache size is ", 0, cacheLiveTime2s.getCacheSize());
    // -----cacheMaxSize0's info retrived from test-configuration (cacheMaxSize0
    // object)
    ExoCache<String, Object> cacheMaxSize0 = service_.getCacheInstance("cacheMaxSize0");
    assertTrue("expect find cacheMaxSize0 configuaration", cacheMaxSize0 instanceof SimpleExoCache);
    assertEquals("expect 'maxsize' of this cache is", 0, cacheMaxSize0.getMaxSize());
    assertEquals("expect 'liveTime' of nocache' is", 4, cacheMaxSize0.getLiveTime());
    cacheMaxSize0.put("mkey", "maxsize object");
    assertTrue("expect can't put any object to  cache", cacheMaxSize0.get("mkey") == null);
    // -----default cache's info is retrived if no cache's info is found
    ExoCache<String, Object> cache = service_.getCacheInstance("exo");
    assertTrue("expect find defaul cache configuaration", cache instanceof SimpleExoCache);
    assertEquals("expect 'maxsize' of this cache is", 100, cache.getMaxSize());
    assertEquals("expect 'liveTime' of this cache' is", 300, cache.getLiveTime());
    cache.put("test", "this is a test");
    String ret = (String) cache.get("test");
    assertTrue("expect object is cached", ret != null);

    /* ----------FIFOExoCache--------------- */
    ExoCache<String, Object> fifoCache = service_.getCacheInstance("fifocache");
    assertTrue("expect find fifo cache configuration", fifoCache instanceof FIFOExoCache);
    assertEquals("expect 'maxsize' of this cache is", 3, fifoCache.getMaxSize());
    assertEquals("expect 'liveTime' of this cache' is", 4, fifoCache.getLiveTime());
    fifoCache.put("key1", "object 1");
    fifoCache.put("key2", "object 2");
    assertEquals("expect FIFOExoCache size is:", 2, fifoCache.getCacheSize());
    String obj1 = (String) fifoCache.get("key1");
    String obj2 = (String) fifoCache.get("key2");
    assertTrue("expect found 'key1' object", obj1 != null && obj1.equals("object 1"));
    assertTrue("expect found 'key2' object", obj2 != null && obj2.equals("object 2"));
    fifoCache.put("skey", "serializable object");
    assertEquals("expect FIFOExoCache size is:", 3, fifoCache.getCacheSize());
    String sobj = (String) fifoCache.get("skey");
    assertTrue(
        "expect found serializable key and it's value",
        sobj != null && sobj.equals("serializable object"));
    fifoCache.put("key4", "object 4");
    // because maxsize of cache is 3, 'object 1' associated with 'key1' is
    // remove form FIFOExoCache
    assertEquals("expect cache size is still:", 3, fifoCache.getCacheSize());
    String obj4 = (String) fifoCache.get("key4");
    assertTrue("expect object has 'key4' is put in cache", obj4 != null && obj4.equals("object 4"));
    assertTrue(
        "expect object has key is 'key1' is remove automatically", fifoCache.get("key1") == null);
    // -------remove a object in cache by key
    fifoCache.remove("key2");
    assertEquals("now, expect cache size is", 2, fifoCache.getCacheSize());
    assertEquals(
        "now, expect number of object in cache is:", 2, fifoCache.getCachedObjects().size());
    assertTrue("expect object has 'key2' is removed", fifoCache.get("key2") == null);
    // -------remove a object in cache by serializable name
    fifoCache.remove(new String("skey"));
    assertEquals("now, expect cache size is", 1, fifoCache.getCacheSize());
    assertEquals(
        "now, expect number of object in cache is:", 1, fifoCache.getCachedObjects().size());
    assertTrue(
        "expect serializable object with name 'skey' is remove",
        fifoCache.get(new String("skey")) == null);
    // --------------clear cache
    fifoCache.clearCache();
    assertEquals("now, expect cache is clear", 0, fifoCache.getCacheSize());
    assertEquals(
        "now, expect number of object in cache is:", 0, fifoCache.getCachedObjects().size());
    /* --------------test cache service with add extenal component plugin------ */
    ExoCache simpleCachePlugin = service_.getCacheInstance("simpleCachePlugin");
    assertTrue(
        "expect found simpleCache from extenal plugin",
        simpleCachePlugin instanceof SimpleExoCache);
    assertEquals("expect 'maxsize' of this cache is", 8, simpleCachePlugin.getMaxSize());
    assertEquals("expect 'LiveTime' of this cache is", 5, simpleCachePlugin.getLiveTime());
    ExoCache fifoCachePlugin = service_.getCacheInstance("fifoCachePlugin");
    assertTrue(
        "expect found fifoCache from extenal plugin", fifoCachePlugin instanceof FIFOExoCache);
    assertEquals("expect 'maxsize' of this cache is", 6, fifoCachePlugin.getMaxSize());
    assertEquals("expect 'LiveTime' of this cache is", 10, fifoCachePlugin.getLiveTime());
    // ----all cache instances---
    Collection<ExoCache<? extends Serializable, ?>> caches = service_.getAllCacheInstances();
    assertEquals("expect number of cache instanse is ", size + 7, caches.size());
    hasObjectInCollection(nocache, caches, new ExoCacheComparator());
    hasObjectInCollection(cacheLiveTime2s, caches, new ExoCacheComparator());
    hasObjectInCollection(cacheMaxSize0, caches, new ExoCacheComparator());
    hasObjectInCollection(fifoCache, caches, new ExoCacheComparator());
    hasObjectInCollection(cache, caches, new ExoCacheComparator());
    hasObjectInCollection(simpleCachePlugin, caches, new ExoCacheComparator());
    hasObjectInCollection(fifoCachePlugin, caches, new ExoCacheComparator());

    // Managed tests
    MBeanServerLocator locator =
        (MBeanServerLocator)
            PortalContainer.getInstance().getComponentInstanceOfType(MBeanServerLocator.class);
    MBeanServer server = locator.server;
    assertNotNull(locator.server);
    ObjectName name = new ObjectName("exo:service=cache,name=cacheLiveTime2s,portal=portal");
    MBeanInfo info = server.getMBeanInfo(name);
    assertNotNull(info);
    Map<String, MBeanAttributeInfo> infoMap = new HashMap<String, MBeanAttributeInfo>();
    for (MBeanAttributeInfo attributeInfo : info.getAttributes()) {
      infoMap.put(attributeInfo.getName(), attributeInfo);
    }
    assertTrue(infoMap.containsKey("Name"));
    assertTrue(infoMap.containsKey("Size"));
    assertTrue(infoMap.containsKey("Capacity"));
    assertTrue(infoMap.containsKey("TimeToLive"));
    assertTrue(infoMap.containsKey("HitCount"));
    assertTrue(infoMap.containsKey("MissCount"));
    assertEquals(6, infoMap.size());
    assertEquals(5, server.getAttribute(name, "Capacity"));
    assertEquals(size + 7, service_.getAllCacheInstances().size());
  }
  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("},");
  }
 private void assertNickName(MBeanAttributeInfo attr) {
   assertNotNull("Nick Name should not be null", attr);
   assertTrue("Nick Name should be writable", attr.isWritable());
   assertTrue("Nick Name should be readable", attr.isReadable());
 }
  /**
   * @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);
  }
Esempio n. 29
0
 /**
  * Subclasses could provide here a different description for the given counter.
  *
  * @param oname
  * @param ainfo
  * @return
  */
 protected String[] getCounterNameAndDescription(ObjectName oname, MBeanAttributeInfo ainfo) {
   return new String[] {ainfo.getName(), ainfo.getDescription()};
 }
Esempio n. 30
0
  private MBeanAttributeInfo[] createMBeanAttributeInfo(
      MBeanMetaData metadata, MBeanDescription description) {
    Logger logger = getLogger();

    HashMap attributes = new HashMap();
    HashMap getterNames = new HashMap();

    Method[] methods = metadata.management.getMethods();
    for (int j = 0; j < methods.length; ++j) {
      Method method = methods[j];
      if (Utils.isAttributeGetter(method)) {
        String name = method.getName();
        boolean isIs = name.startsWith("is");

        String attribute = null;
        if (isIs) attribute = name.substring(2);
        else attribute = name.substring(3);

        String descr = description == null ? null : description.getAttributeDescription(attribute);

        MBeanAttributeInfo info = (MBeanAttributeInfo) attributes.get(attribute);

        if (info != null) {
          // JMX spec does not allow overloading attributes.
          // If an attribute with the same name already exists the MBean is not compliant
          if (!info.getType().equals(method.getReturnType().getName())) {
            if (logger.isEnabledFor(Logger.DEBUG))
              logger.debug("MBean is not compliant: has overloaded attribute " + attribute);
            return null;
          } else {
            // They return the same value,
            if (getterNames.get(name) != null) {
              // This is the case of an attribute being present in multiple interfaces
              // Ignore all but the first, since they resolve to the same method anyways
              continue;
            }

            // there is a chance that one is a get-getter and one is a is-getter
            // for a boolean attribute. In this case, the MBean is not compliant.
            if (info.isReadable()) {
              if (logger.isEnabledFor(Logger.DEBUG))
                logger.debug("MBean is not compliant: has overloaded attribute " + attribute);
              return null;
            }

            // MBeanAttributeInfo is already present due to a setter method, just update its
            // readability
            info =
                new MBeanAttributeInfo(
                    attribute,
                    info.getType(),
                    info.getDescription(),
                    true,
                    info.isWritable(),
                    isIs);
          }
        } else {
          info =
              new MBeanAttributeInfo(
                  attribute, method.getReturnType().getName(), descr, true, false, isIs);
        }

        // Replace if exists
        attributes.put(attribute, info);
        getterNames.put(name, method);
      } else if (Utils.isAttributeSetter(method)) {
        String name = method.getName();
        String attribute = name.substring(3);

        String descr = description == null ? null : description.getAttributeDescription(attribute);

        MBeanAttributeInfo info = (MBeanAttributeInfo) attributes.get(attribute);

        if (info != null) {
          // JMX spec does not allow overloading attributes.
          // If an attribute with the same name already exists the MBean is not compliant
          if (!info.getType().equals(method.getParameterTypes()[0].getName())) {
            if (logger.isEnabledFor(Logger.DEBUG))
              logger.debug("MBean is not compliant: has overloaded attribute " + attribute);
            return null;
          } else {
            // MBeanAttributeInfo is already present due to a getter method, just update its
            // writability
            info =
                new MBeanAttributeInfo(
                    info.getName(),
                    info.getType(),
                    info.getDescription(),
                    info.isReadable(),
                    true,
                    info.isIs());
          }
        } else {
          info =
              new MBeanAttributeInfo(
                  attribute, method.getParameterTypes()[0].getName(), descr, false, true, false);
        }

        // Replace if exists
        attributes.put(attribute, info);
      }
    }

    return (MBeanAttributeInfo[])
        attributes.values().toArray(new MBeanAttributeInfo[attributes.size()]);
  }