Example usage for javax.management Notification getType

List of usage examples for javax.management Notification getType

Introduction

In this page you can find the example usage for javax.management Notification getType.

Prototype

public String getType() 

Source Link

Document

Get the notification type.

Usage

From source file:de.iew.spring.integration.SpringIntegrationJmxTest.java

@Test
public void testJmxSpringIntegrationWithAuditEventMessage() throws Exception {
    // Testfix erstellen
    long timestamp = System.currentTimeMillis();

    Authentication authentication = newAnonymousAuthentication();

    AuditEventMessage auditEventMessage = new AuditEventMessage();
    auditEventMessage.setTimestamp(new Date(timestamp));
    auditEventMessage.setPrincipal(authentication.getName());
    auditEventMessage.setSeverity(Severity.INFO);
    auditEventMessage.setMessage("Foo Bar");

    // Test durchfhren
    Map<String, Object> headers = new Hashtable<String, Object>();
    GenericMessage<AuditEventMessage> message = new GenericMessage<AuditEventMessage>(auditEventMessage,
            headers);/*w  w w .  j  ava2 s .  c om*/
    this.messageChannel.send(message);

    // Test auswerten
    /// Etwas warten, bis die Notifications verschickt wurden
    Thread.sleep(3000);

    Assert.assertEquals(1, this.springIntegrationTestNotificationListener.getNotifications().size());

    Notification notification = this.springIntegrationTestNotificationListener.getNotifications().get(0);

    Assert.assertEquals(AuditEventMessage.class.getName(), notification.getType());
    Assert.assertNull(notification.getMessage());

    AuditEventMessage userData = (AuditEventMessage) notification.getUserData();
    Assert.assertEquals("Foo Bar", userData.getMessage());
    Assert.assertEquals(Severity.INFO, userData.getSeverity());
    Assert.assertEquals(new Date(timestamp), userData.getTimestamp());
}

From source file:org.wso2.carbon.registry.subscription.test.util.JMXClient.java

