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: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// www  .  j a va  2s.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:org.apache.giraph.graph.GraphTaskManager.java

/**
 * Install GC monitoring. This method intercepts all GC, log the gc, and
 * notifies an out-of-core engine (if any is used) about the GC.
 *//*from   w ww .j a  v  a  2  s .  c o  m*/
private void installGCMonitoring() {
    List<GarbageCollectorMXBean> mxBeans = ManagementFactory.getGarbageCollectorMXBeans();
    final OutOfCoreEngine oocEngine = serviceWorker.getServerData().getOocEngine();
    for (GarbageCollectorMXBean gcBean : mxBeans) {
        NotificationEmitter emitter = (NotificationEmitter) gcBean;
        NotificationListener listener = new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handle) {
                if (notification.getType()
                        .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                    GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo
                            .from((CompositeData) notification.getUserData());

                    if (LOG.isInfoEnabled()) {
                        LOG.info("installGCMonitoring: name = " + info.getGcName() + ", action = "
                                + info.getGcAction() + ", cause = " + info.getGcCause() + ", duration = "
                                + info.getGcInfo().getDuration() + "ms");
                    }
                    gcTimeMetric.inc(info.getGcInfo().getDuration());
                    if (oocEngine != null) {
                        oocEngine.gcCompleted(info);
                    }
                }
            }
        };
        //Add the listener
        emitter.addNotificationListener(listener, null, null);
    }
}

From source file:org.hyperic.hq.product.jmx.MxNotificationListener.java

public synchronized void handleNotification(Notification notification, Object handback) {

    String msg;/*from w  w w.  j  a v a 2  s  .com*/
    boolean isAttrChange = notification instanceof AttributeChangeNotification;

    if (log.isDebugEnabled()) {
        log.debug(this.plugin.getName() + " received notification: " + notification);
    }

    if (isAttrChange && this.isConfigTrackEnabled) {
        AttributeChangeNotification change = (AttributeChangeNotification) notification;

        msg = "Attribute: " + change.getAttributeName() + " changed from " + change.getOldValue() + " to "
                + change.getNewValue();
    } else if (this.isLogTrackEnabled) {
        msg = notification.getMessage();
    } else {
        return;
    }

    if (msg == null) {
        Object data = notification.getUserData();
        if (data != null) {
            msg = data.toString();
        } else {
            msg = notification.getType();
        }
    }

    long time = notification.getTimeStamp();

    // Default level to INFO
    int level = LogTrackPlugin.LOGLEVEL_INFO;

    // Check notification.getType() for Error, Warn, Info, Debug (case insensitive)
    String typeString = notification.getType();
    if (typeString != null) {
        if (typeString.equalsIgnoreCase(LogTrackPlugin.LOGLEVEL_ERROR_LABEL)) {
            level = LogTrackPlugin.LOGLEVEL_ERROR;
        } else if (typeString.equalsIgnoreCase(LogTrackPlugin.LOGLEVEL_WARN_LABEL)) {
            level = LogTrackPlugin.LOGLEVEL_WARN;
        } else if (typeString.equalsIgnoreCase(LogTrackPlugin.LOGLEVEL_DEBUG_LABEL)) {
            level = LogTrackPlugin.LOGLEVEL_DEBUG;
        }
    }

    String source = notification.getSource().toString();

    if (isAttrChange) {
        TrackEvent event = new TrackEvent(this.plugin.getName(), time, level, source, msg);
        this.plugin.getManager().reportEvent(event);
    } else {
        //apply filters to msg
        this.plugin.reportEvent(time, level, source, msg);
    }
}

From source file:org.apache.cassandra.tools.NodeProbe.java

public void handleNotification(Notification notification, Object handback) {
    if ("repair".equals(notification.getType())) {
        int[] status = (int[]) notification.getUserData();
        assert status.length == 2;
        if (cmd == status[0]) {
            String message = String.format("[%s] %s", format.format(notification.getTimeStamp()),
                    notification.getMessage());
            out.println(message);//w ww.j  a  v  a  2  s  .c  om
            // repair status is int array with [0] = cmd number, [1] = status
            if (status[1] == ActiveRepairService.Status.SESSION_FAILED.ordinal())
                success = false;
            else if (status[1] == ActiveRepairService.Status.FINISHED.ordinal())
                condition.signalAll();
        }
    } else if (JMXConnectionNotification.NOTIFS_LOST.equals(notification.getType())) {
        String message = String.format(
                "[%s] Lost notification. You should check server log for repair status of keyspace %s",
                format.format(notification.getTimeStamp()), keyspace);
        out.println(message);
    } else if (JMXConnectionNotification.FAILED.equals(notification.getType())
            || JMXConnectionNotification.CLOSED.equals(notification.getType())) {
        String message = String
                .format("JMX connection closed. You should check server log for repair status of keyspace %s"
                        + "(Subsequent keyspaces are not going to be repaired).", keyspace);
        error = new IOException(message);
        condition.signalAll();
    }
}

