Пример #1
0
 private Notification sendNotification(
     StandardEmitterMBean mbean, String type, long seq, Object userData) {
   Notification notif = new Notification(type, mbean, seq);
   notif.setUserData(userData);
   mbean.sendNotification(notif);
   return notif;
 }
    /**
     * Translate the given JMX <code>Notification</code> into an <code>Membership</code> that is
     * delivered to the <code>SystemMembershipListener</code>.
     */
    public void handleNotification(Notification notification, Object handback) {

      final String memberId = notification.getMessage();
      SystemMembershipEvent event =
          new SystemMembershipEvent() {
            public String getMemberId() {
              return memberId;
            }

            public DistributedMember getDistributedMember() {
              return null;
            }
          };

      String type = notification.getType();
      if (AdminDistributedSystemJmxImpl.NOTIF_MEMBER_JOINED.equals(type)) {
        this.listener.memberJoined(event);

      } else if (AdminDistributedSystemJmxImpl.NOTIF_MEMBER_LEFT.equals(type)) {
        this.listener.memberLeft(event);

      } else if (AdminDistributedSystemJmxImpl.NOTIF_MEMBER_CRASHED.equals(type)) {
        this.listener.memberCrashed(event);
      }
    }
 public void notifyCallingAETchange(String[] affectedCalledAETs, String[] newCallingAETs) {
   long eventID = this.getNextNotificationSequenceNumber();
   Notification notif = new Notification(CallingAetChanged.class.getName(), this, eventID);
   notif.setUserData(new CallingAetChanged(affectedCalledAETs, newCallingAETs));
   log.debug("send callingAET changed notif:" + notif);
   this.sendNotification(notif);
 }
Пример #4
0
  /**
   * Tests if the Message Size alert gets thrown when message of higher than threshold limit is sent
   *
   * @throws Exception
   */
  public void testMessageSizeAlert() throws Exception {
    setSession(new InternalTestProtocolSession(getVirtualHost()));
    AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore());
    getSession().addChannel(channel);

    setQueue(
        AMQQueueFactory.createAMQQueueImpl(
            new AMQShortString("testQueue2"),
            false,
            new AMQShortString("AMQueueAlertTest"),
            false,
            false,
            getVirtualHost(),
            null));
    _queueMBean = (AMQQueueMBean) getQueue().getManagedObject();
    _queueMBean.setMaximumMessageCount(MAX_MESSAGE_COUNT);
    _queueMBean.setMaximumMessageSize(MAX_MESSAGE_SIZE);

    sendMessages(channel, 1, MAX_MESSAGE_SIZE * 2);
    assertTrue(_queueMBean.getMessageCount() == 1);

    Notification lastNotification = _queueMBean.getLastNotification();
    assertNotNull(lastNotification);

    String notificationMsg = lastNotification.getMessage();
    assertTrue(notificationMsg.startsWith(NotificationCheck.MESSAGE_SIZE_ALERT.name()));
  }
