Java Code Examples for javax.management.Notification

The following are top voted examples for showing how to use javax.management.Notification. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: NotificationAccessControllerTest.java   View source code 6 votes vote down vote up
/**
 * Check received notifications
 */
public int checkNotifs(int size,
                       List<Notification> received,
                       List<ObjectName> expected) {
    if (received.size() != size) {
        echo("Error: expecting " + size + " notifications, got " +
                received.size());
        return 1;
    } else {
        for (Notification n : received) {
            echo("Received notification: " + n);
            if (!n.getType().equals("nb")) {
                echo("Notification type must be \"nb\"");
                return 1;
            }
            ObjectName o = (ObjectName) n.getSource();
            int index = (int) n.getSequenceNumber();
            ObjectName nb = expected.get(index);
            if (!o.equals(nb)) {
                echo("Notification source must be " + nb);
                return 1;
            }
        }
    }
    return 0;
}
 
Example 2
Project: apache-tomcat-7.0.73-with-comment   File: TestSlowQueryReport.java   View source code 6 votes vote down vote up
@Override
public void handleNotification(Notification notification,
                               Object handback) {
    notificationCount.incrementAndGet();
    System.out.println("\nReceived notification:");
    System.out.println("\tClassName: " + notification.getClass().getName());
    System.out.println("\tSource: " + notification.getSource());
    System.out.println("\tType: " + notification.getType());
    System.out.println("\tMessage: " + notification.getMessage());
    if (notification instanceof AttributeChangeNotification) {
        AttributeChangeNotification acn =
            (AttributeChangeNotification) notification;
        System.out.println("\tAttributeName: " + acn.getAttributeName());
        System.out.println("\tAttributeType: " + acn.getAttributeType());
        System.out.println("\tNewValue: " + acn.getNewValue());
        System.out.println("\tOldValue: " + acn.getOldValue());
    }
}
 
Example 3
Project: monarch   File: ManagementAdapter.java   View source code 6 votes vote down vote up
/**
 * Handles GatewaySender creation
 * 
 * @param sender the specific gateway sender
 * @throws ManagementException
 */
public void handleGatewaySenderCreation(GatewaySender sender) throws ManagementException {
  if (!isServiceInitialised("handleGatewaySenderCreation")) {
    return;
  }
  GatewaySenderMBeanBridge bridge = new GatewaySenderMBeanBridge(sender);

  GatewaySenderMXBean senderMBean = new GatewaySenderMBean(bridge);
  ObjectName senderObjectName = MBeanJMXAdapter.getGatewaySenderMBeanName(
      cacheImpl.getDistributedSystem().getDistributedMember(), sender.getId());

  ObjectName changedMBeanName = service.registerInternalMBean(senderMBean, senderObjectName);

  service.federate(changedMBeanName, GatewaySenderMXBean.class, true);

  Notification notification = new Notification(JMXNotificationType.GATEWAY_SENDER_CREATED,
      memberSource, SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.GATEWAY_SENDER_CREATED_PREFIX);
  memberLevelNotifEmitter.sendNotification(notification);

}
 
Example 4
Project: monarch   File: ManagementAdapter.java   View source code 6 votes vote down vote up
private void createGatewayReceiverMBean(GatewayReceiver recv) {
  GatewayReceiverMBeanBridge bridge = new GatewayReceiverMBeanBridge(recv);

  GatewayReceiverMXBean receiverMBean = new GatewayReceiverMBean(bridge);
  ObjectName recvObjectName = MBeanJMXAdapter
      .getGatewayReceiverMBeanName(cacheImpl.getDistributedSystem().getDistributedMember());

  ObjectName changedMBeanName = service.registerInternalMBean(receiverMBean, recvObjectName);

  service.federate(changedMBeanName, GatewayReceiverMXBean.class, true);

  Notification notification = new Notification(JMXNotificationType.GATEWAY_RECEIVER_CREATED,
      memberSource, SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.GATEWAY_RECEIVER_CREATED_PREFIX);
  memberLevelNotifEmitter.sendNotification(notification);

}
 
Example 5
Project: tomcat7   File: StandardContext.java   View source code 6 votes vote down vote up
/** Destroy needs to clean up the context completely.
 * 
 * The problem is that undoing all the config in start() and restoring 
 * a 'fresh' state is impossible. After stop()/destroy()/init()/start()
 * we should have the same state as if a fresh start was done - i.e
 * read modified web.xml, etc. This can only be done by completely 
 * removing the context object and remapping a new one, or by cleaning
 * up everything.
 * 
 * XXX Should this be done in stop() ?
 * 
 */ 