From source file:com.heliosapm.script.AbstractDeployedScript.java

/**
 * Initializes the configuration//w w  w .j a va  2 s. co  m
 */
public void initConfig() {
    watchedConfig.set(findWatchedConfiguration());
    if (watchedConfig.get() != null) {
        Map<String, String> parentConfig = getParentConfigurationMap();
        if (parentConfig != null && !parentConfig.isEmpty()) {
            this.getConfiguration().load(parentConfig);
        }
        if (watchedConfigListenerRegistered.compareAndSet(false, true)) {
            try {
                JMXHelper.addNotificationListener(watchedConfig.get(), configChangeListener,
                        new NotificationFilter() {
                            /**  */
                            private static final long serialVersionUID = -2890751194005498532L;

                            @Override
                            public boolean isNotificationEnabled(final Notification notification) {
                                final Object userData = notification.getUserData();
                                return (notification.getSource().equals(watchedConfig.get())
                                        && NOTIF_CONFIG_MOD.equals(notification.getType()) && userData != null
                                        && (userData instanceof Configuration)
                                        && !(((Configuration) userData).isEmpty()));
                            }
                        }, null);
            } catch (Exception ex) {
                try {
                    JMXHelper.removeNotificationListener(watchedConfig.get(), configChangeListener);
                } catch (Exception x) {
                    /* No Op */}
                log.error("Failed to register configuration listener", ex);
                watchedConfigListenerRegistered.set(false);
            }
        }
    }
}

From source file:org.apache.coyote.tomcat5.MapperListener.java

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

    if (notification instanceof MBeanServerNotification) {
        ObjectName objectName = ((MBeanServerNotification) notification).getMBeanName();
        String j2eeType = objectName.getKeyProperty("j2eeType");
        String engineName = null;
        if (j2eeType != null) {
            if ((j2eeType.equals("WebModule")) || (j2eeType.equals("Servlet"))) {
                if (mBeanServer.isRegistered(objectName)) {
                    try {
                        engineName = (String) mBeanServer.getAttribute(objectName, "engineName");
                    } catch (Exception e) {
                        // Ignore  
                    }//  www.  j  a  va2s  .c  o m
                }
            }
        }

        // At deployment time, engineName is always = null.
        if ((!"*".equals(domain)) && (!domain.equals(objectName.getDomain()))
                && ((!domain.equals(engineName)) && (engineName != null))) {
            return;
        }

        log.debug("Handle " + objectName);
        if (notification.getType().equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {
            String type = objectName.getKeyProperty("type");
            if ("Host".equals(type)) {
                try {
                    registerHost(objectName);
                } catch (Exception e) {
                    log.warn("Error registering Host " + objectName, e);
                }
            }

            if (j2eeType != null) {
                if (j2eeType.equals("WebModule")) {
                    try {
                        registerContext(objectName);
                    } catch (Throwable t) {
                        log.warn("Error registering Context " + objectName, t);
                    }
                } else if (j2eeType.equals("Servlet")) {
                    try {
                        registerWrapper(objectName);
                    } catch (Throwable t) {
                        log.warn("Error registering Wrapper " + objectName, t);
                    }
                }
            }
        } else if (notification.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
            String type = objectName.getKeyProperty("type");
            if ("Host".equals(type)) {
                try {
                    unregisterHost(objectName);
                } catch (Exception e) {
                    log.warn("Error unregistering Host " + objectName, e);
                }
            }

            if (j2eeType != null) {
                if (j2eeType.equals("WebModule")) {
                    try {
                        unregisterContext(objectName);
                    } catch (Throwable t) {
                        log.warn("Error unregistering webapp " + objectName, t);
                    }
                }
            }
        }
    }

}

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

/**
 * Invoked before sending the specified notification to the listener. Returns whether the given
 * notification is to be sent to the listener.
 *
 * @param notification The notification to be sent.
 * @return true if the notification has to be sent to the listener, false otherwise.
 *//*  www. j a va  2s.  co m*/
