Java Code Examples for javax.management.Attribute

The following are top voted examples for showing how to use javax.management.Attribute. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: keyboard-light-composer   File: CpuUsage.java   Source Code and License 7 votes vote down vote up
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;
	}
 
Example 2
Project: hadoop-oss   File: MetricsDynamicMBeanBase.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 3
Project: hashsdn-controller   File: DynamicWritableWrapper.java   Source Code and License 6 votes vote down vote up
@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);
    }

}
 
Example 4
Project: tomcat7   File: JMXAccessorSetTask.java   Source Code and License 6 votes vote down vote up
/**
 * @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;
}
 
Example 5
Project: tomcat7   File: BaseModelMBean.java   Source Code and License 6 votes vote down vote up
/**
 * 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);

}
 
Example 6
Project: tomcat7   File: BaseModelMBean.java   Source Code and License 6 votes vote down vote up
/**
 * 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));

}
 
Example 7
Project: tomcat7   File: BaseModelMBean.java   Source Code and License 6 votes vote down vote up
/**
 * 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);

}
 
Example 8
Project: twitch4j-chatbot   File: Diagnostics.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 9
Project: lams   File: BaseModelMBean.java   Source Code and License 6 votes vote down vote up
/**
 * 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);

}
 
Example 10
Project: ibm-cos-sdk-java   File: JmxInfoProviderSupport.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 11
Project: jdk8u-jdk   File: RMIConnectorLogAttributesTest.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 12
Project: hashsdn-controller   File: AbstractDynamicWrapperTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 13
Project: OpenJSharp   File: RMIConnector.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 14
Project: monarch   File: MX4JModelMBean.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 15
Project: monarch   File: MX4JModelMBean.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 16
Project: ChronoBike   File: BaseCloseMBean.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 17
Project: apache-tomcat-7.0.73-with-comment   File: JMXAccessorSetTask.java   Source Code and License 6 votes vote down vote up
/**
 * @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;
}
 
Example 18
Project: hashsdn-controller   File: DynamicWritableWrapperTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 19
Project: apache-tomcat-7.0.73-with-comment   File: BaseModelMBean.java   Source Code and License 6 votes vote down vote up
/**
 * 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);

}
 
Example 20
Project: momo-2   File: Diagnostics.java   Source Code and License 6 votes vote down vote up
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;
	}
}
 
Example 21
Project: openjdk-jdk10   File: RMIConnector.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 22
Project: lazycat   File: BaseModelMBean.java   Source Code and License 6 votes vote down vote up
/**
 * 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);

}
 
Example 23
Project: hashsdn-controller   File: DynamicWritableWrapper.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 24
Project: Pogamut3   File: FolderMBean.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 25
Project: kmanager   File: JMXTest.java   Source Code and License 5 votes vote down vote up
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) {

      }
    }
  });

}
 
Example 26
Project: Pogamut3   File: AttributeToPropertyAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public void setValue(Object newValue) throws IntrospectionException {
    try {
        folderMBean.setAttribute(new Attribute(getName(), newValue));
    } catch (Exception ex) {
        throw new IntrospectionException(ex);
    }
}
 
Example 27
Project: hadoop-oss   File: MetricsSourceAdapter.java   Source Code and License 5 votes vote down vote up
@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();
  }
}
 
Example 28
Project: openjdk-jdk10   File: MBeanExceptionTest.java   Source Code and License 5 votes vote down vote up
public void setAttribute(Attribute attr)
        throws MBeanException {
    String attrName = attr.getName();
    if (attrName.equals("UncheckedException"))
        throw theUncheckedException;
    else
        throw new AssertionError();
}
 
Example 29
Project: tqdev-metrics   File: JmxReporter.java   Source Code and License 5 votes vote down vote up
@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");
	}
}
 
Example 30
Project: openjdk-jdk10   File: RequiredModelMBean.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 31
Project: tomcat7   File: MbeansSource.java   Source Code and License 5 votes vote down vote up
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);
    }

}
 
Example 32
Project: hashsdn-controller   File: MergeEditConfigStrategy.java   Source Code and License 5 votes vote down vote up
@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);
        }
    }
}
 
Example 33
Project: flume-release-1.7.0   File: JMXPollUtil.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 34
Project: lams   File: MBeanClientInterceptor.java   Source Code and License 5 votes vote down vote up
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");
	}
}
 
Example 35
Project: lams   File: JMXProxyServlet.java   Source Code and License 5 votes vote down vote up
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());
    }
}
 
Example 36
Project: lazycat   File: MbeansSource.java   Source Code and License 5 votes vote down vote up
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);
	}

}
 
Example 37
Project: lams   File: MbeansSource.java   Source Code and License 5 votes vote down vote up
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);
    }

}
 
Example 38
Project: openjdk-jdk10   File: MBeanServerDelegateImpl.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 39
Project: OpenJSharp   File: MBeanServerDelegateImpl.java   Source Code and License 5 votes vote down vote up
/**
 * 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");
}
 
Example 40
Project: OpenJSharp   File: MBeanServerDelegateImpl.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 41
Project: OpenJSharp   File: MXBeanProxy.java   Source Code and License 5 votes vote down vote up
@Override
Object invoke(MBeanServerConnection mbsc, ObjectName name, Object[] args)
        throws Exception {
    assert(args.length == 1);
    Attribute attr = new Attribute(getName(), args[0]);
    mbsc.setAttribute(name, attr);
    return null;
}
 
Example 42
Project: openjdk-jdk10   File: MBeanSupport.java   Source Code and License 5 votes vote down vote up
public final AttributeList setAttributes(AttributeList attributes) {
    final AttributeList result = new AttributeList(attributes.size());
    for (Object attrObj : attributes) {
        // We can't use AttributeList.asList because it has side-effects
        Attribute attr = (Attribute) attrObj;
        try {
            setAttribute(attr);
            result.add(new Attribute(attr.getName(), attr.getValue()));
        } catch (Exception e) {
            // OK: attribute is not included in returned list, per spec
            // XXX: log the exception
        }
    }
    return result;
}
 
Example 43
Project: OpenJSharp   File: JmxMBeanServer.java   Source Code and License 5 votes vote down vote up
/**
 * Clone attribute.
 */