Пример #5
0
 public void handleNotification(Notification n, Object hb) {
   if (n instanceof JMXConnectionNotification) {
     if (JMXConnectionNotification.FAILED.equals(n.getType())
         || JMXConnectionNotification.CLOSED.equals(n.getType())) {
       markAsDead();
     }
   }
 }
 /**
  * @see de.schouten.store.ElementListener#elementUpdated(de.schouten.store.DomainKey,
  *     de.schouten.store.ElementKey, de.schouten.store.StoreElement)
  */
 @Override
 public void elementUpdated(
     DomainKey aDomainKey, ElementKey elementKey, StoreElement storeElement) {
   Notification notification =
       new Notification(
           "elementnotifications", this, sequenceNumber.incrementAndGet(), "element updated");
   notification.setUserData(String.format("%s : %s", aDomainKey, elementKey));
   sendNotification(notification);
 }
  private void sendNotification(String message, Map<String, Object> status) {

    Notification notification =
        new Notification(
            PlatformMonitor.RESOURCE_STATUS_TYPE, platformMonitor, this.sequenceNumber++, message);

    notification.setUserData(status);

    super.sendNotification(notification);
  }
    /**
     * Translate the given JMX <code>Notification</code> into an <code>Alert</code> that is
     * delivered to the <code>AlertListener</code>.
     */
    public void handleNotification(Notification notification, Object handback) {
      String type = notification.getType();
      if (!AdminDistributedSystemJmxImpl.NOTIF_ALERT.equals(type)) {
        return;
      }

      String message = notification.getMessage();
      final com.gemstone.gemfire.internal.admin.Alert alert0 =
          com.gemstone.gemfire.internal.admin.remote.RemoteAlert.fromString(message);
      Alert alert =
          new Alert() {
            public AlertLevel getLevel() {
              return AlertLevel.forSeverity(alert0.getLevel());
            }

            public SystemMember getSystemMember() {
              String s = "Not implemented yet";
              throw new UnsupportedOperationException(s);
            }

            public String getConnectionName() {
              return alert0.getConnectionName();
            }

            public String getSourceId() {
              return alert0.getSourceId();
            }

            public String getMessage() {
              return alert0.getMessage();
            }

            public Date getDate() {
              return alert0.getDate();
            }

            public String toString() {
              return "Test JMXAdminDistributedSystem Alert date: "
                  + getDate()
                  + " message: \""
                  + getMessage()
                  + "\" source id: \""
                  + getSourceId()
                  + "\" connection name: "
                  + getConnectionName()
                  + " alert level: "
                  + getLevel();
            }
          };
      this.listener.alert(alert);
    }
Пример #9
0
 @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());
   }
 }
 public void handleNotification(Notification notif, Object handback) {
   String type = notif.getType();
   if (type.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
     GarbageCollectionNotificationInfo gcNotif =
         GarbageCollectionNotificationInfo.from((CompositeData) notif.getUserData());
     String source = ((ObjectName) notif.getSource()).getCanonicalName();
     synchronized (synchronizer) {
       if (listenerInvoked.get(source) == null) {
         listenerInvoked.put(((ObjectName) notif.getSource()).getCanonicalName(), gcNotif);
         count++;
         if (count >= number) {
           synchronizer.notify();
         }
       }
     }
   }
 }
Пример #11
0
 public void handleNotification(Notification arg0, Object arg1) {
   // check notifications serializable.
   try {
     if (!(arg0.getSource() instanceof ObjectName)) {
       throw new ClassCastException("Doh!");
     }
     Notification copy = OddjobTestHelper.copy(arg0);
     if (!(copy.getSource() instanceof ObjectName)) {
       throw new ClassCastException("Doh!");
     }
   } catch (Exception e) {
     logger.error("Notification Listener failed.", e);
     throw new RuntimeException(e);
   }
   Pair p = new Pair(arg0, arg1);
   notifications.add(p);
 }
Пример #12
0
 /**
  * Callback routine called by JVM after full gc run. Has two functions: 1) sets the amount of
  * memory to be cleaned from the cache by the Cleaner 2) sets the CAN_ALLOC flag to false if
  * memory level is critical
  *
  * <p>The callback happens in a system thread, and hence not through the usual water.Boot loader
  * - and so any touched classes are in the wrong class loader and you end up with new classes
  * with uninitialized global vars. Limit to touching global vars in the Boot class.
  */
 public void handleNotification(Notification notification, Object handback) {
   String notifType = notification.getType();
   if (notifType.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
     // Memory used after this FullGC
     Boot.TIME_AT_LAST_GC = System.currentTimeMillis();
     Boot.HEAP_USED_AT_LAST_GC = _allMemBean.getHeapMemoryUsage().getUsed();
     Boot.kick_store_cleaner();
   }
 }