public void handleNotification(Notification ntfyObj, Object handback) {
    log.info("***************************************************");
    log.info("* Notification received at " + new Date().toString());
    log.info("* type      = " + ntfyObj.getType());
    log.info("* message   = " + ntfyObj.getMessage());

    if (ntfyObj.getMessage().contains(path)) {
        setSuccess(true);/*w ww  .  jav  a  2 s .  com*/
    }

    log.info("* seqNum    = " + ntfyObj.getSequenceNumber());
    log.info("* source    = " + ntfyObj.getSource());
    log.info("* seqNum    = " + Long.toString(ntfyObj.getSequenceNumber()));
    log.info("* timeStamp = " + new Date(ntfyObj.getTimeStamp()));
    log.info("* userData  = " + ntfyObj.getUserData());
    log.info("***************************************************");
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.GarbageCollectorMetricSet.java

GarbageCollectorMetricSet() {
    this.garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();

    this.minorGcTimer = new Timer();
    this.majorGcTimer = new Timer();

    // Determine the location of the gc log file (note that there's not support for rolling gc logs)
    String gcLogFilePath = null;/*from   www  . j a  v a 2  s .  co m*/
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<String> inputArguments = runtimeMXBean.getInputArguments();
    for (String argument : inputArguments) {
        if (argument.startsWith(LOG_GC_JVM_PARAM)) {
            gcLogFilePath = argument.substring(LOG_GC_JVM_PARAM.length());
            break;
        }
    }

    if (gcLogFilePath != null && !gcLogFilePath.trim().isEmpty()) {
        final File gcLogFile = new File(gcLogFilePath);
        if (gcLogFile.exists()) {
            this.fullCollectionsCounter = new AtomicLong();

            this.gcLogTailer = Tailer.create(gcLogFile, new TailerListenerAdapter() {
                @Override
                public void handle(String line) {
                    if (line != null && line.contains(FULL_GC_LOG_STRING)) {
                        fullCollectionsCounter.incrementAndGet();
                    }
                }
            }, GC_LOG_FILE_TAIL_DELAY_IN_MILLIS);
        }
    }

    // Attach a listener to the GarbageCollectorMXBeans
    this.gcEventListener = new NotificationListener() {
        @Override
        public void handleNotification(Notification notification, Object handback) {
            String notificationType = notification.getType();
            if (notificationType.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                CompositeData compositeData = CompositeData.class.cast(notification.getUserData());
                GarbageCollectionNotificationInfo gcNotificationInfo = GarbageCollectionNotificationInfo
                        .from(compositeData);

                if (GC_NOTIFICATION_MINOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    minorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                } else if (GC_NOTIFICATION_MAJOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    majorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                }
            }
        }
    };

    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        if (NotificationEmitter.class.isInstance(garbageCollectorMXBean)) {
            NotificationEmitter emitter = NotificationEmitter.class.cast(garbageCollectorMXBean);
            emitter.addNotificationListener(gcEventListener, null, null);
        }
    }

    // Set up metrics
    Map<String, Metric> metricsByNames = new HashMap<>();

    if (fullCollectionsCounter != null) {
        this.fullCollectionsGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return fullCollectionsCounter.get();
            }
        };
        metricsByNames.put("fullCollections", fullCollectionsGauge);
    }

    metricsByNames.put("majorGcTimer", majorGcTimer);
    metricsByNames.put("minorGcTimer", minorGcTimer);

    List<GarbageCollectorStatus> garbageCollectorStatuses = new ArrayList<>();
    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        final String garbageCollectorName = garbageCollectorMXBean.getName();
        final String garbageCollectorNamespace = MetricNamingUtil.join("collectors",
                MetricNamingUtil.sanitize(garbageCollectorName));

        final Gauge<Long> collectionsGauge;
        if (garbageCollectorMXBean.getCollectionCount() >= 0) {
            collectionsGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionCount();
                }
            };
            metricsByNames.put(MetricNamingUtil.join(garbageCollectorNamespace, "collections"),
                    collectionsGauge);
        } else {
            collectionsGauge = null;
        }

        final Gauge<Long> totalCollectionDurationInMillisGauge;
        if (garbageCollectorMXBean.getCollectionTime() >= 0) {
            totalCollectionDurationInMillisGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionTime();
                }
            };
            metricsByNames.put(
                    MetricNamingUtil.join(garbageCollectorNamespace, "totalCollectionDurationInMillis"),
                    totalCollectionDurationInMillisGauge);
        } else {
            totalCollectionDurationInMillisGauge = null;
        }

        garbageCollectorStatuses.add(new GarbageCollectorStatus() {
            @Override
            public String getName() {
                return garbageCollectorName;
            }

            @Override
            public Gauge<Long> getCollectionsGauge() {
                return collectionsGauge;
            }

            @Override
            public Gauge<Long> getTotalCollectionDurationInMillisGauge() {
                return totalCollectionDurationInMillisGauge;
            }
        });
    }
    this.garbageCollectorStatuses = garbageCollectorStatuses;

    this.metricsByNames = metricsByNames;
}

From source file:io.fabric8.spi.process.AbstractProcessHandler.java

@Override
public final Future<ManagedProcess> start() {
    State state = managedProcess.getState();
    assertNotDestroyed(state);/*from w w  w.  j  ava2 s  .com*/

    // Setup a call back notification to get the JMX connection of the started process
    final CountDownLatch latch = new CountDownLatch(1);
    String jmxAgentServiceURL = managedProcess
            .getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_SERVER_URL);
    String jmxAgentUsername = managedProcess.getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_USERNAME);
    String jmxAgentPassword = managedProcess.getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_PASSWORD);
    JMXConnector connector = ManagementUtils.getJMXConnector(jmxAgentServiceURL, jmxAgentUsername,
            jmxAgentPassword, 200, TimeUnit.MILLISECONDS);
    try {
        final MBeanServerConnection server = connector.getMBeanServerConnection();
        server.addNotificationListener(Agent.OBJECT_NAME, new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handback) {
                String eventType = notification.getType();
                if (NOTIFICATION_TYPE_AGENT_REGISTRATION.equals(eventType)) {
                    AgentRegistration agentReg = (AgentRegistration) notification.getSource();
                    String agentName = agentReg.getIdentity().getName();
                    String procName = (String) handback;
                    if (agentName.equals(procName)) {
                        try {
                            server.removeNotificationListener(Agent.OBJECT_NAME, this);
                        } catch (Exception ex) {
                            // ignore
                        }
                        latch.countDown();
                    }
                }
            }
        }, null, managedProcess.getIdentity().getName());
    } catch (RuntimeException rte) {
        throw rte;
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    } finally {
        IOUtils.safeClose(connector);
    }

    try {
        if (state == State.CREATED || state == State.STOPPED) {
            doStart(managedProcess);
            IllegalStateAssertion.assertNotNull(process, "No process created");
            managedProcess.setState(State.STARTED);
        }
    } catch (Exception ex) {
        throw new LifecycleException("Cannot start container", ex);
    }

    return new ProcessFuture(managedProcess); //, latch);
}

