Search in sources :

Example 61 with ReflectionException

use of javax.management.ReflectionException 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)

Example 62 with ReflectionException

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

the class RequiredModelMBean method invoke.

/**
     * Invokes a method on or through a RequiredModelMBean and returns
     * the result of the method execution.
     * <P>
     * If the given method to be invoked, together with the provided
     * signature, matches one of RequiredModelMbean
     * accessible methods, this one will be call. Otherwise the call to
     * the given method will be tried on the managed resource.
     * <P>
     * The last value returned by an operation may be cached in
     * the operation's descriptor which
     * is in the ModelMBeanOperationInfo'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 operation method is invoked.
     *      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 operation method is invoked for the attribute.
     *      The 'lastUpdatedTimeStamp' field and `value' fields are set to
     *      the operation's return 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 operation
     *             method is invoked. 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>
     *
     * @param opName The name of the method to be invoked. The
     *     name can be the fully qualified method name including the
     *     classname, or just the method name if the classname is
     *     defined in the 'class' field of the operation descriptor.
     * @param opArgs An array containing the parameters to be set
     *     when the operation is invoked
     * @param sig An array containing the signature of the
     *     operation. The class objects will be loaded using the same
     *     class loader as the one used for loading the MBean on which
     *     the operation was invoked.
     *
     * @return  The object returned by the method, which represents the
     *     result of invoking the method on the specified managed resource.
     *
     * @exception MBeanException  Wraps one of the following Exceptions:
     * <UL>
     * <LI> An Exception thrown by the managed object's invoked method.</LI>
     * <LI> {@link ServiceNotFoundException}: No ModelMBeanOperationInfo or
     *      no descriptor defined for the specified operation or the managed
     *      resource is null.</LI>
     * <LI> {@link InvalidTargetObjectTypeException}: The 'targetType'
     *      field value is not 'objectReference'.</LI>
     * </UL>
     * @exception ReflectionException  Wraps an {@link java.lang.Exception}
     *      thrown while trying to invoke the method.
     * @exception RuntimeOperationsException Wraps an
     *      {@link IllegalArgumentException} Method name is null.
     *
     **/
/*
      The requirement to be able to invoke methods on the
      RequiredModelMBean class itself makes this method considerably
      more complicated than it might otherwise be.  Note that, unlike
      earlier versions, we do not allow you to invoke such methods if
      they are not explicitly mentioned in the ModelMBeanInfo.  Doing
      so was potentially a security problem, and certainly very
      surprising.

      We do not look for the method in the RequiredModelMBean class
      itself if:
      (a) there is a "targetObject" field in the Descriptor for the
      operation; or
      (b) there is a "class" field in the Descriptor for the operation
      and the named class is not RequiredModelMBean or one of its
      superinterfaces; or
      (c) the name of the operation is not the name of a method in
      RequiredModelMBean (this is just an optimization).

      In cases (a) and (b), if you have gone to the trouble of adding
      those fields specifically for this operation then presumably you
      do not want RequiredModelMBean's methods to be called.

      We have to pay attention to class loading issues.  If the
      "class" field is present, the named class has to be resolved
      relative to RequiredModelMBean's class loader to test the
      condition (b) above, and relative to the managed resource's
      class loader to ensure that the managed resource is in fact of
      the named class (or a subclass).  The class names in the sig
      array likewise have to be resolved, first against
      RequiredModelMBean's class loader, then against the managed
      resource's class loader.  There is no point in using any other
      loader because when we call Method.invoke we must call it on
      a Method that is implemented by the target object.
     */
