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: apache-tomcat-7.0.73-with-comment   File: TestSlowQueryReport.java   Source Code and License 7 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 2
Project: monarch   File: ManagementAdapter.java   Source Code and License 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 3
Project: monarch   File: ManagementAdapter.java   Source Code and License 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 4
Project: tomcat7   File: StandardContext.java   Source Code and License 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 5
Project: monarch   File: ManagementAdapter.java   Source Code and License 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 6
Project: openjdk-jdk10   File: CounterMonitorInitThresholdTest.java   Source Code and License 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 7
Project: monarch   File: ManagementAdapter.java   Source Code and License 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 8
Project: lazycat   File: StandardContext.java   Source Code and License 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 9
Project: openjdk-jdk10   File: PoolsIndependenceTest.java   Source Code and License 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 10
Project: openjdk-jdk10   File: ReflectionExceptionTest.java   Source Code and License 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 11
Project: lams   File: ModelMBeanNotificationPublisher.java   Source Code and License 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 12
Project: openjdk-jdk10   File: NotificationEmissionTest.java   Source Code and License 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 13
Project: lams   File: StandardContext.java   Source Code and License 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 14
Project: monarch   File: AgentImpl.java   Source Code and License 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 15
Project: openjdk-jdk10   File: NotificationAccessControllerTest.java   Source Code and License 5 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 16
Project: jdk8u-jdk   File: MissingClassTest.java   Source Code and License 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 17
Project: openjdk-jdk10   File: ServerNotifForwarder.java   Source Code and License 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 18
Project: otus_java_2017_10   File: MemoryUtil.java   Source Code and License 5 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 19
Project: lams   File: BaseModelMBean.java   Source Code and License 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
 */
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 20
Project: lams   File: FixedNotificationFilter.java   Source Code and License 5 votes vote down vote up
/**
 * <p>Test whether notification enabled for this event.
 * Return true if:</p>
 * <ul>
 * <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);
    synchronized (names) {
        if (names.size() < 1)
            return (true);
        else
            return (names.contains(notification.getType()));
    }

}
 
Example 21
Project: lams   File: BaseAttributeFilter.java   Source Code and License 5 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 22
Project: asura   File: QuartzSchedulerMBeanImpl.java   Source Code and License 5 votes vote down vote up
/**
 * sendNotification
 * 
 * @param eventType
 * @param data
 * @param msg
 */
public void sendNotification(String eventType, Object data, String msg) {
	Notification notif = new Notification(eventType, this, sequenceNumber
			.incrementAndGet(), System.currentTimeMillis(), msg);
	if (data != null) {
		notif.setUserData(data);
	}
	emitter.sendNotification(notif);
}
 
Example 23
Project: jdk8u-jdk   File: RMINotifTest.java   Source Code and License 5 votes vote down vote up
public void handleNotification(Notification notif, Object handback) {
    if(++receivedNotifs == nb) {
        synchronized(lock) {
            lock.notifyAll();
        }
    }
}
 
Example 24
Project: OpenJSharp   File: MemoryImpl.java   Source Code and License 5 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 25
Project: openjdk-jdk10   File: ThresholdNotificationsTest.java   Source Code and License 5 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);
        if (poolName.equals(btype.getMemoryPool().getName())) {
            counter++;
        }
    }
}
 
Example 26
Project: OpenJSharp   File: SnmpMibTable.java   Source Code and License 5 votes vote down vote up
/**
 * Enable this <CODE>SnmpMibTable</CODE> to send a notification.
 *
 * <p>
 * @param notification The notification to send.
 */
private synchronized void sendNotification(Notification notification) {

    // loop on listener
    //
    for(java.util.Enumeration<NotificationListener> k = handbackTable.keys();
        k.hasMoreElements(); ) {

        NotificationListener listener = k.nextElement();

        // Get the associated handback list and the associated filter list
        //
        java.util.Vector<?> handbackList = handbackTable.get(listener) ;
        java.util.Vector<NotificationFilter> filterList =
            filterTable.get(listener) ;

        // loop on handback
        //
        java.util.Enumeration<NotificationFilter> f = filterList.elements();
        for(java.util.Enumeration<?> h = handbackList.elements();
            h.hasMoreElements(); ) {

            Object handback = h.nextElement();
            NotificationFilter filter = f.nextElement();

            if ((filter == null) ||
                 (filter.isNotificationEnabled(notification))) {

                listener.handleNotification(notification,handback) ;
            }
        }
    }
}
 
