@Test
  @DirtiesContext
  @Ignore("not yet implemented")
  public void testMultipleDownAndSingleUpCase() throws Exception {

    // Get engine
    DroolsCorrelationEngine engine = findEngineByName("monolithicDependencyRules");

    // Anticipate down event
    getAnticipator().reset();
    anticipate(
        createComponentImpactedEvent(
            "ServiceElementComponent",
            "jnxVpnPw-vcid(50)",
            "NA-SvcElemComp",
            "9876,jnxVpnPw-vcid(50)",
            17));
    anticipate(
        createComponentImpactedEvent("ServiceElement", "PE2,SE1", "NA-ServiceElement", "9876", 17));
    anticipate(createComponentImpactedEvent("Service", "CokeP2P", "NA-Service", "123", 17));

    // Generate down event
    Event event = createVpnPwDownEvent(m_pe2NodeId, "10.1.1.1", "5", "ge-3/1/4.50");
    event.setDbid(17);
    System.err.println("SENDING VpnPwDown EVENT!!");
    engine.correlate(event);

    // Check down event
    getAnticipator().verifyAnticipated();

    // Generate additional down event - nothing should happen
    getAnticipator().reset();
    event = createVpnPwDownEvent(m_pe2NodeId, "10.1.1.1", "5", "ge-3/1/4.50");
    event.setDbid(18);
    System.err.println("SENDING VpnPwDown EVENT!!");
    engine.correlate(event);
    getAnticipator().verifyAnticipated();

    // Anticipate up event
    getAnticipator().reset();
    anticipate(
        createComponentResolvedEvent(
            "ServiceElementComponent",
            "jnxVpnPw-vcid(50)",
            "NA-SvcElemComp",
            "9876,jnxVpnPw-vcid(50)",
            17));
    anticipate(
        createComponentResolvedEvent("ServiceElement", "PE2,SE1", "NA-ServiceElement", "9876", 17));
    anticipate(createComponentResolvedEvent("Service", "CokeP2P", "NA-Service", "123", 17));

    // Generate up event
    event = createVpnPwUpEvent(m_pe2NodeId, "10.1.1.1", "5", "ge-3/1/4.50");
    event.setDbid(17);
    System.err.println("SENDING VpnPwUp EVENT!!");
    engine.correlate(event);

    // Check up event
    getAnticipator().verifyAnticipated();
  }
  /**
   * {@inheritDoc}
   *
   * <p>This method is invoked by the event manager when a new event is available for processing.
   * Each message is examined for its Universal Event Identifier and the appropriate action is
   * taking based on each UEI.
   */
  @Override
  public void onEvent(Event event) {

    LOG.debug("onEvent: received event, UEI = {}", event.getUei());
    EventBuilder ebldr = null;

    if (isReloadConfigEvent(event)) {
      LOG.info(
          "onEvent: Reloading events configuration in response to event with UEI "
              + event.getUei());
      try {
        m_eventConfDao.reload();
        ebldr = new EventBuilder(EventConstants.RELOAD_DAEMON_CONFIG_SUCCESSFUL_UEI, getName());
        ebldr.addParam(EventConstants.PARM_DAEMON_NAME, "Eventd");

      } catch (Throwable e) {
        LOG.error("onEvent: Could not reload events config", e);
        ebldr = new EventBuilder(EventConstants.RELOAD_DAEMON_CONFIG_SUCCESSFUL_UEI, getName());
        ebldr.addParam(EventConstants.PARM_DAEMON_NAME, "Eventd");
        ebldr.addParam(EventConstants.PARM_REASON, e.getLocalizedMessage().substring(0, 128));
      }

      if (ebldr != null) {
        m_eventIpcManager.sendNow(ebldr.getEvent());
      }
    }
  }
 /**
  * setMonitoredService
  *
  * @param monitoredService a {@link org.opennms.netmgt.model.OnmsMonitoredService} object.
  * @return a {@link org.opennms.netmgt.model.events.EventBuilder} object.
  */
 public EventBuilder setMonitoredService(final OnmsMonitoredService monitoredService) {
   if (monitoredService != null) {
     m_event.setNodeid(monitoredService.getNodeId().longValue());
     m_event.setInterfaceAddress(monitoredService.getIpAddress());
     m_event.setService(monitoredService.getServiceName());
   }
   return this;
 }
 /**
  * setIpInterface
  *
  * @param iface a {@link org.opennms.netmgt.model.OnmsIpInterface} object.
  * @return a {@link org.opennms.netmgt.model.events.EventBuilder} object.
  */
 public EventBuilder setIpInterface(final OnmsIpInterface iface) {
   if (iface != null) {
     if (iface.getNode() != null) {
       m_event.setNodeid(iface.getNode().getId().longValue());
     }
     m_event.setInterfaceAddress(iface.getIpAddress());
   }
   return this;
 }
    OutageChecker(MockService svc, Event lostSvcEvent, Event regainedSvcEvent) {
      super(m_db, "select * from outages where nodeid = ? and ipAddr = ? and serviceId = ?");

      m_svc = svc;
      m_lostSvcEvent = lostSvcEvent;
      m_lostSvcTime = m_db.convertEventTimeToTimeStamp(m_lostSvcEvent.getTime());
      m_regainedSvcEvent = regainedSvcEvent;
      if (m_regainedSvcEvent != null)
        m_regainedSvcTime = m_db.convertEventTimeToTimeStamp(m_regainedSvcEvent.getTime());
    }
  private void completeEventListAndAddToEvents(
      Events events, List<Event> eventList, LatencyInterface latIface)
      throws ThresholdingException {
    for (Event event : eventList) {
      event.setNodeid((long) latIface.getNodeId());
      event.setInterfaceAddress(latIface.getInetAddress());
      event.setService(latIface.getServiceName());

      events.addEvent(event);
    }
  }
 @Override
 public String toString() {
   return getClass().getSimpleName()
       + " ["
       + "component="
       + m_component
       + ", event="
       + m_event.getUei()
       + "("
       + m_event.getDbid()
       + ")"
       + "]";
 }
  private boolean isReloadConfigEvent(Event event) {
    boolean isTarget = false;

    if (EventConstants.RELOAD_DAEMON_CONFIG_UEI.equals(event.getUei())) {
      if ("Eventd".equalsIgnoreCase(EventUtils.getParm(event, EventConstants.PARM_DAEMON_NAME))) {
        isTarget = true;
      }
      // Deprecating this one...
    } else if (EventConstants.EVENTSCONFIG_CHANGED_EVENT_UEI.equals(event.getUei())) {
      isTarget = true;
    }

    return isTarget;
  }
    /**
     * Process the received events. For each event, use the EventExpander to look up matching
     * eventconf entry and load info from that match, expand event parms, add event to database and
     * send event to appropriate listeners.
     */
    @Override
    public void run() {
      Events events = m_eventLog.getEvents();
      if (events == null || events.getEventCount() <= 0) {
        // no events to process
        return;
      }

      for (final Event event : events.getEventCollection()) {
        final ThreadCategory log = log();
        if (log.isDebugEnabled()) {
          // Log the uei, source, and other important aspects
          final String uuid = event.getUuid();
          log.debug("Event {");
          log.debug("  uuid  = " + (uuid != null && uuid.length() > 0 ? uuid : "<not-set>"));
          log.debug("  uei   = " + event.getUei());
          log.debug("  src   = " + event.getSource());
          log.debug("  iface = " + event.getInterface());
          log.debug("  time  = " + event.getTime());
          if (event.getParmCollection().size() > 0) {
            log.debug("  parms {");
            for (final Parm parm : event.getParmCollection()) {
              if ((parm.getParmName() != null) && (parm.getValue().getContent() != null)) {
                log.debug(
                    "    ("
                        + parm.getParmName().trim()
                        + ", "
                        + parm.getValue().getContent().trim()
                        + ")");
              }
            }
            log.debug("  }");
          }
          log.debug("}");
        }

        for (final EventProcessor eventProcessor : m_eventProcessors) {
          try {
            eventProcessor.process(m_eventLog.getHeader(), event);
          } catch (SQLException e) {
            log.warn(
                "Unable to process event using processor "
                    + eventProcessor
                    + "; not processing with any later processors.  Exception: "
                    + e,
                e);
            break;
          } catch (Throwable t) {
            log.warn(
                "Unknown exception processing event with processor "
                    + eventProcessor
                    + "; not processing with any later processors.  Exception: "
                    + t,
                t);
            break;
          }
        }
      }
    }
  /**
   * @param event
   * @param log
   * @return
   */
  private int getEventServiceId(final Event event) {
    if (event.getService() == null) {
      return -1;
    }

    try {
      return getServiceID(event.getService());
    } catch (final Throwable t) {
      LOG.warn(
          "Error converting service name \"{}\" to an integer identifier, storing -1.",
          event.getService(),
          t);
      return -1;
    }
  }
  @Test
  public void testImportNoRescan() throws Exception {
    createRequisition();

    final MockEventProxy eventProxy = getEventProxy();
    eventProxy.resetEvents();

    sendRequest(PUT, "/requisitions/test/import", parseParamData("rescanExisting=false"), 303);

    assertEquals(1, eventProxy.getEvents().size());
    final Event event = eventProxy.getEvents().get(0);
    final List<Parm> parms = event.getParmCollection();
    assertEquals(2, parms.size());
    assertEquals("false", parms.get(1).getValue().getContent());
  }
 private void sendEvent(Event event) throws ServletException {
   try {
     Util.createEventProxy().send(event);
   } catch (Throwable e) {
     throw new ServletException("Could not send event " + event.getUei(), e);
   }
 }
  /**
   * setParam
   *
   * @param parmName a {@link java.lang.String} object.
   * @param val a {@link java.lang.String} object.
   * @return a {@link org.opennms.netmgt.model.events.EventBuilder} object.
   */
  public EventBuilder setParam(final String parmName, final String val) {
    if (m_event.getParmCollection().size() < 1) {
      return addParam(parmName, val);
    }

    for (final Parm parm : m_event.getParmCollection()) {
      if (parm.getParmName().equals(val)) {
        final Value value = new Value();
        value.setContent(val);
        parm.setValue(value);
        return this;
      }
    }

    return addParam(parmName, val);
  }
  public void testGetEventForStateDefaultUEIS() {
    Threshold threshold = new Threshold();
    threshold.setType("relativeChange");
    threshold.setDsName("ds-name");
    threshold.setDsType("ds-type");
    threshold.setValue(99.0);
    threshold.setRearm(95.0);
    threshold.setTrigger(1);
    ThresholdConfigWrapper wrapper = new ThresholdConfigWrapper(threshold);

    ThresholdEvaluatorStateRelativeChange item = new ThresholdEvaluatorStateRelativeChange(wrapper);
    Event event = item.getEventForState(Status.TRIGGERED, new Date(), 100.0, null);
    assertEquals(
        "UEI should be the relativeChangeThresholdTriggerd",
        EventConstants.RELATIVE_CHANGE_THRESHOLD_EVENT_UEI,
        event.getUei());
  }
 public void processRow(ResultSet rs) throws SQLException {
   assertEquals(m_svc.getNodeId(), rs.getInt("nodeId"));
   assertEquals(m_svc.getIpAddr(), rs.getString("ipAddr"));
   assertEquals(m_svc.getId(), rs.getInt("serviceId"));
   assertEquals(m_lostSvcEvent.getDbid(), Integer.valueOf(rs.getInt("svcLostEventId")));
   assertEquals(m_lostSvcTime, rs.getTimestamp("ifLostService"));
   assertEquals(getRegainedEventId(), rs.getObject("svcRegainedEventId"));
   assertEquals(m_regainedSvcTime, rs.getTimestamp("ifRegainedService"));
 }
 private void sendRearmForTriggeredStates() {
   for (String instance : m_thresholdEvaluatorStates.keySet()) {
     for (ThresholdEvaluatorState state : m_thresholdEvaluatorStates.get(instance)) {
       if (state.isTriggered()) {
         Event e = state.getEventForState(Status.RE_ARMED, new Date(), Double.NaN, null);
         Parm p = new Parm();
         p.setParmName("reason");
         Value v = new Value();
         v.setContent("Configuration has been changed");
         p.setValue(v);
         e.addParm(p);
         log().info("sendRearmForTriggeredStates: sending rearm for " + e);
         ThresholdingEventProxyFactory.getFactory().getProxy().add(e);
         state.clearState();
       }
     }
   }
 }
  public void testGetEventForStateTriggered() {
    Threshold threshold = new Threshold();
    threshold.setType("relativeChange");
    threshold.setDsName("ds-name");
    threshold.setDsType("ds-type");
    threshold.setValue(1.1);
    threshold.setRearm(0.5);
    threshold.setTrigger(3);
    ThresholdConfigWrapper wrapper = new ThresholdConfigWrapper(threshold);
    ThresholdEvaluatorStateRelativeChange evaluator =
        new ThresholdEvaluatorStateRelativeChange(wrapper);

    assertEquals("should not trigger", Status.NO_CHANGE, evaluator.evaluate(8.0));
    assertEquals("should trigger", Status.TRIGGERED, evaluator.evaluate(10.0));

    // Do it once with a null instance
    Event event = evaluator.getEventForState(Status.TRIGGERED, new Date(), 10.0, null);
    assertNotNull("should have created an event", event);
    assertEquals(
        "UEIs should be the same",
        EventConstants.RELATIVE_CHANGE_THRESHOLD_EVENT_UEI,
        event.getUei());
    assertNotNull("event should have parms", event.getParmCollection());
    parmPresentAndValueNonNull(event, "instance");
    parmPresentWithValue(event, "value", "10.0");
    parmPresentWithValue(event, "previousValue", "8.0");
    parmPresentWithValue(event, "multiplier", "1.1");

    // And again with a non-null instance
    event =
        evaluator.getEventForState(
            Status.TRIGGERED, new Date(), 10.0, new MockCollectionResourceWrapper("testInstance"));
    assertNotNull("should have created an event", event);
    assertEquals(
        "UEIs should be the same",
        EventConstants.RELATIVE_CHANGE_THRESHOLD_EVENT_UEI,
        event.getUei());
    assertNotNull("event should have parms", event.getParmCollection());
    parmPresentWithValue(event, "instance", "testInstance");
    parmPresentWithValue(event, "value", "10.0");
    parmPresentWithValue(event, "previousValue", "8.0");
    parmPresentWithValue(event, "multiplier", "1.1");
  }
  /**
   * Create an SNMP trap, based on the content of the specified event, and forward the trap to the
   * specified address and port. It is assumed that the specified event represents an SNMP V1 or V2
   * trap that was received by OpenNMS (TrapD). The type of trap to be created depends on the type
   * of the original trap (i.e. if the original trap was an SNMP V1 trap, an SNMP V1 trap will be
   * created; if the original trap was an SNMP V2 trap, an SNMP V2 trap will be created).
   *
   * @param event The event upon which the trap content should be based
   * @param destAddr The address to which the trap should be forwarded
   * @param destPort The port to which the trap should be forwarded
   * @exception Throws SnmpTrapHelperException if the variable binding cannot be added to the trap
   *     for any reason.
   * @throws org.opennms.netmgt.scriptd.helper.SnmpTrapHelperException if any.
   */
  public void forwardTrap(Event event, String destAddr, int destPort)
      throws SnmpTrapHelperException {

    Snmp snmpInfo = event.getSnmp();

    if (snmpInfo == null) {
      throw new SnmpTrapHelperException(
          "Cannot forward an event with no SNMP info: " + event.getUei());
    }

    String version = snmpInfo.getVersion();

    if ("v1".equals(version)) {
      forwardV1Trap(event, destAddr, destPort);
    } else if ("v2".equals(version)) {
      forwardV2Trap(event, destAddr, destPort);
    } else {
      throw new SnmpTrapHelperException("Invalid SNMP version: " + version);
    }
  }
  public void testGetEventForStateCustomUEIS() {
    String triggeredUEI = "uei.opennms.org/custom/relativeChangeThresholdTriggered";
    Threshold threshold = new Threshold();
    threshold.setType("relativeChange");
    threshold.setDsName("ds-name");
    threshold.setDsType("ds-type");
    threshold.setValue(99.0);
    threshold.setRearm(95.0);
    threshold.setTrigger(1);
    threshold.setTriggeredUEI(triggeredUEI);

    ThresholdConfigWrapper wrapper = new ThresholdConfigWrapper(threshold);

    ThresholdEvaluatorStateRelativeChange item = new ThresholdEvaluatorStateRelativeChange(wrapper);
    Event event = item.getEventForState(Status.TRIGGERED, new Date(), 100.0, null);
    assertEquals(
        "UEI should be the uei.opennms.org/custom/relativeChangeThresholdTriggered",
        triggeredUEI,
        event.getUei());
  }
