Search in sources :

Example 91 with MBeanException

use of javax.management.MBeanException in project jdk8u_jdk by JetBrains.

the class SnmpMibAgent method setSnmpAdaptorName.

/**
     * Sets the reference to the SNMP protocol adaptor through which the MIB
     * will be SNMP accessible and add this new MIB in the SNMP MIB handler
     * associated to the specified <CODE>name</CODE>.
     *
     * @param name The name of the SNMP protocol adaptor.
     * @param contextName The MIB context name. If null is passed, will be registered in the default context.
     * @param oids The set of OIDs this agent implements.
     * @exception InstanceNotFoundException The SNMP protocol adaptor does
     *     not exist in the MBean server.
     *
     * @exception ServiceNotFoundException This SNMP MIB is not registered
     *     in the MBean server or the requested service is not supported.
     *
     * @since 1.5
     */
@Override
public void setSnmpAdaptorName(ObjectName name, String contextName, SnmpOid[] oids) throws InstanceNotFoundException, ServiceNotFoundException {
    if (server == null) {
        throw new ServiceNotFoundException(mibName + " is not registered in the MBean server");
    }
    //
    if (adaptor != null) {
        adaptor.removeMib(this, contextName);
    }
    // Then update the reference to the new adaptor server.
    //
    Object[] params = { this, contextName, oids };
    String[] signature = { "com.sun.jmx.snmp.agent.SnmpMibAgent", "java.lang.String", oids.getClass().getName() };
    try {
        adaptor = (SnmpMibHandler) (server.invoke(name, "addMib", params, signature));
    } catch (InstanceNotFoundException e) {
        throw new InstanceNotFoundException(name.toString());
    } catch (ReflectionException e) {
        throw new ServiceNotFoundException(name.toString());
    } catch (MBeanException e) {
    // Should never occur...
    }
    adaptorName = name;
}
Also used : ReflectionException(javax.management.ReflectionException) ServiceNotFoundException(javax.management.ServiceNotFoundException) InstanceNotFoundException(javax.management.InstanceNotFoundException) MBeanException(javax.management.MBeanException)

Example 92 with MBeanException

use of javax.management.MBeanException in project jdk8u_jdk by JetBrains.

the class AddAttributeChangeNotificationListenerTest method run.

private void run(String[] args) throws Exception {
    int errCount = 0;
    String testName = "AddAttributeChangeNotificationListenerTest0001";
    ObjectName modelMBeanObjectName = null;
    ModelMBeanInfo modelMBeanInfo = null;
    MBeanServer mbeanserver = MBeanServerFactory.newMBeanServer();
    String modelMBeanName = "RequiredModelMBean";
    String modelMBeanClassName = "javax.management.modelmbean.RequiredModelMBean";
    modelMBeanObjectName = new ObjectName("AddAttributeChangeNotificationListenerTest:type=" + modelMBeanName);
    System.out.println("Build a ModelMBeanInfo without attribute State");
    modelMBeanInfo = createModelMBeanInfo();
    System.out.println("Create and register a RequiredModelMBean " + "with that MBeanInfo");
    Object[] params = { modelMBeanInfo };
    String[] sig = { "javax.management.modelmbean.ModelMBeanInfo" };
    mbeanserver.createMBean(modelMBeanClassName, modelMBeanObjectName, params, sig);
    ModelMBeanListener aListener = new ModelMBeanListener();
    // add an attribute change listener
    System.out.println("Add an attribute change listener for State");
    try {
        mbeanserver.invoke(modelMBeanObjectName, "addAttributeChangeNotificationListener", (new Object[] { aListener, "State", null }), (new String[] { "javax.management.NotificationListener", "java.lang.String", "java.lang.Object" }));
        System.out.println("NOK: Did not get expected " + "RuntimeOperationsException");
        errCount++;
    } catch (Exception e) {
        if (e instanceof MBeanException)
            e = ((MBeanException) e).getTargetException();
        if (e instanceof RuntimeOperationsException) {
            RuntimeOperationsException roe = (RuntimeOperationsException) e;
            Exception target = roe.getTargetException();
            System.out.println("OK: Got expected RuntimeOperationsException");
            if (target instanceof IllegalArgumentException) {
                System.out.println("OK: Got expected " + "wrapped IllegalArgumentException");
            } else {
                System.out.println("NOK: Got wrapped " + target + " as we expect IllegalArgumentException");
                errCount++;
            }
        } else {
            System.out.println("NOK: Got " + e + " as we expect RuntimeOperationsException");
            errCount++;
        }
    }
    if (errCount != 0)
        throw new Exception(errCount + " error(s) occured");
}
Also used : MBeanException(javax.management.MBeanException) RuntimeOperationsException(javax.management.RuntimeOperationsException) ObjectName(javax.management.ObjectName) MBeanException(javax.management.MBeanException) MBeanServer(javax.management.MBeanServer) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 93 with MBeanException