Example 27
Project: monarch   File: ManagementAdapter.java   Source Code and License 5 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 28
Project: monarch   File: DistributedSystemBridge.java   Source Code and License 5 votes vote down vote up
public void memberJoined(InternalDistributedMember id) {

    Notification notification = new Notification(JMXNotificationType.CACHE_MEMBER_JOINED,
        MBeanJMXAdapter.getMemberNameOrId(id), SequenceNumber.next(), System.currentTimeMillis(),
        ManagementConstants.CACHE_MEMBER_JOINED_PREFIX + MBeanJMXAdapter.getMemberNameOrId(id));
    systemLevelNotifEmitter.sendNotification(notification);

  }
 
Example 29
Project: OpenJSharp   File: ServerNotifForwarder.java   Source Code and License 5 votes vote down vote up
private void snoopOnUnregister(NotificationResult nr) {
    List<IdAndFilter> copy = null;
    synchronized (listenerMap) {
        Set<IdAndFilter> delegateSet = listenerMap.get(MBeanServerDelegate.DELEGATE_NAME);
        if (delegateSet == null || delegateSet.isEmpty()) {
            return;
        }
        copy = new ArrayList<>(delegateSet);
    }

    for (TargetedNotification tn : nr.getTargetedNotifications()) {
        Integer id = tn.getListenerID();
        for (IdAndFilter idaf : copy) {
            if (idaf.id == id) {
                // This is a notification from the MBeanServerDelegate.
                Notification n = tn.getNotification();
                if (n instanceof MBeanServerNotification &&
                        n.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
                    MBeanServerNotification mbsn = (MBeanServerNotification) n;
                    ObjectName gone = mbsn.getMBeanName();
                    synchronized (listenerMap) {
                        listenerMap.remove(gone);
                    }
                }
            }
        }
    }
}
 
Example 30
Project: jdk8u-jdk   File: DirectoryScanner.java   Source Code and License 5 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 31
Project: openjdk-jdk10   File: MissingClassTest.java   Source Code and License 5 votes vote down vote up
public void handleNotification(Notification n, Object o) {
    if (n instanceof JMXConnectionNotification) {
        JMXConnectionNotification jn = (JMXConnectionNotification)n;
        if (JMXConnectionNotification.FAILED.equals(jn.getType())) {
            failed = true;
        }
    }
}
 
Example 32
Project: apache-tomcat-7.0.73-with-comment   File: FixedNotificationFilter.java   Source Code and License 5 votes vote down vote up
/**
 * <p>Test whether notification enabled for this event.
 * Return true if:</p>
 * <ul>
 * <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>
 */
@Override
public boolean isNotificationEnabled(Notification notification) {

    if (notification == null)
        return (false);
    synchronized (names) {
        if (names.size() < 1)
            return (true);
        else
            return (names.contains(notification.getType()));
    }

}
 
Example 33
Project: jdk8u-jdk   File: NotificationAccessControllerTest.java   Source Code and License 5 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 34
Project: OpenJSharp   File: TargetedNotification.java   Source Code and License 5 votes vote down vote up
private static void validate(Notification notif, Integer id) throws IllegalArgumentException {
    if (notif == null) {
        throw new IllegalArgumentException("Invalid notification: null");
    }
    if (id == null) {
        throw new IllegalArgumentException("Invalid listener ID: null");
    }
}
 
Example 35
Project: openjdk-jdk10   File: JMXConnectorServer.java   Source Code and License 5 votes vote down vote up
private void sendNotification(String type, String connectionId,
                              String message, Object userData) {
    Notification notif =
        new JMXConnectionNotification(type,
                                      getNotificationSource(),
                                      connectionId,
                                      nextSequenceNumber(),
                                      message,
                                      userData);
    sendNotification(notif);
}
 
Example 36
Project: OpenJSharp   File: JMXConnectorServer.java   Source Code and License 5 votes vote down vote up
private void sendNotification(String type, String connectionId,
                              String message, Object userData) {
    Notification notif =
        new JMXConnectionNotification(type,
                                      getNotificationSource(),
                                      connectionId,
                                      nextSequenceNumber(),
                                      message,
                                      userData);
    sendNotification(notif);
}
 
