Java 类javax.management.Attribute 实例源码

项目:keyboard-light-composer    文件:CpuUsage.java   
public static double getProcessCpuLoad() throws Exception {

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
        AttributeList list = mbs.getAttributes(name, new String[] { "SystemCpuLoad" });

        if (list.isEmpty())
            return Double.NaN;

        Attribute att = (Attribute) list.get(0);
        Double value = (Double) att.getValue();

        // usually takes a couple of seconds before we get real values
        if (value == -1.0)
            return Double.NaN;
        // returns a percentage value with 1 decimal point precision
        return value;
    }
项目:hadoop-oss    文件:MetricsDynamicMBeanBase.java   
@Override
public AttributeList getAttributes(String[] attributeNames) {
  if (attributeNames == null || attributeNames.length == 0) 
    throw new IllegalArgumentException();

  updateMbeanInfoIfMetricsListChanged();

  AttributeList result = new AttributeList(attributeNames.length);
  for (String iAttributeName : attributeNames) {
    try {
      Object value = getAttribute(iAttributeName);
      result.add(new Attribute(iAttributeName, value));
    } catch (Exception e) {
      continue;
    } 
  }
  return result;
}
项目:hashsdn-controller    文件:DynamicWritableWrapper.java   
@Override
public synchronized void setAttribute(final Attribute attribute)
        throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
    Attribute newAttribute = attribute;
    if (configBeanModificationDisabled.get()) {
        throw new IllegalStateException("Operation is not allowed now");
    }

    if ("Attribute".equals(newAttribute.getName())) {
        setAttribute((Attribute) newAttribute.getValue());
        return;
    }

    try {
        if (newAttribute.getValue() instanceof ObjectName) {
            newAttribute = fixDependencyAttribute(newAttribute);
        } else if (newAttribute.getValue() instanceof ObjectName[]) {
            newAttribute = fixDependencyListAttribute(newAttribute);
        }

        internalServer.setAttribute(objectNameInternal, newAttribute);
    } catch (final InstanceNotFoundException e) {
        throw new MBeanException(e);
    }

}
项目:tomcat7    文件:JMXAccessorSetTask.java   
/**
 * @param jmxServerConnection
 * @param name
 * @throws Exception
 */
protected String jmxSet(MBeanServerConnection jmxServerConnection,
        String name) throws Exception {
    Object realValue;
    if (type != null) {
        realValue = convertStringToType(value, type);
    } else {
        if (isConvert()) {
            String mType = getMBeanAttributeType(jmxServerConnection, name,
                    attribute);
            realValue = convertStringToType(value, mType);
        } else
            realValue = value;
    }
    jmxServerConnection.setAttribute(new ObjectName(name), new Attribute(
            attribute, realValue));
    return null;
}
项目:tomcat7    文件:BaseModelMBean.java   
/**
 * Obtain and return the values of several attributes of this MBean.
 *
 * @param names Names of the requested attributes
 */
@Override
public AttributeList getAttributes(String names[]) {

    // Validate the input parameters
    if (names == null)
        throw new RuntimeOperationsException
            (new IllegalArgumentException("Attribute names list is null"),
             "Attribute names list is null");

    // Prepare our response, eating all exceptions
    AttributeList response = new AttributeList();
    for (int i = 0; i < names.length; i++) {
        try {
            response.add(new Attribute(names[i],getAttribute(names[i])));
        } catch (Exception e) {
            // Not having a particular attribute in the response
            // is the indication of a getter problem
        }
    }
    return (response);

}
项目:tomcat7    文件:BaseModelMBean.java   
/**
 * Set the values of several attributes of this MBean.
 *
 * @param attributes THe names and values to be set
 *
 * @return The list of attributes that were set and their new values
 */
@Override
public AttributeList setAttributes(AttributeList attributes) {
    AttributeList response = new AttributeList();

    // Validate the input parameters
    if (attributes == null)
        return response;

    // Prepare and return our response, eating all exceptions
    String names[] = new String[attributes.size()];
    int n = 0;
    Iterator<?> items = attributes.iterator();
    while (items.hasNext()) {
        Attribute item = (Attribute) items.next();
        names[n++] = item.getName();
        try {
            setAttribute(item);
        } catch (Exception e) {
            // Ignore all exceptions
        }
    }

    return (getAttributes(names));

}
项目:tomcat7    文件:BaseModelMBean.java   
/**
 * Send an <code>AttributeChangeNotification</code> to all registered
 * listeners.
 *
 * @param oldValue The original value of the <code>Attribute</code>
 * @param newValue The new value of the <code>Attribute</code>
 *
 * @exception MBeanException if an object initializer throws an
 *  exception
 * @exception RuntimeOperationsException wraps IllegalArgumentException
 *  when the specified notification is <code>null</code> or invalid
 */