use of javax.management.MBeanException in project jdk8u_jdk by JetBrains.

the class RelationService method addRelation.

/**
     * Adds an MBean created by the user (and registered by him in the MBean
     * Server) as a relation in the Relation Service.
     * <P>To be added as a relation, the MBean must conform to the
     * following:
     * <P>- implement the Relation interface
     * <P>- have for RelationService ObjectName the ObjectName of current
     * Relation Service
     * <P>- have a relation id unique and unused in current Relation Service
     * <P>- have for relation type a relation type created in the Relation
     * Service
     * <P>- have roles conforming to the role info provided in the relation
     * type.
     *
     * @param relationObjectName  ObjectName of the relation MBean to be added.
     *
     * @exception IllegalArgumentException  if null parameter
     * @exception RelationServiceNotRegisteredException  if the Relation
     * Service is not registered in the MBean Server
     * @exception NoSuchMethodException  If the MBean does not implement the
     * Relation interface
     * @exception InvalidRelationIdException  if:
     * <P>- no relation identifier in MBean
     * <P>- the relation identifier is already used in the Relation Service
     * @exception InstanceNotFoundException  if the MBean for given ObjectName
     * has not been registered
     * @exception InvalidRelationServiceException  if:
     * <P>- no Relation Service name in MBean
     * <P>- the Relation Service name in the MBean is not the one of the
     * current Relation Service
     * @exception RelationTypeNotFoundException  if:
     * <P>- no relation type name in MBean
     * <P>- the relation type name in MBean does not correspond to a relation
     * type created in the Relation Service
     * @exception InvalidRoleValueException  if:
     * <P>- the number of referenced MBeans in a role is less than
     * expected minimum degree
     * <P>- the number of referenced MBeans in a role exceeds expected
     * maximum degree
     * <P>- one referenced MBean in the value is not an Object of the MBean
     * class expected for that role
     * <P>- an MBean provided for a role does not exist
     * @exception RoleNotFoundException  if a value is provided for a role
     * that does not exist in the relation type
     */