@Override
protected void destroyInternal() throws LifecycleException {
    
    // If in state NEW when destroy is called, the object name will never
    // have been set so the notification can't be created
    if (getObjectName() != null) { 
        // Send j2ee.object.deleted notification 
        Notification notification = 
            new Notification("j2ee.object.deleted", this.getObjectName(), 
                             sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }

    if (namingResources != null) {
        namingResources.destroy();
    }

    synchronized (instanceListenersLock) {
        instanceListeners = new String[0];
    }

    super.destroyInternal();
}
 
Example 6
Project: monarch   File: ManagementAdapter.java   View source code 6 votes vote down vote up
/**
 * Sends the alert with the Object source as member. This notification will get filtered out for
 * particular alert level
 * 
 * @param details
 */
public void handleSystemNotification(AlertDetails details) {
  if (!isServiceInitialised("handleSystemNotification")) {
    return;
  }
  if (service.isManager()) {
    String systemSource = "DistributedSystem("
        + service.getDistributedSystemMXBean().getDistributedSystemId() + ")";
    Map<String, String> userData = prepareUserData(details);


    Notification notification = new Notification(JMXNotificationType.SYSTEM_ALERT, systemSource,
        SequenceNumber.next(), details.getMsgTime().getTime(), details.getMsg());

    notification.setUserData(userData);
    service.handleNotification(notification);
  }

}
 
Example 7
Project: openjdk-jdk10   File: CounterMonitorInitThresholdTest.java   View source code 6 votes vote down vote up
public void handleNotification(Notification n, Object hb) {
    System.out.println("\tReceived notification: " + n.getType());
    if (n instanceof MonitorNotification) {
        MonitorNotification mn = (MonitorNotification) n;
        System.out.println("\tSource: " +
            mn.getSource());
        System.out.println("\tType: " +
            mn.getType());
        System.out.println("\tTimeStamp: " +
            mn.getTimeStamp());
        System.out.println("\tObservedObject: " +
            mn.getObservedObject());
        System.out.println("\tObservedAttribute: " +
            mn.getObservedAttribute());
        System.out.println("\tDerivedGauge: " +
            mn.getDerivedGauge());
        System.out.println("\tTrigger: " +
            mn.getTrigger());
    }
}
 
Example 8
Project: monarch   File: ManagementAdapter.java   View source code 6 votes vote down vote up
/**
 * Handles Gateway receiver creation
 * 
 * @param recv specific gateway receiver
 * @throws ManagementException
 */
public void handleGatewayReceiverStop(GatewayReceiver recv) throws ManagementException {
  if (!isServiceInitialised("handleGatewayReceiverStop")) {
    return;
  }
  GatewayReceiverMBean mbean = (GatewayReceiverMBean) service.getLocalGatewayReceiverMXBean();
  GatewayReceiverMBeanBridge bridge = mbean.getBridge();

  bridge.stopServer();

  Notification notification = new Notification(JMXNotificationType.GATEWAY_RECEIVER_STOPPED,
      memberSource, SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.GATEWAY_RECEIVER_STOPPED_PREFIX);
  memberLevelNotifEmitter.sendNotification(notification);

}
 
Example 9
Project: lazycat   File: StandardContext.java   View source code 6 votes vote down vote up
@Override
protected void initInternal() throws LifecycleException {
	super.initInternal();

	if (processTlds) {
		this.addLifecycleListener(new TldConfig());
	}

	// Register the naming resources
	if (namingResources != null) {
		namingResources.init();
	}

	// Send j2ee.object.created notification
	if (this.getObjectName() != null) {
		Notification notification = new Notification("j2ee.object.created", this.getObjectName(),
				sequenceNumber.getAndIncrement());
		broadcaster.sendNotification(notification);
	}
}
 
Example 10
Project: openjdk-jdk10   File: PoolsIndependenceTest.java   View source code 6 votes vote down vote up
@Override
public void handleNotification(Notification notification, Object handback) {
    String nType = notification.getType();
    String poolName
            = CodeCacheUtils.getPoolNameFromNotification(notification);
    // consider code cache events only
    if (CodeCacheUtils.isAvailableCodeHeapPoolName(poolName)) {
        Asserts.assertEQ(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED,
                nType, "Unexpected event received: " + nType);
        // receiving events from available CodeCache-related beans only
        if (counters.get(poolName) != null) {
            counters.get(poolName).incrementAndGet();
            lastEventTimestamp = System.currentTimeMillis();
        }
    }
}
 
Example 11
Project: openjdk-jdk10   File: ReflectionExceptionTest.java   View source code 6 votes vote down vote up
public void handleNotification(Notification notification, Object handback) {
    echo(">>> Received notification: " + notification);
    if (notification instanceof MonitorNotification) {
        String type = notification.getType();
        if (type.equals(MonitorNotification.RUNTIME_ERROR)) {
            MonitorNotification mn = (MonitorNotification) notification;
            echo("\tType: " + mn.getType());
            echo("\tTimeStamp: " + mn.getTimeStamp());
            echo("\tObservedObject: " + mn.getObservedObject());
            echo("\tObservedAttribute: " + mn.getObservedAttribute());
            echo("\tDerivedGauge: " + mn.getDerivedGauge());
            echo("\tTrigger: " + mn.getTrigger());

            synchronized (this) {
                messageReceived = true;
                notifyAll();
            }
        }
    }
}
 
Example 12
Project: lams   File: ModelMBeanNotificationPublisher.java   View source code 6 votes vote down vote up
/**
 * Send the supplied {@link Notification} using the wrapped
 * {@link ModelMBean} instance.
 * @param notification the {@link Notification} to be sent
 * @throws IllegalArgumentException if the supplied {@code notification} is {@code null}
 * @throws UnableToSendNotificationException if the supplied {@code notification} could not be sent
 */
@Override
public void sendNotification(Notification notification) {
	Assert.notNull(notification, "Notification must not be null");
	replaceNotificationSourceIfNecessary(notification);
	try {
		if (notification instanceof AttributeChangeNotification) {
			this.modelMBean.sendAttributeChangeNotification((AttributeChangeNotification) notification);
		}
		else {
			this.modelMBean.sendNotification(notification);
		}
	}
	catch (MBeanException ex) {
		throw new UnableToSendNotificationException("Unable to send notification [" + notification + "]", ex);
	}
}
 
Example 13
Project: openjdk-jdk10   File: NotificationEmissionTest.java   View source code 6 votes vote down vote up
public int checkNotifs(int size,
                       List<Notification> received,
                       List<ObjectName> expected) {
    if (received.size() != size) {
        echo("Error: expecting " + size + " notifications, got " +
                received.size());
        return 1;
    } else {
        for (Notification n : received) {
            echo("Received notification: " + n);
            if (!n.getType().equals("nb")) {
                echo("Notification type must be \"nb\"");
                return 1;
            }
            ObjectName o = (ObjectName) n.getSource();
            int index = (int) n.getSequenceNumber();
            ObjectName nb = expected.get(index);
            if (!o.equals(nb)) {
                echo("Notification source must be " + nb);
                return 1;
            }
        }
    }
    return 0;
}
 
Example 14
Project: lams   File: StandardContext.java   View source code 6 votes vote down vote up
/** Destroy needs to clean up the context completely.
 * 
 * The problem is that undoing all the config in start() and restoring 
 * a 'fresh' state is impossible. After stop()/destroy()/init()/start()
 * we should have the same state as if a fresh start was done - i.e
 * read modified web.xml, etc. This can only be done by completely 
 * removing the context object and remapping a new one, or by cleaning
 * up everything.
 * 
 * XXX Should this be done in stop() ?
 * 
 */ 
public void destroy() throws Exception {
    if( oname != null ) { 
        // Send j2ee.object.deleted notification 
        Notification notification = 
            new Notification("j2ee.object.deleted", this.getObjectName(), 
                            sequenceNumber++);
        broadcaster.sendNotification(notification);
    } 
    super.destroy();

    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(DESTROY_EVENT, null);

    instanceListeners = new String[0];

}
 
Example 15
Project: otus_java_2017_10   File: MemoryUtil.java   View source code 6 votes vote down vote up
@Override
public void handleNotification(Notification notification, Object handback) {
    if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
        System.out.println("0XDEADBEAF");
        GarbageCollectionNotificationInfo notifInfo = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());

        GcInfo gcInfo = notifInfo.getGcInfo();
        System.out.printf("Action: %s, %s, %s\n", notifInfo.getGcAction(), notifInfo.getGcCause(), notifInfo.getGcName());
        System.out.printf("Time: %d, %d, %d\n", gcInfo.getStartTime(), gcInfo.getEndTime(), gcInfo.getDuration());
        System.out.printf("Memory: %s, %s\n", gcInfo.getMemoryUsageBeforeGc().toString(), gcInfo.getMemoryUsageAfterGc().toString());



        Map<String, MemoryUsage> memBefore = notifInfo.getGcInfo().getMemoryUsageBeforeGc();
        Map<String, MemoryUsage> memAfter = notifInfo.getGcInfo().getMemoryUsageAfterGc();
        StringBuilder sb = new StringBuilder();
        sb.append("[").append(notifInfo.getGcAction()).append(" / ").append(notifInfo.getGcCause())
                .append(" / ").append(notifInfo.getGcName()).append(" / (");
        appendMemUsage(sb, memBefore);
        sb.append(") -> (");
        appendMemUsage(sb, memAfter);
        sb.append("), ").append(notifInfo.getGcInfo().getDuration()).append(" ms]");
        System.out.println(sb.toString());
    }
}
 