Example 37
Project: openjdk-jdk10   File: StartTest.java   Source Code and License 5 votes vote down vote up
public void handleNotification(Notification n, Object hb) {
        if (!stopping) {
            received++;
            System.out.println(
                ">>> myListener-handleNotification: received " +
                n.getSequenceNumber());
    }
}
 
Example 38
Project: jdk8u-jdk   File: MissingClassTest.java   Source Code and License 5 votes vote down vote up
public void handleNotification(Notification n, Object h) {
    /* Connectors can handle unserializable notifications in
       one of two ways.  Either they can arrange for the
       client to get a NotSerializableException from its
       fetchNotifications call (RMI connector), or they can
       replace the unserializable notification by a
       JMXConnectionNotification.NOTIFS_LOST (JMXMP
       connector).  The former case is handled by code within
       the connector client which will end up sending a
       NOTIFS_LOST to our LostListener.  The logic here
       handles the latter case by converting it into the
       former.
     */
    if (n instanceof JMXConnectionNotification
        && n.getType().equals(JMXConnectionNotification.NOTIFS_LOST)) {
        lostListener.handleNotification(n, h);
        return;
    }

    synchronized (result) {
        if (!n.getType().equals("interesting")
            || !n.getUserData().equals("known")) {
            System.out.println("TestListener received strange notif: "
                               + notificationString(n));
            result.failed = true;
            result.notifyAll();
        } else {
            result.knownCount++;
            if (result.knownCount == NNOTIFS)
                result.notifyAll();
        }
    }
}
 
Example 39
Project: monarch   File: RegionManagementDUnitTest.java   Source Code and License 5 votes vote down vote up
@Override
public void handleNotification(Notification notification, Object handback) {
  assertNotNull(notification);
  Notification rn = notification;
  LogWriterUtils.getLogWriter().info("<ExpectedString> Distributed System Notifications"
      + rn.toString() + "</ExpectedString> ");
}
 