@Override
public void sendAttributeChangeNotification
    (Attribute oldValue, Attribute newValue)
    throws MBeanException, RuntimeOperationsException {

    // Calculate the class name for the change notification
    String type = null;
    if (newValue.getValue() != null)
        type = newValue.getValue().getClass().getName();
    else if (oldValue.getValue() != null)
        type = oldValue.getValue().getClass().getName();
    else
        return;  // Old and new are both null == no change

    AttributeChangeNotification notification =
        new AttributeChangeNotification
        (this, 1, System.currentTimeMillis(),
         "Attribute value has changed",
         oldValue.getName(), type,
         oldValue.getValue(), newValue.getValue());
    sendAttributeChangeNotification(notification);

}
项目:twitch4j-chatbot    文件:Diagnostics.java   
/**
 * Get CPU Load of Host System
 *
 * @author http://stackoverflow.com/questions/18489273/how-to-get-percentage-of-cpu-usage-of-os-from-java
 */
private double getCpuLoad() {
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
        AttributeList list = mbs.getAttributes(name, new String[]{"ProcessCpuLoad"});

        if (list.isEmpty())
            return Double.NaN;

        Attribute att = (Attribute) list.get(0);
        Double value = (Double) att.getValue();

        // usually takes a couple of seconds before we get real values
        if (value == -1.0)
            return Double.NaN;
        // returns a percentage value with 1 decimal point precision
        return ((int) (value * 1000) / 10.0);
    } catch (Exception e) {
        return Double.NaN;
    }
}
项目:lams    文件:BaseModelMBean.java   
/**
 * Obtain and return the values of several attributes of this MBean.
 *
 * @param names Names of the requested attributes
 */