public void addRelation(ObjectName relationObjectName) throws IllegalArgumentException, RelationServiceNotRegisteredException, NoSuchMethodException, InvalidRelationIdException, InstanceNotFoundException, InvalidRelationServiceException, RelationTypeNotFoundException, RoleNotFoundException, InvalidRoleValueException {
    if (relationObjectName == null) {
        String excMsg = "Invalid parameter.";
        throw new IllegalArgumentException(excMsg);
    }
    RELATION_LOGGER.entering(RelationService.class.getName(), "addRelation", relationObjectName);
    // Can throw RelationServiceNotRegisteredException
    isActive();
    // registered MBean (else will throw an InstanceNotFoundException)
    if ((!(myMBeanServer.isInstanceOf(relationObjectName, "javax.management.relation.Relation")))) {
        String excMsg = "This MBean does not implement the Relation interface.";
        throw new NoSuchMethodException(excMsg);
    }
    // Checks there is a relation id in the relation MBean (its uniqueness
    // is checked in addRelationInt())
    // Can throw InstanceNotFoundException (but detected above)
    // No MBeanException as no exception raised by this method, and no
    // ReflectionException
    String relId;
    try {
        relId = (String) (myMBeanServer.getAttribute(relationObjectName, "RelationId"));
    } catch (MBeanException exc1) {
        throw new RuntimeException((exc1.getTargetException()).getMessage());
    } catch (ReflectionException exc2) {
        throw new RuntimeException(exc2.getMessage());
    } catch (AttributeNotFoundException exc3) {
        throw new RuntimeException(exc3.getMessage());
    }
    if (relId == null) {
        String excMsg = "This MBean does not provide a relation id.";
        throw new InvalidRelationIdException(excMsg);
    }
    // Checks that the Relation Service where the relation MBean is
    // expected to be added is the current one
    // Can throw InstanceNotFoundException (but detected above)
    // No MBeanException as no exception raised by this method, no
    // ReflectionException
    ObjectName relServObjName;
    try {
        relServObjName = (ObjectName) (myMBeanServer.getAttribute(relationObjectName, "RelationServiceName"));
    } catch (MBeanException exc1) {
        throw new RuntimeException((exc1.getTargetException()).getMessage());
    } catch (ReflectionException exc2) {
        throw new RuntimeException(exc2.getMessage());
    } catch (AttributeNotFoundException exc3) {
        throw new RuntimeException(exc3.getMessage());
    }
    boolean badRelServFlag = false;
    if (relServObjName == null) {
        badRelServFlag = true;
    } else if (!(relServObjName.equals(myObjName))) {
        badRelServFlag = true;
    }
    if (badRelServFlag) {
        String excMsg = "The Relation Service referenced in the MBean is not the current one.";
        throw new InvalidRelationServiceException(excMsg);
    }
    // Checks that a relation type has been specified for the relation
    // Can throw InstanceNotFoundException (but detected above)
    // No MBeanException as no exception raised by this method, no
    // ReflectionException
    String relTypeName;
    try {
        relTypeName = (String) (myMBeanServer.getAttribute(relationObjectName, "RelationTypeName"));
    } catch (MBeanException exc1) {
        throw new RuntimeException((exc1.getTargetException()).getMessage());
    } catch (ReflectionException exc2) {
        throw new RuntimeException(exc2.getMessage());
    } catch (AttributeNotFoundException exc3) {
        throw new RuntimeException(exc3.getMessage());
    }
    if (relTypeName == null) {
        String excMsg = "No relation type provided.";
        throw new RelationTypeNotFoundException(excMsg);
    }
    // Retrieves all roles without considering read mode
    // Can throw InstanceNotFoundException (but detected above)
    // No MBeanException as no exception raised by this method, no
    // ReflectionException
    RoleList roleList;
    try {
        roleList = (RoleList) (myMBeanServer.invoke(relationObjectName, "retrieveAllRoles", null, null));
    } catch (MBeanException exc1) {
        throw new RuntimeException((exc1.getTargetException()).getMessage());
    } catch (ReflectionException exc2) {
        throw new RuntimeException(exc2.getMessage());
    }
    // Can throw RoleNotFoundException, InvalidRelationIdException,
    // RelationTypeNotFoundException, InvalidRoleValueException
    addRelationInt(false, null, relationObjectName, relId, relTypeName, roleList);
    // Adds relation MBean ObjectName in map
    synchronized (myRelMBeanObjName2RelIdMap) {
        myRelMBeanObjName2RelIdMap.put(relationObjectName, relId);
    }
    // of the Relation interface, so may be not supported.
    try {
        myMBeanServer.setAttribute(relationObjectName, new Attribute("RelationServiceManagementFlag", Boolean.TRUE));
    } catch (Exception exc) {
    // OK : The flag is not supported.
    }
    // Updates listener information to received notification for
    // unregistration of this MBean
    List<ObjectName> newRefList = new ArrayList<ObjectName>();
    newRefList.add(relationObjectName);
    updateUnregistrationListener(newRefList, null);
    RELATION_LOGGER.exiting(RelationService.class.getName(), "addRelation");
    return;
}
Also used : ReflectionException(javax.management.ReflectionException) AttributeNotFoundException(javax.management.AttributeNotFoundException) Attribute(javax.management.Attribute) ArrayList(java.util.ArrayList) AttributeNotFoundException(javax.management.AttributeNotFoundException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ReflectionException(javax.management.ReflectionException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) MBeanException(javax.management.MBeanException) ObjectName(javax.management.ObjectName) MBeanException(javax.management.MBeanException)

Example 94 with MBeanException

use of javax.management.MBeanException in project jdk8u_jdk by JetBrains.

the class RequiredModelMBean method setAttribute.

/**
     * Sets the value of a specific attribute of a named ModelMBean.
     *
     * If the 'setMethod' field of the attribute's descriptor
     * contains the name of a valid operation descriptor, then the
     * method described by the operation descriptor is executed.
     * In this implementation, the operation descriptor must be specified
     * correctly and assigned to the modelMBeanInfo so that the 'setMethod'
     * works correctly.
     * The response from the method is set as the value of the attribute
     * in the descriptor.
     *
     * <p>If currencyTimeLimit is &gt; 0, then the new value for the
     * attribute is cached in the attribute descriptor's
     * 'value' field and the 'lastUpdatedTimeStamp' field is set to
     * the current time stamp.
     *
     * <p>If the persist field of the attribute's descriptor is not null
     * then Persistence policy from the attribute descriptor is used to
     * guide storing the attribute in a persistent store.
     * <br>Store the MBean if 'persistPolicy' field is:
     * <UL>
     * <Li> != "never"</Li>
     * <Li> = "always"</Li>
     * <Li> = "onUpdate"</Li>
     * <Li> {@literal = "onTimer" and now > 'lastPersistTime' + 'persistPeriod'}</Li>
     * <Li> {@literal = "NoMoreOftenThan" and now > 'lastPersistTime' +
     *         'persistPeriod'}</Li>
     * </UL>
     * Do not store the MBean if 'persistPolicy' field is:
     * <UL>
     * <Li> = "never"</Li>
     * <Li> = {@literal = "onTimer" && now < 'lastPersistTime' + 'persistPeriod'}</Li>
     * <Li> = "onUnregister"</Li>
     * <Li> = {@literal = "NoMoreOftenThan" and now < 'lastPersistTime' +
     *        'persistPeriod'}</Li>
     * </UL>
     *
     * <p>The ModelMBeanInfo of the Model MBean is stored in a file.
     *
     * @param attribute The Attribute instance containing the name of
     *        the attribute to be set and the value it is to be set to.
     *
     *
     * @exception AttributeNotFoundException The specified attribute is
     *   not accessible in the MBean.
     *   <br>The following cases may result in an AttributeNotFoundException:
     *   <UL>
     *     <LI> No ModelMBeanAttributeInfo is found for the specified
     *          attribute.</LI>
     *     <LI> The ModelMBeanAttributeInfo's isWritable method returns
     *          'false'.</LI>
     *   </UL>
     * @exception InvalidAttributeValueException No descriptor is defined
     *   for the specified attribute.
     * @exception MBeanException Wraps one of the following Exceptions:
     *   <UL>
     *     <LI> An Exception thrown by the managed object's setter.</LI>
     *     <LI> A {@link ServiceNotFoundException} if a setMethod field is
     *          defined in the descriptor for the attribute and the managed
     *          resource is null; or if no setMethod field is defined and
     *          caching is not enabled for the attribute.
     *          Note that if there is no getMethod field either, then caching
     *          is automatically enabled.</LI>
     *     <LI> {@link InvalidTargetObjectTypeException} The 'targetType'
     *          field value is not 'objectReference'.</LI>
     *     <LI> An Exception thrown by the managed object's getter.</LI>
     *   </UL>
     * @exception ReflectionException  Wraps an {@link java.lang.Exception}
     *   thrown while trying to invoke the setter.
     * @exception RuntimeOperationsException Wraps an
     *   {@link IllegalArgumentException}: The attribute in parameter is
     *   null.
     *
     * @see #getAttribute(java.lang.String)
     **/
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
    final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute()", "Entry");
    }
    if (attribute == null)
        throw new RuntimeOperationsException(new IllegalArgumentException("attribute must not be null"), "Exception occurred trying to set an attribute of a " + "RequiredModelMBean");
    /* run setMethod if there is one */
    /* return cached value if its current */
    /* set cached value in descriptor and set date/time */
    /* send attribute change Notification */
    /* check persistence policy and persist if need be */
    String attrName = attribute.getName();
    Object attrValue = attribute.getValue();
    boolean updateDescriptor = false;
    ModelMBeanAttributeInfo attrInfo = modelMBeanInfo.getAttribute(attrName);
    if (attrInfo == null)
        throw new AttributeNotFoundException("setAttribute failed: " + attrName + " is not found ");
    Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor();
    Descriptor attrDescr = attrInfo.getDescriptor();
    if (attrDescr != null) {
        if (!attrInfo.isWritable())
            throw new AttributeNotFoundException("setAttribute failed: " + attrName + " is not writable ");
        String attrSetMethod = (String) (attrDescr.getFieldValue("setMethod"));
        String attrGetMethod = (String) (attrDescr.getFieldValue("getMethod"));
        String attrType = attrInfo.getType();
        Object currValue = "Unknown";
        try {
            currValue = this.getAttribute(attrName);
        } catch (Throwable t) {
        // OK: Default "Unknown" value used for unknown attribute
        }
        Attribute oldAttr = new Attribute(attrName, currValue);
        /* run method from operations descriptor */
        if (attrSetMethod == null) {
            if (attrValue != null) {
                try {
                    final Class<?> clazz = loadClass(attrType);
                    if (!clazz.isInstance(attrValue))
                        throw new InvalidAttributeValueException(clazz.getName() + " expected, " + attrValue.getClass().getName() + " received.");
                } catch (ClassNotFoundException x) {
                    if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
                        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", "Class " + attrType + " for attribute " + attrName + " not found: ", x);
                    }
                }
            }
            updateDescriptor = true;
        } else {
            invoke(attrSetMethod, (new Object[] { attrValue }), (new String[] { attrType }));
        }
        /* change cached value */
        Object objctl = attrDescr.getFieldValue("currencyTimeLimit");
        String ctl;
        if (objctl != null)
            ctl = objctl.toString();
        else
            ctl = null;
        if ((ctl == null) && (mmbDesc != null)) {
            objctl = mmbDesc.getFieldValue("currencyTimeLimit");
            if (objctl != null)
                ctl = objctl.toString();
            else
                ctl = null;
        }
        final boolean updateCache = ((ctl != null) && !(ctl.equals("-1")));
        if (attrSetMethod == null && !updateCache && attrGetMethod != null)
            throw new MBeanException(new ServiceNotFoundException("No " + "setMethod field is defined in the descriptor for " + attrName + " attribute and caching is not enabled " + "for it"));
        if (updateCache || updateDescriptor) {
            if (tracing) {
                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", "setting cached value of " + attrName + " to " + attrValue);
            }
            attrDescr.setField("value", attrValue);
            if (updateCache) {
                final String currtime = String.valueOf((new Date()).getTime());
                attrDescr.setField("lastUpdatedTimeStamp", currtime);
            }
            attrInfo.setDescriptor(attrDescr);
            modelMBeanInfo.setDescriptor(attrDescr, "attribute");
            if (tracing) {
                final StringBuilder strb = new StringBuilder().append("new descriptor is ").append(attrDescr).append(". AttributeInfo descriptor is ").append(attrInfo.getDescriptor()).append(". AttributeInfo descriptor is ").append(modelMBeanInfo.getDescriptor(attrName, "attribute"));
                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", strb.toString());
            }
        }
        if (tracing) {
            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", "sending sendAttributeNotification");
        }
        sendAttributeChangeNotification(oldAttr, attribute);
    } else {
        if (tracing) {
            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", "setMethod failed " + attrName + " not in attributeDescriptor\n");
        }
        throw new InvalidAttributeValueException("Unable to resolve attribute value, " + "no defined in descriptor for attribute");
    }
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", "Exit");
    }
}
Also used : AttributeNotFoundException(javax.management.AttributeNotFoundException) Attribute(javax.management.Attribute) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) Date(java.util.Date) ServiceNotFoundException(javax.management.ServiceNotFoundException) Descriptor(javax.management.Descriptor) MBeanException(javax.management.MBeanException) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 95 with MBeanException