Example 16
Project: lams   File: BaseAttributeFilter.java   View source code 6 votes vote down vote up
/**
 * <p>Test whether notification enabled for this event.
 * Return true if:</p>
 * <ul>
 * <li>This is an attribute change notification</li>
 * <li>Either the set of accepted names is empty (implying that all
 *     attribute names are of interest) or the set of accepted names
 *     includes the name of the attribute in this notification</li>
 * </ul>
 */
public boolean isNotificationEnabled(Notification notification) {

    if (notification == null)
        return (false);
    if (!(notification instanceof AttributeChangeNotification))
        return (false);
    AttributeChangeNotification acn =
        (AttributeChangeNotification) notification;
    if (!AttributeChangeNotification.ATTRIBUTE_CHANGE.equals(acn.getType()))
        return (false);
    synchronized (names) {
        if (names.size() < 1)
            return (true);
        else
            return (names.contains(acn.getAttributeName()));
    }

}
 
Example 17
Project: OpenJSharp   File: MemoryImpl.java   View source code 6 votes vote down vote up
static void createNotification(String notifType,
                               String poolName,
                               MemoryUsage usage,
                               long count) {
    MemoryImpl mbean = (MemoryImpl) ManagementFactory.getMemoryMXBean();
    if (!mbean.hasListeners()) {
        // if no listener is registered.
        return;
    }
    long timestamp = System.currentTimeMillis();
    String msg = getNotifMsg(notifType);
    Notification notif = new Notification(notifType,
                                          mbean.getObjectName(),
                                          getNextSeqNumber(),
                                          timestamp,
                                          msg);
    MemoryNotificationInfo info =
        new MemoryNotificationInfo(poolName,
                                   usage,
                                   count);
    CompositeData cd =
        MemoryNotifInfoCompositeData.toCompositeData(info);
    notif.setUserData(cd);
    mbean.sendNotification(notif);
}
 