public AttributeList getAttributes(String names[]) {

    // Validate the input parameters
    if (names == null)
        throw new RuntimeOperationsException
            (new IllegalArgumentException("Attribute names list is null"),
             "Attribute names list is null");

    // Prepare our response, eating all exceptions
    AttributeList response = new AttributeList();
    for (int i = 0; i < names.length; i++) {
        try {
            response.add(new Attribute(names[i],getAttribute(names[i])));
        } catch (Exception e) {
            ; // Not having a particular attribute in the response
            ; // is the indication of a getter problem
        }
    }
    return (response);

}
项目:ibm-cos-sdk-java    文件:JmxInfoProviderSupport.java   
@Override
public long[] getFileDecriptorInfo() {
    MBeanServer mbsc = MBeans.getMBeanServer();
    AttributeList attributes;
    try {
        attributes = mbsc.getAttributes(
            new ObjectName("java.lang:type=OperatingSystem"), 
            new String[]{"OpenFileDescriptorCount", "MaxFileDescriptorCount"});
        List<Attribute> attrList = attributes.asList();
        long openFdCount = (Long)attrList.get(0).getValue();
        long maxFdCount = (Long)attrList.get(1).getValue();
        long[] fdCounts = { openFdCount, maxFdCount};
        return fdCounts;
    } catch (Exception e) {
        LogFactory.getLog(SdkMBeanRegistrySupport.class).debug(
                "Failed to retrieve file descriptor info", e);
    }
    return null;
}
项目:jdk8u-jdk    文件:RMIConnectorLogAttributesTest.java   
private void doTest(JMXConnector connector) throws IOException,
MalformedObjectNameException, ReflectionException,
InstanceAlreadyExistsException, MBeanRegistrationException,
MBeanException, NotCompliantMBeanException, InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException {
    MBeanServerConnection  mbsc = connector.getMBeanServerConnection();


    ObjectName objName = new ObjectName("com.redhat.test.jmx:type=NameMBean");
    System.out.println("DEBUG: Calling createMBean");
    mbsc.createMBean(Name.class.getName(), objName);

    System.out.println("DEBUG: Calling setAttributes");
    AttributeList attList = new AttributeList();
    attList.add(new Attribute("FirstName", ANY_NAME));
    attList.add(new Attribute("LastName", ANY_NAME));
    mbsc.setAttributes(objName, attList);
}
项目:hashsdn-controller    文件:AbstractDynamicWrapperTest.java   
@Test
public void testReadAttributes() throws Exception {
    DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class);

    assertEquals(threadCount, proxy.getAttribute(THREAD_COUNT));

    assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(),
            proxy.getAttribute(TRIGGER_NEW_INSTANCE_CREATION));

    AttributeList attributes = proxy.getAttributes(new String[] { THREAD_COUNT, TRIGGER_NEW_INSTANCE_CREATION });
    assertEquals(2, attributes.size());
    Attribute threadCountAttr = (Attribute) attributes.get(0);
    assertEquals(THREAD_COUNT, threadCountAttr.getName());
    assertEquals(threadCount, threadCountAttr.getValue());
    Attribute boolTestAttr = (Attribute) attributes.get(1);
    assertEquals(TRIGGER_NEW_INSTANCE_CREATION, boolTestAttr.getName());
    assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(), boolTestAttr.getValue());

    MBeanInfo beanInfo = proxy.getMBeanInfo();
    assertEquals(2, beanInfo.getAttributes().length);
}
项目:OpenJSharp    文件:RMIConnector.java   
public void setAttribute(ObjectName name,
        Attribute attribute)
        throws InstanceNotFoundException,
        AttributeNotFoundException,
        InvalidAttributeValueException,
        MBeanException,
        ReflectionException,
        IOException {

    if (logger.debugOn()) logger.debug("setAttribute",
            "name=" + name + ", attribute="
            + attribute);

    final MarshalledObject<Attribute> sAttribute =
            new MarshalledObject<Attribute>(attribute);
    final ClassLoader old = pushDefaultClassLoader();
    try {
        connection.setAttribute(name, sAttribute, delegationSubject);
    } catch (IOException ioe) {
        communicatorAdmin.gotIOException(ioe);

        connection.setAttribute(name, sAttribute, delegationSubject);
    } finally {
        popDefaultClassLoader(old);
    }
}
项目:monarch    文件:MX4JModelMBean.java   
public void sendAttributeChangeNotification(Attribute oldAttribute, Attribute newAttribute)
    throws MBeanException, RuntimeOperationsException {
  if (oldAttribute == null || newAttribute == null)
    throw new RuntimeOperationsException(new IllegalArgumentException(
        LocalizedStrings.MX4JModelMBean_ATTRIBUTE_CANNOT_BE_NULL.toLocalizedString()));
  if (!oldAttribute.getName().equals(newAttribute.getName()))
    throw new RuntimeOperationsException(new IllegalArgumentException(
        LocalizedStrings.MX4JModelMBean_ATTRIBUTE_NAMES_CANNOT_BE_DIFFERENT.toLocalizedString()));

  // TODO: the source must be the object name of the MBean if the listener was registered through
  // MBeanServer
  Object oldValue = oldAttribute.getValue();
  AttributeChangeNotification n = new AttributeChangeNotification(this, 1,
      System.currentTimeMillis(), "Attribute value changed", oldAttribute.getName(),
      oldValue == null ? null : oldValue.getClass().getName(), oldValue, newAttribute.getValue());
  sendAttributeChangeNotification(n);
}
项目:monarch    文件:MX4JModelMBean.java   
public AttributeList setAttributes(AttributeList attributes) {
  if (attributes == null)
    throw new RuntimeOperationsException(new IllegalArgumentException(
        LocalizedStrings.MX4JModelMBean_ATTRIBUTE_LIST_CANNOT_BE_NULL.toLocalizedString()));

  Logger logger = getLogger();

  AttributeList list = new AttributeList();
  for (Iterator i = attributes.iterator(); i.hasNext();) {
    Attribute attribute = (Attribute) i.next();
    String name = attribute.getName();
    try {
      setAttribute(attribute);
      list.add(attribute);
    } catch (Exception x) {
      if (logger.isEnabledFor(Logger.TRACE))
        logger.trace("setAttribute for attribute " + name + " failed", x);
      // And go on with the next one
    }
  }
  return list;
}
项目:ChronoBike    文件:BaseCloseMBean.java   
public AttributeList getAttributes(String[] attributeNames) 
{
       if(attributeNames != null)
       {
        AttributeList resultList = new AttributeList();

        if (attributeNames.length == 0)
            return resultList;

        // Build the result attribute list
        for(int i=0 ; i<attributeNames.length; i++)
        {
            try 
            {        
                Object oValue = getAttribute(attributeNames[i]);     
                resultList.add(new Attribute(attributeNames[i], oValue));
            } 
            catch (Exception e) 
            {
            }
        }
        return resultList;
    }
       return null;
}
项目:apache-tomcat-7.0.73-with-comment    文件:JMXAccessorSetTask.java   
/**
 * @param jmxServerConnection
 * @param name
 * @throws Exception
 */