use of javax.management.MBeanException in project jdk8u_jdk by JetBrains.

the class RequiredModelMBean method getAttribute.

/**
     * Returns the value of a specific attribute defined for this
     * ModelMBean.
     * The last value returned by an attribute may be cached in the
     * attribute's descriptor.
     * The valid value will be in the 'value' field if there is one.
     * If the 'currencyTimeLimit' field in the descriptor is:
     * <UL>
     * <LI>  <b>&lt;0</b> Then the value is not cached and is never valid.
     *       The getter method is invoked for the attribute.
     *       The 'value' and 'lastUpdatedTimeStamp' fields are cleared.</LI>
     * <LI>  <b>=0</b> Then the value is always cached and always valid.
     *       The 'value' field is returned. If there is no'value' field
     *       then the getter method is invoked for the attribute.
     *       The 'lastUpdatedTimeStamp' field and `value' fields are set
     *       to the attribute's value and the current time stamp.</LI>
     * <LI>  <b>&gt;0</b> Represents the number of seconds that the 'value'
     *       field is valid.
     *       The 'value' field is no longer valid when
     *       'lastUpdatedTimeStamp' + 'currencyTimeLimit' &gt; Now.
     *   <UL>
     *        <LI>When 'value' is valid, 'value' is returned.</LI>
     *        <LI>When 'value' is no longer valid then the getter
     *            method is invoked for the attribute.
     *            The 'lastUpdatedTimeStamp' field and `value' fields
     *            are updated.</LI>
     *   </UL></LI>
     * </UL>
     *
     * <p><b>Note:</b> because of inconsistencies in previous versions of
     * this specification, it is recommended not to use negative or zero
     * values for <code>currencyTimeLimit</code>.  To indicate that a
     * cached value is never valid, omit the
     * <code>currencyTimeLimit</code> field.  To indicate that it is
     * always valid, use a very large number for this field.</p>
     *
     * <p>If the 'getMethod' field contains the name of a valid
     * operation descriptor, then the method described by the
     * operation descriptor is executed.  The response from the
     * method is returned as the value of the attribute.  If the
     * operation fails or the returned value is not compatible with
     * the declared type of the attribute, an exception will be thrown.</p>
     *
     * <p>If no 'getMethod' field is defined then the default value of the
     * attribute is returned. If the returned value is not compatible with
     * the declared type of the attribute, an exception will be thrown.</p>
     *
     * <p>The declared type of the attribute is the String returned by
     * {@link ModelMBeanAttributeInfo#getType()}.  A value is compatible
     * with this type if one of the following is true:
     * <ul>
     * <li>the value is null;</li>
     * <li>the declared name is a primitive type name (such as "int")
     *     and the value is an instance of the corresponding wrapper
     *     type (such as java.lang.Integer);</li>
     * <li>the name of the value's class is identical to the declared name;</li>
     * <li>the declared name can be loaded by the value's class loader and
     *     produces a class to which the value can be assigned.</li>
     * </ul>
     *
     * <p>In this implementation, in every case where the getMethod needs to
     * be called, because the method is invoked through the standard "invoke"
     * method and thus needs operationInfo, an operation must be specified
     * for that getMethod so that the invocation works correctly.</p>
     *
     * @param attrName A String specifying the name of the
     * attribute to be retrieved. It must match the name of a
     * ModelMBeanAttributeInfo.
     *
     * @return The value of the retrieved attribute from the
     * descriptor 'value' field or from the invocation of the
     * operation in the 'getMethod' field of the descriptor.
     *
     * @exception AttributeNotFoundException The specified attribute is
     *    not accessible in the MBean.
     *    The following cases may result in an AttributeNotFoundException:
     *    <UL>
     *      <LI> No ModelMBeanInfo was found for the Model MBean.</LI>
     *      <LI> No ModelMBeanAttributeInfo was found for the specified
     *           attribute name.</LI>
     *      <LI> The ModelMBeanAttributeInfo isReadable method returns
     *           'false'.</LI>
     *    </UL>
     * @exception MBeanException  Wraps one of the following Exceptions:
     *    <UL>
     *      <LI> {@link InvalidAttributeValueException}: A wrong value type
     *           was received from the attribute's getter method or
     *           no 'getMethod' field defined in the descriptor for
     *           the attribute and no default value exists.</LI>
     *      <LI> {@link ServiceNotFoundException}: No
     *           ModelMBeanOperationInfo defined for the attribute's
     *           getter method or no descriptor associated with the
     *           ModelMBeanOperationInfo or the managed resource is
     *           null.</LI>
     *      <LI> {@link InvalidTargetObjectTypeException} The 'targetType'
     *           field value is not 'objectReference'.</LI>
     *      <LI> An Exception thrown by the managed object's getter.</LI>
     *    </UL>
     * @exception ReflectionException  Wraps an {@link java.lang.Exception}
     *    thrown while trying to invoke the getter.
     * @exception RuntimeOperationsException Wraps an
     *    {@link IllegalArgumentException}: The attribute name in
     *    parameter is null.
     *
     * @see #setAttribute(javax.management.Attribute)
     **/