Example 18
Project: monarch   File: ManagementAdapter.java   View source code 6 votes vote down vote up
/**
 * Handles Disk Creation. Will create DiskStoreMXBean and will send a notification
 * 
 * @param disk the disk store for which the call back is invoked
 */
public void handleDiskCreation(DiskStore disk) throws ManagementException {
  if (!isServiceInitialised("handleDiskCreation")) {
    return;
  }
  DiskStoreMBeanBridge bridge = new DiskStoreMBeanBridge(disk);
  DiskStoreMXBean diskStoreMBean = new DiskStoreMBean(bridge);
  ObjectName diskStoreMBeanName = MBeanJMXAdapter.getDiskStoreMBeanName(
      cacheImpl.getDistributedSystem().getDistributedMember(), disk.getName());
  ObjectName changedMBeanName = service.registerInternalMBean(diskStoreMBean, diskStoreMBeanName);

  service.federate(changedMBeanName, DiskStoreMXBean.class, true);

  Notification notification = new Notification(JMXNotificationType.DISK_STORE_CREATED,
      memberSource, SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.DISK_STORE_CREATED_PREFIX + disk.getName());
  memberLevelNotifEmitter.sendNotification(notification);
  memberMBeanBridge.addDiskStore(disk);
}
 
Example 19
Project: jdk8u-jdk   File: DirectoryScanner.java   View source code 6 votes vote down vote up
private boolean notifyMatch(File file) {
    try {
        final Notification n =
                new Notification(FILE_MATCHES_NOTIFICATION,this,
                getNextSeqNumber(),
                file.getAbsolutePath());

        // This method *is not* called from any synchronized block, so
        // we can happily call broadcaster.sendNotification() here.
        // Note that verifying whether a method is called from within
        // a synchronized block demends a thoroughful code reading,
        // examining each of the 'parent' methods in turn.
        //
        broadcaster.sendNotification(n);
        return true;
    } catch (Exception x) {
        LOG.fine("Failed to notify: "+file.getAbsolutePath());
    }
    return false;
}
 