private Attribute cloneAttribute(Attribute attribute) {
    if (attribute != null) {
        if (!attribute.getClass().equals(Attribute.class)) {
            return new Attribute(attribute.getName(), attribute.getValue());
        }
    }
    return attribute;
}
 
Example 44
Project: OpenJSharp   File: MBeanSupport.java   Source Code and License 5 votes vote down vote up
public final AttributeList getAttributes(String[] attributes) {
    final AttributeList result = new AttributeList(attributes.length);
    for (String attrName : attributes) {
        try {
            final Object attrValue = getAttribute(attrName);
            result.add(new Attribute(attrName, attrValue));
        } catch (Exception e) {
            // OK: attribute is not included in returned list, per spec
            // XXX: log the exception
        }
    }
    return result;
}
 
Example 45
Project: OpenJSharp   File: MBeanSupport.java   Source Code and License 5 votes vote down vote up
public final void setAttribute(Attribute attribute)
        throws AttributeNotFoundException,
               InvalidAttributeValueException,
               MBeanException,
               ReflectionException {
    final String name = attribute.getName();
    final Object value = attribute.getValue();
    perInterface.setAttribute(resource, name, value, getCookie());
}
 
Example 46
Project: OpenJSharp   File: MBeanSupport.java   Source Code and License 5 votes vote down vote up
public final AttributeList setAttributes(AttributeList attributes) {
    final AttributeList result = new AttributeList(attributes.size());
    for (Object attrObj : attributes) {
        // We can't use AttributeList.asList because it has side-effects
        Attribute attr = (Attribute) attrObj;
        try {
            setAttribute(attr);
            result.add(new Attribute(attr.getName(), attr.getValue()));
        } catch (Exception e) {
            // OK: attribute is not included in returned list, per spec
            // XXX: log the exception
        }
    }
    return result;
}
 
Example 47
Project: OpenJSharp   File: SnmpGenericObjectServer.java   Source Code and License 5 votes vote down vote up
/**
 * Set the value of an SNMP variable.
 *
 * <p><b><i>
 * You should never need to use this method directly.
 * </i></b></p>
 *
 * @param meta  The impacted metadata object
 * @param name  The ObjectName of the impacted MBean
 * @param x     The new requested SnmpValue
 * @param id    The OID arc identifying the variable we're trying to set.
 * @param data  User contextual data allocated through the
 *        {@link com.sun.jmx.snmp.agent.SnmpUserDataFactory}
 *
 * @return The new value of the variable after the operation.
 *
 * @exception SnmpStatusException whenever an SNMP exception must be
 *      raised. Raising an exception will abort the request. <br>
 *      Exceptions should never be raised directly, but only by means of
 * <code>
 * req.registerSetException(<i>VariableId</i>,<i>SnmpStatusException</i>)
 * </code>
 **/
