Example usage for javax.management Notification getUserData

List of usage examples for javax.management Notification getUserData

Introduction

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

Prototype

public Object getUserData() 

Source Link

Document

Get the user data.

Usage

From source file:org.helios.netty.jmx.ThreadPoolFactory.java

/**
 * {@inheritDoc}/*from   w  ww  .  j a  va2 s.c  om*/
 * @see javax.management.NotificationFilter#isNotificationEnabled(javax.management.Notification)
 */
@Override
public boolean isNotificationEnabled(Notification notification) {
    String notifType = notification.getType();
    return (METRIC_NAME_NOTIFICATION.equals(notifType) && notification.getUserData() instanceof Set)
            || (METRIC_NOTIFICATION.equals(notifType) && notification.getUserData() instanceof JSONObject);
}

From source file:org.helios.netty.jmx.ThreadPoolFactory.java

/**
 * {@inheritDoc}//from  w w  w .  j  ava2s  . co  m
 * @see javax.management.NotificationListener#handleNotification(javax.management.Notification, java.lang.Object)
 */
@SuppressWarnings("unchecked")
@Override
public void handleNotification(Notification notification, Object handback) {
    String notifType = notification.getType();
    if (METRIC_NAME_NOTIFICATION.equals(notifType)) {
        Set<String> names = (Set<String>) notification.getUserData();
        names.addAll(metricNames);
    } else {
        addMetrics((JSONObject) notification.getUserData());
    }
}

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

private String formatNotification(Notification notification) {
    StringBuilder sb = new StringBuilder();
    sb.append("recieved notification class: ").append(notification.getType());
    sb.append(", method: ").append(notification.getSource());
    sb.append(", sequence: ").append(notification.getSequenceNumber());
    sb.append(",  timestamp: ").append(notification.getTimeStamp());
    sb.append(",  data: ");

    Object userData = notification.getUserData();
    String formattedUserData;//w w w  .  j a  v  a2 s.co  m
    if (userData == null) {
        formattedUserData = "";
    } else if (userData instanceof String) {
        formattedUserData = StringUtils.arrayToCommaDelimitedString((Object[]) notification.getUserData());
    } else {
        formattedUserData = userData.toString();
    }
    sb.append(formattedUserData);

    return sb.toString();
}

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);/* ww  w. j a v  a  2 s  .  c o m*/
    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.apache.pig.impl.util.SpillableMemoryManager.java