Example 20
Project: jdk8u-jdk   File: NotificationAccessControllerTest.java   View source code 6 votes vote down vote up
@Override
public void fetchNotification(
    String connectionId,
    ObjectName name,
    Notification notification,
    Subject subject)
    throws SecurityException {
    echo("fetchNotification:");
    echo("\tconnectionId: " +  connectionId);
    echo("\tname: " +  name);
    echo("\tnotification: " +  notification);
    echo("\tsubject: " +
         (subject == null ? null : subject.getPrincipals()));
    if (!throwException)
        if (name.getCanonicalName().equals("domain:name=2,type=NB")
            &&
            subject != null
            &&
            subject.getPrincipals().contains(new JMXPrincipal("role")))
            throw new SecurityException();
}
 
Example 21
Project: jdk8u-jdk   File: DefaultMBeanServerInterceptor.java   View source code 6 votes vote down vote up
public void handleNotification(Notification notification,
                               Object handback) {
    if (notification != null) {
        if (notification.getSource() == mbean)
            notification.setSource(name);
    }

    /*
     * Listeners are not supposed to throw exceptions.  If
     * this one does, we could remove it from the MBean.  It
     * might indicate that a connector has stopped working,
     * for instance, and there is no point in sending future
     * notifications over that connection.  However, this
     * seems rather drastic, so instead we propagate the
     * exception and let the broadcaster handle it.
     */
    listener.handleNotification(notification, handback);
}
 
Example 22
Project: openjdk-jdk10   File: NotificationAccessControllerTest.java   View source code 6 votes vote down vote up
@Override
public void fetchNotification(
    String connectionId,
    ObjectName name,
    Notification notification,
    Subject subject)
    throws SecurityException {
    echo("fetchNotification:");
    echo("\tconnectionId: " +  connectionId);
    echo("\tname: " +  name);
    echo("\tnotification: " +  notification);
    echo("\tsubject: " +
         (subject == null ? null : subject.getPrincipals()));
    if (!throwException)
        if (name.getCanonicalName().equals("domain:name=2,type=NB")
            &&
            subject != null
            &&
            subject.getPrincipals().contains(new JMXPrincipal("role")))
            throw new SecurityException();
}
 
Example 23
Project: monarch   File: AgentImpl.java   View source code 6 votes vote down vote up
/**
 * If the handback object passed is an AgentImpl, updates the JMX client count
 *
 * @param notification JMXConnectionNotification for change in client connection status
 * @param handback An opaque object which helps the listener to associate information regarding
 *        the MBean emitter. This object is passed to the MBean during the addListener call and
 *        resent, without modification, to the listener. The MBean object should not use or modify
 *        the object. (NOTE: copied from javax.management.NotificationListener)
 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "BC_UNCONFIRMED_CAST",
    justification = "Only JMXConnectionNotification instances are used.")
public void handleNotification(Notification notification, Object handback) {
  if (handback instanceof AgentImpl) {
    AgentImpl agent = (AgentImpl) handback;

    JMXConnectionNotification jmxNotifn = (JMXConnectionNotification) notification;

    if (logger.isDebugEnabled()) {
      logger.debug("Connection notification for connection id : '{}'",
          jmxNotifn.getConnectionId());
    }

    agent.updateRmiClientsCount();
  }
}
 
Example 24
Project: monarch   File: NotificationHubClient.java   View source code 6 votes vote down vote up
/**
 * send the notification to actual client on the Managing node VM
 * 
 * it does not throw any exception. it will capture all exception and log a warning
 * 
 * @param event
 */
public void sendNotification(EntryEvent<NotificationKey, Notification> event) {

  NotificationBroadCasterProxy notifBroadCaster;
  try {

    notifBroadCaster = proxyFactory.findProxy(event.getKey().getObjectName(),
        NotificationBroadCasterProxy.class);
    // Will return null if the Bean is filtered out.
    if (notifBroadCaster != null) {
      notifBroadCaster.sendNotification(event.getNewValue());
    }

  } catch (Exception e) {
    if (logger.isDebugEnabled()) {
      logger.debug(" NOTIFICATION Not Done {}", e.getMessage(), e);
    }
    logger.warn(e.getMessage(), e);
  }

}
 
Example 25
Project: openjdk-jdk10   File: SimpleListener.java   View source code 6 votes vote down vote up
public synchronized void handleNotification(Notification notification,
                                            Object handback) {
    Utils.debug(Utils.DEBUG_STANDARD,
        "SimpleListener::handleNotification :" + notification);
    try {
        received = true;
        type = notification.getType();
        this.handback = handback;
        handbacks.add(handback);
        nbrec++;
        notify();
    } catch(Exception e) {
        System.out.println("(ERROR) SimpleListener::handleNotification :"
                    + " Caught exception "
                    + e) ;
    }
}
 