protected String jmxSet(MBeanServerConnection jmxServerConnection,
        String name) throws Exception {
    Object realValue;
    if (type != null) {
        realValue = convertStringToType(value, type);
    } else {
        if (isConvert()) {
            String mType = getMBeanAttributeType(jmxServerConnection, name,
                    attribute);
            realValue = convertStringToType(value, mType);
        } else
            realValue = value;
    }
    jmxServerConnection.setAttribute(new ObjectName(name), new Attribute(
            attribute, realValue));
    return null;
}
项目:hashsdn-controller    文件:DynamicWritableWrapperTest.java   
@Test
public void testSetAttribute() throws Exception {
    DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class);

    proxy.setAttribute(new Attribute(THREAD_COUNT, newThreadCount));

    assertEquals(newThreadCount, proxy.getAttribute(THREAD_COUNT));
    assertEquals(newThreadCount, threadPoolConfigBean.getThreadCount());

    AttributeList attributeList = new AttributeList();
    attributeList.add(new Attribute(THREAD_COUNT, threadCount));
    boolean bool = true;
    attributeList.add(new Attribute(TRIGGER_NEW_INSTANCE_CREATION, bool));
    proxy.setAttributes(attributeList);

    assertEquals(threadCount, threadPoolConfigBean.getThreadCount());
    assertEquals(bool, threadPoolConfigBean.isTriggerNewInstanceCreation());
}
项目:apache-tomcat-7.0.73-with-comment    文件:BaseModelMBean.java   
/**
 * Send an <code>AttributeChangeNotification</code> to all registered
 * listeners.
 *
 * @param oldValue The original value of the <code>Attribute</code>
 * @param newValue The new value of the <code>Attribute</code>
 *
 * @exception MBeanException if an object initializer throws an
 *  exception
 * @exception RuntimeOperationsException wraps IllegalArgumentException
 *  when the specified notification is <code>null</code> or invalid
 */
@Override
public void sendAttributeChangeNotification
    (Attribute oldValue, Attribute newValue)
    throws MBeanException, RuntimeOperationsException {

    // Calculate the class name for the change notification
    String type = null;
    if (newValue.getValue() != null)
        type = newValue.getValue().getClass().getName();
    else if (oldValue.getValue() != null)
        type = oldValue.getValue().getClass().getName();
    else
        return;  // Old and new are both null == no change

    AttributeChangeNotification notification =
        new AttributeChangeNotification
        (this, 1, System.currentTimeMillis(),
         "Attribute value has changed",
         oldValue.getName(), type,
         oldValue.getValue(), newValue.getValue());
    sendAttributeChangeNotification(notification);

}
项目:momo-2    文件:Diagnostics.java   
private static double getCpuLoad() {
    // http://stackoverflow.com/questions/18489273/how-to-get-percentage-of-cpu-usage-of-os-from-java
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
        AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" });

        if (list.isEmpty())
            return Double.NaN;

        Attribute att = (Attribute)list.get(0);
        Double value  = (Double)att.getValue();

        // usually takes a couple of seconds before we get real values
        if (value == -1.0)    
            return Double.NaN;
        // returns a percentage value with 1 decimal point precision
        return ((int)(value * 1000) / 10.0);
    } catch(Exception e) {
        return Double.NaN;
    }
}
项目:openjdk-jdk10    文件:RMIConnector.java   
public void setAttribute(ObjectName name,
        Attribute attribute)
        throws InstanceNotFoundException,
        AttributeNotFoundException,
        InvalidAttributeValueException,
        MBeanException,
        ReflectionException,
        IOException {

    if (logger.debugOn()) logger.debug("setAttribute",
            "name=" + name + ", attribute name="
            + attribute.getName());

    final MarshalledObject<Attribute> sAttribute =
            new MarshalledObject<Attribute>(attribute);
    final ClassLoader old = pushDefaultClassLoader();
    try {
        connection.setAttribute(name, sAttribute, delegationSubject);
    } catch (IOException ioe) {
        communicatorAdmin.gotIOException(ioe);

        connection.setAttribute(name, sAttribute, delegationSubject);
    } finally {
        popDefaultClassLoader(old);
    }
}
项目:lazycat    文件:BaseModelMBean.java   
/**
 * Obtain and return the values of several attributes of this MBean.
 *
 * @param names
 *            Names of the requested attributes
 */