Пример #13
0
  public void handleNotification(Notification notification, Object handback) {

    log.warn("================================================================================");

    String message = notification.getMessage();
    log.warn("Message: " + message);

    String type = notification.getType();
    log.warn("Type: " + type);

    if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)
        || type.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {

      CompositeData cd = (CompositeData) notification.getUserData();
      MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);

      String poolName = info.getPoolName();
      log.warn("Pool Name: " + poolName);

      long count = info.getCount();
      log.warn("Count: " + count);

      MemoryUsage usage = info.getUsage();

      long maxMemory = usage.getMax();
      long maxMB = maxMemory / (1024 * 1024);

      long usedMemory = usage.getUsed();
      long usedMB = usedMemory / (1024 * 1024);

      double percentUsed = (double) usedMemory / maxMemory;
      log.debug(
          "Used Memory : "
              + usedMB
              + "/"
              + maxMB
              + " MB ("
              + percentFormat.format(percentUsed)
              + ")");
    }
  }
 public void handleNotification(Notification notification, Object handback) {
   String type = notification.getType();
   if (type.equals(NotificationType.requestReceived)) {
     RequestNotificationData data = (RequestNotificationData) notification.getUserData();
     String key = keysList.get(data.getMethodName());
     if (key != null) {
       ((MethodStatisticsAbstract) statistics.get(key))
           .notifyArrivalOfRequest(notification.getTimeStamp());
     }
   } else if (type.equals(NotificationType.servingStarted)) {
     RequestNotificationData data = (RequestNotificationData) notification.getUserData();
     String key = keysList.get(data.getMethodName());
     if (key != null) {
       ((MethodStatisticsAbstract) statistics.get(key))
           .notifyDepartureOfRequest(notification.getTimeStamp());
     }
   } else if (type.equals(NotificationType.replySent)) {
     RequestNotificationData data = (RequestNotificationData) notification.getUserData();
     String key = keysList.get(data.getMethodName());
     if (key != null) {
       ((MethodStatisticsAbstract) statistics.get(key))
           .notifyReplyOfRequestSent(notification.getTimeStamp());
     }
   } else if (type.equals(NotificationType.voidRequestServed)) {
     RequestNotificationData data = (RequestNotificationData) notification.getUserData();
     String key = keysList.get(data.getMethodName());
     if (key != null) {
       ((MethodStatisticsAbstract) statistics.get(key))
           .notifyReplyOfRequestSent(notification.getTimeStamp());
     }
   } else if (type.equals(NotificationType.setOfNotifications)) {
     @SuppressWarnings("unchecked")
     ConcurrentLinkedQueue<Notification> notificationsList =
         (ConcurrentLinkedQueue<Notification>) notification.getUserData();
     for (Iterator<Notification> iterator = notificationsList.iterator(); iterator.hasNext(); ) {
       handleNotification(iterator.next(), handback);
     }
   }
 }
Пример #15
0
  public void handleNotification(Notification ntfyObj, Object handback) {
    log.info("***************************************************");
    log.info("* Notification received at " + new Date().toString());
    log.info("* type      = " + ntfyObj.getType());
    log.info("* message   = " + ntfyObj.getMessage());

    if (ntfyObj.getMessage().contains(path)) {
      setSuccess(true);
    }

    log.info("* seqNum    = " + ntfyObj.getSequenceNumber());
    log.info("* source    = " + ntfyObj.getSource());
    log.info("* seqNum    = " + Long.toString(ntfyObj.getSequenceNumber()));
    log.info("* timeStamp = " + new Date(ntfyObj.getTimeStamp()));
    log.info("* userData  = " + ntfyObj.getUserData());
    log.info("***************************************************");
  }
  @Override
  public void sendNotification(Notification aNotification) {
    PreparedStatement stmt = null;
    try {
      // prepare the insert statement
      stmt = connection.prepareStatement(NOTIF_INSERT_SQL);
      stmt.setString(1, aNotification.getMessage());
      stmt.setLong(2, aNotification.getSequenceNumber());
      if (aNotification.getSource() instanceof Serializable) {
        stmt.setObject(3, aNotification.getSource());
      } else {
        stmt.setObject(3, "No source");
      }
      stmt.setLong(4, aNotification.getTimeStamp());
      stmt.setString(5, aNotification.getType());
      if (aNotification.getUserData() instanceof Serializable) {
        stmt.setObject(6, aNotification.getUserData());
      } else {
        stmt.setObject(6, "No user data");
      }

      // execute amnd commit
      stmt.executeUpdate();

      // this should really be managed by the transaction
      // manager and connections
      connection.commit();
    } catch (Exception e) {
      LOG.error("Failed to persist notification", e);
    } finally {
      try {
        if (stmt != null) {
          stmt.close();
        }
      } catch (SQLException sqle) {
        LOG.error("failed to close statement", sqle);
      }
    }
    super.sendNotification(aNotification);
  }