Example 26
Project: jdk8u-jdk   File: NotificationEmitterSupport.java   View source code 6 votes vote down vote up
void sendNotification(Notification notification) {

        if (notification == null) {
            return;
        }

        List<ListenerInfo> currentList;
        synchronized (listenerLock) {
            currentList = listenerList;
        }

        final int size = currentList.size();
        for (int i = 0; i < size; i++) {
            ListenerInfo li =  currentList.get(i);

            if (li.filter == null
                || li.filter.isNotificationEnabled(notification)) {
                try {
                    li.listener.handleNotification(notification, li.handback);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new AssertionError("Error in invoking listener");
                }
            }
        }
    }
 
Example 27
Project: jdk8u-jdk   File: MissingClassTest.java   View source code 5 votes vote down vote up
private void handle(Notification n, Object h) {
    if (!(n instanceof JMXConnectionNotification)) {
        System.out.println("LostListener received strange notif: " +
                           notificationString(n));
        result.failed = true;
        result.notifyAll();
        return;
    }

    JMXConnectionNotification jn = (JMXConnectionNotification) n;
    if (!jn.getType().equals(jn.NOTIFS_LOST)) {
        System.out.println("Ignoring JMXConnectionNotification: " +
                           notificationString(jn));
        return;
    }
    final String msg = jn.getMessage();
    if ((!msg.startsWith("Dropped ")
         || !msg.endsWith("classes were missing locally"))
        && (!msg.startsWith("Not serializable: "))) {
        System.out.println("Surprising NOTIFS_LOST getMessage: " +
                           msg);
    }
    if (!(jn.getUserData() instanceof Long)) {
        System.out.println("JMXConnectionNotification userData " +
                           "not a Long: " + jn.getUserData());
        result.failed = true;
    } else {
        int lost = ((Long) jn.getUserData()).intValue();
        result.lostCount += lost;
        if (result.lostCount == NNOTIFS*2)
            result.notifyAll();
    }
}
 
Example 28
Project: monarch   File: DistributedSystemDUnitTest.java   View source code 5 votes vote down vote up
@Override
public synchronized void handleNotification(Notification notification, Object handback) {
  assertNotNull(notification);
  logger.info("Notification received {}", notification);
  Map<String, String> notifUserData = (Map<String, String>) notification.getUserData();
  if (notifUserData.get(JMXNotificationUserData.ALERT_LEVEL).equalsIgnoreCase("warning")) {
    assertEquals(WARNING_LEVEL_MESSAGE, notification.getMessage());
    ++warnigAlertCount;
  }
  if (notifUserData.get(JMXNotificationUserData.ALERT_LEVEL).equalsIgnoreCase("severe")) {
    assertEquals(SEVERE_LEVEL_MESSAGE, notification.getMessage());
    ++severAlertCount;
  }
}
 
