javax.management.Attribute Java Examples

The following examples show how to use javax.management.Attribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JMXAccessorSetTask.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Set property value.
 *
 * @param jmxServerConnection Connection to the JMX server
 * @param name The MBean name
 * @return null (no error message to report other than exception)
 * @throws Exception An error occurred
 */
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 #2
Source File: RMIConnector.java    From TencentKona-8 with GNU General Public License v2.0 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 #3
Source File: RMIConnectorLogAttributesTest.java    From TencentKona-8 with GNU General Public License v2.0 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 #4
Source File: RMIConnector.java    From openjdk-jdk8u with GNU General Public License v2.0 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 #5
Source File: RMIConnector.java    From dragonwell8_jdk with GNU General Public License v2.0 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 #6
Source File: JmxClient.java    From vjtools with Apache License 2.0 6 votes vote down vote up
private synchronized NameValueMap getCachedAttributes(ObjectName objName, Set<String> attrNames)
		throws InstanceNotFoundException, ReflectionException, IOException {
	NameValueMap values = cachedValues.get(objName);
	if (values != null && values.keySet().containsAll(attrNames)) {
		return values;
	}
	attrNames = new TreeSet<String>(attrNames);
	Set<String> oldNames = cachedNames.get(objName);
	if (oldNames != null) {
		attrNames.addAll(oldNames);
	}
	values = new NameValueMap();
	final AttributeList attrs = conn.getAttributes(objName, attrNames.toArray(new String[attrNames.size()]));
	for (Attribute attr : attrs.asList()) {
		values.put(attr.getName(), attr.getValue());
	}
	cachedValues.put(objName, values);
	cachedNames.put(objName, attrNames);
	return values;
}
 
Example #7
Source File: MBeanClientInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
private Object invokeAttribute(PropertyDescriptor pd, MethodInvocation invocation)
		throws JMException, IOException {

	Assert.state(this.serverToUse != null, "No MBeanServerConnection available");

	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 #8
Source File: MBeanServerDelegateImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 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 #9
Source File: JMXProxyServlet.java    From Tomcat8-Source-Read with MIT 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 #10
Source File: OldMBeanServerTest.java    From dragonwell8_jdk with GNU General Public License v2.0 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 #11
Source File: OldMBeanServerTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public AttributeList getAttributes(String[] attributes) {
    AttributeList list = new AttributeList();
    for (String attr : attributes) {
        try {
            list.add(new Attribute(attr, getAttribute(attr)));
        } catch (Exception e) {
            // OK: ignore per spec
        }
    }
    return list;
}
 
Example #12
Source File: MBeanServerAccessController.java    From TencentKona-8 with GNU General Public License v2.0 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 #13
Source File: SnmpGenericObjectServer.java    From JDKSourceCode1.8 with MIT 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 #14
Source File: AuthorizationTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
protected int doSetRequest(MBeanServerConnection mbsc,
                           ObjectName on,
                           boolean expectedException) {
    int errorCount = 0;

    try {
        Utils.debug(Utils.DEBUG_STANDARD,
            "ClientSide::doSetRequest: Set attributes of the MBean") ;

        Attribute attribute = new Attribute("Attribute", "My value") ;
        mbsc.setAttribute(on, attribute) ;

        if (expectedException) {
            System.out.println("ClientSide::doSetRequest: " +
                "(ERROR) Set did not fail with expected SecurityException");
            errorCount++;
        } else {
            System.out.println("ClientSide::doSetRequest: (OK) Set succeed") ;
        }
    } catch(Exception e) {
        Utils.printThrowable(e, true) ;
        if (expectedException) {
            if (e instanceof java.lang.SecurityException) {
                System.out.println("ClientSide::doSetRequest: " +
                    "(OK) Set failed with expected SecurityException") ;
            } else {
                System.out.println("ClientSide::doSetRequest: " +
                    "(ERROR) Set failed with " +
                    e.getClass() + " instead of expected SecurityException");
                errorCount++;
            }
        } else {
            System.out.println("ClientSide::doSetRequest: (ERROR) Set failed");
            errorCount++;
        }
    }
    return errorCount;
}
 
Example #15
Source File: MBeanExceptionTest.java    From TencentKona-8 with GNU General Public License v2.0 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 #16
Source File: MBeanExporterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testWithExposeClassLoader() throws Exception {
	String name = "Rob Harrop";
	String otherName = "Juergen Hoeller";

	JmxTestBean bean = new JmxTestBean();
	bean.setName(name);
	ObjectName objectName = ObjectNameManager.getInstance("spring:type=Test");

	Map<String, Object> beans = new HashMap<>();
	beans.put(objectName.toString(), bean);

	MBeanExporter exporter = new MBeanExporter();
	exporter.setServer(getServer());
	exporter.setBeans(beans);
	exporter.setExposeManagedResourceClassLoader(true);
	start(exporter);

	assertIsRegistered("Bean instance not registered", objectName);

	Object result = server.invoke(objectName, "add", new Object[] {new Integer(2), new Integer(3)}, new String[] {
			int.class.getName(), int.class.getName()});

	assertEquals("Incorrect result return from add", result, new Integer(5));
	assertEquals("Incorrect attribute value", name, server.getAttribute(objectName, "Name"));

	server.setAttribute(objectName, new Attribute("Name", otherName));
	assertEquals("Incorrect updated name.", otherName, bean.getName());
}
 
Example #17
Source File: RequiredModelMBean.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the values of several attributes in the ModelMBean.
 * Executes a getAttribute for each attribute name in the
 * attrNames array passed in.
 *
 * @param attrNames A String array of names of the attributes
 * to be retrieved.
 *
 * @return The array of the retrieved attributes.
 *
 * @exception RuntimeOperationsException Wraps an
 * {@link IllegalArgumentException}: The object name in parameter is
 * null or attributes in parameter is null.
 *
 * @see #setAttributes(javax.management.AttributeList)
 */
public AttributeList getAttributes(String[] attrNames)      {
    if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
        MODELMBEAN_LOGGER.logp(Level.FINER,
                RequiredModelMBean.class.getName(),
        "getAttributes(String[])","Entry");
    }

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

    AttributeList responseList = new AttributeList();
    for (int i = 0; i < attrNames.length; i++) {
        try {
            responseList.add(new Attribute(attrNames[i],
                                 getAttribute(attrNames[i])));
        } catch (Exception e) {
            // eat exceptions because interface doesn't have an
            // exception on it
            if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
                MODELMBEAN_LOGGER.logp(Level.FINER,
                        RequiredModelMBean.class.getName(),
                    "getAttributes(String[])",
                        "Failed to get \"" + attrNames[i] + "\": ", e);
            }
        }
    }

    if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
        MODELMBEAN_LOGGER.logp(Level.FINER,
            RequiredModelMBean.class.getName(),
                "getAttributes(String[])","Exit");
    }

    return responseList;
}
 