Пример #17
0
 private void thresholdNotificationLogger(Notification notification) {
   CompositeData cd = (CompositeData) notification.getUserData();
   MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);
   MemoryPoolMXBean memPool = memoryPoolMap.get(info.getPoolName());
   log.error(
       "memory threshold "
           + getPercentFormat(getThresholdPercent(memPool))
           + " exceeded on memory pool "
           + info.getPoolName()
           + ", count:"
           + info.getCount()
           + ", "
           + getUsagePercent(memPool)
           + "["
           + info.getUsage()
           + "]");
   if (verbose) {
     logStats(memoryPoolMap.get(info.getPoolName()), Level.WARN);
   }
 }
  /**
   * Jesli otrzymana notyfikacja jest o stanie procesu deploymentu to aktualizuje licznik i
   * przekazuje notyfikacje do wszystkich listenerow postepu procesu deploymentu
   */
  @Override
  public synchronized void handleNotification(Notification notification, Object handback) {

    Object userData = notification.getUserData();

    log.info("Received notification from WorkerProgress ");

    if (notification.getUserData() != null
        && notification.getUserData() instanceof TaskCompletedNotification) {

      updateProgress(
          new ProgressNotification(
              ++index,
              totalTasks,
              ((TaskCompletedNotification) notification.getUserData()).getNodeIpAddress()));

    } else if (notification.getUserData() != null
        && notification.getUserData() instanceof LogNotification) {

      updateLogs(((LogNotification) notification.getUserData()).getLog());
    }
  }
 void sendJMXNotification(Object o) {
   long eventID = super.getNextNotificationSequenceNumber();
   Notification notif = new Notification(o.getClass().getName(), this, eventID);
   notif.setUserData(o);
   super.sendNotification(notif);
 }
Пример #20
0
 public void handleNotification(Notification notification, Object handback) {
   if (notification.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
     thresholdNotificationLogger(notification);
     thresholdNotificationWatch(notification);
   }
 }
    public void handleNotification(Notification notification, Object handback) {
      try {
        String type = notification.getType();

        if (NotificationType.GCMRuntimeRegistered.equals(type)) {
          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Notification received");
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Notification received");
          }
          GCMRuntimeRegistrationNotificationData data =
              (GCMRuntimeRegistrationNotificationData) notification.getUserData();
          if (data.getDeploymentId() != listener.getDeployID()) {
            return;
          }
          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Notification accepted");
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Notification accepted");
            outDebug.flush();
          }

          ProActiveRuntime childRuntime = data.getChildRuntime();
          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Creating Node");
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Creating Node");
          }
          Node scilabNode = null;
          try {
            scilabNode =
                childRuntime.createLocalNode(
                    nodeBaseName + "_" + nodeName + "_" + nodeCount, true, null, null);
          } catch (Exception e) {
            if (debug) {
              e.printStackTrace();
              e.printStackTrace(outDebug);
            }
            throw e;
          }
          nodeCount++;
          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Node Created : "
                    + scilabNode.getNodeInformation().getURL());
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Node Created :"
                    + scilabNode.getNodeInformation().getURL());
          }
          listener.setNode(scilabNode);

          if (debug) {
            System.out.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Waking up main thread");
            outDebug.println(
                "["
                    + new java.util.Date()
                    + " "
                    + host
                    + " "
                    + this.getClass().getSimpleName()
                    + "] Waking up main thread");
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
        if (debug) {
          e.printStackTrace(outDebug);
        }
      } finally {
        semaphore.release();
      }
    }