@Override
public void handleNotification(Notification n, Object o) {
    CompositeData cd = (CompositeData) n.getUserData();
    MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);
    // free the amount exceeded over the threshold and then a further half
    // so if threshold = heapmax/2, we will be trying to free
    // used - heapmax/2 + heapmax/4
    long toFree = 0L;
    if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
        toFree = info.getUsage().getUsed() - memoryThresholdSize + (long) (memoryThresholdSize * 0.5);

        //log//from   w w w  .j ava2s .  com
        String msg = "memory handler call- Usage threshold " + info.getUsage() + ", toFree = " + toFree;
        if (!firstUsageThreshExceededLogged) {
            log.info("first " + msg);
            firstUsageThreshExceededLogged = true;
        } else {
            log.debug(msg);
        }
    } else { // MEMORY_COLLECTION_THRESHOLD_EXCEEDED CASE
        toFree = info.getUsage().getUsed() - collectionThresholdSize + (long) (collectionThresholdSize * 0.5);

        //log
        String msg = "memory handler call - Collection threshold " + info.getUsage() + ", toFree = " + toFree;
        if (!firstCollectionThreshExceededLogged) {
            log.info("first " + msg);
            firstCollectionThreshExceededLogged = true;
        } else {
            log.debug(msg);
        }

    }
    if (toFree < 0) {
        log.debug("low memory handler returning " + "because there is nothing to free");
        return;
    }

    // Use a separate spillLock to block multiple handleNotification calls
    synchronized (spillLock) {
        synchronized (spillables) {
            spillablesSR = new LinkedList<SpillablePtr>();
            for (Iterator<WeakReference<Spillable>> i = spillables.iterator(); i.hasNext();) {
                Spillable s = i.next().get();
                if (s == null) {
                    i.remove();
                    continue;
                }
                // Create a list with spillable size for stable sorting. Refer PIG-4012
                spillablesSR.add(new SpillablePtr(s, s.getMemorySize()));
            }
            log.debug("Spillables list size: " + spillablesSR.size());
            Collections.sort(spillablesSR, new Comparator<SpillablePtr>() {
                @Override
                public int compare(SpillablePtr o1Ref, SpillablePtr o2Ref) {
                    long o1Size = o1Ref.getMemorySize();
                    long o2Size = o2Ref.getMemorySize();

                    if (o1Size == o2Size) {
                        return 0;
                    }
                    if (o1Size < o2Size) {
                        return 1;
                    }
                    return -1;
                }
            });
            // Block new bags from being registered
            blockRegisterOnSpill = true;
        }

        try {
            long estimatedFreed = 0;
            int numObjSpilled = 0;
            boolean invokeGC = false;
            boolean extraGCCalled = false;
            boolean isGroupingSpillable = false;
            for (Iterator<SpillablePtr> i = spillablesSR.iterator(); i.hasNext();) {
                SpillablePtr sPtr = i.next();
                Spillable s = sPtr.get();
                // Still need to check for null here, even after we removed
                // above, because the reference may have gone bad on us
                // since the last check.
                if (s == null) {
                    i.remove();
                    continue;
                }
                long toBeFreed = sPtr.getMemorySize();
                log.debug("Memorysize = " + toBeFreed + ", spillFilesizethreshold = " + spillFileSizeThreshold
                        + ", gcactivationsize = " + gcActivationSize);
                // Don't keep trying if the rest of files are too small
                if (toBeFreed < spillFileSizeThreshold) {
                    log.debug("spilling small files - getting out of memory handler");
                    break;
                }
                isGroupingSpillable = (s instanceof GroupingSpillable);
                // If single Spillable is bigger than the threshold,
                // we force GC to make sure we really need to keep this
                // object before paying for the expensive spill().
                // Done at most once per handleNotification.
                // Do not invoke extraGC for GroupingSpillable. Its size will always exceed
                // extraGCSpillSizeThreshold and the data is always strong referenced.
                if (!extraGCCalled && extraGCSpillSizeThreshold != 0 && toBeFreed > extraGCSpillSizeThreshold
                        && !isGroupingSpillable) {
                    log.debug("Single spillable has size " + toBeFreed + "bytes. Calling extra gc()");
                    // this extra assignment to null is needed so that gc can free the
                    // spillable if nothing else is pointing at it
                    s = null;
                    System.gc();
                    extraGCCalled = true;
                    // checking again to see if this reference is still valid
                    s = sPtr.get();
                    if (s == null) {
                        i.remove();
                        accumulatedFreeSize = 0;
                        invokeGC = false;
                        continue;
                    }
                }
                // Unblock registering of new bags temporarily as aggregation
                // of POPartialAgg requires new record to be loaded.
                blockRegisterOnSpill = !isGroupingSpillable;
                long numSpilled;
                try {
                    numSpilled = s.spill();
                } finally {
                    blockRegisterOnSpill = true;
                }

                if (numSpilled > 0) {
                    numObjSpilled++;
                    estimatedFreed += toBeFreed;
                    accumulatedFreeSize += toBeFreed;
                }
                // This should significantly reduce the number of small files
                // in case that we have a lot of nested bags
                if (accumulatedFreeSize > gcActivationSize) {
                    invokeGC = true;
                }

                if (estimatedFreed > toFree) {
                    log.debug("Freed enough space - getting out of memory handler");
                    invokeGC = true;
                    break;
                }
            }
            spillablesSR = null;
            /* Poke the GC again to see if we successfully freed enough memory */
            if (invokeGC) {
                System.gc();
                // now that we have invoked the GC, reset accumulatedFreeSize
                accumulatedFreeSize = 0;
            }
            if (estimatedFreed > 0) {
                String msg = "Spilled an estimate of " + estimatedFreed + " bytes from " + numObjSpilled
                        + " objects. " + info.getUsage();
                ;
                log.info(msg);
            }
        } finally {
            blockRegisterOnSpill = false;
        }
    }

}

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 w  w w. jav  a2s . c  om
    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: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>/*ww  w  . ja  v a  2s .com*/
 * 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:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * Handles notifications from the old repair API (forceRepairAsync)
 *//*from   w  w  w  . j a v a  2s . com*/
private void processOldApiNotification(Notification notification) {
    try {
        int[] data = (int[]) notification.getUserData();
        // get the repair sequence number
        int repairNo = data[0];
        // get the repair status
        ActiveRepairService.Status status = ActiveRepairService.Status.values()[data[1]];
        // this is some text message like "Starting repair...", "Finished repair...", etc.
        String message = notification.getMessage();
        // let the handler process the event
        repairStatusHandler.get().handle(repairNo, Optional.of(status), Optional.absent(), message);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        LOG.error("Error while processing JMX notification", e);
    }
}

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

/**
 * Handles notifications from the new repair API (repairAsync)
 *///from   w w  w .j a va  2s.  c om
private void processNewApiNotification(Notification notification) {
    Map<String, Integer> data = (Map<String, Integer>) notification.getUserData();
    try {
        // get the repair sequence number
        int repairNo = Integer.parseInt(((String) notification.getSource()).split(":")[1]);
        // get the progress status
        ProgressEventType progress = ProgressEventType.values()[data.get("type")];
        // this is some text message like "Starting repair...", "Finished repair...", etc.
        String message = notification.getMessage();
        // let the handler process the event
        repairStatusHandler.get().handle(repairNo, Optional.absent(), Optional.of(progress), message);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        LOG.error("Error while processing JMX notification", e);
    }
}

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);/*from   w  w  w  .  j a  v  a  2 s .  c  o m*/
    }

    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("***************************************************");
}