@Override
public AttributeList getAttributes(String names[]) {

    // Validate the input parameters
    if (names == null)
        throw new RuntimeOperationsException(new IllegalArgumentException("Attribute names list is null"),
                "Attribute names list is null");

    // Prepare our response, eating all exceptions
    AttributeList response = new AttributeList();
    for (int i = 0; i < names.length; i++) {
        try {
            response.add(new Attribute(names[i], getAttribute(names[i])));
        } catch (Exception e) {
            // Not having a particular attribute in the response
            // is the indication of a getter problem
        }
    }
    return (response);

}
项目:hashsdn-controller    文件:DynamicWritableWrapper.java   
@Override
public AttributeList setAttributes(final AttributeList attributes) {
    AttributeList result = new AttributeList();
    for (Object attributeObject : attributes) {
        Attribute attribute = (Attribute) attributeObject;
        try {
            setAttribute(attribute);
            result.add(attribute);
        } catch (final InvalidAttributeValueException | AttributeNotFoundException | MBeanException
                | ReflectionException e) {
            LOG.warn("Setting attribute {} failed on {}", attribute.getName(), moduleIdentifier, e);
            throw new IllegalArgumentException(
                    "Setting attribute failed - " + attribute.getName() + " on " + moduleIdentifier, e);
        }
    }
    return result;
}
项目:Pogamut3    文件:FolderMBean.java   
@Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
    try {
        folder.getProperty(attribute.getName()).setValue(attribute.getValue());
    } catch (IntrospectionException ex) {
        throw new MBeanException(ex);
    }
}
项目:kmanager    文件:JMXTest.java   
public static void objectNames(KafkaJMX kafkaJMX) {
  kafkaJMX.doWithConnection("10.16.238.94", 8888, Optional.of(""), Optional.of(""), false, new JMXExecutor() {

    @Override
    public void doWithConnection(MBeanServerConnection mbsc) {
      // KafkaMetrics kafkaMetrics = new KafkaMetrics();
      try (FileWriter fw = new FileWriter("objectNames.json", true);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter out = new PrintWriter(bw)) {
        Set<ObjectInstance> beans = mbsc.queryMBeans(null, null);
        JSONArray objectName = new JSONArray();
        for (ObjectInstance bean : beans) {
          if (excludeInternalTopic && bean.getObjectName().toString().contains("__consumer_offsets")) {
            continue;
          }
          System.out.println("ObjectName: " + bean.getObjectName());
          objectName.put(bean.getObjectName().toString());
          MBeanInfo mbeanInfo = mbsc.getMBeanInfo(bean.getObjectName());
          System.out.println("\tMBeanInfo: " + mbeanInfo);
          MBeanAttributeInfo[] attributes = mbeanInfo.getAttributes();
          String[] attributeArr = new String[attributes.length];
          for (int i = 0; i < attributes.length; i++) {
            attributeArr[i] = attributes[i].getName();
          }
          AttributeList attributeList = mbsc.getAttributes(bean.getObjectName(), attributeArr);
          List<Attribute> attributeList1 = attributeList.asList();

          for (Attribute attr : attributeList1) {
            System.out.println("\t\tName: " + attr.getName() + " Value: " + attr.getValue());
          }
        }
        out.println(objectName.toString());
      } catch (Exception e) {

      }
    }
  });

}
项目:Pogamut3    文件:AttributeToPropertyAdapter.java   
@Override
public void setValue(Object newValue) throws IntrospectionException {
    try {
        folderMBean.setAttribute(new Attribute(getName(), newValue));
    } catch (Exception ex) {
        throw new IntrospectionException(ex);
    }
}
项目:hadoop-oss    文件:MetricsSourceAdapter.java   
@Override
public Object getAttribute(String attribute)
    throws AttributeNotFoundException, MBeanException, ReflectionException {
  updateJmxCache();
  synchronized(this) {
    Attribute a = attrCache.get(attribute);
    if (a == null) {
      throw new AttributeNotFoundException(attribute +" not found");
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug(attribute +": "+ a);
    }
    return a.getValue();
  }
}
项目:openjdk-jdk10    文件:MBeanExceptionTest.java   
public void setAttribute(Attribute attr)
        throws MBeanException {
    String attrName = attr.getName();
    if (attrName.equals("UncheckedException"))
        throw theUncheckedException;
    else
        throw new AssertionError();
}
项目:tqdev-metrics    文件:JmxReporter.java   
@Override
public void setAttribute(Attribute attribute)
        throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
    if (attribute.getName().equals("enabled")) {
        registry.setEnabled((boolean) attribute.getValue());
    } else {
        throw new AttributeNotFoundException("No writable attribute has been found");
    }
}
项目:openjdk-jdk10    文件:RequiredModelMBean.java   
/**
 * Sets the values of an array of attributes of this ModelMBean.
 * Executes the setAttribute() method for each attribute in the list.
 *
 * @param attributes A list of attributes: The identification of the
 * attributes to be set and  the values they are to be set to.
 *
 * @return  The array of attributes that were set, with their new
 *    values in Attribute instances.
 *
 * @exception RuntimeOperationsException Wraps an
 *   {@link IllegalArgumentException}: The object name in parameter
 *   is null or attributes in parameter is null.
 *
 * @see #getAttributes
 **/