Exemple #20
0
  @Test
  @JUnitTemporaryDatabase(
      tempDbClass = MockDatabase.class) // Relies on specific IDs so we need a fresh database
  public void testNorthbounder() throws Exception {
    assertTrue(m_northbounder.isInitialized());
    assertTrue(m_northbounder.getAlarms().isEmpty());

    final EventBuilder bldr = new EventBuilder("testNoLogmsg", "AlarmdTest");
    bldr.setAlarmData(new AlarmData());
    bldr.setLogMessage("This is a test.");

    final Event event = bldr.getEvent();
    event.setDbid(17);

    MockNode node = m_mockNetwork.getNode(1);
    sendNodeDownEvent("%nodeid%", node);

    final List<NorthboundAlarm> alarms = m_northbounder.getAlarms();
    assertTrue(alarms.size() > 0);
  }
  /**
   * nodeInterfaceServiceValid
   *
   * @param notif a {@link org.opennms.netmgt.config.notifications.Notification} object.
   * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
   * @return a boolean.
   */
  protected boolean nodeInterfaceServiceValid(final Notification notif, final Event event) {
    Assert.notNull(notif, "notif argument must not be null");
    Assert.notNull(event, "event argument must not be null");
    Assert.notNull(notif.getRule(), "getRule() on notif argument must not return null");

    /*
     *  If the event doesn't have a nodeId, interface, or service,
     *  return true since there is nothing on which to filter.
     */
    if (event.getNodeid() == 0 && event.getInterface() == null && event.getService() == null) {
      if ("MATCH-ANY-UEI".equals(notif.getUei())) {
        // TODO: Trim parentheses from the filter and trim whitespace from inside the
        // filter statement. This comparison is very brittle as it is.
        if ("ipaddr != '0.0.0.0'".equals(notif.getRule().toLowerCase())
            || "ipaddr iplike *.*.*.*".equals(notif.getRule().toLowerCase())) {
          return true;
        } else {
          return false;
        }
      }
      return true;
    }

    StringBuffer constraints = new StringBuffer();
    if (event.getNodeid() != 0) {
      constraints.append(" & (nodeId == " + event.getNodeid() + ")");
    }

    if (event.getInterface() != null && !"0.0.0.0".equals(event.getInterface())) {
      constraints.append(" & (ipAddr == '" + event.getInterface() + "')");
      if (event.getService() != null) {
        constraints.append(" & (serviceName == '" + event.getService() + "')");
      }
    }

    String rule = "((" + notif.getRule() + ")" + constraints + ")";

    return isRuleMatchingFilter(notif, rule);
  }