Пример #22
0
 public void handleNotification(Notification notification, Object handback) {
   String type = notification.getType();
   if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
     System.out.println("内存占用量超过阈值。");
   }
 }
    private void doRun() {
      synchronized (ClientNotifForwarder.this) {
        currentFetchThread = Thread.currentThread();

        if (state == STARTING) {
          setState(STARTED);
        }
      }

      NotificationResult nr = null;
      if (!shouldStop() && (nr = fetchNotifs()) != null) {
        // nr == null means got exception

        final TargetedNotification[] notifs = nr.getTargetedNotifications();
        final int len = notifs.length;
        final Map<Integer, ClientListenerInfo> listeners;
        final Integer myListenerID;

        long missed = 0;

        synchronized (ClientNotifForwarder.this) {
          // check sequence number.
          //
          if (clientSequenceNumber >= 0) {
            missed = nr.getEarliestSequenceNumber() - clientSequenceNumber;
          }

          clientSequenceNumber = nr.getNextSequenceNumber();

          final int size = infoList.size();
          listeners = new HashMap<Integer, ClientListenerInfo>();

          for (int i = 0; i < len; i++) {
            final TargetedNotification tn = notifs[i];
            final Integer listenerID = tn.getListenerID();

            // check if an mbean unregistration notif
            if (!listenerID.equals(mbeanRemovedNotifID)) {
              final ClientListenerInfo li = infoList.get(listenerID);
              if (li != null) {
                listeners.put(listenerID, li);
              }
              continue;
            }
            final Notification notif = tn.getNotification();
            final String unreg = MBeanServerNotification.UNREGISTRATION_NOTIFICATION;
            if (notif instanceof MBeanServerNotification && notif.getType().equals(unreg)) {

              MBeanServerNotification mbsn = (MBeanServerNotification) notif;
              ObjectName name = mbsn.getMBeanName();

              removeNotificationListener(name);
            }
          }
          myListenerID = mbeanRemovedNotifID;
        }

        if (missed > 0) {
          final String msg =
              "May have lost up to " + missed + " notification" + (missed == 1 ? "" : "s");
          lostNotifs(msg, missed);
          logger.trace("NotifFetcher.run", msg);
        }

        // forward
        for (int i = 0; i < len; i++) {
          final TargetedNotification tn = notifs[i];
          dispatchNotification(tn, myListenerID, listeners);
        }
      }

      synchronized (ClientNotifForwarder.this) {
        currentFetchThread = null;
      }

      if (nr == null || shouldStop()) {
        // tell that the thread is REALLY stopped
        setState(STOPPED);
      } else {
        executor.execute(this);
      }
    }