From source file:org.zenoss.jmxnl.NotificationListener.java

public void handleNotification(Notification notification, Object obj) {
    Boolean sendEvent = true;//w w  w .  j  av a 2 s. c om
    Boolean reconnect = false;
    String type = notification.getType();

    Map<String, String> evt = new HashMap<String, String>();
    evt.put("device", (String) obj);
    evt.put("severity", "2");
    evt.put("eventClassKey", type);

    if (notification instanceof JMXConnectionNotification) {
        if (type.equals(JMXConnectionNotification.CLOSED)) {
            sendConnectionEvent("4", "JMX connection has been closed");
            reconnect = true;
        } else if (type.equals(JMXConnectionNotification.FAILED)) {
            sendConnectionEvent("4", "JMX connection has failed");
            reconnect = true;
        } else if (type.equals(JMXConnectionNotification.NOTIFS_LOST)) {
            sendConnectionEvent("3", "JMX connection has possibly lost notifications");
        } else if (type.equals(JMXConnectionNotification.OPENED)) {
            sendConnectionEvent("0", "JMX connection has been opened");
        }

        // Event has already been sent
        sendEvent = false;
    } else if (notification instanceof AttributeChangeNotification) {
        AttributeChangeNotification notif = (AttributeChangeNotification) notification;
        evt.put("component", notif.getAttributeName());
        evt.put("eventKey", notif.getSource().toString() + ":" + notif.getAttributeName());
        evt.put("summary", "Attribute changed from " + notif.getOldValue() + " to " + notif.getNewValue());
    } else if (notification instanceof MBeanServerNotification) {
        MBeanServerNotification notif = (MBeanServerNotification) notification;
        evt.put("severity", "1");
        evt.put("component", notif.getMBeanName().getDomain());
        evt.put("eventKey", notif.getMBeanName().toString());
        if (type.equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {
            evt.put("summary", "MBean Registered");
        } else if (type.equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
            evt.put("summary", "MBean Unregistered");
        } else {
            evt.put("summary", "Unknown MBean Server Notification");
        }

        // These are too noisy and unlikely to be useful
        sendEvent = false;
    } else if (notification instanceof MonitorNotification) {
        MonitorNotification notif = (MonitorNotification) notification;
        evt.put("severity", "3");
        evt.put("component", notif.getObservedObject().toString() + ":" + notif.getObservedAttribute());
        if (type.equals(MonitorNotification.OBSERVED_ATTRIBUTE_ERROR)) {
            evt.put("summary", "Observed attribute not contained within the observed object");
        } else if (type.equals(MonitorNotification.OBSERVED_ATTRIBUTE_TYPE_ERROR)) {
            evt.put("summary", "Type of the observed attribute is not correct");
        } else if (type.equals(MonitorNotification.OBSERVED_OBJECT_ERROR)) {
            evt.put("summary", "The observed object is not registered in the MBean server");
        } else if (type.equals(MonitorNotification.RUNTIME_ERROR)) {
            evt.put("summary", "Non pre-defined error has occurred");
        } else if (type.equals(MonitorNotification.STRING_TO_COMPARE_VALUE_DIFFERED)) {
            evt.put("summary", "Attribute differs from the string to compare");
        } else if (type.equals(MonitorNotification.STRING_TO_COMPARE_VALUE_MATCHED)) {
            evt.put("summary", "Attribute matched the string to compare");
        } else if (type.equals(MonitorNotification.THRESHOLD_ERROR)) {
            evt.put("summary", "Type of threshold is not correct");
        } else if (type.equals(MonitorNotification.THRESHOLD_HIGH_VALUE_EXCEEDED)) {
            evt.put("summary", "Attribute has exceeded the threshold high value");
        } else if (type.equals(MonitorNotification.THRESHOLD_LOW_VALUE_EXCEEDED)) {
            evt.put("summary", "Attribute has exceeded the threshold low value");
        } else if (type.equals(MonitorNotification.THRESHOLD_VALUE_EXCEEDED)) {
            evt.put("summary", "Attribute has reached the threshold value");
        } else {
            evt.put("summary", "Unknown Monitor Notification");
        }
    } else if (notification instanceof RelationNotification) {
        RelationNotification notif = (RelationNotification) notification;
        evt.put("component", notif.getRelationId());
        if (type.equals(RelationNotification.RELATION_BASIC_CREATION)) {
            evt.put("summary", "Internal relation created");
        } else if (type.equals(RelationNotification.RELATION_BASIC_REMOVAL)) {
            evt.put("summary", "Internal relation removed");
        } else if (type.equals(RelationNotification.RELATION_BASIC_UPDATE)) {
            evt.put("summary", "Internal relation updated");
        } else if (type.equals(RelationNotification.RELATION_MBEAN_CREATION)) {
            evt.put("summary", "MBean relation created");
        } else if (type.equals(RelationNotification.RELATION_MBEAN_REMOVAL)) {
            evt.put("summary", "MBean relation removed");
        } else if (type.equals(RelationNotification.RELATION_MBEAN_UPDATE)) {
            evt.put("summary", "MBean relation updated");
        }
    } else {
        if (notification.getMessage().equals("")) {
            evt.put("summary", "Unknown JMX Notification Type");
        } else {
            evt.put("summary", notification.getMessage());
        }
    }

    if (sendEvent) {
        try {
            EventSender.getEventSender().sendEvent(evt);
        } catch (XmlRpcException e) {
            log.error("Error sending event: " + e);
        }
    }

    if (reconnect) {
        run();
    }
}

From source file:com.googlecode.psiprobe.beans.ContainerListenerBean.java

/**
 * Handles creation and deletion of new "worker" threads.
 */// www .j  a  v a 2  s  .  c o m
public synchronized void handleNotification(Notification notification, Object object) {
    if (notification instanceof MBeanServerNotification) {
        ObjectName objectName = ((MBeanServerNotification) notification).getMBeanName();

        if (notification.getType().equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {

            if ("RequestProcessor".equals(objectName.getKeyProperty("type"))) {
                ThreadPoolObjectName threadPoolObjectName = findPool(objectName.getKeyProperty("worker"));
                if (threadPoolObjectName != null) {
                    threadPoolObjectName.getRequestProcessorNames().add(objectName);
                }
            }

        } else if (notification.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {

            if ("RequestProcessor".equals(objectName.getKeyProperty("type"))) {
                ThreadPoolObjectName threadPoolObjectName = findPool(objectName.getKeyProperty("worker"));
                if (threadPoolObjectName != null) {
                    threadPoolObjectName.getRequestProcessorNames().remove(objectName);
                }
            }
        }
    }
}

From source file:org.apache.catalina.manager.StatusManagerServlet.java

public void handleNotification(Notification notification, java.lang.Object handback) {

    if (notification instanceof MBeanServerNotification) {
        ObjectName objectName = ((MBeanServerNotification) notification).getMBeanName();
        if (notification.getType().equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {
            String type = objectName.getKeyProperty("type");
            if (type != null) {
                if (type.equals("ProtocolHandler")) {
                    protocolHandlers.addElement(objectName);
                } else if (type.equals("ThreadPool")) {
                    threadPools.addElement(objectName);
                } else if (type.equals("GlobalRequestProcessor")) {
                    globalRequestProcessors.addElement(objectName);
                } else if (type.equals("RequestProcessor")) {
                    requestProcessors.addElement(objectName);
                }/*from w  w  w  .j  a v a2 s.co m*/
            }
        } else if (notification.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
            String type = objectName.getKeyProperty("type");
            if (type != null) {
                if (type.equals("ProtocolHandler")) {
                    protocolHandlers.removeElement(objectName);
                } else if (type.equals("ThreadPool")) {
                    threadPools.removeElement(objectName);
                } else if (type.equals("GlobalRequestProcessor")) {
                    globalRequestProcessors.removeElement(objectName);
                } else if (type.equals("RequestProcessor")) {
                    requestProcessors.removeElement(objectName);
                }
            }
            String j2eeType = objectName.getKeyProperty("j2eeType");
            if (j2eeType != null) {

            }
        }
    }

}

From source file:org.apache.geode.admin.jmx.internal.StatisticResourceJmxImpl.java

/**
 * Handles notification to refresh. Reacts by refreshing the values of this SystemMember's
 * ConfigurationParamaters. Any other notification is ignored. Given notification is handled only
 * if there is any JMX client connected to the system.
 * <p>/*from  w ww  .j a v a 2 s. c  o m*/
 * TODO: investigate use of NotificationFilter instead of explicit check...
 * 
 * @param notification the JMX notification being received
 * @param hb handback object is unused
 */
public void handleNotification(Notification notification, Object hb) {
    AdminDistributedSystemJmxImpl adminDSJmx = (AdminDistributedSystemJmxImpl) this.member
            .getDistributedSystem();

    String typeStatResourceStats = RefreshNotificationType.STATISTIC_RESOURCE_STATISTICS.getType();

    if (typeStatResourceStats.equals(notification.getType())
            && getMBeanName().equals(notification.getUserData()) && !adminDSJmx.isRmiClientCountZero()) {
        try {
            refresh();

        } catch (org.apache.geode.admin.AdminException e) {
            logger.warn(e.getMessage(), e);
        } catch (org.apache.geode.admin.OperationCancelledException e) {
            // underlying resource is no longer reachable by remote admin
            logger.warn(e.getMessage(), e);
            _setRefreshInterval(0);
        } catch (CancelException e) {
            // shutting down - okay to ignore
        } catch (java.lang.RuntimeException e) {
            logger.debug(e.getMessage(), e); // dead in water, print, and then ignore
            _setRefreshInterval(0); // zero out to avoid more exceptions
        } catch (VirtualMachineError err) {
            SystemFailure.initiateFailure(err);
            // If this ever returns, rethrow the error. We're poisoned
            // now, so don't let this thread continue.
            throw err;
        } catch (java.lang.Error e) {
            // Whenever you catch Error or Throwable, you must also
            // catch VirtualMachineError (see above). However, there is
            // _still_ a possibility that you are dealing with a cascading
            // error condition, so you also need to check to see if the JVM
            // is still usable:
            SystemFailure.checkFailure();
            logger.error(e.getMessage(), e); // dead in water, print, and then ignore
            this.refreshInterval = 0; // zero out to avoid more exceptions
        }
    }
}

From source file:org.jboss.web.tomcat.tc5.Tomcat5.java

public void handleNotification(Notification msg, Object handback) {
    String type = msg.getType();
    if (type.equals(Server.START_NOTIFICATION_TYPE)) {
        log.debug("Saw " + type + " notification, starting connectors");
        try {//w  ww  .  j  av  a  2  s  .  c o m
            startConnectors();
        } catch (Exception e) {
            log.warn("Failed to startConnectors", e);
        }
    }
}

From source file:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * Invoked when the MBean this class listens to publishes an event.
 * We're only interested in repair-related events.
 * Their format is explained at {@link org.apache.cassandra.service.StorageServiceMBean#forceRepairAsync}
 * The format is: notification type: "repair" notification userData: int array of length 2 where
 * [0] = command number [1] = ordinal of AntiEntropyService.Status
 *//*from  ww  w . java 2 s.c o m*/
@Override
public void handleNotification(Notification notification, Object handback) {
    Thread.currentThread().setName(clusterName);
    // we're interested in "repair"
    String type = notification.getType();
    LOG.debug("Received notification: {} with type {} and repairStatusHandler {}", notification, type,
            repairStatusHandler);
    if (repairStatusHandler.isPresent() && ("repair").equals(type)) {
        processOldApiNotification(notification);
    }

    if (repairStatusHandler.isPresent() && ("progress").equals(type)) {
        processNewApiNotification(notification);
    }
}