public Object invoke(String opName, Object[] opArgs, String[] sig) throws MBeanException, ReflectionException {
    final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
    final String mth = "invoke(String, Object[], String[])";
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry");
    }
    if (opName == null) {
        final RuntimeException x = new IllegalArgumentException("Method name must not be null");
        throw new RuntimeOperationsException(x, "An exception occurred while trying to " + "invoke a method on a RequiredModelMBean");
    }
    String opClassName = null;
    String opMethodName;
    // Parse for class name and method
    int opSplitter = opName.lastIndexOf(".");
    if (opSplitter > 0) {
        opClassName = opName.substring(0, opSplitter);
        opMethodName = opName.substring(opSplitter + 1);
    } else
        opMethodName = opName;
    /* Ignore anything after a left paren.  We keep this for
           compatibility but it isn't specified.  */
    opSplitter = opMethodName.indexOf("(");
    if (opSplitter > 0)
        opMethodName = opMethodName.substring(0, opSplitter);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Finding operation " + opName + " as " + opMethodName);
    }
    ModelMBeanOperationInfo opInfo = modelMBeanInfo.getOperation(opMethodName);
    if (opInfo == null) {
        final String msg = "Operation " + opName + " not in ModelMBeanInfo";
        throw new MBeanException(new ServiceNotFoundException(msg), msg);
    }
    final Descriptor opDescr = opInfo.getDescriptor();
    if (opDescr == null) {
        final String msg = "Operation descriptor null";
        throw new MBeanException(new ServiceNotFoundException(msg), msg);
    }
    final Object cached = resolveForCacheValue(opDescr);
    if (cached != null) {
        if (tracing) {
            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Returning cached value");
        }
        return cached;
    }
    if (opClassName == null)
        opClassName = (String) opDescr.getFieldValue("class");
    // may still be null now
    opMethodName = (String) opDescr.getFieldValue("name");
    if (opMethodName == null) {
        final String msg = "Method descriptor must include `name' field";
        throw new MBeanException(new ServiceNotFoundException(msg), msg);
    }
    final String targetTypeField = (String) opDescr.getFieldValue("targetType");
    if (targetTypeField != null && !targetTypeField.equalsIgnoreCase("objectReference")) {
        final String msg = "Target type must be objectReference: " + targetTypeField;
        throw new MBeanException(new InvalidTargetObjectTypeException(msg), msg);
    }
    final Object targetObjectField = opDescr.getFieldValue("targetObject");
    if (tracing && targetObjectField != null)
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Found target object in descriptor");
    /* Now look for the method, either in RequiredModelMBean itself
           or in the target object.  Set "method" and "targetObject"
           appropriately.  */
    Method method;
    Object targetObject;
    method = findRMMBMethod(opMethodName, targetObjectField, opClassName, sig);
    if (method != null)
        targetObject = this;
    else {
        if (tracing) {
            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "looking for method in managedResource class");
        }
        if (targetObjectField != null)
            targetObject = targetObjectField;
        else {
            targetObject = managedResource;
            if (targetObject == null) {
                final String msg = "managedResource for invoke " + opName + " is null";
                Exception snfe = new ServiceNotFoundException(msg);
                throw new MBeanException(snfe);
            }
        }
        final Class<?> targetClass;
        if (opClassName != null) {
            try {
                AccessControlContext stack = AccessController.getContext();
                final Object obj = targetObject;
                final String className = opClassName;
                final ClassNotFoundException[] caughtException = new ClassNotFoundException[1];
                targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {

                    @Override
                    public Class<?> run() {
                        try {
                            ReflectUtil.checkPackageAccess(className);
                            final ClassLoader targetClassLoader = obj.getClass().getClassLoader();
                            return Class.forName(className, false, targetClassLoader);
                        } catch (ClassNotFoundException e) {
                            caughtException[0] = e;
                        }
                        return null;
                    }
                }, stack, acc);
                if (caughtException[0] != null) {
                    throw caughtException[0];
                }
            } catch (ClassNotFoundException e) {
                final String msg = "class for invoke " + opName + " not found";
                throw new ReflectionException(e, msg);
            }
        } else
            targetClass = targetObject.getClass();
        method = resolveMethod(targetClass, opMethodName, sig);
    }
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "found " + opMethodName + ", now invoking");
    }
    final Object result = invokeMethod(opName, method, targetObject, opArgs);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "successfully invoked method");
    }
    if (result != null)
        cacheResult(opInfo, opDescr, result);
    return result;
}
Also used : ReflectionException(javax.management.ReflectionException) Method(java.lang.reflect.Method) 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) PrivilegedAction(java.security.PrivilegedAction) ServiceNotFoundException(javax.management.ServiceNotFoundException) MBeanException(javax.management.MBeanException) Descriptor(javax.management.Descriptor) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 63 with ReflectionException

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

the class Monitor method monitor.

/**
     * This method is called by the monitor each time
     * the granularity period has been exceeded.
     * @param o The observed object.
     */