Пример #24
0
 public void handleNotification(Notification notif, Object handback) {
   String spsuid = (String) notif.getUserData();
   Dataset pps = DcmObjectFactory.getInstance().newDataset();
   try {
     Dataset sps;
     GPWLManager gpwlmgr = getGPWLManager();
     sps = gpwlmgr.getWorklistItem(spsuid);
     String ppsiuid = spsuid + ppsuidSuffix;
     String status = sps.getString(Tags.GPSPSStatus);
     pps.putCS(Tags.GPPPSStatus, status);
     pps.putUI(Tags.SOPInstanceUID, ppsiuid);
     Date now = new Date();
     if ("IN PROGRESS".equals(status)) {
       try {
         getGPPPSManager().getGPPPS(ppsiuid);
         return; // avoid duplicate N_CREATE
       } catch (Exception e) {
       }
       pps.putSH(Tags.PPSID, "PPS" + ppsiuid.hashCode());
       pps.putDA(Tags.PPSStartDate, now);
       pps.putTM(Tags.PPSStartTime, now);
       pps.putDA(Tags.PPSEndDate);
       pps.putTM(Tags.PPSEndTime);
       for (int i = 0; i < N_CREATE_TYPE2_ATTRS.length; i++) {
         pps.putXX(N_CREATE_TYPE2_ATTRS[i]);
       }
       pps.putAll(sps.subSet(N_CREATE_SPS_ATTRS));
       copyCode(
           copyWorkitemCode,
           sps.getItem(Tags.ScheduledWorkitemCodeSeq),
           pps.putSQ(Tags.PerformedWorkitemCodeSeq));
       copyCode(
           copyStationNameCode,
           sps.getItem(Tags.ScheduledStationNameCodeSeq),
           pps.putSQ(Tags.PerformedStationNameCodeSeq));
       copyCode(
           copyStationClassCode,
           sps.getItem(Tags.ScheduledStationClassCodeSeq),
           pps.putSQ(Tags.PerformedStationClassCodeSeq));
       copyCode(
           copyStationGeographicLocationCode,
           sps.getItem(Tags.ScheduledStationGeographicLocationCodeSeq),
           pps.putSQ(Tags.PerformedStationGeographicLocationCodeSeq));
       copyCode(
           copyProcessingApplicationsCode,
           sps.getItem(Tags.ScheduledProcessingApplicationsCodeSeq),
           pps.putSQ(Tags.PerformedProcessingApplicationsCodeSeq));
     } else if ("COMPLETED".equals(status) || "DISCONTINUED".equals(status)) {
       pps.putDA(Tags.PPSEndDate, now);
       pps.putTM(Tags.PPSEndTime, now);
       pps.putAll(gpwlmgr.getOutputInformation(spsuid));
     } else {
       return;
     }
   } catch (Exception e) {
     log.error("Failed to access GP-SPS[" + spsuid + "]", e);
     return;
   }
   for (int i = 0; i < destAETs.length; i++) {
     PPSOrder order = new PPSOrder(pps, destAETs[i]);
     try {
       log.info("Scheduling " + order);
       jmsDelegate.queue(queueName, order, Message.DEFAULT_PRIORITY, 0L);
     } catch (Exception e) {
       log.error("Failed to schedule " + order, e);
     }
   }
 }
    public void handleNotification(Notification notification, Object handback) {
      log.debug("handleNotification", "Received notification [ " + notification.getType() + "]");

      String type = notification.getType();
      if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)
          || type.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
        MemoryNotificationInfo minfo =
            MemoryNotificationInfo.from((CompositeData) notification.getUserData());
        SnmpCounter64 count = new SnmpCounter64(minfo.getCount());
        SnmpCounter64 used = new SnmpCounter64(minfo.getUsage().getUsed());
        SnmpString poolName = new SnmpString(minfo.getPoolName());
        SnmpOid entryIndex = getJvmMemPoolEntryIndex(minfo.getPoolName());

        if (entryIndex == null) {
          log.error(
              "handleNotification",
              "Error: Can't find entry index for Memory Pool: "
                  + minfo.getPoolName()
                  + ": "
                  + "No trap emitted for "
                  + type);
          return;
        }

        SnmpOid trap = null;

        final SnmpOidTable mibTable = getOidTable();
        try {
          SnmpOid usedOid = null;
          SnmpOid countOid = null;

          if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
            trap = new SnmpOid(mibTable.resolveVarName("jvmLowMemoryPoolUsageNotif").getOid());
            usedOid =
                new SnmpOid(mibTable.resolveVarName("jvmMemPoolUsed").getOid() + "." + entryIndex);
            countOid =
                new SnmpOid(
                    mibTable.resolveVarName("jvmMemPoolThreshdCount").getOid() + "." + entryIndex);
          } else if (type.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
            trap = new SnmpOid(mibTable.resolveVarName("jvmLowMemoryPoolCollectNotif").getOid());
            usedOid =
                new SnmpOid(
                    mibTable.resolveVarName("jvmMemPoolCollectUsed").getOid() + "." + entryIndex);
            countOid =
                new SnmpOid(
                    mibTable.resolveVarName("jvmMemPoolCollectThreshdCount").getOid()
                        + "."
                        + entryIndex);
          }

          // Datas
          SnmpVarBindList list = new SnmpVarBindList();
          SnmpOid poolNameOid =
              new SnmpOid(mibTable.resolveVarName("jvmMemPoolName").getOid() + "." + entryIndex);

          SnmpVarBind varCount = new SnmpVarBind(countOid, count);
          SnmpVarBind varUsed = new SnmpVarBind(usedOid, used);
          SnmpVarBind varPoolName = new SnmpVarBind(poolNameOid, poolName);

          list.add(varPoolName);
          list.add(varCount);
          list.add(varUsed);

          sendTrap(trap, list);
        } catch (Exception e) {
          log.error("handleNotification", "Exception occured : " + e);
        }
      }
    }