public SnmpValue set(SnmpGenericMetaServer meta, ObjectName name,
                     SnmpValue x, long id, Object data)
    throws SnmpStatusException {
    final String attname = meta.getAttributeName(id);
    final Object attvalue=
        meta.buildAttributeValue(id,x);
    final Attribute att = new Attribute(attname,attvalue);

    Object result = null;

    try {
        server.setAttribute(name,att);
        result = server.getAttribute(name,attname);
    } catch(InvalidAttributeValueException iv) {
        throw new
            SnmpStatusException(SnmpStatusException.snmpRspWrongValue);
    } catch (InstanceNotFoundException f) {
        throw new
            SnmpStatusException(SnmpStatusException.snmpRspInconsistentName);
    } catch (ReflectionException r) {
        throw new
            SnmpStatusException(SnmpStatusException.snmpRspInconsistentName);
    } catch (MBeanException m) {
        Exception t = m.getTargetException();
        if (t instanceof SnmpStatusException)
            throw (SnmpStatusException) t;
        throw new
            SnmpStatusException(SnmpStatusException.noAccess);
    } catch (Exception e) {
        throw new
            SnmpStatusException(SnmpStatusException.noAccess);
    }

    return meta.buildSnmpValue(id,result);
}
 
Example 48
Project: OpenJSharp   File: MBeanServerAccessController.java   Source Code and License 5 votes vote down vote up
/**
 * Call <code>checkWrite()</code>, then forward this method to the
 * wrapped object.
 */
public void setAttribute(ObjectName name, Attribute attribute)
    throws
    InstanceNotFoundException,
    AttributeNotFoundException,
    InvalidAttributeValueException,
    MBeanException,
    ReflectionException {
    checkWrite();
    getMBeanServer().setAttribute(name, attribute);
}
 
Example 49
Project: OpenJSharp   File: RequiredModelMBean.java   Source Code and License 5 votes vote down vote up
/**
 * 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.FINER)) {
        MODELMBEAN_LOGGER.logp(Level.FINER,
                RequiredModelMBean.class.getName(),
            "setAttribute(Attribute)", "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;
}
 
Example 50
Project: openjdk-jdk10   File: MBeanSupport.java   Source Code and License 5 votes vote down vote up
public final AttributeList getAttributes(String[] attributes) {
    final AttributeList result = new AttributeList(attributes.length);
    for (String attrName : attributes) {
        try {
            final Object attrValue = getAttribute(attrName);
            result.add(new Attribute(attrName, attrValue));
        } catch (Exception e) {
            // OK: attribute is not included in returned list, per spec
            // XXX: log the exception
        }
    }
    return result;
}
 
Example 51
Project: monarch   File: MBeanServerWrapper.java   Source Code and License 5 votes vote down vote up
@Override
public void setAttribute(ObjectName name, Attribute attribute)
    throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException,
    MBeanException, ReflectionException {
  ResourcePermission ctx = getOperationContext(name, attribute.getName(), false);
  this.securityService.authorize(ctx);
  mbs.setAttribute(name, attribute);
}
 
Example 52
Project: monarch   File: MBeanServerWrapper.java   Source Code and License 5 votes vote down vote up
@Override
public AttributeList setAttributes(ObjectName name, AttributeList attributes)
    throws InstanceNotFoundException, ReflectionException {
  // call setAttribute instead to use the authorization logic
  for (Attribute attribute : attributes.asList()) {
    try {
      setAttribute(name, attribute);
    } catch (Exception e) {
      throw new GemFireSecurityException("error setting attribute " + attribute + " of " + name,
          e);
    }
  }
  return attributes;
}
 
Example 53
Project: monarch   File: OffHeapManagementDUnitTest.java   Source Code and License 5 votes vote down vote up
/**
 * Creates and adds a generic GaugeMonitor for an attribute of the MemberMXBean.
 * 
 * @param attribute the attribute to monitor.
 * @param highThreshold the high threshold trigger.
 * @param lowThreshold the low threshold trigger.
 */