private void monitor(ObservedObject o, int index, int[] an) {
    String attribute;
    String notifType = null;
    String msg = null;
    Object derGauge = null;
    Object trigger = null;
    ObjectName object;
    Comparable<?> value = null;
    MonitorNotification alarm = null;
    if (!isActive())
        return;
    //
    synchronized (this) {
        object = o.getObservedObject();
        attribute = getObservedAttribute();
        if (object == null || attribute == null) {
            return;
        }
    }
    // Check that the observed object is registered in the
    // MBean server and that the observed attribute
    // belongs to the observed object.
    //
    Object attributeValue = null;
    try {
        attributeValue = getAttribute(server, object, attribute);
        if (attributeValue == null)
            if (isAlreadyNotified(o, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED))
                return;
            else {
                notifType = OBSERVED_ATTRIBUTE_TYPE_ERROR;
                setAlreadyNotified(o, index, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED, an);
                msg = "The observed attribute value is null.";
                MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
            }
    } catch (NullPointerException np_ex) {
        if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
            return;
        else {
            notifType = RUNTIME_ERROR;
            setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
            msg = "The monitor must be registered in the MBean " + "server or an MBeanServerConnection must be " + "explicitly supplied.";
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", np_ex.toString());
        }
    } catch (InstanceNotFoundException inf_ex) {
        if (isAlreadyNotified(o, OBSERVED_OBJECT_ERROR_NOTIFIED))
            return;
        else {
            notifType = OBSERVED_OBJECT_ERROR;
            setAlreadyNotified(o, index, OBSERVED_OBJECT_ERROR_NOTIFIED, an);
            msg = "The observed object must be accessible in " + "the MBeanServerConnection.";
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", inf_ex.toString());
        }
    } catch (AttributeNotFoundException anf_ex) {
        if (isAlreadyNotified(o, OBSERVED_ATTRIBUTE_ERROR_NOTIFIED))
            return;
        else {
            notifType = OBSERVED_ATTRIBUTE_ERROR;
            setAlreadyNotified(o, index, OBSERVED_ATTRIBUTE_ERROR_NOTIFIED, an);
            msg = "The observed attribute must be accessible in " + "the observed object.";
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", anf_ex.toString());
        }
    } catch (MBeanException mb_ex) {
        if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
            return;
        else {
            notifType = RUNTIME_ERROR;
            setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
            msg = mb_ex.getMessage() == null ? "" : mb_ex.getMessage();
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", mb_ex.toString());
        }
    } catch (ReflectionException ref_ex) {
        if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED)) {
            return;
        } else {
            notifType = RUNTIME_ERROR;
            setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
            msg = ref_ex.getMessage() == null ? "" : ref_ex.getMessage();
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", ref_ex.toString());
        }
    } catch (IOException io_ex) {
        if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
            return;
        else {
            notifType = RUNTIME_ERROR;
            setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
            msg = io_ex.getMessage() == null ? "" : io_ex.getMessage();
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", io_ex.toString());
        }
    } catch (RuntimeException rt_ex) {
        if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
            return;
        else {
            notifType = RUNTIME_ERROR;
            setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
            msg = rt_ex.getMessage() == null ? "" : rt_ex.getMessage();
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
            MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", rt_ex.toString());
        }
    }
    synchronized (this) {
        //
        if (!isActive())
            return;
        //
        if (!attribute.equals(getObservedAttribute()))
            return;
        //
        if (msg == null) {
            try {
                value = getComparableFromAttribute(object, attribute, attributeValue);
            } catch (ClassCastException e) {
                if (isAlreadyNotified(o, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED))
                    return;
                else {
                    notifType = OBSERVED_ATTRIBUTE_TYPE_ERROR;
                    setAlreadyNotified(o, index, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED, an);
                    msg = "The observed attribute value does not " + "implement the Comparable interface.";
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", e.toString());
                }
            } catch (AttributeNotFoundException e) {
                if (isAlreadyNotified(o, OBSERVED_ATTRIBUTE_ERROR_NOTIFIED))
                    return;
                else {
                    notifType = OBSERVED_ATTRIBUTE_ERROR;
                    setAlreadyNotified(o, index, OBSERVED_ATTRIBUTE_ERROR_NOTIFIED, an);
                    msg = "The observed attribute must be accessible in " + "the observed object.";
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", e.toString());
                }
            } catch (RuntimeException e) {
                if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
                    return;
                else {
                    notifType = RUNTIME_ERROR;
                    setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
                    msg = e.getMessage() == null ? "" : e.getMessage();
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", e.toString());
                }
            }
        }
        //
        if (msg == null) {
            if (!isComparableTypeValid(object, attribute, value)) {
                if (isAlreadyNotified(o, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED))
                    return;
                else {
                    notifType = OBSERVED_ATTRIBUTE_TYPE_ERROR;
                    setAlreadyNotified(o, index, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED, an);
                    msg = "The observed attribute type is not valid.";
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
                }
            }
        }
        //
        if (msg == null) {
            if (!isThresholdTypeValid(object, attribute, value)) {
                if (isAlreadyNotified(o, THRESHOLD_ERROR_NOTIFIED))
                    return;
                else {
                    notifType = THRESHOLD_ERROR;
                    setAlreadyNotified(o, index, THRESHOLD_ERROR_NOTIFIED, an);
                    msg = "The threshold type is not valid.";
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
                }
            }
        }
        //
        if (msg == null) {
            msg = buildErrorNotification(object, attribute, value);
            if (msg != null) {
                if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
                    return;
                else {
                    notifType = RUNTIME_ERROR;
                    setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
                    MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(), "monitor", msg);
                }
            }
        }
        //
        if (msg == null) {
            // Clear all already notified flags.
            //
            resetAllAlreadyNotified(o, index, an);
            // Get derived gauge from comparable value.
            //
            derGauge = getDerivedGaugeFromComparable(object, attribute, value);
            o.setDerivedGauge(derGauge);
            o.setDerivedGaugeTimeStamp(System.currentTimeMillis());
            // Check if an alarm must be fired.
            //
            alarm = buildAlarmNotification(object, attribute, (Comparable<?>) derGauge);
        }
    }
    //
    if (msg != null)
        sendNotification(notifType, System.currentTimeMillis(), msg, derGauge, trigger, object, true);
    //
    if (alarm != null && alarm.getType() != null)
        sendNotification(alarm.getType(), System.currentTimeMillis(), alarm.getMessage(), derGauge, alarm.getTrigger(), object, false);
}
Also used : ReflectionException(javax.management.ReflectionException) MonitorNotification(javax.management.monitor.MonitorNotification) AttributeNotFoundException(javax.management.AttributeNotFoundException) InstanceNotFoundException(javax.management.InstanceNotFoundException) IOException(java.io.IOException) ObjectName(javax.management.ObjectName) MBeanException(javax.management.MBeanException)

