Search in sources :

Example 56 with Descriptor

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

the class MXBeanNotifTest method run.

public void run(Map<String, Object> args) {
    System.out.println("MXBeanNotifTest::run: Start");
    int errorCount = 0;
    try {
        parseArgs(args);
        notifList = new ArrayBlockingQueue<Notification>(numOfNotifications);
        // JMX MbeanServer used inside single VM as if remote.
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
        JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
        cs.start();
        JMXServiceURL addr = cs.getAddress();
        JMXConnector cc = JMXConnectorFactory.connect(addr);
        MBeanServerConnection mbsc = cc.getMBeanServerConnection();
        // ----
        System.out.println("MXBeanNotifTest::run: Create and register the MBean");
        ObjectName objName = new ObjectName("sqe:type=Basic,protocol=rmi");
        mbsc.createMBean(BASIC_MXBEAN_CLASS_NAME, objName);
        System.out.println("---- OK\n");
        // ----
        System.out.println("MXBeanNotifTest::run: Add me as notification listener");
        mbsc.addNotificationListener(objName, this, null, null);
        // ----
        System.out.println("MXBeanNotifTest::run: Retrieve the Descriptor" + " that should be in MBeanNotificationInfo");
        TabularData tabData = (TabularData) mbsc.getAttribute(objName, "NotifDescriptorAsMapAtt");
        Map<String, String> descrMap = new HashMap<>();
        for (Iterator<?> it = tabData.values().iterator(); it.hasNext(); ) {
            CompositeData compData = (CompositeData) it.next();
            descrMap.put((String) compData.get("key"), (String) compData.get("value"));
        }
        Descriptor refNotifDescriptor = new ImmutableDescriptor(descrMap);
        System.out.println("---- OK\n");
        // ----
        // Because the MBean holding the targeted attribute is MXBean, we
        // should use for the setAttribute a converted form for the
        // attribute value as described by the MXBean mapping rules.
        // This explains all that lovely stuff for creating a
        // TabularDataSupport.
        //
        // WARNING : the MBeanInfo of the MXBean used on opposite side
        // is computed when the MBean is registered.
        // It means the Descriptor considered for the MBeanNotificationInfo
        // is not the one we set in the lines below, it is too late.
        // However, we check that set is harmless when we check
        // the MBeanNotificationInfo.
        //
        System.out.println("MXBeanNotifTest::run: Set a Map<String, String>" + " attribute");
        String typeName = "java.util.Map<java.lang.String,java.lang.String>";
        String[] keyValue = new String[] { "key", "value" };
        OpenType<?>[] openTypes = new OpenType<?>[] { SimpleType.STRING, SimpleType.STRING };
        CompositeType rowType = new CompositeType(typeName, typeName, keyValue, keyValue, openTypes);
        TabularType tabType = new TabularType(typeName, typeName, rowType, new String[] { "key" });
        TabularDataSupport convertedDescrMap = new TabularDataSupport(tabType);
        for (int i = 0; i < numOfNotifDescriptorElements; i++) {
            Object[] descrValue = { "field" + i, "value" + i };
            CompositeData data = new CompositeDataSupport(rowType, keyValue, descrValue);
            convertedDescrMap.put(data);
        }
        Attribute descrAtt = new Attribute("NotifDescriptorAsMapAtt", convertedDescrMap);
        mbsc.setAttribute(objName, descrAtt);
        System.out.println("---- OK\n");
        // ----
        System.out.println("MXBeanNotifTest::run: Compare the Descriptor from" + " the MBeanNotificationInfo against a reference");
        MBeanInfo mbInfo = mbsc.getMBeanInfo(objName);
        errorCount += checkMBeanInfo(mbInfo, refNotifDescriptor);
        System.out.println("---- DONE\n");
        // ----
        System.out.println("Check isInstanceOf(Basic)");
        if (!mbsc.isInstanceOf(objName, BASIC_MXBEAN_CLASS_NAME)) {
            errorCount++;
            System.out.println("---- ERROR isInstanceOf returned false\n");
        } else {
            System.out.println("---- OK\n");
        }
        // ----
        System.out.println("Check isInstanceOf(BasicMXBean)");
        if (!mbsc.isInstanceOf(objName, BASIC_MXBEAN_INTERFACE_NAME)) {
            errorCount++;
            System.out.println("---- ERROR isInstanceOf returned false\n");
        } else {
            System.out.println("---- OK\n");
        }
        // ----
        System.out.println("MXBeanNotifTest::run: Ask for " + numOfNotifications + " notification(s)");
        Object[] sendNotifParam = new Object[1];
        String[] sendNotifSig = new String[] { "java.lang.String" };
        for (int i = 0; i < numOfNotifications; i++) {
            // Select which type of notification we ask for
            if (i % 2 == 0) {
                sendNotifParam[0] = Basic.NOTIF_TYPE_0;
            } else {
                sendNotifParam[0] = Basic.NOTIF_TYPE_1;
            }
            // Trigger notification emission
            mbsc.invoke(objName, "sendNotification", sendNotifParam, sendNotifSig);
            // Wait for it then check it when it comes early enough
            Notification notif = notifList.poll(timeForNotificationInSeconds, TimeUnit.SECONDS);
            // notifications are delivered with, we prefer to secure it.
            if (i == 0 && notif == null) {
                System.out.println("MXBeanNotifTest::run: Wait extra " + timeForNotificationInSeconds + " second(s) the " + " very first notification");
                notif = notifList.poll(timeForNotificationInSeconds, TimeUnit.SECONDS);
            }
            if (notif == null) {
                errorCount++;
                System.out.println("---- ERROR No notification received" + " within allocated " + timeForNotificationInSeconds + " second(s) !");
            } else {
                errorCount += checkNotification(notif, (String) sendNotifParam[0], Basic.NOTIFICATION_MESSAGE, objName);
            }
        }
        int toc = 0;
        while (notifList.size() < 2 && toc < 10) {
            Thread.sleep(499);
            toc++;
        }
        System.out.println("---- DONE\n");
    } catch (Exception e) {
        Utils.printThrowable(e, true);
        throw new RuntimeException(e);
    }
    if (errorCount == 0) {
        System.out.println("MXBeanNotifTest::run: Done without any error");
    } else {
        System.out.println("MXBeanNotifTest::run: Done with " + errorCount + " error(s)");
        throw new RuntimeException("errorCount = " + errorCount);
    }
}
Also used : OpenType(javax.management.openmbean.OpenType) ImmutableDescriptor(javax.management.ImmutableDescriptor) MBeanInfo(javax.management.MBeanInfo) HashMap(java.util.HashMap) Attribute(javax.management.Attribute) CompositeData(javax.management.openmbean.CompositeData) TabularType(javax.management.openmbean.TabularType) Notification(javax.management.Notification) TabularData(javax.management.openmbean.TabularData) JMXConnector(javax.management.remote.JMXConnector) MBeanServer(javax.management.MBeanServer) JMXServiceURL(javax.management.remote.JMXServiceURL) CompositeDataSupport(javax.management.openmbean.CompositeDataSupport) JMXConnectorServer(javax.management.remote.JMXConnectorServer) ObjectName(javax.management.ObjectName) TabularDataSupport(javax.management.openmbean.TabularDataSupport) Descriptor(javax.management.Descriptor) ImmutableDescriptor(javax.management.ImmutableDescriptor) MBeanServerConnection(javax.management.MBeanServerConnection) CompositeType(javax.management.openmbean.CompositeType)