Example 40
Project: monarch   File: SystemMemberJmxImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Implementation handles creation of region by extracting the details from the given event object
 * and sending the {@link SystemMemberJmx#NOTIF_REGION_CREATED} notification to the connected JMX
 * Clients. Region Path is set as User Data in Notification.
 * 
 * @param event event object corresponding to the creation of a region
 */
public void handleRegionCreate(SystemMemberRegionEvent event) {
  Notification notification = new Notification(NOTIF_REGION_CREATED, this.modelMBean,
      Helper.getNextNotificationSequenceNumber(), Helper.getRegionEventDetails(event));

  notification.setUserData(event.getRegionPath());

  Helper.sendNotification(this, notification);
}
 
Example 41
Project: jdk8u-jdk   File: UnexpectedNotifTest.java   Source Code and License 5 votes vote down vote up
public void handleNotification(Notification notif, Object handback) {
    System.out.println("Received: " + notif + " (" +
                       notif.getSequenceNumber() + ")");
    synchronized(lock) {
        if(++receivedNotifs == nb) {
            lock.notifyAll();
        } else if (receivedNotifs > nb) {
            System.out.println("The client expected to receive " +
                               nb + " notifs, but got at least " +
                               receivedNotifs);
            System.exit(1);
        }
    }
}
 
Example 42
Project: openjdk-jdk10   File: RMINotifTest.java   Source Code and License 5 votes vote down vote up
public void handleNotification(Notification notif, Object handback) {
    if(++receivedNotifs == nb) {
        synchronized(lock) {
            lock.notifyAll();
        }
    }
}
 
Example 43
Project: jdk8u-jdk   File: DefaultMBeanServerInterceptor.java   Source Code and License 5 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 44
Project: openjdk-jdk10   File: NotificationAccessControllerTest.java   Source Code and License 5 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 45
Project: monarch   File: CacheServerJmxImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Implementation handles creation of region by extracting the details from the given event object
 * and sending the {@link SystemMemberJmx#NOTIF_REGION_CREATED} notification to the connected JMX
 * Clients. Region Path is set as User Data in Notification.
 * 
 * @param event event object corresponding to the creation of a region
 */
public void handleRegionCreate(SystemMemberRegionEvent event) {
  Notification notification = new Notification(NOTIF_REGION_CREATED, this.modelMBean,
      Helper.getNextNotificationSequenceNumber(), Helper.getRegionEventDetails(event));

  notification.setUserData(event.getRegionPath());

  Helper.sendNotification(this, notification);
}
 
Example 46
Project: monarch   File: NotificationHubClient.java   Source Code and License 5 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 47
Project: monarch   File: NotificationCacheListener.java   Source Code and License 5 votes vote down vote up
@Override
public void afterCreate(EntryEvent<NotificationKey, Notification> event) {
  if (!readyForEvents) {
    return;
  }
  notifClient.sendNotification(event);

}
 
Example 48
Project: openjdk-jdk10   File: SimpleListener.java   Source Code and License 5 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 49
Project: lazycat   File: FixedNotificationFilter.java   Source Code and License 5 votes vote down vote up
/**
 * <p>
 * Test whether notification enabled for this event. Return true if:
 * </p>
 * <ul>
 * <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>
 */
@Override
public boolean isNotificationEnabled(Notification notification) {

	if (notification == null)
		return (false);
	synchronized (names) {
		if (names.size() < 1)
			return (true);
		else
			return (names.contains(notification.getType()));
	}

}
 
Example 50
Project: monarch   File: ManagementAdapter.java   Source Code and License 5 votes vote down vote up
public void handleGatewaySenderPaused(GatewaySender sender) throws ManagementException {
  if (!isServiceInitialised("handleGatewaySenderPaused")) {
    return;
  }

  Notification notification = new Notification(JMXNotificationType.GATEWAY_SENDER_PAUSED,
      memberSource, SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.GATEWAY_SENDER_PAUSED_PREFIX + sender.getId());

  memberLevelNotifEmitter.sendNotification(notification);

}
 
Example 51
Project: monarch   File: ManagementAdapter.java   Source Code and License 5 votes vote down vote up
/**
 * Handles DiskStore Removal
 * 
 * @param disk
 */
public void handleDiskRemoval(DiskStore disk) throws ManagementException {

  if (!isServiceInitialised("handleDiskRemoval")) {
    return;
  }

  ObjectName diskStoreMBeanName = MBeanJMXAdapter.getDiskStoreMBeanName(
      cacheImpl.getDistributedSystem().getDistributedMember(), disk.getName());

  DiskStoreMBean bean = null;
  try {
    bean = (DiskStoreMBean) service.getLocalDiskStoreMBean(disk.getName());
    if (bean == null) {
      return;
    }
  } catch (ManagementException e) {
    // If no bean found its a NO-OP
    if (logger.isDebugEnabled()) {
      logger.debug(e.getMessage(), e);
    }
    return;
  }

  bean.stopMonitor();

  service.unregisterMBean(diskStoreMBeanName);

  Notification notification = new Notification(JMXNotificationType.DISK_STORE_CLOSED,
      memberSource, SequenceNumber.next(), System.currentTimeMillis(),
      ManagementConstants.DISK_STORE_CLOSED_PREFIX + disk.getName());
  memberLevelNotifEmitter.sendNotification(notification);
  memberMBeanBridge.removeDiskStore(disk);
}
 
Example 52
Project: jdk8u-jdk   File: ResultLogManager.java   Source Code and License 5 votes vote down vote up
private void clearMemoryLog()throws IOException {
    synchronized(this) {
        memoryLog.clear();
        memCapacityReached = false;
    }
    sendNotification(new Notification(MEMORY_LOG_CLEARED,
            objectName,
            getNextSeqNumber(),"memory log cleared"));
}
 
Example 53
Project: jdk8u-jdk   File: NotificationEmitterSupport.java   Source Code and License 5 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 54
Project: phone-simulator   File: TesterHostStandardMBean.java   Source Code and License 4 votes vote down vote up
@Override
public MBeanInfo getMBeanInfo() {

    MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[] {
            new MBeanAttributeInfo("Started", boolean.class.getName(), "Tester host is started now", true, false, true),
            new MBeanAttributeInfo("Instance_L1", Instance_L1.class.getName(), "Tester Level 1 agent", true, true, false),
            new MBeanAttributeInfo("Instance_L2", Instance_L2.class.getName(), "Tester Level 2 agent", true, true, false),
            new MBeanAttributeInfo("Instance_L3", Instance_L3.class.getName(), "Tester Level 3 agent", true, true, false),
            new MBeanAttributeInfo("Instance_TestTask", Instance_TestTask.class.getName(), "Tester task", true, true, false),
            new MBeanAttributeInfo("Instance_L1_Value", String.class.getName(), "Tester Level 1 agent", true, false, false),
            new MBeanAttributeInfo("Instance_L2_Value", String.class.getName(), "Tester Level 2 agent", true, false, false),
            new MBeanAttributeInfo("Instance_L3_Value", String.class.getName(), "Tester Level 3 agent", true, false, false),
            new MBeanAttributeInfo("Instance_TestTask_Value", String.class.getName(), "Tester task", true, false, false),
            new MBeanAttributeInfo("L1State", String.class.getName(), "Tester Level 1 state", true, false, false),
            new MBeanAttributeInfo("L2State", String.class.getName(), "Tester Level 2 state", true, false, false),
            new MBeanAttributeInfo("L3State", String.class.getName(), "Tester Level 3 state", true, false, false),
            new MBeanAttributeInfo("TestTaskState", String.class.getName(), "Tester TestTask state", true, false, false), };

    MBeanParameterInfo[] signString = new MBeanParameterInfo[] { new MBeanParameterInfo("val", String.class.getName(),
            "Index number or value") };
    MBeanParameterInfo[] signEmpty = new MBeanParameterInfo[] {};

    MBeanOperationInfo[] operations = new MBeanOperationInfo[] {
            new MBeanOperationInfo("putInstance_L1Value", "Tester Level 1 agent: 0:NO,1:M3UA,2:DialogicCard", signString,
                    Void.TYPE.getName(), MBeanOperationInfo.ACTION),
            new MBeanOperationInfo("putInstance_L2Value", "Tester Level 2 agent: 0:NO,1:SCCP,2:ISUP", signString,
                    Void.TYPE.getName(), MBeanOperationInfo.ACTION),
            new MBeanOperationInfo("putInstance_L3Value", "Tester Level 3 agent: 0:NO,1:MAP,2:CAP,3:INAP", signString,
                    Void.TYPE.getName(), MBeanOperationInfo.ACTION),
            new MBeanOperationInfo(
                    "putInstance_TestTaskValue",
                    "Tester task: 0:NO,1:USSD_TEST_CLIENT,2:USSD_TEST_SERVER,3:SMS_TEST_CLIENT,4:SMS_TEST_SERVER,5:CAP_TEST_SCF,6:CAP_TEST_SSF,7:ATI_TEST_CLIENT,8:ATI_TEST_SERVER,9:CHECK_IMEI_TEST_CLIENT,10:CHECK_IMEI_TEST_SERVER",
                    signString, Void.TYPE.getName(), MBeanOperationInfo.ACTION),
            new MBeanOperationInfo("start", "Starting a tester process", signEmpty, Void.TYPE.getName(),
                    MBeanOperationInfo.ACTION),
            new MBeanOperationInfo("stop", "Stopping a tester process", signEmpty, Void.TYPE.getName(),
                    MBeanOperationInfo.ACTION),
            new MBeanOperationInfo("quit", "Stop a tester process and terminate an application", signEmpty,
                    Void.TYPE.getName(), MBeanOperationInfo.ACTION), };

    MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[] { new MBeanNotificationInfo(
            new String[] { TesterHost.SS7_EVENT }, Notification.class.getName(), "SS7 events notification"), };

    return new MBeanInfo(TesterHost.class.getName(), "Tester host", attributes, null, operations, notifications);
}
 
Example 55
Project: phone-simulator   File: TesterHost.java   Source Code and License 4 votes vote down vote up
private synchronized void doSendNotif(String source, String msg, String userData) {
    Notification notif = new Notification(SS7_EVENT + "-" + source, "TesterHost", ++sequenceNumber,
            System.currentTimeMillis(), msg);
    notif.setUserData(userData);
    this.sendNotification(notif);
}
 
Example 56
Project: monarch   File: DistributedSystemDUnitTest.java   Source Code and License 4 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 57
Project: Pogamut3   File: FlagJMXProxy.java   Source Code and License 4 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 58
Project: monarch   File: CustomMBean.java   Source Code and License 4 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 59
Project: JRediClients   File: JCacheMBeanServerBuilder.java   Source Code and License 4 votes vote down vote up
@Override
public void sendNotification(Notification notification) {
    delegate.sendNotification(notification);
}
 
Example 60
Project: openjdk-jdk10   File: NotificationAccessControllerTest.java   Source Code and License 4 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();
}