protected void setupOffHeapMonitor(String attribute, long highThreshold, long lowThreshold) {
  ObjectName memberMBeanObjectName = MBeanJMXAdapter.getMemberMBeanName(
      InternalDistributedSystem.getConnectedInstance().getDistributedMember());
  assertNotNull(memberMBeanObjectName);

  try {
    ObjectName offHeapMonitorName = new ObjectName("monitors:type=Gauge,attr=" + attribute);
    mbeanServer.createMBean("javax.management.monitor.GaugeMonitor", offHeapMonitorName);

    AttributeList al = new AttributeList();
    al.add(new Attribute("ObservedObject", memberMBeanObjectName));
    al.add(new Attribute("GranularityPeriod", 500));
    al.add(new Attribute("ObservedAttribute", attribute));
    al.add(new Attribute("Notify", true));
    al.add(new Attribute("NotifyHigh", true));
    al.add(new Attribute("NotifyLow", true));
    al.add(new Attribute("HighTheshold", highThreshold));
    al.add(new Attribute("LowThreshold", lowThreshold));

    mbeanServer.setAttributes(offHeapMonitorName, al);
    mbeanServer.addNotificationListener(offHeapMonitorName, notificationListener, null, null);
    mbeanServer.invoke(offHeapMonitorName, "start", new Object[] {}, new String[] {});
  } catch (Exception e) {
    fail(e.getMessage());
  }
}
 
Example 54
Project: jdk8u-jdk   File: OldMBeanServerTest.java   Source Code and License 5 votes vote down vote up
public AttributeList setAttributes(AttributeList attributes) {
    AttributeList list = new AttributeList();
    // We carefully avoid using any new stuff from AttributeList here!
    for (Iterator<?> it = attributes.iterator(); it.hasNext(); ) {
        Attribute attr = (Attribute) it.next();
        try {
            setAttribute(attr);
            list.add(attr);
        } catch (Exception e) {
            // OK: ignore per spec
        }
    }
    return list;
}
 
Example 55
Project: ChronoBike   File: BaseCloseMBean.java   Source Code and License 5 votes vote down vote up
public AttributeList setAttributes(AttributeList attributes) 
 {
       // Check attributes is not null to avoid NullPointerException later on
       //
       if (attributes != null) 
       {
        AttributeList resultList = new AttributeList();

        // If attributeNames is empty, nothing more to do
        //
        if (attributes.isEmpty())
            return resultList;

        // For each attribute, try to set it and add to the result list if
        // successfull
        //
        for (Iterator i = attributes.iterator(); i.hasNext();)
        {
            Attribute attr = (Attribute) i.next();
            try
            {
                setAttribute(attr);
                String name = attr.getName();
                Object value = getAttribute(name); 
                resultList.add(new Attribute(name,value));
            } 
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        return resultList;
   	}
       return null;
}
 
Example 56
Project: apache-tomcat-7.0.73-with-comment   File: JMXProxyServlet.java   Source Code and License 5 votes vote down vote up
/**
 * Sets an MBean attribute's value.
 */
private void setAttributeInternal(String onameStr,
                                  String attributeName,
                                  String value)
    throws OperationsException, MBeanException, ReflectionException {
    ObjectName oname=new ObjectName( onameStr );
    String type=registry.getType(oname, attributeName);
    Object valueObj=registry.convertValue(type, value );
    mBeanServer.setAttribute( oname, new Attribute(attributeName, valueObj));
}
 
Example 57
Project: apache-tomcat-7.0.73-with-comment   File: MbeansSource.java   Source Code and License 5 votes vote down vote up
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);
    }

}
 
Example 58
Project: openjdk-jdk10   File: MBeanServerAccessController.java   Source Code and License 5 votes vote down vote up
/**
 * Call <code>checkWrite()</code>, then forward this method to the
 * wrapped object.
 */
public void setAttribute(ObjectName name, Attribute attribute)
    throws
    InstanceNotFoundException,
    AttributeNotFoundException,
    InvalidAttributeValueException,
    MBeanException,
    ReflectionException {
    checkWrite();
    getMBeanServer().setAttribute(name, attribute);
}
 
Example 59
Project: hadoop   File: MetricsSourceAdapter.java   Source Code and License 5 votes vote down vote up
@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();
  }
}
 
Example 60
Project: jdk8u-jdk   File: MBeanExceptionTest.java   Source Code and License 5 votes vote down vote up
public void setAttribute(Attribute attr)
        throws MBeanException {
    String attrName = attr.getName();
    if (attrName.equals("UncheckedException"))
        throw theUncheckedException;
    else
        throw new AssertionError();
}