Example 57 with Descriptor

use of javax.management.Descriptor in project geode by apache.

the class MX4JModelMBean method getAttribute.

public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
    if (attribute == null)
        throw new RuntimeOperationsException(new IllegalArgumentException(LocalizedStrings.MX4JModelMBean_ATTRIBUTE_NAME_CANNOT_BE_NULL.toLocalizedString()));
    Logger logger = getLogger();
    // I want the real info, not its clone
    ModelMBeanInfo info = getModelMBeanInfo();
    if (info == null)
        throw new AttributeNotFoundException(LocalizedStrings.MX4JModelMBean_MODELMBEANINFO_IS_NULL.toLocalizedString());
    if (logger.isEnabledFor(Logger.DEBUG))
        logger.debug("ModelMBeanInfo is: " + info);
    // This is a clone, we use it read only
    ModelMBeanAttributeInfo attrInfo = info.getAttribute(attribute);
    if (attrInfo == null)
        throw new AttributeNotFoundException(LocalizedStrings.MX4JModelMBean_CANNOT_FIND_MODELMBEANATTRIBUTEINFO_FOR_ATTRIBUTE_0.toLocalizedString(attribute));
    if (logger.isEnabledFor(Logger.DEBUG))
        logger.debug("Attribute info is: " + attrInfo);
    if (!attrInfo.isReadable())
        throw new AttributeNotFoundException(LocalizedStrings.MX4JModelMBean_ATTRIBUTE_0_IS_NOT_READABLE.toLocalizedString(attribute));
    // This returns a clone of the mbean descriptor, we use it read only
    Descriptor mbeanDescriptor = info.getMBeanDescriptor();
    if (mbeanDescriptor == null)
        throw new AttributeNotFoundException(LocalizedStrings.MX4JModelMBean_MBEAN_DESCRIPTOR_CANNOT_BE_NULL.toLocalizedString());
    if (logger.isEnabledFor(Logger.DEBUG))
        logger.debug("MBean descriptor is: " + mbeanDescriptor);
    // This descriptor is a clone
    Descriptor attributeDescriptor = attrInfo.getDescriptor();
    if (attributeDescriptor == null)
        throw new AttributeNotFoundException(LocalizedStrings.MX4JModelMBean_ATTRIBUTE_DESCRIPTOR_FOR_ATTRIBUTE_0_CANNOT_BE_NULL.toLocalizedString(attribute));
    if (logger.isEnabledFor(Logger.DEBUG))
        logger.debug("Attribute descriptor is: " + attributeDescriptor);
    Object returnValue = null;
    String lastUpdateField = "lastUpdatedTimeStamp";
    int staleness = getStaleness(attributeDescriptor, mbeanDescriptor, lastUpdateField);
    if (staleness == ALWAYS_STALE || staleness == STALE) {
        if (logger.isEnabledFor(Logger.TRACE))
            logger.trace("Value is stale");
        String getter = (String) attributeDescriptor.getFieldValue("getMethod");
        if (logger.isEnabledFor(Logger.DEBUG))
            logger.debug("getMethod field is: " + getter);
        if (getter == null) {
            // No getter, use default value
            returnValue = attributeDescriptor.getFieldValue("default");
            if (returnValue != null) {
                // Check if the return type is of the same type
                // As an extension allow covariant return type
                Class returned = returnValue.getClass();
                Class declared = loadClassWithContextClassLoader(attrInfo.getType());
                checkAssignability(returned, declared);
            }
            if (logger.isEnabledFor(Logger.DEBUG))
                logger.debug("getAttribute for attribute " + attribute + " returns default value: " + returnValue);
        } else {
            if (logger.isEnabledFor(Logger.TRACE))
                logger.trace("Invoking attribute getter...");
            // As an extension, allow attributes to be called on target objects also
            Object target = resolveTargetObject(attributeDescriptor);
            returnValue = invokeMethod(target, getter, new Class[0], new Object[0]);
            if (logger.isEnabledFor(Logger.DEBUG))
                logger.debug("Returned value is: " + returnValue);
            if (returnValue != null) {
                // Check if the return type is of the same type
                // As an extension allow covariant return type
                Class returned = returnValue.getClass();
                Class declared = loadClassWithContextClassLoader(attrInfo.getType());
                checkAssignability(returned, declared);
            }
            // Cache the new value only if caching is needed
            if (staleness != ALWAYS_STALE) {
                attributeDescriptor.setField("value", returnValue);
                attributeDescriptor.setField(lastUpdateField, Long.valueOf(System.currentTimeMillis()));
                if (logger.isEnabledFor(Logger.TRACE))
                    logger.trace("Returned value has been cached");
                // And now replace the descriptor with the updated clone
                info.setDescriptor(attributeDescriptor, "attribute");
            }
            if (logger.isEnabledFor(Logger.DEBUG))
                logger.debug("getAttribute for attribute " + attribute + " returns invoked value: " + returnValue);
        }
    } else {
        // Return cached value
        returnValue = attributeDescriptor.getFieldValue("value");
        if (returnValue != null) {
            // Check if the return type is of the same type
            // As an extension allow covariant return type
            Class returned = returnValue.getClass();
            Class declared = loadClassWithContextClassLoader(attrInfo.getType());
            checkAssignability(returned, declared);
        }
        if (logger.isEnabledFor(Logger.DEBUG))
            logger.debug("getAttribute for attribute " + attribute + " returns cached value: " + returnValue);
    }
    // Puff, everything went ok
    return returnValue;
}
Also used : AttributeNotFoundException(javax.management.AttributeNotFoundException) ModelMBeanAttributeInfo(javax.management.modelmbean.ModelMBeanAttributeInfo) Descriptor(javax.management.Descriptor) Logger(mx4j.log.Logger) FileLogger(mx4j.log.FileLogger) MBeanLogger(mx4j.log.MBeanLogger) ModelMBeanInfo(javax.management.modelmbean.ModelMBeanInfo) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 58 with Descriptor