Пример #26
0
  /*
   This test sends some messages to the queue with subscribers needing message to be acknowledged.
   The messages will not be acknowledged and will be required twice. Why we are checking this is because
   the bug reported said that the queueDepth keeps increasing when messages are requeued.
   // TODO - queue depth now includes unacknowledged messages so does not go down when messages are delivered

   The QueueDepth should decrease when messages are delivered from the queue (QPID-408)
  */
  public void testQueueDepthAlertWithSubscribers() throws Exception {
    AMQChannel channel = new AMQChannel(getSession(), 2, getMessageStore());
    getSession().addChannel(channel);

    // Create queue
    setQueue(getNewQueue());
    Subscription subscription =
        SUBSCRIPTION_FACTORY.createSubscription(
            channel.getChannelId(),
            getSession(),
            new AMQShortString("consumer_tag"),
            true,
            null,
            false,
            channel.getCreditManager());

    getQueue().registerSubscription(subscription, false);

    _queueMBean = (AMQQueueMBean) getQueue().getManagedObject();
    _queueMBean.setMaximumMessageCount(9999l); // Set a high value, because this is not being tested
    _queueMBean.setMaximumQueueDepth(MAX_QUEUE_DEPTH);

    // Send messages(no of message to be little more than what can cause a Queue_Depth alert)
    int messageCount = Math.round(MAX_QUEUE_DEPTH / MAX_MESSAGE_SIZE) + 10;
    long totalSize = (messageCount * MAX_MESSAGE_SIZE);
    sendMessages(channel, messageCount, MAX_MESSAGE_SIZE);

    // Check queueDepth. There should be no messages on the queue and as the subscriber is listening
    // so there should be no Queue_Deoth alert raised
    assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth()));
    Notification lastNotification = _queueMBean.getLastNotification();
    //        assertNull(lastNotification);

    // Kill the subscriber and check for the queue depth values.
    // Messages are unacknowledged, so those should get requeued. All messages should be on the
    // Queue
    getQueue().unregisterSubscription(subscription);
    channel.requeue();

    assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth()));

    lastNotification = _queueMBean.getLastNotification();
    assertNotNull(lastNotification);
    String notificationMsg = lastNotification.getMessage();
    assertTrue(notificationMsg.startsWith(NotificationCheck.QUEUE_DEPTH_ALERT.name()));

    // Connect a consumer again and check QueueDepth values. The queue should get emptied.
    // Messages will get delivered but still are unacknowledged.
    Subscription subscription2 =
        SUBSCRIPTION_FACTORY.createSubscription(
            channel.getChannelId(),
            getSession(),
            new AMQShortString("consumer_tag"),
            true,
            null,
            false,
            channel.getCreditManager());

    getQueue().registerSubscription(subscription2, false);

    while (getQueue().getUndeliveredMessageCount() != 0) {
      Thread.sleep(100);
    }
    //        assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth()));

    // Kill the subscriber again. Now those messages should get requeued again. Check if the queue
    // depth
    // value is correct.
    getQueue().unregisterSubscription(subscription2);
    channel.requeue();

    assertEquals(new Long(totalSize), new Long(_queueMBean.getQueueDepth()));
    getSession().closeSession();

    // Check the clear queue
    _queueMBean.clearQueue();
    assertEquals(new Long(0), new Long(_queueMBean.getQueueDepth()));
  }