public Object getAttribute(String attrName) throws AttributeNotFoundException, MBeanException, ReflectionException {
    if (attrName == null)
        throw new RuntimeOperationsException(new IllegalArgumentException("attributeName must not be null"), "Exception occurred trying to get attribute of a " + "RequiredModelMBean");
    final String mth = "getAttribute(String)";
    final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry with " + attrName);
    }
    /* Check attributeDescriptor for getMethod */
    Object response;
    try {
        if (modelMBeanInfo == null)
            throw new AttributeNotFoundException("getAttribute failed: ModelMBeanInfo not found for " + attrName);
        ModelMBeanAttributeInfo attrInfo = modelMBeanInfo.getAttribute(attrName);
        Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor();
        if (attrInfo == null)
            throw new AttributeNotFoundException("getAttribute failed:" + " ModelMBeanAttributeInfo not found for " + attrName);
        Descriptor attrDescr = attrInfo.getDescriptor();
        if (attrDescr != null) {
            if (!attrInfo.isReadable())
                throw new AttributeNotFoundException("getAttribute failed: " + attrName + " is not readable ");
            response = resolveForCacheValue(attrDescr);
            /* return current cached value */
            if (tracing) {
                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "*** cached value is " + response);
            }
            if (response == null) {
                /* no cached value, run getMethod */
                if (tracing) {
                    MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "**** cached value is null - getting getMethod");
                }
                String attrGetMethod = (String) (attrDescr.getFieldValue("getMethod"));
                if (attrGetMethod != null) {
                    /* run method from operations descriptor */
                    if (tracing) {
                        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "invoking a getMethod for " + attrName);
                    }
                    Object getResponse = invoke(attrGetMethod, new Object[] {}, new String[] {});
                    if (getResponse != null) {
                        // error/validity check return value here
                        if (tracing) {
                            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "got a non-null response " + "from getMethod\n");
                        }
                        response = getResponse;
                        // change cached value in attribute descriptor
                        Object objctl = attrDescr.getFieldValue("currencyTimeLimit");
                        String ctl;
                        if (objctl != null)
                            ctl = objctl.toString();
                        else
                            ctl = null;
                        if ((ctl == null) && (mmbDesc != null)) {
                            objctl = mmbDesc.getFieldValue("currencyTimeLimit");
                            if (objctl != null)
                                ctl = objctl.toString();
                            else
                                ctl = null;
                        }
                        if ((ctl != null) && !(ctl.equals("-1"))) {
                            if (tracing) {
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "setting cached value and " + "lastUpdatedTime in descriptor");
                            }
                            attrDescr.setField("value", response);
                            final String stamp = String.valueOf((new Date()).getTime());
                            attrDescr.setField("lastUpdatedTimeStamp", stamp);
                            attrInfo.setDescriptor(attrDescr);
                            modelMBeanInfo.setDescriptor(attrDescr, "attribute");
                            if (tracing) {
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "new descriptor is " + attrDescr);
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "AttributeInfo descriptor is " + attrInfo.getDescriptor());
                                final String attStr = modelMBeanInfo.getDescriptor(attrName, "attribute").toString();
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "modelMBeanInfo: AttributeInfo " + "descriptor is " + attStr);
                            }
                        }
                    } else {
                        // response was invalid or really returned null
                        if (tracing) {
                            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "got a null response from getMethod\n");
                        }
                        response = null;
                    }
                } else {
                    // not getMethod so return descriptor (default) value
                    String qualifier = "";
                    response = attrDescr.getFieldValue("value");
                    if (response == null) {
                        qualifier = "default ";
                        response = attrDescr.getFieldValue("default");
                    }
                    if (tracing) {
                        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "could not find getMethod for " + attrName + ", returning descriptor " + qualifier + "value");
                    }
                // !! cast response to right class
                }
            }
            // make sure response class matches type field
            final String respType = attrInfo.getType();
            if (response != null) {
                String responseClass = response.getClass().getName();
                if (!respType.equals(responseClass)) {
                    boolean wrongType = false;
                    boolean primitiveType = false;
                    boolean correspondingTypes = false;
                    for (int i = 0; i < primitiveTypes.length; i++) {
                        if (respType.equals(primitiveTypes[i])) {
                            primitiveType = true;
                            if (responseClass.equals(primitiveWrappers[i]))
                                correspondingTypes = true;
                            break;
                        }
                    }
                    if (primitiveType) {
                        // inequality may come from primitive/wrapper class
                        if (!correspondingTypes)
                            wrongType = true;
                    } else {
                        // inequality may come from type subclassing
                        boolean subtype;
                        try {
                            final Class respClass = response.getClass();
                            final Exception[] caughException = new Exception[1];
                            AccessControlContext stack = AccessController.getContext();
                            Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {

                                @Override
                                public Class<?> run() {
                                    try {
                                        ReflectUtil.checkPackageAccess(respType);
                                        ClassLoader cl = respClass.getClassLoader();
                                        return Class.forName(respType, true, cl);
                                    } catch (Exception e) {
                                        caughException[0] = e;
                                    }
                                    return null;
                                }
                            }, stack, acc);
                            if (caughException[0] != null) {
                                throw caughException[0];
                            }
                            subtype = c.isInstance(response);
                        } catch (Exception e) {
                            subtype = false;
                            if (tracing) {
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exception: ", e);
                            }
                        }
                        if (!subtype)
                            wrongType = true;
                    }
                    if (wrongType) {
                        if (tracing) {
                            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Wrong response type '" + respType + "'");
                        }
                        // back right attribute type
                        throw new MBeanException(new InvalidAttributeValueException("Wrong value type received for get attribute"), "An exception occurred while trying to get an " + "attribute value through a RequiredModelMBean");
                    }
                }
            }
        } else {
            if (tracing) {
                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "getMethod failed " + attrName + " not in attributeDescriptor\n");
            }
            throw new MBeanException(new InvalidAttributeValueException("Unable to resolve attribute value, " + "no getMethod defined in descriptor for attribute"), "An exception occurred while trying to get an " + "attribute value through a RequiredModelMBean");
        }
    } catch (MBeanException mbe) {
        throw mbe;
    } catch (AttributeNotFoundException t) {
        throw t;
    } catch (Exception e) {
        if (tracing) {
            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "getMethod failed with " + e.getMessage() + " exception type " + (e.getClass()).toString());
        }
        throw new MBeanException(e, "An exception occurred while trying " + "to get an attribute value: " + e.getMessage());
    }
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exit");
    }
    return response;
}
Also used : AttributeNotFoundException(javax.management.AttributeNotFoundException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) Date(java.util.Date) AttributeNotFoundException(javax.management.AttributeNotFoundException) ServiceNotFoundException(javax.management.ServiceNotFoundException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ReflectionException(javax.management.ReflectionException) RuntimeErrorException(javax.management.RuntimeErrorException) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) MBeanException(javax.management.MBeanException) ListenerNotFoundException(javax.management.ListenerNotFoundException) RuntimeOperationsException(javax.management.RuntimeOperationsException) AccessControlContext(java.security.AccessControlContext) Descriptor(javax.management.Descriptor) MBeanException(javax.management.MBeanException) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Aggregations

MBeanException (javax.management.MBeanException)105 ReflectionException (javax.management.ReflectionException)50 InstanceNotFoundException (javax.management.InstanceNotFoundException)41 AttributeNotFoundException (javax.management.AttributeNotFoundException)35 ObjectName (javax.management.ObjectName)32 NotCompliantMBeanException (javax.management.NotCompliantMBeanException)31 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)26 MalformedObjectNameException (javax.management.MalformedObjectNameException)19 InvocationTargetException (java.lang.reflect.InvocationTargetException)18 RuntimeOperationsException (javax.management.RuntimeOperationsException)18 ServiceNotFoundException (javax.management.ServiceNotFoundException)17 Attribute (javax.management.Attribute)14 RuntimeErrorException (javax.management.RuntimeErrorException)14 Method (java.lang.reflect.Method)10 DynamicMBean (javax.management.DynamicMBean)10 ListenerNotFoundException (javax.management.ListenerNotFoundException)10 Descriptor (javax.management.Descriptor)9 InvalidTargetObjectTypeException (javax.management.modelmbean.InvalidTargetObjectTypeException)8 MalformedURLException (java.net.MalformedURLException)7 MBeanRegistrationException (javax.management.MBeanRegistrationException)7