Exemple #22
0
  /**
   * Format the list of event parameters
   *
   * @param event TODO
   * @return the formatted event parameters string
   */
  public static String format(final Event event) {
    if (event == null
        || event.getParmCollection() == null
        || event.getParmCollection().size() == 0) {
      return null;
    }

    boolean first = true;
    StringBuffer parmbuf = new StringBuffer();

    for (final Parm parm : event.getParmCollection()) {
      if (parm.getParmName() != null
          && parm.getValue() != null
          && parm.getValue().getContent() != null) {
        if (!first) {
          parmbuf.append(Constants.MULTIPLE_VAL_DELIM);
        }
        parmbuf.append(format(parm));
        first = false;
      }
    }

    return parmbuf.toString();
  }
  /**
   * {@inheritDoc}
   *
   * <p>This method is invoked by the EventIpcManager when a new event is available for processing.
   * Each message is examined for its Universal Event Identifier and the appropriate action is
   * taking based on each UEI.
   */
  public void onEvent(Event event) {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    String eventUei = event.getUei();
    if (eventUei == null) {
      log.warn("Received an unexpected event with a null UEI");
      return;
    }

    if (log.isDebugEnabled()) {
      log.debug("Received event: " + eventUei);
    }

    if (eventUei.equals(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI)
        || eventUei.equals(EventConstants.INTERFACE_REPARENTED_EVENT_UEI)) {
      String action =
          eventUei.equals(EventConstants.INTERFACE_REPARENTED_EVENT_UEI) ? "reparent" : "add";
      if (Long.toString(event.getNodeid()) == null) {
        log.warn("Not " + action + "ing interface to known node list: " + "nodeId is null");
      } else if (event.getInterface() == null) {
        log.warn("Not " + action + "ing interface to known node list: " + "interface is null");
      } else {
        m_trapdIpMgr.setNodeId(event.getInterface(), event.getNodeid());
        if (log.isDebugEnabled()) {
          log.debug(
              "Successfully " + action + "ed " + event.getInterface() + " to known node list");
        }
      }
    } else if (eventUei.equals(EventConstants.INTERFACE_DELETED_EVENT_UEI)) {
      if (event.getInterface() != null) {
        m_trapdIpMgr.removeNodeId(event.getInterface());
        if (log.isDebugEnabled()) {
          log.debug("Removed " + event.getInterface() + " from known node list");
        }
      }
    } else {
      log.warn("Received an unexpected event with UEI of \"" + eventUei + "\"");
    }
  }
  private boolean isReloadConfigEventTarget(final Event event) {
    boolean isTarget = false;

    for (final Parm parm : event.getParmCollection()) {
      if (EventConstants.PARM_DAEMON_NAME.equals(parm.getParmName())
          && ("Provisiond." + NAME).equalsIgnoreCase(parm.getValue().getContent())) {
        isTarget = true;
        break;
      }
    }

    log()
        .debug(
            "isReloadConfigEventTarget: Provisiond."
                + NAME
                + " was target of reload event: "
                + isTarget);
    return isTarget;
  }
  /**
   * getEventHost
   *
   * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
   * @param connection a {@link java.sql.Connection} object.
   * @return a {@link java.lang.String} object.
   */
  protected String getEventHost(final Event event) {
    if (event.getHost() == null) {
      return null;
    }

    // If the event doesn't have a node ID, we can't lookup the IP address and be sure we have the
    // right one since we don't know what node it is on
    if (!event.hasNodeid()) {
      return event.getHost();
    }

    try {
      return getHostName(event.getNodeid().intValue(), event.getHost());
    } catch (final Throwable t) {
      LOG.warn(
          "Error converting host IP \"{}\" to a hostname, storing the IP.", event.getHost(), t);
      return event.getHost();
    }
  }
  /**
   * matchNotificationParameters
   *
   * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
   * @param notification a {@link org.opennms.netmgt.config.notifications.Notification} object.
   * @return a boolean.
   */
  public boolean matchNotificationParameters(Event event, Notification notification) {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    boolean parmmatch = false;
    if (notification.getVarbind() != null && notification.getVarbind().getVbname() != null) {
      String notfValue = null;
      String notfName = notification.getVarbind().getVbname();

      if (notification.getVarbind().getVbvalue() != null) {
        notfValue = notification.getVarbind().getVbvalue();
      } else {
        if (log.isDebugEnabled()) {
          log.debug(
              "BroadcastEventProcessor:matchNotificationParameters:  Null value for varbind, assuming true.");
        }
        parmmatch = true;
      }

      for (final Parm parm : event.getParmCollection()) {
        final String parmName = parm.getParmName();
        final Value parmValue = parm.getValue();
        final String parmContent;
        if (parmValue == null) {
          continue;
        } else {
          parmContent = parmValue.getContent();
        }

        if (parmName.equals(notfName) && parmContent.startsWith(notfValue)) {
          parmmatch = true;
        }
      }
    } else if (notification.getVarbind() == null || notification.getVarbind().getVbname() == null) {
      parmmatch = true;
    }

    return parmmatch;
  }
 private Integer getRegainedEventId() {
   if (m_regainedSvcEvent == null) return null;
   return Integer.valueOf(m_regainedSvcEvent.getDbid());
 }
  /**
   * acknowledgeNotice
   *
   * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
   * @param uei a {@link java.lang.String} object.
   * @param matchList an array of {@link java.lang.String} objects.
   * @return a {@link java.util.Collection} object.
   * @throws java.sql.SQLException if any.
   * @throws java.io.IOException if any.
   * @throws org.exolab.castor.xml.MarshalException if any.
   * @throws org.exolab.castor.xml.ValidationException if any.
   */
  public Collection<Integer> acknowledgeNotice(
      final Event event, final String uei, final String[] matchList)
      throws SQLException, IOException, MarshalException, ValidationException {
    Connection connection = null;
    List<Integer> notifIDs = new LinkedList<Integer>();
    final DBUtils d = new DBUtils(getClass());
    ThreadCategory log = this.log();

    try {
      // First get most recent event ID from notifications
      // that match the matchList, then get all notifications
      // with this event ID
      connection = getConnection();
      d.watch(connection);
      int eventID = 0;
      boolean wasAcked = false;
      StringBuffer sql = new StringBuffer("SELECT eventid FROM notifications WHERE eventuei=? ");
      for (int i = 0; i < matchList.length; i++) {
        sql.append("AND ").append(matchList[i]).append("=? ");
      }
      sql.append("ORDER BY eventid desc limit 1");
      PreparedStatement statement = connection.prepareStatement(sql.toString());
      d.watch(statement);
      statement.setString(1, uei);

      for (int i = 0; i < matchList.length; i++) {
        if (matchList[i].equals("nodeid")) {
          statement.setLong(i + 2, event.getNodeid());
        }

        if (matchList[i].equals("interfaceid")) {
          statement.setString(i + 2, event.getInterface());
        }

        if (matchList[i].equals("serviceid")) {
          statement.setInt(i + 2, getServiceId(event.getService()));
        }
      }

      ResultSet results = statement.executeQuery();
      d.watch(results);
      if (results != null && results.next()) {
        eventID = results.getInt(1);
        if (log.isDebugEnabled()) log.debug("EventID for notice(s) to be acked: " + eventID);

        sql =
            new StringBuffer(
                "SELECT notifyid, answeredby, respondtime FROM notifications WHERE eventID=?");

        statement = connection.prepareStatement(sql.toString());
        statement.setInt(1, eventID);

        results = statement.executeQuery();

        if (results != null) {
          while (results.next()) {
            int notifID = results.getInt(1);
            String ansBy = results.getString(2);
            Timestamp ts = results.getTimestamp(3);
            if (ansBy == null) {
              ansBy = "auto-acknowledged";
              ts = new Timestamp((new Date()).getTime());
            } else if (ansBy.indexOf("auto-acknowledged") > -1) {
              if (log.isDebugEnabled())
                log.debug("Notice has previously been auto-acknowledged. Skipping...");
              continue;
            } else {
              wasAcked = true;
              ansBy = ansBy + "/auto-acknowledged";
            }
            if (log.isDebugEnabled())
              log.debug(
                  "Matching DOWN notifyID = "
                      + notifID
                      + ", was acked by user = "******", ansBy = "
                      + ansBy);
            final PreparedStatement update =
                connection.prepareStatement(
                    getConfigManager().getConfiguration().getAcknowledgeUpdateSql());
            d.watch(update);

            update.setString(1, ansBy);
            update.setTimestamp(2, ts);
            update.setInt(3, notifID);

            update.executeUpdate();
            update.close();
            if (wasAcked) {
              notifIDs.add(-1 * notifID);
            } else {
              notifIDs.add(notifID);
            }
          }
        }
      } else {
        if (log.isDebugEnabled()) log.debug("No matching DOWN eventID found");
      }
    } finally {
      d.cleanUp();
    }
    return notifIDs;
  }
  /**
   * getNotifForEvent
   *
   * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
   * @return an array of {@link org.opennms.netmgt.config.notifications.Notification} objects.
   * @throws java.io.IOException if any.
   * @throws org.exolab.castor.xml.MarshalException if any.
   * @throws org.exolab.castor.xml.ValidationException if any.
   */
  public Notification[] getNotifForEvent(final Event event)
      throws IOException, MarshalException, ValidationException {
    update();
    List<Notification> notifList = new ArrayList<Notification>();
    boolean matchAll = getConfigManager().getNotificationMatch();
    ThreadCategory log = this.log();

    // This if statement will check to see if notification should be suppressed for this event.

    if (event == null) {
      log.warn("unable to get notification for null event!");
      return null;
    } else if (event.getLogmsg() != null && !(event.getLogmsg().getNotify())) {
      if (log.isDebugEnabled())
        log.debug("Event " + event.getUei() + " is configured to suppress notifications.");
      return null;
    }

    for (Notification curNotif : m_notifications.getNotificationCollection()) {
      if (log.isDebugEnabled())
        log.debug("Checking " + event.getUei() + " against " + curNotif.getUei());

      if (event.getUei().equals(curNotif.getUei()) || "MATCH-ANY-UEI".equals(curNotif.getUei())) {
        // Match!
      } else if (curNotif.getUei().charAt(0) == '~') {
        if (event.getUei().matches(curNotif.getUei().substring(1))) {
          // Match!
        } else {
          if (log.isDebugEnabled())
            log.debug(
                "Notification regex "
                    + curNotif.getUei()
                    + " failed to match event UEI: "
                    + event.getUei());
          continue;
        }
      } else {
        if (log.isDebugEnabled())
          log.debug("Event UEI " + event.getUei() + " did not match " + curNotif.getUei());
        continue;
      }

      /** Check if event severity matches pattern in notification */
      if (log.isDebugEnabled())
        log.debug(
            "Checking event severity: "
                + event.getSeverity()
                + " against notification severity: "
                + curNotif.getEventSeverity());
      // parameter is optional, return true if not set
      if (curNotif.getEventSeverity() == null) {
        // Skip matching on severity
      } else if (event
          .getSeverity()
          .toLowerCase()
          .matches(curNotif.getEventSeverity().toLowerCase())) {
        // Severities match
      } else {
        if (log.isDebugEnabled())
          log.debug(
              "Event severity: "
                  + event.getSeverity()
                  + " did not match notification severity: "
                  + curNotif.getEventSeverity());
        continue;
      }

      // The notice has to be "on"
      // The notice has to match a severity if configured - currHasSeverity should be true if there
      // is no severity rule
      // The notice has to match the UEI of the event or MATCH-ANY-UEI
      // If all those things are true:
      // Then the service has to match if configured, the interface if configured, and the node if
      // configured.

      if (curNotif.getStatus().equals("on")) {
        if (nodeInterfaceServiceValid(curNotif, event)) {
          boolean parmsmatched = getConfigManager().matchNotificationParameters(event, curNotif);

          if (!parmsmatched) {
            if (log.isDebugEnabled())
              log.debug(
                  "Event "
                      + event.getUei()
                      + " did not match parameters for notice "
                      + curNotif.getName());
            continue;
          }
          // Add this notification to the return value
          notifList.add(curNotif);

          if (log.isDebugEnabled())
            log.debug("Event " + event.getUei() + " matched notice " + curNotif.getName());

          if (!matchAll) break;
        } else {
          if (log.isDebugEnabled())
            log.debug("Node/interface/service combination in the event was invalid");
        }
      } else {
        if (log.isDebugEnabled()) log.debug("Current notification is turned off.");
      }
    }

    if (!notifList.isEmpty()) {
      return notifList.toArray(new Notification[0]);
    } else {
      return null;
    }
  }
  /**
   * Create an SNMP trap, based on the content of an event derived from a TL1 autonomous message
   * received by Tl1d, and forward the trap to the specified address and port. The type of trap
   * created depends on the value of the "trapVersion" parameter. The "community" parameter
   * determines the SNMP community string of the resulting trap, defaulting to "public".
   *
   * @param event The event upon which the trap content should be based
   * @param destAddr The address to which the trap should be sent
   * @param destPort The port to which the trap should be sent
   * @param trapVersion The SNMP version ("v1" or "v2c") of the trap
   * @param community The SNMP community string for the trap (defaults to "public")
   * @throws org.opennms.netmgt.scriptd.helper.SnmpTrapHelperException if any.
   * @throws java.net.UnknownHostException if any.
   * @exception Throws SnmpTrapHelperException if the event is not of the appropriate type.
   * @exception Throws UnknownHostException if agent-addr resolution fails for the case of an SNMPv1
   *     trap
   * @exception Throws SnmpTrapHelperException if the event is not of the appropriate type.
   * @exception Throws UnknownHostException if agent-addr resolution fails for the case of an SNMPv1
   *     trap
   */
  public void sendTL1AutonomousMsgTrap(
      Event event, String destAddr, int destPort, String trapVersion, String community)
      throws SnmpTrapHelperException, UnknownHostException {

    // Check first thing that the event is of the right type.
    if (!org.opennms.netmgt.EventConstants.TL1_AUTONOMOUS_MESSAGE_UEI.equals(event.getUei())) {
      throw new SnmpTrapHelperException(
          "The event must have a UEI of "
              + org.opennms.netmgt.EventConstants.TL1_AUTONOMOUS_MESSAGE_UEI);
    }

    // Create a TrapBuilder and bootstrap it according to trapVersion
    SnmpTrapBuilder trapBuilder = null;
    // What to do about timestamp? Hard-wiring to zero for now.
    long trapTimeStamp = 0;

    final String iface = event.getInterface();
    if ("v1".equalsIgnoreCase(trapVersion)) {
      trapBuilder =
          createV1Trap(
              ".1.3.6.1.4.1.5813.1", // OPENNMS-MIB::openNMS-traps
              iface,
              ENTERPRISE_SPECIFIC,
              2, // OPENNMS-MIB::openNMS-tl1AutonomousMessageTrap
              trapTimeStamp);
    } else if ("v2c".equalsIgnoreCase(trapVersion)) {
      trapBuilder =
          createV2Trap(
              ".1.3.6.1.4.1.5813.1.0.2", // OPENNMS-MIB::openNMS-tl1AutonomousMessageTrap
              Long.toString(trapTimeStamp));
    } else {
      throw new SnmpTrapHelperException("The trap SNMP version must be either v1 or v2c");
    }

    // Add all the MIB-specified varbinds
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.1.8.0", // OPENNMS-MIB::openNMS-event-nodeid
        EventConstants.TYPE_SNMP_OCTET_STRING,
        Long.toString(event.getNodeid()));
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.1.9.0", // OPENNMS-MIB::openNMS-event-time
        EventConstants.TYPE_SNMP_OCTET_STRING,
        event.getTime());
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.1.10.0", // OPENNMS-MIB::openNMS-event-host
        EventConstants.TYPE_SNMP_OCTET_STRING,
        event.getHost());
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.1.11.0", // OPENNMS-MIB::openNMS-event-interface
        EventConstants.TYPE_SNMP_OCTET_STRING,
        iface);
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.1.13.0", // OPENNMS-MIB::openNMS-event-service
        EventConstants.TYPE_SNMP_OCTET_STRING,
        event.getService());
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.1.18.0", // OPENNMS-MIB::openNMS-event-severity
        EventConstants.TYPE_SNMP_OCTET_STRING,
        event.getSeverity());
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.2.1.1.0", // OPENNMS-MIB::tl1amRawMessage
        EventConstants.TYPE_SNMP_OCTET_STRING,
        EventUtil.expandParms("%parm[raw-message]%", event));
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.2.1.2.0", // OPENNMS-MIB::tl1amAlarmCode
        EventConstants.TYPE_SNMP_OCTET_STRING,
        EventUtil.expandParms("%parm[alarm-code]%", event));
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.2.1.3.0", // OPENNMS-MIB::tl1amAutonomousTag
        EventConstants.TYPE_SNMP_OCTET_STRING,
        EventUtil.expandParms("%parm[atag]%", event));
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.2.1.4.0", // OPENNMS-MIB::tl1amVerb
        EventConstants.TYPE_SNMP_OCTET_STRING,
        EventUtil.expandParms("%parm[verb]%", event));
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.2.1.5.0", // OPENNMS-MIB::tl1amAutoBlock
        EventConstants.TYPE_SNMP_OCTET_STRING,
        EventUtil.expandParms("%parm[autoblock]%", event));
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.2.1.6.0", // OPENNMS-MIB::tl1amAID
        EventConstants.TYPE_SNMP_OCTET_STRING,
        EventUtil.expandParms("%parm[aid]%", event));
    addVarBinding(
        trapBuilder,
        ".1.3.6.1.4.1.5813.20.2.1.7.0", // OPENNMS-MIB::tl1amAdditionalParams
        EventConstants.TYPE_SNMP_OCTET_STRING,
        EventUtil.expandParms("%parm[additionalParams]%", event));

    // Finally, send the trap!
    this.sendTrap(destAddr, destPort, community, trapBuilder);
  }