public AttributeList setAttributes(AttributeList attributes) {

    if (MODELMBEAN_LOGGER.isLoggable(Level.TRACE)) {
        MODELMBEAN_LOGGER.log(Level.TRACE, "Entry");
    }

    if (attributes == null)
        throw new RuntimeOperationsException(new
            IllegalArgumentException("attributes must not be null"),
            "Exception occurred trying to set attributes of a "+
            "RequiredModelMBean");

    final AttributeList responseList = new AttributeList();

    // Go through the list of attributes
    for (Attribute attr : attributes.asList()) {
        try {
            setAttribute(attr);
            responseList.add(attr);
        } catch (Exception excep) {
            responseList.remove(attr);
        }
    }

    return responseList;
}
项目:tomcat7    文件:MbeansSource.java   
private void processAttribute(MBeanServer server,
                              Node descN, String objectName ) {
    String attName=DomUtil.getAttribute(descN, "name");
    String value=DomUtil.getAttribute(descN, "value");
    String type=null; // DomUtil.getAttribute(descN, "type");
    if( value==null ) {
        // The value may be specified as CDATA
        value=DomUtil.getContent(descN);
    }
    try {
        if( log.isDebugEnabled())
            log.debug("Set attribute " + objectName + " " + attName +
                    " " + value);
        ObjectName oname=new ObjectName(objectName);
        // find the type
        type=registry.getType(  oname, attName );

        if( type==null ) {
            log.info("Can't find attribute " + objectName + " " + attName );

        } else {
            Object valueO=registry.convertValue( type, value);
            server.setAttribute(oname, new Attribute(attName, valueO));
        }
    } catch( Exception ex) {
        log.error("Error processing attribute " + objectName + " " +
                attName + " " + value, ex);
    }

}
项目:hashsdn-controller    文件:MergeEditConfigStrategy.java   
@Override
@SuppressWarnings("IllegalCatch")
void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on,
        ServiceRegistryWrapper services) throws ConfigHandlingException {

    for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
        try {
            AttributeConfigElement ace = configAttributeEntry.getValue();

            if (!ace.getResolvedValue().isPresent()) {
                LOG.debug("Skipping attribute {} for {}", configAttributeEntry.getKey(), on);
                continue;
            }

            Object toBeMergedIn = ace.getResolvedValue().get();
            // Get the existing values so we can merge the new values with them.
            Attribute currentAttribute = ta.getAttribute(on, ace.getJmxName());
            Object oldValue = currentAttribute != null ? currentAttribute.getValue() : null;
            // Merge value with currentValue
            toBeMergedIn = merge(oldValue, toBeMergedIn);
            ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), toBeMergedIn));
            LOG.debug("Attribute {} set to {} for {}", configAttributeEntry.getKey(), toBeMergedIn, on);
        } catch (RuntimeException e) {
            LOG.error("Error while merging object names of {}", on, e);
            throw new ConfigHandlingException(String.format("Unable to set attributes for %s, "
                            + "Error with attribute %s : %s ",
                    on,
                    configAttributeEntry.getKey(),
                    configAttributeEntry.getValue()),
                    DocumentedException.ErrorType.APPLICATION,
                    DocumentedException.ErrorTag.OPERATION_FAILED,
                    DocumentedException.ErrorSeverity.ERROR);
        }
    }
}
项目:flume-release-1.7.0    文件:JMXPollUtil.java   
public static Map<String, Map<String, String>> getAllMBeans() {
  Map<String, Map<String, String>> mbeanMap = Maps.newHashMap();
  Set<ObjectInstance> queryMBeans = null;
  try {
    queryMBeans = mbeanServer.queryMBeans(null, null);
  } catch (Exception ex) {
    LOG.error("Could not get Mbeans for monitoring", ex);
    Throwables.propagate(ex);
  }
  for (ObjectInstance obj : queryMBeans) {
    try {
      if (!obj.getObjectName().toString().startsWith("org.apache.flume")) {
        continue;
      }
      MBeanAttributeInfo[] attrs = mbeanServer.getMBeanInfo(obj.getObjectName()).getAttributes();
      String[] strAtts = new String[attrs.length];
      for (int i = 0; i < strAtts.length; i++) {
        strAtts[i] = attrs[i].getName();
      }
      AttributeList attrList = mbeanServer.getAttributes(obj.getObjectName(), strAtts);
      String component = obj.getObjectName().toString().substring(
          obj.getObjectName().toString().indexOf('=') + 1);
      Map<String, String> attrMap = Maps.newHashMap();

      for (Object attr : attrList) {
        Attribute localAttr = (Attribute) attr;
        if (localAttr.getName().equalsIgnoreCase("type")) {
          component = localAttr.getValue() + "." + component;
        }
        attrMap.put(localAttr.getName(), localAttr.getValue().toString());
      }
      mbeanMap.put(component, attrMap);
    } catch (Exception e) {
      LOG.error("Unable to poll JMX for metrics.", e);
    }
  }
  return mbeanMap;
}
项目:lams    文件:MBeanClientInterceptor.java   
private Object invokeAttribute(PropertyDescriptor pd, MethodInvocation invocation)
        throws JMException, IOException {

    String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing);
    MBeanAttributeInfo inf = 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.serverToUse.getAttribute(this.objectName, attributeName);
        }
        else {
            throw new InvalidInvocationException("Attribute '" + attributeName + "' is not readable");
        }
    }
    else if (invocation.getMethod().equals(pd.getWriteMethod())) {
        if (inf.isWritable()) {
            this.serverToUse.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");
    }
}
项目:lams    文件:JMXProxyServlet.java   
public void setAttribute( PrintWriter writer,
                          String onameStr, String att, String val )
{
    try {
        ObjectName oname=new ObjectName( onameStr );
        String type=registry.getType(oname, att);
        Object valueObj=registry.convertValue(type, val );
        mBeanServer.setAttribute( oname, new Attribute(att, valueObj));
        writer.println("OK - Attribute set");
    } catch( Exception ex ) {
        writer.println("Error - " + ex.toString());
    }
}
项目:lazycat    文件:MbeansSource.java   
private void processAttribute(MBeanServer server, Node descN, String objectName) {
    String attName = DomUtil.getAttribute(descN, "name");
    String value = DomUtil.getAttribute(descN, "value");
    String type = null; // DomUtil.getAttribute(descN, "type");
    if (value == null) {
        // The value may be specified as CDATA
        value = DomUtil.getContent(descN);
    }
    try {
        if (log.isDebugEnabled())
            log.debug("Set attribute " + objectName + " " + attName + " " + value);
        ObjectName oname = new ObjectName(objectName);
        // find the type
        type = registry.getType(oname, attName);

        if (type == null) {
            log.info("Can't find attribute " + objectName + " " + attName);

        } else {
            Object valueO = registry.convertValue(type, value);
            server.setAttribute(oname, new Attribute(attName, valueO));
        }
    } catch (Exception ex) {
        log.error("Error processing attribute " + objectName + " " + attName + " " + value, ex);
    }

}
项目:lams    文件:MbeansSource.java   
private void processAttribute(MBeanServer server,
                              Node descN, String objectName ) {
    String attName=DomUtil.getAttribute(descN, "name");
    String value=DomUtil.getAttribute(descN, "value");
    String type=null; // DomUtil.getAttribute(descN, "type");
    if( value==null ) {
        // The value may be specified as CDATA
        value=DomUtil.getContent(descN);
    }
    try {
        if( log.isDebugEnabled())
            log.debug("Set attribute " + objectName + " " + attName +
                    " " + value);
        ObjectName oname=new ObjectName(objectName);
        // find the type
        if( type==null )
            type=registry.getType(  oname, attName );

        if( type==null ) {
            log.info("Can't find attribute " + objectName + " " + attName );

        } else {
            Object valueO=registry.convertValue( type, value);
            server.setAttribute(oname, new Attribute(attName, valueO));
        }
    } catch( Exception ex) {
        log.error("Error processing attribute " + objectName + " " +
                attName + " " + value, ex);
    }

}
项目:openjdk-jdk10    文件:MBeanServerDelegateImpl.java   
/**
 * Makes it possible to get the values of several attributes of
 * the MBeanServerDelegate.
 *
 * @param attributes A list of the attributes to be retrieved.
 *
 * @return  The list of attributes retrieved.
 *
 */