use of javax.management.Descriptor in project geode by apache.

the class MX4JModelMBean method addAttributeChangeNotificationListener.

public void addAttributeChangeNotificationListener(NotificationListener listener, String attributeName, Object handback) throws MBeanException, RuntimeOperationsException, IllegalArgumentException {
    if (listener == null)
        throw new RuntimeOperationsException(new IllegalArgumentException(LocalizedStrings.MX4JModelMBean_LISTENER_CANNOT_BE_NULL.toLocalizedString()));
    AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter();
    if (attributeName != null) {
        filter.enableAttribute(attributeName);
    } else {
        MBeanAttributeInfo[] ai = m_modelMBeanInfo.getAttributes();
        for (int i = 0; i < ai.length; i++) {
            Descriptor d = ((ModelMBeanAttributeInfo) ai[i]).getDescriptor();
            filter.enableAttribute((String) d.getFieldValue("name"));
        }
    }
    getAttributeChangeBroadcaster().addNotificationListener(listener, filter, handback);
    Logger logger = getLogger();
    if (logger.isEnabledFor(Logger.DEBUG))
        logger.debug("Listener " + listener + " for attribute " + attributeName + " added successfully, handback is " + handback);
}
Also used : ModelMBeanAttributeInfo(javax.management.modelmbean.ModelMBeanAttributeInfo) AttributeChangeNotificationFilter(javax.management.AttributeChangeNotificationFilter) Descriptor(javax.management.Descriptor) Logger(mx4j.log.Logger) FileLogger(mx4j.log.FileLogger) MBeanLogger(mx4j.log.MBeanLogger) MBeanAttributeInfo(javax.management.MBeanAttributeInfo) ModelMBeanAttributeInfo(javax.management.modelmbean.ModelMBeanAttributeInfo) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 59 with Descriptor