Example #18
Source File: MBeanServerDelegateImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 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 #19
Source File: JmxClient.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private AttributeList getAttributes(ObjectName objName, String[] attrNames)
		throws InstanceNotFoundException, ReflectionException, IOException {
	final NameValueMap values = getCachedAttributes(objName, new TreeSet<String>(Arrays.asList(attrNames)));
	final AttributeList list = new AttributeList();
	for (String attrName : attrNames) {
		final Object value = values.get(attrName);
		if (value != null || values.containsKey(attrName)) {
			list.add(new Attribute(attrName, value));
		}
	}
	return list;
}
 
Example #20
Source File: SpringModelMBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Switches the {@link Thread#getContextClassLoader() context ClassLoader} for the
 * managed resources {@link ClassLoader} before allowing the invocation to occur.
 * @see javax.management.modelmbean.ModelMBean#setAttribute
 */
@Override
public void setAttribute(Attribute attribute)
		throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {

	ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
	try {
		Thread.currentThread().setContextClassLoader(this.managedResourceClassLoader);
		super.setAttribute(attribute);
	}
	finally {
		Thread.currentThread().setContextClassLoader(currentClassLoader);
	}
}
 
Example #21
Source File: MBeanServerDelegateImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 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 #22
Source File: XMBeanAttributes.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void tableChanged(final TableModelEvent e) {
    // only post changes to the draggable column
    if (isColumnEditable(e.getColumn())) {
        final TableModel model = (TableModel)e.getSource();
        Object tableValue = model.getValueAt(e.getFirstRow(),
                                         e.getColumn());

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.finer("tableChanged: firstRow="+e.getFirstRow()+
                ", lastRow="+e.getLastRow()+", column="+e.getColumn()+
                ", value="+tableValue);
        }
        // if it's a String, try construct new value
        // using the defined type.
        if (tableValue instanceof String) {
            try {
                tableValue =
                    Utils.createObjectFromString(getClassName(e.getFirstRow()), // type
                    (String)tableValue);// value
            } catch (Throwable ex) {
                popupAndLog(ex,"tableChanged",
                            Messages.PROBLEM_SETTING_ATTRIBUTE);
            }
        }
        final String attributeName = getValueName(e.getFirstRow());
        final Attribute attribute =
              new Attribute(attributeName,tableValue);
        setAttribute(attribute, "tableChanged");
    }
}
 
Example #23
Source File: RMIConnector.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
static String getAttributesNames(AttributeList attributes) {
    return attributes != null ?
            attributes.asList().stream()
                    .map(Attribute::getName)
                    .collect(Collectors.joining(", ", "[", "]"))
            : "[]";
}
 