public AttributeList getAttributes(String[] attributes) {
    // If attributes is null, the get all attributes.
    //
    final String[] attn = (attributes==null?attributeNames:attributes);

    // Prepare the result list.
    //
    final int len = attn.length;
    final AttributeList list = new AttributeList(len);

    // Get each requested attribute.
    //
    for (int i=0;i<len;i++) {
        try {
            final Attribute a =
                new Attribute(attn[i],getAttribute(attn[i]));
            list.add(a);
        } catch (Exception x) {
            // Skip the attribute that couldn't be obtained.
            //
            if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) {
                MBEANSERVER_LOGGER.log(Level.TRACE,
                        "Attribute " + attn[i] + " not found");
            }
        }
    }

    // Finally return the result.
    //
    return list;
}
项目:OpenJSharp    文件:MBeanServerDelegateImpl.java   
/**
 * This method always fail since all MBeanServerDelegateMBean attributes
 * are read-only.
 *
 * @param attribute The identification of the attribute to
 * be set and  the value it is to be set to.
 *
 * @exception AttributeNotFoundException
 */
public void setAttribute(Attribute attribute)
    throws AttributeNotFoundException, InvalidAttributeValueException,
           MBeanException, ReflectionException {

    // Now we will always fail:
    // Either because the attribute is null or because it is not
    // accessible (or does not exist).
    //
    final String attname = (attribute==null?null:attribute.getName());
    if (attname == null) {
        final RuntimeException r =
            new IllegalArgumentException("Attribute name cannot be null");
        throw new RuntimeOperationsException(r,
            "Exception occurred trying to invoke the setter on the MBean");
    }

    // This is a hack: we call getAttribute in order to generate an
    // AttributeNotFoundException if the attribute does not exist.
    //
    Object val = getAttribute(attname);

    // If we reach this point, we know that the requested attribute
    // exists. However, since all attributes are read-only, we throw
    // an AttributeNotFoundException.
    //
    throw new AttributeNotFoundException(attname + " not accessible");
}
项目:OpenJSharp    文件:MBeanServerDelegateImpl.java   
/**
 * Makes it possible to get the values of several attributes of
 * the MBeanServerDelegate.
 *
 * @param attributes A list of the attributes to be retrieved.
 *
 * @return  The list of attributes retrieved.
 *
 */
public AttributeList getAttributes(String[] attributes) {
    // If attributes is null, the get all attributes.
    //
    final String[] attn = (attributes==null?attributeNames:attributes);

    // Prepare the result list.
    //
    final int len = attn.length;
    final AttributeList list = new AttributeList(len);

    // Get each requested attribute.
    //
    for (int i=0;i<len;i++) {
        try {
            final Attribute a =
                new Attribute(attn[i],getAttribute(attn[i]));
            list.add(a);
        } catch (Exception x) {
            // Skip the attribute that couldn't be obtained.
            //
            if (MBEANSERVER_LOGGER.isLoggable(Level.FINEST)) {
                MBEANSERVER_LOGGER.logp(Level.FINEST,
                        MBeanServerDelegateImpl.class.getName(),
                        "getAttributes",
                        "Attribute " + attn[i] + " not found");
            }
        }
    }

    // Finally return the result.
    //
    return list;
}