use of javax.management.Descriptor in project geode by apache.

the class MX4JModelMBean method getModelMBeanLogger.

private Logger getModelMBeanLogger(String notificationType) throws MBeanException {
    // Get a copy to avoid synchronization
    ModelMBeanInfo info = getModelMBeanInfo();
    // First look if there is a suitable notification descriptor, otherwise use MBean descriptor
    Descriptor descriptor = null;
    Logger modelMBeanLogger = null;
    if (notificationType != null) {
        descriptor = info.getDescriptor(notificationType, "notification");
        modelMBeanLogger = findLogger(descriptor);
    }
    if (modelMBeanLogger == null) {
        descriptor = info.getMBeanDescriptor();
        modelMBeanLogger = findLogger(descriptor);
        if (modelMBeanLogger != null)
            return modelMBeanLogger;
    }
    return null;
}
Also used : Descriptor(javax.management.Descriptor) Logger(mx4j.log.Logger) FileLogger(mx4j.log.FileLogger) MBeanLogger(mx4j.log.MBeanLogger) ModelMBeanInfo(javax.management.modelmbean.ModelMBeanInfo)

Example 60 with Descriptor

use of javax.management.Descriptor in project tomee by apache.

the class DynamicMBeanWrapper method parameters.

static MBeanParameterInfo[] parameters(final MBeanOperationInfo jvmInfo, final Class<?>[] classes, final Annotation[][] annots) {
    final MBeanParameterInfo[] params = new MBeanParameterInfo[classes.length];
    assert classes.length == annots.length;
    String desc = "";
    for (int i = 0; i < classes.length; i++) {
        final Descriptor d = jvmInfo.getSignature()[i].getDescriptor();
        final String pn = "arg" + i;
        for (final Annotation a : annots[i]) {
            final Class<? extends Annotation> type = a.annotationType();
            if (type.equals(Description.class) || type.equals(OPENEJB_API_TO_JAVAX.get(Description.class))) {
                desc = getDescription(annotationProxy(a, Description.class), desc);
                break;
            }
        }
        params[i] = new MBeanParameterInfo(pn, classes[i].getName(), desc, d);
    }
    return params;
}
Also used : Description(org.apache.openejb.api.jmx.Description) Descriptor(javax.management.Descriptor) ImmutableDescriptor(javax.management.ImmutableDescriptor) Annotation(java.lang.annotation.Annotation) MBeanParameterInfo(javax.management.MBeanParameterInfo)

Aggregations

Descriptor (javax.management.Descriptor)60 RuntimeOperationsException (javax.management.RuntimeOperationsException)18 ModelMBeanInfo (javax.management.modelmbean.ModelMBeanInfo)16 ModelMBeanAttributeInfo (javax.management.modelmbean.ModelMBeanAttributeInfo)15 ImmutableDescriptor (javax.management.ImmutableDescriptor)9 MBeanException (javax.management.MBeanException)9 ModelMBeanOperationInfo (javax.management.modelmbean.ModelMBeanOperationInfo)9 AttributeNotFoundException (javax.management.AttributeNotFoundException)8 MBeanServer (javax.management.MBeanServer)8 ObjectName (javax.management.ObjectName)8 ServiceNotFoundException (javax.management.ServiceNotFoundException)8 Method (java.lang.reflect.Method)7 InstanceNotFoundException (javax.management.InstanceNotFoundException)7 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)7 FileLogger (mx4j.log.FileLogger)7 Logger (mx4j.log.Logger)7 MBeanLogger (mx4j.log.MBeanLogger)7 InvocationTargetException (java.lang.reflect.InvocationTargetException)6 Date (java.util.Date)6 ListenerNotFoundException (javax.management.ListenerNotFoundException)6