Example #24
Source File: RequiredModelMBean.java    From jdk1.8-source-analysis with Apache License 2.0 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 #25
Source File: RequiredModelMBean.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the values of several attributes in the ModelMBean.
 * Executes a getAttribute for each attribute name in the
 * attrNames array passed in.
 *
 * @param attrNames A String array of names of the attributes
 * to be retrieved.
 *
 * @return The array of the retrieved attributes.
 *
 * @exception RuntimeOperationsException Wraps an
 * {@link IllegalArgumentException}: The object name in parameter is
 * null or attributes in parameter is null.
 *
 * @see #setAttributes(javax.management.AttributeList)
 */
public AttributeList getAttributes(String[] attrNames)      {
    if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
        MODELMBEAN_LOGGER.logp(Level.FINER,
                RequiredModelMBean.class.getName(),
        "getAttributes(String[])","Entry");
    }

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

    AttributeList responseList = new AttributeList();
    for (int i = 0; i < attrNames.length; i++) {
        try {
            responseList.add(new Attribute(attrNames[i],
                                 getAttribute(attrNames[i])));
        } catch (Exception e) {
            // eat exceptions because interface doesn't have an
            // exception on it
            if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
                MODELMBEAN_LOGGER.logp(Level.FINER,
                        RequiredModelMBean.class.getName(),
                    "getAttributes(String[])",
                        "Failed to get \"" + attrNames[i] + "\": ", e);
            }
        }
    }

    if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
        MODELMBEAN_LOGGER.logp(Level.FINER,
            RequiredModelMBean.class.getName(),
                "getAttributes(String[])","Exit");
    }

    return responseList;
}
 
Example #26
Source File: MBeanServerAccessController.java    From jdk1.8-source-analysis with Apache License 2.0 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 #27
Source File: NotificationListenerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testRegisterNotificationListenerWithObjectNameBeforeBeanNameMappedToSameBeanInstance() throws Exception {
	String beanName = "testBean";
	ObjectName objectName = ObjectName.getInstance("spring:name=Test");

	SelfNamingTestBean testBean = new SelfNamingTestBean();
	testBean.setObjectName(objectName);

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerSingleton(beanName, testBean);

	Map<String, Object> beans = new HashMap<>();
	beans.put(beanName, testBean);

	Map listenerMappings = new HashMap();
	CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
	listenerMappings.put(objectName, listener);
	listenerMappings.put(beanName, listener);

	MBeanExporter exporter = new MBeanExporter();
	exporter.setServer(server);
	exporter.setBeans(beans);
	exporter.setNotificationListenerMappings(listenerMappings);
	exporter.setBeanFactory(factory);
	start(exporter);
	assertIsRegistered("Should have registered MBean", objectName);

	server.setAttribute(objectName, new Attribute("Age", new Integer(77)));
	assertEquals("Listener should have been notified exactly once", 1, listener.getCount("Age"));
}
 
Example #28
Source File: XMBeanAttributes.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void tableChanged(final TableModelEvent e) {
    // only post changes to the draggable column
    if (isColumnEditable(e.getColumn())) {
        final TableModel model = (TableModel)e.getSource();
        Object tableValue = model.getValueAt(e.getFirstRow(),
                                         e.getColumn());

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.finer("tableChanged: firstRow="+e.getFirstRow()+
                ", lastRow="+e.getLastRow()+", column="+e.getColumn()+
                ", value="+tableValue);
        }
        // if it's a String, try construct new value
        // using the defined type.
        if (tableValue instanceof String) {
            try {
                tableValue =
                    Utils.createObjectFromString(getClassName(e.getFirstRow()), // type
                    (String)tableValue);// value
            } catch (Throwable ex) {
                popupAndLog(ex,"tableChanged",
                            Messages.PROBLEM_SETTING_ATTRIBUTE);
            }
        }
        final String attributeName = getValueName(e.getFirstRow());
        final Attribute attribute =
              new Attribute(attributeName,tableValue);
        setAttribute(attribute, "tableChanged");
    }
}
 
Example #29
Source File: JmxMBeanServer.java    From jdk1.8-source-analysis with Apache License 2.0 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 #30
Source File: NotificationListenerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testNotificationListenerRegistrar() throws Exception {
	ObjectName objectName = ObjectName.getInstance("spring:name=Test");
	JmxTestBean bean = new JmxTestBean();

	Map<String, Object> beans = new HashMap<>();
	beans.put(objectName.getCanonicalName(), bean);

	MBeanExporter exporter = new MBeanExporter();
	exporter.setServer(server);
	exporter.setBeans(beans);
	start(exporter);

	CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();

	NotificationListenerRegistrar registrar = new NotificationListenerRegistrar();
	registrar.setServer(server);
	registrar.setNotificationListener(listener);
	registrar.setMappedObjectName(objectName);
	registrar.afterPropertiesSet();

	// update the attribute
	String attributeName = "Name";
	server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
	assertEquals("Listener not notified", 1, listener.getCount(attributeName));

	registrar.destroy();

	// try to update the attribute again
	server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
	assertEquals("Listener notified after destruction", 1, listener.getCount(attributeName));
}