public boolean isNotificationEnabled(Notification notification) {
    boolean isThisNotificationEnabled = false;
    if (notification.getType().equals(JMXConnectionNotification.OPENED)
            || notification.getType().equals(JMXConnectionNotification.CLOSED)
            || notification.getType().equals(JMXConnectionNotification.FAILED)) {
        isThisNotificationEnabled = true;
    }
    return isThisNotificationEnabled;
}

From source file:com.pivotal.gemfire.tools.pulse.internal.data.JMXDataUpdater.java

/**
 * System Notification Listener/*ww  w. jav a2  s  .co  m*/
 */
@Override
public void handleNotification(Notification notification, Object handback) {
    String type = notification.getType();

    if (PulseConstants.NOTIFICATION_TYPE_SYSTEM_ALERT.equals(type)) {
        Cluster.Alert alert = new Cluster.Alert();
        Long timeStamp = notification.getTimeStamp();
        Date date = new Date(timeStamp);
        alert.setTimestamp(date);
        String notificationSource = (String) notification.getUserData();
        alert.setMemberName(notificationSource);
        String alertDescription = notification.getMessage();
        if (alertDescription.startsWith("[error")) {
            alert.setSeverity(Cluster.Alert.ERROR);
        } else if (alertDescription.startsWith("[warning")) {
            alert.setSeverity(Cluster.Alert.WARNING);
        } else if (alertDescription.startsWith("[severe")) {
            alert.setSeverity(Cluster.Alert.SEVERE);
        } else {
            alert.setSeverity(Cluster.Alert.INFO);
        }
        alert.setDescription(notification.getMessage());
        alert.setAcknowledged(false);
        alert.setId(Cluster.Alert.nextID());
        cluster.addAlert(alert);
    } else {
        Cluster.Alert alert = new Cluster.Alert();
        Long timeStamp = notification.getTimeStamp();
        Date date = new Date(timeStamp);
        alert.setTimestamp(date);
        String notificationSource = (String) notification.getSource();
        alert.setMemberName(notificationSource);
        String alertDescription = notification.getMessage();
        alert.setDescription(alertDescription);

        alert.setSeverity(Cluster.Alert.INFO);

        alert.setAcknowledged(false);
        alert.setId(Cluster.Alert.nextID());
        cluster.addAlert(alert);
    }
}

From source file:edu.nwpu.gemfire.monitor.data.JMXDataUpdater.java

/**
 * System Notification Listener/*from  w w  w  .java 2s  . c  o m*/
 */
@Override
public void handleNotification(Notification notification, Object handback) {
    String type = notification.getType();

    if (PulseConstants.NOTIFICATION_TYPE_SYSTEM_ALERT.equals(type)) {
        Cluster.Alert alert = new Cluster.Alert();
        Long timeStamp = notification.getTimeStamp();
        Date date = new Date(timeStamp);
        alert.setTimestamp(date);
        String notificationSource = (String) notification.getUserData();
        alert.setMemberName(notificationSource);
        String alertDescription = notification.getMessage();
        if (alertDescription.startsWith("[error")) {
            alert.setSeverity(Cluster.Alert.ERROR);
        } else if (alertDescription.startsWith("[warning")) {
            alert.setSeverity(Cluster.Alert.WARNING);
        } else if (alertDescription.startsWith("[severe")) {
            alert.setSeverity(Cluster.Alert.SEVERE);
        } else {
            alert.setSeverity(Cluster.Alert.INFO);
        }
        alert.setDescription(notification.getMessage());
        alert.setAcknowledged(false);
        alert.setId(Cluster.Alert.nextID());
        cluster.addAlert(alert);
    } else {
        Cluster.Alert alert = new Cluster.Alert();
        Long timeStamp = notification.getTimeStamp();
        Date date = new Date(timeStamp);
        alert.setTimestamp(date);
        String notificationSource = (String) notification.getSource();
        alert.setMemberName(notificationSource);
        String alertDescription = notification.getMessage();
        alert.setDescription(alertDescription);

        alert.setSeverity(Cluster.Alert.INFO);

        alert.setAcknowledged(false);
        alert.setId(Cluster.Alert.nextID());
        cluster.addAlert(alert);

        if (PulseConstants.NOTIFICATION_TYPE_REGION_DESTROYED.equals(type)) {
            // Remove deleted region from member's regions list
            String msg = notification.getMessage();
            String deletedRegion = msg.substring(msg.indexOf("Name ") + "Name ".length());
            String memberName = notificationSource;
            Cluster.Member member = cluster.getMembersHMap().get(memberName);

            if (member.getMemberRegions().get(deletedRegion) != null) {
                member.getMemberRegions().remove(deletedRegion);
                member.setTotalRegionCount(member.getMemberRegions().size());
            }
        }
    }
}