Example 64 with ReflectionException

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

the class MLet method getMBeansFromURL.

/**
      * Loads a text file containing MLET tags that define the MBeans to
      * be added to the MBean server. The location of the text file is specified by
      * a URL. The MBeans specified in the MLET file will be instantiated and
      * registered in the MBean server.
      *
      * @param url The URL of the text file to be loaded as String object.
      *
      * @return A set containing one entry per MLET tag in the m-let
      * text file loaded.  Each entry specifies either the
      * ObjectInstance for the created MBean, or a throwable object
      * (that is, an error or an exception) if the MBean could not be
      * created.
      *
      * @exception ServiceNotFoundException One of the following
      * errors has occurred: The m-let text file does not contain an
      * MLET tag, the m-let text file is not found, a mandatory
      * attribute of the MLET tag is not specified, the url is
      * malformed.
      * @exception IllegalStateException MLet MBean is not registered
      * with an MBeanServer.
      *
      */
public Set<Object> getMBeansFromURL(String url) throws ServiceNotFoundException {
    String mth = "getMBeansFromURL";
    if (server == null) {
        throw new IllegalStateException("This MLet MBean is not " + "registered with an MBeanServer.");
    }
    // Parse arguments
    if (url == null) {
        MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "URL is null");
        throw new ServiceNotFoundException("The specified URL is null");
    } else {
        url = url.replace(File.separatorChar, '/');
    }
    if (MLET_LOGGER.isLoggable(Level.FINER)) {
        MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "<URL = " + url + ">");
    }
    // Parse URL
    try {
        MLetParser parser = new MLetParser();
        mletList = parser.parseURL(url);
    } catch (Exception e) {
        final String msg = "Problems while parsing URL [" + url + "], got exception [" + e.toString() + "]";
        MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg);
        throw EnvHelp.initCause(new ServiceNotFoundException(msg), e);
    }
    // Check that the list of MLets is not empty
    if (mletList.size() == 0) {
        final String msg = "File " + url + " not found or MLET tag not defined in file";
        MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg);
        throw new ServiceNotFoundException(msg);
    }
    // Walk through the list of MLets
    Set<Object> mbeans = new HashSet<Object>();
    for (MLetContent elmt : mletList) {
        // Initialize local variables
        String code = elmt.getCode();
        if (code != null) {
            if (code.endsWith(".class")) {
                code = code.substring(0, code.length() - 6);
            }
        }
        String name = elmt.getName();
        URL codebase = elmt.getCodeBase();
        String version = elmt.getVersion();
        String serName = elmt.getSerializedObject();
        String jarFiles = elmt.getJarFiles();
        URL documentBase = elmt.getDocumentBase();
        // Display debug information
        if (MLET_LOGGER.isLoggable(Level.FINER)) {
            final StringBuilder strb = new StringBuilder().append("\n\tMLET TAG     = ").append(elmt.getAttributes()).append("\n\tCODEBASE     = ").append(codebase).append("\n\tARCHIVE      = ").append(jarFiles).append("\n\tCODE         = ").append(code).append("\n\tOBJECT       = ").append(serName).append("\n\tNAME         = ").append(name).append("\n\tVERSION      = ").append(version).append("\n\tDOCUMENT URL = ").append(documentBase);
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, strb.toString());
        }
        // Load classes from JAR files
        StringTokenizer st = new StringTokenizer(jarFiles, ",", false);
        while (st.hasMoreTokens()) {
            String tok = st.nextToken().trim();
            if (MLET_LOGGER.isLoggable(Level.FINER)) {
                MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Load archive for codebase <" + codebase + ">, file <" + tok + ">");
            }
            //
            try {
                codebase = check(version, codebase, tok, elmt);
            } catch (Exception ex) {
                MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), mth, "Got unexpected exception", ex);
                mbeans.add(ex);
                continue;
            }
            // URLs to search for classes and resources.
            try {
                if (!Arrays.asList(getURLs()).contains(new URL(codebase.toString() + tok))) {
                    addURL(codebase + tok);
                }
            } catch (MalformedURLException me) {
            // OK : Ignore jar file if its name provokes the
            // URL to be an invalid one.
            }
        }
        // Instantiate the class specified in the
        // CODE or OBJECT section of the MLet tag
        //
        Object o;
        ObjectInstance objInst;
        if (code != null && serName != null) {
            final String msg = "CODE and OBJECT parameters cannot be specified at the " + "same time in tag MLET";
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg);
            mbeans.add(new Error(msg));
            continue;
        }
        if (code == null && serName == null) {
            final String msg = "Either CODE or OBJECT parameter must be specified in " + "tag MLET";
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg);
            mbeans.add(new Error(msg));
            continue;
        }
        try {
            if (code != null) {
                List<String> signat = elmt.getParameterTypes();
                List<String> stringPars = elmt.getParameterValues();
                List<Object> objectPars = new ArrayList<Object>();
                for (int i = 0; i < signat.size(); i++) {
                    objectPars.add(constructParameter(stringPars.get(i), signat.get(i)));
                }
                if (signat.isEmpty()) {
                    if (name == null) {
                        objInst = server.createMBean(code, null, mletObjectName);
                    } else {
                        objInst = server.createMBean(code, new ObjectName(name), mletObjectName);
                    }
                } else {
                    Object[] parms = objectPars.toArray();
                    String[] signature = new String[signat.size()];
                    signat.toArray(signature);
                    if (MLET_LOGGER.isLoggable(Level.FINEST)) {
                        final StringBuilder strb = new StringBuilder();
                        for (int i = 0; i < signature.length; i++) {
                            strb.append("\n\tSignature     = ").append(signature[i]).append("\t\nParams        = ").append(parms[i]);
                        }
                        MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), mth, strb.toString());
                    }
                    if (name == null) {
                        objInst = server.createMBean(code, null, mletObjectName, parms, signature);
                    } else {
                        objInst = server.createMBean(code, new ObjectName(name), mletObjectName, parms, signature);
                    }
                }
            } else {
                o = loadSerializedObject(codebase, serName);
                if (name == null) {
                    server.registerMBean(o, null);
                } else {
                    server.registerMBean(o, new ObjectName(name));
                }
                objInst = new ObjectInstance(name, o.getClass().getName());
            }
        } catch (ReflectionException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "ReflectionException", ex);
            mbeans.add(ex);
            continue;
        } catch (InstanceAlreadyExistsException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "InstanceAlreadyExistsException", ex);
            mbeans.add(ex);
            continue;
        } catch (MBeanRegistrationException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "MBeanRegistrationException", ex);
            mbeans.add(ex);
            continue;
        } catch (MBeanException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "MBeanException", ex);
            mbeans.add(ex);
            continue;
        } catch (NotCompliantMBeanException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "NotCompliantMBeanException", ex);
            mbeans.add(ex);
            continue;
        } catch (InstanceNotFoundException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "InstanceNotFoundException", ex);
            mbeans.add(ex);
            continue;
        } catch (IOException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "IOException", ex);
            mbeans.add(ex);
            continue;
        } catch (SecurityException ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "SecurityException", ex);
            mbeans.add(ex);
            continue;
        } catch (Exception ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Exception", ex);
            mbeans.add(ex);
            continue;
        } catch (Error ex) {
            MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Error", ex);
            mbeans.add(ex);
            continue;
        }
        mbeans.add(objInst);
    }
    return mbeans;
}
Also used : MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) URL(java.net.URL) HashSet(java.util.HashSet) ReflectionException(javax.management.ReflectionException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ObjectInstance(javax.management.ObjectInstance) IOException(java.io.IOException) ServiceNotFoundException(javax.management.ServiceNotFoundException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ReflectionException(javax.management.ReflectionException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MBeanException(javax.management.MBeanException) ObjectName(javax.management.ObjectName) StringTokenizer(java.util.StringTokenizer) ServiceNotFoundException(javax.management.ServiceNotFoundException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) MBeanException(javax.management.MBeanException) MBeanRegistrationException(javax.management.MBeanRegistrationException)

Example 65 with ReflectionException

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

the class RequiredModelMBean method findRMMBMethod.

/* Find a method in RequiredModelMBean as determined by the given
       parameters.  Return null if there is none, or if the parameters
       exclude using it.  Called from invoke. */
private Method findRMMBMethod(String opMethodName, Object targetObjectField, String opClassName, String[] sig) {
    final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "invoke(String, Object[], String[])", "looking for method in RequiredModelMBean class");
    }
    if (!isRMMBMethodName(opMethodName))
        return null;
    if (targetObjectField != null)
        return null;
    final Class<RequiredModelMBean> rmmbClass = RequiredModelMBean.class;
    final Class<?> targetClass;
    if (opClassName == null)
        targetClass = rmmbClass;
    else {
        AccessControlContext stack = AccessController.getContext();
        final String className = opClassName;
        targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {

            @Override
            public Class<?> run() {
                try {
                    ReflectUtil.checkPackageAccess(className);
                    final ClassLoader targetClassLoader = rmmbClass.getClassLoader();
                    Class clz = Class.forName(className, false, targetClassLoader);
                    if (!rmmbClass.isAssignableFrom(clz))
                        return null;
                    return clz;
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }
        }, stack, acc);
    }
    try {
        return targetClass != null ? resolveMethod(targetClass, opMethodName, sig) : null;
    } catch (ReflectionException e) {
        return null;
    }
}
Also used : ReflectionException(javax.management.ReflectionException) AccessControlContext(java.security.AccessControlContext) PrivilegedAction(java.security.PrivilegedAction)

Aggregations

ReflectionException (javax.management.ReflectionException)72 InstanceNotFoundException (javax.management.InstanceNotFoundException)50 MBeanException (javax.management.MBeanException)46 AttributeNotFoundException (javax.management.AttributeNotFoundException)31 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)23 ObjectName (javax.management.ObjectName)22 Attribute (javax.management.Attribute)19 RuntimeOperationsException (javax.management.RuntimeOperationsException)17 InvocationTargetException (java.lang.reflect.InvocationTargetException)16 IntrospectionException (javax.management.IntrospectionException)13 Method (java.lang.reflect.Method)12 AttributeList (javax.management.AttributeList)12 ServiceNotFoundException (javax.management.ServiceNotFoundException)12 IOException (java.io.IOException)11 MBeanInfo (javax.management.MBeanInfo)11 RuntimeErrorException (javax.management.RuntimeErrorException)11 MalformedObjectNameException (javax.management.MalformedObjectNameException)10 ListenerNotFoundException (javax.management.ListenerNotFoundException)9 MBeanAttributeInfo (javax.management.MBeanAttributeInfo)9 MBeanRegistrationException (javax.management.MBeanRegistrationException)9