Example 29
Project: Pogamut3   File: FlagJMXProxy.java   View source code 5 votes vote down vote up
public FlagJMXProxy(final ObjectName source, final MBeanServerConnection mbsc, final String flagName) throws MalformedObjectNameException {
    ObjectName name = PogamutJMX.getObjectName(source, flagName, PogamutJMX.FLAGS_SUBTYPE);
    try {
        listener = new NotificationListener() {

            @Override
            public void handleNotification(Notification notification, Object handback) {
                if (notification.getSource().equals(source) && notification.getType().equals(flagName)) {
                    setFlag((T) notification.getUserData());
                }
            }
        };
        // get current value of the flag
        T val = (T) mbsc.getAttribute(name, "Flag");
        setFlag(val);

        /* NOTE filters are send over RMI to the server !!! it is better to
         handle filtering in the listener itself.
         
        NotificationFilter nf = new NotificationFilter() {

        @Override
        public boolean isNotificationEnabled(Notification notification) {
        return notification.getSource().equals(source) && notification.getType().equals(flagName);
        }
        };
         */
        mbsc.addNotificationListener(name, listener, null, mbsc);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}
 
Example 30
Project: monarch   File: CustomMBean.java   View source code 5 votes vote down vote up
@Override
public void writeName(String name) {
  this.name = name;

  Notification n = new AttributeChangeNotification(this, sequenceNumber++,
      System.currentTimeMillis(), "staticField changed", "staticField", "int", name, this.name);

  sendNotification(n);
}
 
Example 31
Project: openjdk-jdk10   File: NotificationAccessControllerTest.java   View source code 5 votes vote down vote up
@Override
public void handleNotification(Notification n, Object h) {
    echo("handleNotification:");
    echo("\tNotification = " + n);
    echo("\tNotification.SeqNum = " + n.getSequenceNumber());
    echo("\tHandback = " + h);
    notifs.add(n);
    s.release();
}
 
Example 32
Project: monarch   File: ManagementAdapter.java   View source code 5 votes vote down vote up
/**
 * Invoked when a client has gracefully disconnected from this process or when this process has
 * gracefully disconnected from a CacheServer.
 */
public void memberLeft(ClientMembershipEvent event) {
  Notification notification = new Notification(JMXNotificationType.CLIENT_LEFT, serverSource,
      SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.CLIENT_LEFT_PREFIX + event.getMemberId());
  serverLevelNotifEmitter.sendNotification(notification);
  memberLevelNotifEmitter.sendNotification(notification);
}
 
Example 33
Project: openjdk-jdk10   File: ServerNotifForwarder.java   View source code 5 votes vote down vote up
public void apply(List<TargetedNotification> targetedNotifs,
                  ObjectName source, Notification notif) {
    // We proceed in two stages here, to avoid holding the listenerMap
    // lock while invoking the filters (which are user code).
    final IdAndFilter[] candidates;
    synchronized (listenerMap) {
        final Set<IdAndFilter> set = listenerMap.get(source);
        if (set == null) {
            logger.debug("bufferFilter", "no listeners for this name");
            return;
        }
        candidates = new IdAndFilter[set.size()];
        set.toArray(candidates);
    }
    // We don't synchronize on targetedNotifs, because it is a local
    // variable of our caller and no other thread can see it.
    for (IdAndFilter idaf : candidates) {
        final NotificationFilter nf = idaf.getFilter();
        if (nf == null || nf.isNotificationEnabled(notif)) {
            logger.debug("bufferFilter", "filter matches");
            final TargetedNotification tn =
                    new TargetedNotification(notif, idaf.getId());
            if (allowNotificationEmission(source, tn))
                targetedNotifs.add(tn);
        }
    }
}
 
Example 34
Project: jdk8u-jdk   File: ServerNotifForwarder.java   View source code 5 votes vote down vote up
public void apply(List<TargetedNotification> targetedNotifs,
                  ObjectName source, Notification notif) {
    // We proceed in two stages here, to avoid holding the listenerMap
    // lock while invoking the filters (which are user code).
    final IdAndFilter[] candidates;
    synchronized (listenerMap) {
        final Set<IdAndFilter> set = listenerMap.get(source);
        if (set == null) {
            logger.debug("bufferFilter", "no listeners for this name");
            return;
        }
        candidates = new IdAndFilter[set.size()];
        set.toArray(candidates);
    }
    // We don't synchronize on targetedNotifs, because it is a local
    // variable of our caller and no other thread can see it.
    for (IdAndFilter idaf : candidates) {
        final NotificationFilter nf = idaf.getFilter();
        if (nf == null || nf.isNotificationEnabled(notif)) {
            logger.debug("bufferFilter", "filter matches");
            final TargetedNotification tn =
                    new TargetedNotification(notif, idaf.getId());
            if (allowNotificationEmission(source, tn))
                targetedNotifs.add(tn);
        }
    }
}
 
Example 35
Project: tomcat7   File: BaseModelMBean.java   View source code 5 votes vote down vote up
/**
 * Send a <code>Notification</code> to all registered listeners as a
 * <code>jmx.modelmbean.general</code> notification.
 *
 * @param notification The <code>Notification</code> that will be passed
 *
 * @exception MBeanException if an object initializer throws an
 *  exception
 * @exception RuntimeOperationsException wraps IllegalArgumentException
 *  when the specified notification is <code>null</code> or invalid
 */
@Override
public void sendNotification(Notification notification)
    throws MBeanException, RuntimeOperationsException {

    if (notification == null)
        throw new RuntimeOperationsException
            (new IllegalArgumentException("Notification is null"),
             "Notification is null");
    if (generalBroadcaster == null)
        return; // This means there are no registered listeners
    generalBroadcaster.sendNotification(notification);

}
 
Example 36
Project: monarch   File: ManagementAdapter.java   View source code 5 votes vote down vote up
/**
 * Invoked when a client has connected to this process or when this process has connected to a
 * CacheServer.
 */
public void memberJoined(ClientMembershipEvent event) {
  Notification notification = new Notification(JMXNotificationType.CLIENT_JOINED, serverSource,
      SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.CLIENT_JOINED_PREFIX + event.getMemberId());
  serverLevelNotifEmitter.sendNotification(notification);
  memberLevelNotifEmitter.sendNotification(notification);

}
 
Example 37
Project: openjdk-jdk10   File: MBeanListener.java   View source code 5 votes vote down vote up
public void handleNotification(
        final Notification notifIn,
        final Object handback)
{
    if (notifIn instanceof MBeanServerNotification)
    {
        final MBeanServerNotification notif = (MBeanServerNotification) notifIn;
        final ObjectName objectName = notif.getMBeanName();

        boolean match = false;
        if ( mObjectName != null && mObjectName.equals(objectName) )
        {
            match = true;
        }
        else if ( objectName.getDomain().equals( mJMXDomain ) )
        {
            if ( mType != null && mType.equals(objectName.getKeyProperty(TYPE_KEY)) )
            {
                final String mbeanName = objectName.getKeyProperty(NAME_KEY);
                if (mName != null && mName.equals(mbeanName))
                {
                    match = true;
                }
            }
        }

        if ( match )
        {
            final String notifType = notif.getType();
            if (MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(notifType))
            {
                mCallback.mbeanRegistered(objectName, this);
            }
            else if (MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(notifType))
            {
                mCallback.mbeanUnregistered(objectName, this);
            }
        }
    }
}
 
Example 38
Project: monarch   File: ManagementAdapter.java   View source code 5 votes vote down vote up
/**
 * Handles LockService Creation
 * 
 * @param lockService
 */
public void handleLockServiceCreation(DLockService lockService) throws ManagementException {
  if (!isServiceInitialised("handleLockServiceCreation")) {
    return;
  }
  /** Internal Locks Should not be exposed to client for monitoring **/
  if (internalLocks.contains(lockService.getName())) {
    return;
  }
  LockServiceMBeanBridge bridge = new LockServiceMBeanBridge(lockService);
  LockServiceMXBean lockServiceMBean = new LockServiceMBean(bridge);

  ObjectName lockServiceMBeanName = MBeanJMXAdapter.getLockServiceMBeanName(
      cacheImpl.getDistributedSystem().getDistributedMember(), lockService.getName());

  ObjectName changedMBeanName =
      service.registerInternalMBean(lockServiceMBean, lockServiceMBeanName);

  service.federate(changedMBeanName, LockServiceMXBean.class, true);

  Notification notification = new Notification(JMXNotificationType.LOCK_SERVICE_CREATED,
      memberSource, SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.LOCK_SERVICE_CREATED_PREFIX + lockService.getName());
  memberLevelNotifEmitter.sendNotification(notification);

  memberMBeanBridge.addLockServiceStats(lockService);
}
 
Example 39
Project: lams   File: StandardContext.java   View source code 5 votes vote down vote up
private void registerJMX() {
    try {
        if (log.isDebugEnabled()) {
            log.debug("Checking for " + oname );
        }
        if(! Registry.getRegistry(null, null)
            .getMBeanServer().isRegistered(oname)) {
            controller = oname;
            Registry.getRegistry(null, null)
                .registerComponent(this, oname, null);
            
            // Send j2ee.object.created notification 
            if (this.getObjectName() != null) {
                Notification notification = new Notification(
                                                    "j2ee.object.created", 
                                                    this.getObjectName(), 
                                                    sequenceNumber++);
                broadcaster.sendNotification(notification);
            }
        }
        Container children[] = findChildren();
        for (int i=0; children!=null && i<children.length; i++) {
            ((StandardWrapper)children[i]).registerJMX( this );
        }
    } catch (Exception ex) {
        if(log.isInfoEnabled())
            log.info("Error registering wrapper with jmx " + this + " " +
                oname + " " + ex.toString(), ex );
    }
}
 
Example 40
Project: jdk8u-jdk   File: DirectoryScanner.java   View source code 5 votes vote down vote up
/**
 * The {@link DirectoryScannerMXBean} may send two types of
 * notifications: filematch, and state attribute changed.
 **/
public MBeanNotificationInfo[] getNotificationInfo() {
    return new MBeanNotificationInfo[] {
        new MBeanNotificationInfo(
                new String[] {FILE_MATCHES_NOTIFICATION},
                Notification.class.getName(),
                "Emitted when a file that matches the scan criteria is found"
                ),
        new MBeanNotificationInfo(
                new String[] {AttributeChangeNotification.ATTRIBUTE_CHANGE},
                AttributeChangeNotification.class.getName(),
                "Emitted when the State attribute changes"
                )
    };
}