/**
   * {@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.
   */
  @Override
  public void onEvent(Event event) {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    String eventUei = event.getUei();
    if (eventUei == null) return;

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

    if (eventUei.equals(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI)) {
      // add to known nodes
      if (Long.toString(event.getNodeid()) != null && event.getInterface() != null) {
        SyslogdIPMgr.setNodeId(event.getInterface(), event.getNodeid());
      }
      if (log.isDebugEnabled()) {
        log.debug("Added " + event.getInterface() + " to known node list");
      }
    } else if (eventUei.equals(EventConstants.INTERFACE_DELETED_EVENT_UEI)) {
      // remove from known nodes
      if (event.getInterface() != null) {
        SyslogdIPMgr.removeNodeId(event.getInterface());
      }
      if (log.isDebugEnabled()) {
        log.debug("Removed " + event.getInterface() + " from known node list");
      }
    } else if (eventUei.equals(EventConstants.INTERFACE_REPARENTED_EVENT_UEI)) {
      // add to known nodes
      if (Long.toString(event.getNodeid()) != null && event.getInterface() != null) {
        SyslogdIPMgr.setNodeId(event.getInterface(), event.getNodeid());
      }
      if (log.isDebugEnabled()) {
        log.debug("Reparented " + event.getInterface() + " to known node list");
      }
    }
  }
    /**
     * 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;
          }
        }
      }
    }
  /** {@inheritDoc} */
  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    BufferedWriter bw =
        new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    ThreadCategory.setPrefix(MapsConstants.LOG4J_CATEGORY);
    log = ThreadCategory.getInstance(this.getClass());

    try {
      String user = request.getRemoteUser();

      if (log.isDebugEnabled()) log.debug("MapStartUp for user:"******"Error in map's startup", e);
      bw.write(ResponseAssembler.getMapErrorResponse(MapsConstants.MAPS_STARTUP_ACTION));
    } finally {
      bw.close();
    }

    return null;
  }
  /*
   * stop the current receiver
   * @throws InterruptedException
   *
   */
  void stop() throws InterruptedException {
    m_stop = true;

    // Shut down the thread pools that are executing SyslogConnection and SyslogProcessor tasks
    for (ExecutorService service : m_executors) {
      service.shutdown();
    }

    if (m_context != null) {
      ThreadCategory log = ThreadCategory.getInstance(getClass());
      log.debug("Stopping and joining thread context " + m_context.getName());
      m_context.interrupt();
      m_context.join();
      log.debug("Thread context stopped and joined");
    }
  }
  /** {@inheritDoc} */
  @Override
  public void runAndRender(
      ReportParameters parameters, ReportMode mode, OutputStream outputStream) {

    // TODO remove this debug code
    Map<String, Object> reportParms = parameters.getReportParms(mode);
    for (String key : reportParms.keySet()) {
      String value;
      if (reportParms.get(key) == null) {
        value = "NULL";
      } else {
        value = reportParms.get(key).toString();
      }
      log.debug("param " + key + " set " + value);
    }

    try {
      getReportService(parameters.getReportId())
          .runAndRender(
              parameters.getReportParms(mode),
              parameters.getReportId(),
              parameters.getFormat(),
              outputStream);
    } catch (ReportException reportException) {
      log.error("failed to run or render report: " + parameters.getReportId(), reportException);
    }
  }
  /**
   * {@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 + "\"");
    }
  }
  /** Reset the user timer. */
  public synchronized void resetUserTimer() {
    // Reset the user timer
    if (m_userTask != null) return;

    ThreadCategory log = ThreadCategory.getInstance(getClass());

    try {
      m_timer.schedule((m_userTask = new RTCTimerTask(USERTIMER)), 0, m_userRefreshInterval);
      if (log.isDebugEnabled()) log.debug("resetUserTimer: " + USERTIMER + " scheduled");
    } catch (IllegalStateException isE) {
      log.error("dataReceived: Illegal State adding new RTCTimerTask", isE);
    }
  }
  /**
   * updateNoticeWithUserInfo
   *
   * @throws java.io.IOException if any.
   * @throws org.exolab.castor.xml.ValidationException if any.
   * @throws org.exolab.castor.xml.MarshalException if any.
   * @param userId a {@link java.lang.String} object.
   * @param noticeId a int.
   * @param media a {@link java.lang.String} object.
   * @param contactInfo a {@link java.lang.String} object.
   * @param autoNotify a {@link java.lang.String} object.
   * @throws java.sql.SQLException if any.
   */
  public void updateNoticeWithUserInfo(
      final String userId,
      final int noticeId,
      final String media,
      final String contactInfo,
      final String autoNotify)
      throws SQLException, MarshalException, ValidationException, IOException {
    if (noticeId < 0) return;
    int userNotifId = getUserNotifId();
    ThreadCategory log = this.log();
    if (log.isDebugEnabled()) {
      log.debug(
          "updating usersnotified: ID = "
              + userNotifId
              + " User = "******", notice ID = "
              + noticeId
              + ", conctactinfo = "
              + contactInfo
              + ", media = "
              + media
              + ", autoNotify = "
              + autoNotify);
    }
    Connection connection = null;
    final DBUtils d = new DBUtils(getClass());
    try {
      connection = getConnection();
      d.watch(connection);
      final PreparedStatement insert =
          connection.prepareStatement(
              "INSERT INTO usersNotified (id, userid, notifyid, notifytime, media, contactinfo, autonotify) values (?,?,?,?,?,?,?)");
      d.watch(insert);

      insert.setInt(1, userNotifId);
      insert.setString(2, userId);
      insert.setInt(3, noticeId);

      insert.setTimestamp(4, new Timestamp((new Date()).getTime()));

      insert.setString(5, media);
      insert.setString(6, contactInfo);
      insert.setString(7, autoNotify);

      insert.executeUpdate();
    } finally {
      d.cleanUp();
    }
  }
 /**
  * Determines when a group is next on duty. If a group has no duty schedules listed in the
  * configuration file, that group is assumed to always be on duty.
  *
  * @param group the group whose duty schedule we want
  * @param time the time to check for a duty schedule
  * @return long, the time in milliseconds until the group is next on duty
  * @throws java.io.IOException if any.
  * @throws org.exolab.castor.xml.MarshalException if any.
  * @throws org.exolab.castor.xml.ValidationException if any.
  */
 public long groupNextOnDuty(String group, Calendar time)
     throws IOException, MarshalException, ValidationException {
   ThreadCategory log = ThreadCategory.getInstance(this.getClass());
   long next = -1;
   update();
   // if the group has no duty schedules then it is on duty
   if (!m_dutySchedules.containsKey(group)) {
     return 0;
   }
   List<DutySchedule> dutySchedules = m_dutySchedules.get(group);
   for (int i = 0; i < dutySchedules.size(); i++) {
     DutySchedule curSchedule = dutySchedules.get(i);
     long tempnext = curSchedule.nextInSchedule(time);
     if (tempnext < next || next == -1) {
       if (log.isDebugEnabled()) {
         log.debug("isGroupOnDuty: On duty in " + tempnext + " millisec from schedule " + i);
       }
       next = tempnext;
     }
   }
   return next;
 }
  /**
   * 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;
  }
  /** {@inheritDoc} */
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    ThreadCategory.setPrefix(MapsConstants.LOG4J_CATEGORY);
    log = ThreadCategory.getInstance(this.getClass());
    String action = request.getParameter("action");
    String elems = request.getParameter("elems");
    log.debug("Adding Nodes action:" + action + ", elems=" + elems);

    BufferedWriter bw =
        new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    try {
      Integer[] nodeids = null;

      boolean actionfound = false;

      if (action.equals(MapsConstants.ADDNODES_ACTION)) {
        log.debug("Adding nodes by id: " + elems);
        actionfound = true;
        String[] snodeids = elems.split(",");
        nodeids = new Integer[snodeids.length];
        for (int i = 0; i < snodeids.length; i++) {
          nodeids[i] = new Integer(snodeids[i]);
        }
      }

      if (action.equals(MapsConstants.ADDNODES_BY_CATEGORY_ACTION)) {
        log.debug("Adding nodes by category: " + elems);
        actionfound = true;
        String categoryName = elems;
        CategoryFactory.init();
        CatFactory cf = CategoryFactory.getInstance();
        cf.getReadLock().lock();
        try {
          final String rule = cf.getEffectiveRule(categoryName);
          final List<InetAddress> nodeIPs = FilterDaoFactory.getInstance().getIPAddressList(rule);
          LogUtils.debugf(this, "ips found: %s", nodeIPs.toString());
          nodeids = new Integer[nodeIPs.size()];
          for (int i = 0; i < nodeIPs.size(); i++) {
            final InetAddress nodeIp = nodeIPs.get(i);
            final List<Integer> ids =
                NetworkElementFactory.getInstance(getServletContext())
                    .getNodeIdsWithIpLike(InetAddressUtils.str(nodeIp));
            LogUtils.debugf(this, "Ids by ipaddress %s: %s", nodeIp, ids.toString());
            nodeids[i] = ids.get(0);
          }
        } finally {
          cf.getReadLock().unlock();
        }
      }

      if (action.equals(MapsConstants.ADDNODES_BY_LABEL_ACTION)) {
        log.debug("Adding nodes by label: " + elems);
        actionfound = true;
        List<OnmsNode> nodes = NetworkElementFactory.getInstance(getServletContext()).getAllNodes();
        nodeids = new Integer[nodes.size()];
        for (int i = 0; i < nodes.size(); i++) {
          nodeids[i] = nodes.get(i).getId();
        }
      }

      if (action.equals(MapsConstants.ADDRANGE_ACTION)) {
        log.debug("Adding nodes by range: " + elems);
        actionfound = true;
        nodeids =
            (Integer[])
                NetworkElementFactory.getInstance(getServletContext())
                    .getNodeIdsWithIpLike(elems)
                    .toArray(new Integer[0]);
      }

      if (action.equals(MapsConstants.ADDNODES_NEIG_ACTION)) {
        log.debug("Adding nodes neighbor of:" + elems);
        actionfound = true;
        nodeids =
            (Integer[])
                NetworkElementFactory.getInstance(getServletContext())
                    .getLinkedNodeIdOnNode(WebSecurityUtils.safeParseInt(elems))
                    .toArray(new Integer[0]);
      }

      if (action.equals(MapsConstants.ADDNODES_WITH_NEIG_ACTION)) {
        log.debug("Adding nodes with neighbor of:" + elems);
        actionfound = true;
        Set<Integer> linkednodeids =
            NetworkElementFactory.getInstance(getServletContext())
                .getLinkedNodeIdOnNode(WebSecurityUtils.safeParseInt(elems));
        linkednodeids.add(new Integer(elems));
        nodeids = linkednodeids.toArray(new Integer[linkednodeids.size()]);
      }

      VMap map = manager.openMap();
      if (log.isDebugEnabled()) log.debug("Got map from manager " + map);

      List<VElement> velems = new ArrayList<VElement>();
      // response for addElement
      if (actionfound) {
        log.debug("Before Checking map contains elems");

        for (int i = 0; i < nodeids.length; i++) {
          int elemId = nodeids[i].intValue();
          if (map.containsElement(elemId, MapsConstants.NODE_TYPE)) {
            log.debug(
                "Action: "
                    + action
                    + " . Map Contains Element: "
                    + elemId
                    + MapsConstants.NODE_TYPE);
            continue;
          }

          velems.add(manager.newElement(map.getId(), elemId, MapsConstants.NODE_TYPE));
        } // end for

        // get links and add elements to map
        map = manager.addElements(map, velems);
        log.debug("After getting/adding links");

        bw.write(ResponseAssembler.getAddElementResponse(null, velems, map.getLinks()));
      }
    } catch (Throwable e) {
      log.error("Error while adding nodes for action: " + action, e);
      bw.write(ResponseAssembler.getMapErrorResponse(action));
    } finally {
      bw.close();
    }

    return null;
  }
Example #12
0
  /**
   * Return all notices (optionally only unacknowledged notices) sorted by the given sort style.
   *
   * <p><strong>Note: </strong> This limit/offset code is <em>Postgres specific!</em> Per <a
   * href="mailto:[email protected]">Shane </a>, this is okay for now until we can come up with an
   * Oracle alternative too.
   *
   * @param limit if -1 or zero, no limit or offset is used
   * @param offset if -1, no limit or offset if used
   * @param sortStyle a {@link org.opennms.web.outage.SortStyle} object.
   * @param outType a {@link org.opennms.web.outage.OutageType} object.
   * @param filters an array of org$opennms$web$filter$Filter objects.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutages(
      SortStyle sortStyle, OutageType outType, Filter[] filters, int limit, int offset)
      throws SQLException {
    if (sortStyle == null || outType == null || filters == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    boolean useLimits = false;
    if (limit > 0 && offset > -1) {
      useLimits = true;
    }

    Outage[] outages = null;
    final Connection conn = Vault.getDbConnection();
    final DBUtils d = new DBUtils(OutageFactory.class, conn);

    try {
      StringBuffer select =
          new StringBuffer(
              "SELECT OUTAGES.*, NODE.NODELABEL, IPINTERFACE.IPHOSTNAME, SERVICE.SERVICENAME, NOTIFICATIONS.NOTIFYID, NOTIFICATIONS.ANSWEREDBY FROM OUTAGES "
                  + "JOIN NODE USING(NODEID) "
                  + "JOIN IPINTERFACE ON OUTAGES.NODEID=IPINTERFACE.NODEID AND OUTAGES.IPADDR=IPINTERFACE.IPADDR "
                  + "JOIN IFSERVICES ON OUTAGES.NODEID=IFSERVICES.NODEID AND OUTAGES.IPADDR=IFSERVICES.IPADDR AND OUTAGES.SERVICEID=IFSERVICES.SERVICEID "
                  + "LEFT OUTER JOIN SERVICE ON OUTAGES.SERVICEID=SERVICE.SERVICEID "
                  + "LEFT OUTER JOIN NOTIFICATIONS ON SVCLOSTEVENTID=NOTIFICATIONS.EVENTID "
                  + "WHERE (NODE.NODETYPE != 'D' AND IPINTERFACE.ISMANAGED != 'D' AND IFSERVICES.STATUS != 'D') "
                  + "AND ");
      select.append(outType.getClause());

      for (Filter filter : filters) {
        select.append(" AND ");
        select.append(filter.getParamSql());
      }

      select.append(sortStyle.getOrderByClause());

      if (useLimits) {
        select.append(" LIMIT ");
        select.append(limit);
        select.append(" OFFSET ");
        select.append(offset);
      }

      log.debug(select.toString());

      final PreparedStatement stmt = conn.prepareStatement(select.toString());
      d.watch(stmt);

      int parameterIndex = 1;
      for (Filter filter : filters) {
        parameterIndex += filter.bindParam(stmt, parameterIndex);
      }

      final ResultSet rs = stmt.executeQuery();
      d.watch(rs);

      outages = rs2Outages(rs);
    } finally {
      d.cleanUp();
    }

    return outages;
  }
  /** The execution context. */
  @Override
  public void run() {
    // get the context
    m_context = Thread.currentThread();

    // Get a log instance
    ThreadCategory.setPrefix(m_logPrefix);
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    if (m_stop) {
      log.debug("Stop flag set before thread started, exiting");
      return;
    } else log.debug("Thread context started");

    // allocate a buffer
    final int length = 0xffff;
    final byte[] buffer = new byte[length];

    // set an SO timeout to make sure we don't block forever
    // if a socket is closed.
    try {
      log.debug("Setting socket timeout to " + SOCKET_TIMEOUT + "ms");
      m_dgSock.setSoTimeout(SOCKET_TIMEOUT);
    } catch (SocketException e) {
      log.warn("An I/O error occured while trying to set the socket timeout", e);
    }

    // Increase the receive buffer for the socket
    try {
      log.debug("Setting receive buffer size to " + length);
      m_dgSock.setReceiveBufferSize(length);
    } catch (SocketException e) {
      log.info("Failed to set the receive buffer to " + length, e);
    }
    // set to avoid numerous tracing message
    boolean ioInterrupted = false;
    // now start processing incoming requests
    while (!m_stop) {
      if (m_context.isInterrupted()) {
        log.debug("Thread context interrupted");
        break;
      }

      try {
        if (!ioInterrupted) {
          log.debug("Waiting on a datagram to arrive");
        }

        DatagramPacket pkt = new DatagramPacket(buffer, length);
        m_dgSock.receive(pkt);

        // SyslogConnection *Must* copy packet data and InetAddress as DatagramPacket is a mutable
        // type
        WaterfallExecutor.waterfall(
            m_executors,
            new SyslogConnection(
                pkt,
                m_matchPattern,
                m_hostGroup,
                m_messageGroup,
                m_UeiList,
                m_HideMessages,
                m_discardUei));
        ioInterrupted = false; // reset the flag
      } catch (SocketTimeoutException e) {
        ioInterrupted = true;
        continue;
      } catch (InterruptedIOException e) {
        ioInterrupted = true;
        continue;
      } catch (ExecutionException e) {
        log.error("Task execution failed in " + this.getClass().getSimpleName(), e);
        break;
      } catch (InterruptedException e) {
        log.error("Task interrupted in " + this.getClass().getSimpleName(), e);
        break;
      } catch (IOException e) {
        log.error("An I/O exception occured on the datagram receipt port, exiting", e);
        break;
      }
    } // end while status OK

    log.debug("Thread context exiting");
  }
  /**
   * 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;
    }
  }
Example #16
0
  /**
   * Test to see if the passed host-port pair is the endpoint for a TCP server. If there is a TCP
   * server at that destination then a value of true is returned from the method. Otherwise a false
   * value is returned to the caller. In order to return true the remote host must generate a banner
   * line which contains the text from the bannerMatch argument.
   *
   * @param host The remote host to connect to.
   * @param port The remote port on the host.
   * @param bannerResult Banner line generated by the remote host must contain this text.
   * @return True if a connection is established with the host and the banner line contains the
   *     bannerMatch text.
   */
  private boolean isServer(
      InetAddress host, int port, int retries, int timeout, RE regex, StringBuffer bannerResult) {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    boolean isAServer = false;
    for (int attempts = 0; attempts <= retries && !isAServer; attempts++) {
      Socket socket = null;
      try {
        // create a connected socket
        //
        socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), timeout);
        socket.setSoTimeout(timeout);
        log.debug("TcpPlugin: connected to host: " + host + " on port: " + port);

        // If banner matching string is null or wildcard ("*") then we
        // only need to test connectivity and we've got that!
        //
        if (regex == null) {
          isAServer = true;
        } else {
          // get a line reader
          //
          BufferedReader lineRdr =
              new BufferedReader(new InputStreamReader(socket.getInputStream()));

          // Read the server's banner line ouptput and validate it
          // against
          // the bannerMatch parameter to determine if this interface
          // supports the
          // service.
          //
          String response = lineRdr.readLine();
          if (regex.match(response)) {
            if (log.isDebugEnabled()) log.debug("isServer: matching response=" + response);
            isAServer = true;
            if (bannerResult != null) bannerResult.append(response);
          } else {
            // Got a response but it didn't match...no need to
            // attempt retries
            isAServer = false;
            if (log.isDebugEnabled()) log.debug("isServer: NON-matching response=" + response);
            break;
          }
        }
      } catch (ConnectException e) {
        // Connection refused!! Continue to retry.
        //
        log.debug("TcpPlugin: Connection refused to " + InetAddressUtils.str(host) + ":" + port);
        isAServer = false;
      } catch (NoRouteToHostException e) {
        // No Route to host!!!
        //
        e.fillInStackTrace();
        log.info(
            "TcpPlugin: Could not connect to host "
                + InetAddressUtils.str(host)
                + ", no route to host",
            e);
        isAServer = false;
        throw new UndeclaredThrowableException(e);
      } catch (InterruptedIOException e) {
        // This is an expected exception
        //
        log.debug(
            "TcpPlugin: did not connect to host within timeout: "
                + timeout
                + " attempt: "
                + attempts);
        isAServer = false;
      } catch (IOException e) {
        log.info(
            "TcpPlugin: An expected I/O exception occured connecting to host "
                + InetAddressUtils.str(host)
                + " on port "
                + port,
            e);
        isAServer = false;
      } catch (Throwable t) {
        isAServer = false;
        log.warn(
            "TcpPlugin: An undeclared throwable exception was caught connecting to host "
                + InetAddressUtils.str(host)
                + " on port "
                + port,
            t);
      } finally {
        try {
          if (socket != null) socket.close();
        } catch (IOException e) {
        }
      }
    }

    //
    // return the success/failure of this
    // attempt to contact an ftp server.
    //
    return isAServer;
  }
  /**
   * This method maps OpenNMS alarm to an OSS/J alarms and adds additional information
   *
   * @param _openNMSalarm data to use to populate the OSS/J alarm
   * @param alarmValueSpecification AlarmValue object to be populated - Invariant (Specifcation)
   *     values should be already populated
   * @return the _av OSS/J AlarmValue populated with opennms data
   * @throws java.lang.IllegalArgumentException if any.
   * @throws javax.oss.UnsupportedAttributeException if any.
   */
  public AlarmValue populateOssjAlarmFromOpenNMSAlarm(
      AlarmValue alarmValueSpecification, OnmsAlarm _openNMSalarm)
      throws IllegalArgumentException, UnsupportedAttributeException {
    ThreadCategory log = getLog();
    String logheader =
        "\t\t" + this.getClass().getSimpleName() + "populateOssjAlarmFromOpenNMSAlarm():";

    // Node node = null;
    OnmsNode node = null;

    // Asset asset = null;
    OnmsAssetRecord asset = null;

    boolean isQoSDrxAlarm = false; // true if alarm is received from Qosdrx

    if (log.isDebugEnabled()) log.debug(logheader + ": Populating alarm");

    // test to see if opennms alarm already has type and instance information set. If yes then it
    // has most likely
    // come from Qosdrx.
    if ((_openNMSalarm.getManagedObjectInstance() != null)
        && (_openNMSalarm.getManagedObjectType() != null)
        && (!_openNMSalarm.getManagedObjectInstance().equals(""))
        && (!_openNMSalarm.getManagedObjectType().equals(""))) {
      isQoSDrxAlarm = true;
      if (log.isDebugEnabled())
        log.debug(
            logheader
                + ": isQoSDrxAlarm TRUE - because OpenNMS alarm has ManagedObjectInstance and ManagedObjectType");
    } else {
      isQoSDrxAlarm = false;
      if (log.isDebugEnabled())
        log.debug(
            logheader
                + ": isQoSDrxAlarm FALSE - because OpenNMS alarm NOT POPULATED ManagedObjectInstance and ManagedObjectType");
    }

    try {
      // If the alarm has both an acknowledge time and an acknowledge user
      // then the alarm has been acknowledged. Set the corrsponding parameters
      // in the OSS/J alarm
      if ((null != _openNMSalarm.getAlarmAckTime()) && (null != _openNMSalarm.getAlarmAckUser())) {
        alarmValueSpecification.setAckUserId(_openNMSalarm.getAlarmAckUser());
        // OnmsAlarm can contain java.sql.Timestamp - convert to Date
        alarmValueSpecification.setAckTime(new Date(_openNMSalarm.getAlarmAckTime().getTime()));
        alarmValueSpecification.setAlarmAckState(AlarmAckState.ACKNOWLEDGED);
      } else {
        alarmValueSpecification.setAlarmAckState(AlarmAckState.UNACKNOWLEDGED);
      }

      // if the alarm is cleared, then set the alarm cleared time
      // to that of the lasteventtime as this must be the time
      // the clear occured.
      if (_openNMSalarm.getSeverity() == OnmsSeverity.CLEARED) {
        // OnmsAlarm can contain java.sql.Timestamp - convert to Date
        alarmValueSpecification.setAlarmClearedTime(
            new Date(_openNMSalarm.getLastEventTime().getTime()));
      } else {
        alarmValueSpecification.setAlarmClearedTime(null);
      }

      // Set the alarmRaisedTime to the FirstEventTime of the OpenNMS
      // alarm. Set the alarm changed time to the last event time.
      // OnmsAlarm can contain java.sql.Timestamp - convert to Date
      if (null != _openNMSalarm.getFirstEventTime()) {
        alarmValueSpecification.setAlarmRaisedTime(
            new Date(_openNMSalarm.getFirstEventTime().getTime()));
      }
      if (null != _openNMSalarm.getLastEventTime()) {
        alarmValueSpecification.setAlarmChangedTime(
            new Date(_openNMSalarm.getLastEventTime().getTime()));
      }

    } catch (Throwable e) {
      log.error(logheader + ": Problem getting ACK time information", e);
    }

    Matcher matcher = null;
    String _uei_no_html = "NOT_SET";
    try {
      String uei = _openNMSalarm.getUei();
      if (null != uei) {
        matcher = p.matcher(uei);
        _uei_no_html = matcher.replaceAll(" "); // remove any HTML tags from uei
      }
      alarmValueSpecification.setAlarmType(
          (_openNMSalarm.getX733AlarmType() == null)
              ? javax.oss.fm.monitor.AlarmType.EQUIPMENT_ALARM
              : _openNMSalarm.getX733AlarmType());
    } catch (Throwable e) {
      log.error(logheader + ": Problem getting  X733AlarmType or Uei", e);
    }

    // Get some local node information as to where the alarm came from
    // This includes, what type of managed element the node is
    // and what its node id and label are.*/
    //		String mftr = "NOT_SET"; // FIXME: Not read
    //		String modelNo = "NOT_SET"; // FIXME: Not read
    //		String assetserno = "NOT_SET"; // FIXME: Not read
    //		String nodelabel = "NOT_SET"; // FIXME: Not read
    //		String alarmIP = "NOT_SET"; // FIXME: Not read
    String managedObjectType = "NOT_SET";
    String managedObjectInstance = "NOT_SET";
    String assetManagedObjectType = "NOT_SET";
    String assetManagedObjectInstance = "NOT_SET";

    String assetDescription = "NOT_SET";
    String assetAddress2 = "NOT_SET";

    if (!isQoSDrxAlarm) { // if is locally generated alarm
      try {
        // some opennms alarms don't have node information
        // set default values if no node information present
        if (_openNMSalarm.getNode() != null) {
          node = ossDao.findNodeByID(_openNMSalarm.getNode().getId());

          asset = node.getAssetRecord();

          //					alarmIP = _openNMSalarm.getIpAddr(); // Not read
          //					if (node != null) {
          //					nodelabel = node.getLabel(); // Not read
          //					}
          if (asset != null) {
            //						if (asset.getManufacturer()!= null) mftr = asset.getManufacturer(); // Not read
            //						if (asset.getModelNumber()!= null) modelNo = asset.getModelNumber(); // Not read
            //						if (asset.getSerialNumber()!= null) assetserno = asset.getSerialNumber(); // Not
            // read
            if (asset.getDescription() != null)
              assetDescription =
                  asset.getDescription(); // TODO was used for managed object class as is 128 char
            // long
            if (asset.getAddress2() != null)
              assetAddress2 =
                  asset.getAddress2(); // TODO was used for managed object instance - as is 256 char
            // long string
            if (asset.getManagedObjectInstance() != null)
              assetManagedObjectInstance = asset.getManagedObjectInstance();
            if (asset.getManagedObjectType() != null)
              assetManagedObjectType = asset.getManagedObjectType();
          }

          managedObjectInstance = assetManagedObjectInstance;
          managedObjectType = assetManagedObjectType;

          if (log.isDebugEnabled())
            log.debug(
                logheader
                    + ": isQoSDrxAlarm=FALSE  OpenNMS type and instance not set. Using from Node Asset record: ManagedObjectInstance: "
                    + managedObjectInstance
                    + " ManagedObjectType:"
                    + managedObjectType);
        }
      } catch (Throwable ex) {
        log.error(logheader + ": Problem getting node and asset information", ex);
      }
    } else { // is a received alarm
      try {
        managedObjectInstance = _openNMSalarm.getManagedObjectInstance();
        managedObjectType = _openNMSalarm.getManagedObjectType();

        if (log.isDebugEnabled())
          log.debug(
              logheader
                  + ": isQoSDrxAlarm=TRUE  OpenNMS type and instance set. Using from OnmsAlarm: ManagedObjectInstance: "
                  + managedObjectInstance
                  + " ManagedObjectType:"
                  + managedObjectType);
      } catch (Throwable ex) {
        log.error(logheader + ": Problem managedObjectInstance or managedObjectType", ex);
      }
    }

    alarmValueSpecification.setManagedObjectClass(managedObjectType);
    if (log.isDebugEnabled())
      log.debug(logheader + ": _av.setManagedObjectClass set to: " + managedObjectType);

    alarmValueSpecification.setManagedObjectInstance(managedObjectInstance);
    if (log.isDebugEnabled())
      log.debug(logheader + ": _av.setManagedObjectInstance set to: " + managedObjectInstance);

    // set severity and probable cause
    try {
      alarmValueSpecification.setPerceivedSeverity(
          onmsSeverityToOssjSeverity(_openNMSalarm.getSeverity()));

      //			alarmValueSpecification.setProbableCause((short)-1); // OSS/J set to -1  then text
      // contains description
      alarmValueSpecification.setProbableCause((short) _openNMSalarm.getX733ProbableCause());

    } catch (Throwable e) {
      log.error(logheader + ": Problem getting severity or probable cause: ", e);
    }

    if (!isQoSDrxAlarm) { // if is a locally generated alarm

      try {
        String _opinstr = _openNMSalarm.getOperInstruct();
        if (null != _opinstr) {
          matcher = p.matcher(_opinstr);
          _opinstr = matcher.replaceAll(" "); // remove all HTML tags from operator instructions
        } else _opinstr = "NOT_SET";
        alarmValueSpecification.setProposedRepairActions(_opinstr);

        String _logmsg = _openNMSalarm.getLogMsg();
        if (null != _logmsg) {
          matcher = p.matcher(_logmsg);
          _logmsg = matcher.replaceAll(" "); // remove all HTML tags from operator instructions
        } else _logmsg = "NOT_SET";

        String _description = _openNMSalarm.getDescription();
        if (null != _description) {
          matcher = p.matcher(_description);
          _description = matcher.replaceAll(" "); // remove all HTML tags from description
        } else _description = "NOT_SET";

        // using manufacturers own definition of specific problem here ( OSS/J )
        alarmValueSpecification.setSpecificProblem(_logmsg);
        Integer alarmid = _openNMSalarm.getId();
        Integer counter = _openNMSalarm.getCounter();
        String reductionkey = _openNMSalarm.getReductionKey();

        // note some OnmsAlarms can have null nodes - we use a default value of 0 for ID
        Integer nodeid = 0;
        String onmsnodelabel = "";
        if (_openNMSalarm.getNode() != null) {
          nodeid = _openNMSalarm.getNode().getId();
          onmsnodelabel = _openNMSalarm.getNode().getLabel();
        }
        InetAddress ipaddress = _openNMSalarm.getIpAddr();
        String x733AlarmType = _openNMSalarm.getX733AlarmType();
        String x733ProbableCause;
        try {
          x733ProbableCause =
              OOSSProbableCause.getStringforEnum((short) _openNMSalarm.getX733ProbableCause());
        } catch (Throwable e) {
          x733ProbableCause = "X733 Probable Cause Incorrectly Defined";
        }

        alarmValueSpecification.setAdditionalText(
            "<alarmid>"
                + alarmid
                + "</alarmid>"
                + "\n            "
                + "<logmsg>"
                + _logmsg
                + "</logmsg>"
                + "\n            "
                + "<uei>"
                + _uei_no_html
                + "<uei>"
                + "\n            "
                + "<x733AlarmType>"
                + x733AlarmType
                + "</x733AlarmType>"
                + "\n            "
                + "<x733ProbableCause>"
                + x733ProbableCause
                + "</x733ProbableCause>"
                + "\n            "
                + "<counter>"
                + counter
                + "</counter>"
                + "\n            "
                + "<reductionkey>"
                + reductionkey
                + "</reductionkey>"
                + "\n            "
                + "<nodeid>"
                + nodeid
                + "</nodeid>"
                + "\n            "
                + "<nodelabel>"
                + onmsnodelabel
                + "</nodelabel>"
                + "\n            "
                + "<ipaddress>"
                + InetAddressUtils.toIpAddrString(ipaddress)
                + "</ipaddress>"
                + "\n            "
                + "<description>"
                + _description
                + "</description>"
                + "\n            "
                + "<opinstr>"
                + _opinstr
                + "</opinstr>"
                + "\n            "
                + "<asset.managedobjectinstance>"
                + assetManagedObjectInstance
                + "</asset.managedobjectinstance>"
                + "\n            "
                + // TODO - was used for object instance
                "<asset.managedobjecttype>"
                + assetManagedObjectType
                + "</asset.managedobjecttype>"
                + "\n            "
                + "<asset.address2>"
                + assetAddress2
                + "</asset.address2>"
                + "\n            "
                + // TODO - was used for object instance
                "<asset.description>"
                + assetDescription
                + "</asset.description>"
                + "\n"); // TODO - was used for object instancetype

      } catch (Throwable e) {
        log.error(
            logheader + ": Problem setting description, logmessage or operator instrctions: ", e);
      }

    } else { // is a received alarm
      try {
        String _opinstr = _openNMSalarm.getOperInstruct();
        if (null == _opinstr) _opinstr = "NOT_SET";
        alarmValueSpecification.setProposedRepairActions(_opinstr);

        String _logmsg = _openNMSalarm.getLogMsg();
        if (null == _logmsg) _logmsg = "NOT_SET";
        // using manufacturers own definition of specific problem here ( OSS/J )
        alarmValueSpecification.setSpecificProblem(_logmsg);

        String _description = _openNMSalarm.getDescription();
        if (null == _description) _description = "NOT_SET";
        alarmValueSpecification.setAdditionalText(_description);

      } catch (Throwable e) {
        log.error(
            logheader + ": Problem setting description, logmessage or operator instrctions: ", e);
      }
    }

    // TODO replacement method to populate the alarm key
    try {
      // populate alarm key
      // TODO was AlarmKey ak = new OOSSAlarmKey(Integer.toString(_openNMSalarm.getId()));
      AlarmKey ak = alarmValueSpecification.getAlarmKey();
      ak.setAlarmPrimaryKey(Integer.toString(_openNMSalarm.getId()));
      ak.setPrimaryKey(ak.getAlarmPrimaryKey());
    } catch (Throwable e) {
      log.error(logheader + ": Problem setting AlarmKey: ", e);
    }

    if (log.isDebugEnabled()) log.debug(logheader + ": Alarm Populated");

    return alarmValueSpecification;
  } // end populateAlarm()
  /**
   * {@inheritDoc}
   *
   * <p>Poll the specified address for service availability.
   *
   * <p>During the poll an attempt is made to call the specified external script or program. If the
   * connection request is successful, the banner line returned as standard output by the script or
   * program is parsed for a partial match with the banner string specified in the poller
   * configuration. Provided that the script's response is valid we set the service status to
   * SERVICE_AVAILABLE and return.
   *
   * <p>The timeout is handled by ExecRunner and is also passed as a parameter to the script or
   * program being called.
   */
  public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    NetworkInterface<InetAddress> iface = svc.getNetInterface();

    //
    // Process parameters
    //
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    //
    // Get interface address from NetworkInterface
    //
    if (iface.getType() != NetworkInterface.TYPE_INET)
      throw new NetworkInterfaceNotSupportedException(
          "Unsupported interface type, only TYPE_INET currently supported");

    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);

    String hoption = ParameterMap.getKeyedString(parameters, "hoption", "--hostname");
    String toption = ParameterMap.getKeyedString(parameters, "toption", "--timeout");
    //
    // convert timeout to seconds for ExecRunner
    //
    String args = ParameterMap.getKeyedString(parameters, "args", null);

    // Script
    //
    String script = ParameterMap.getKeyedString(parameters, "script", null);
    if (script == null) {
      throw new RuntimeException(
          "GpMonitor: required parameter 'script' is not present in supplied properties.");
    }

    // BannerMatch
    //
    String strBannerMatch = (String) parameters.get("banner");

    // Script standard output
    //
    String scriptoutput = "";

    // Script error output
    //
    String scripterror = "";

    // Get the address instance.
    //
    InetAddress ipv4Addr = (InetAddress) iface.getAddress();

    final String hostAddress = InetAddressUtils.str(ipv4Addr);
    if (log.isDebugEnabled())
      log.debug(
          "poll: address = "
              + hostAddress
              + ", script = "
              + script
              + ", arguments = "
              + args
              + ", "
              + tracker);

    // Give it a whirl
    //
    PollStatus serviceStatus = PollStatus.unavailable();

    for (tracker.reset();
        tracker.shouldRetry() && !serviceStatus.isAvailable();
        tracker.nextAttempt()) {
      try {
        tracker.startAttempt();

        int exitStatus = 100;

        // Some scripts, such as Nagios check scripts, look for -H and -t versus --hostname and
        // --timeout. If the optional parameter option-type is set to short, then the former
        // will be used.

        int timeoutInSeconds = (int) tracker.getTimeoutInSeconds();

        ExecRunner er = new ExecRunner();
        er.setMaxRunTimeSecs(timeoutInSeconds);
        if (args == null)
          exitStatus =
              er.exec(
                  script
                      + " "
                      + hoption
                      + " "
                      + hostAddress
                      + " "
                      + toption
                      + " "
                      + timeoutInSeconds);
        else
          exitStatus =
              er.exec(
                  script
                      + " "
                      + hoption
                      + " "
                      + hostAddress
                      + " "
                      + toption
                      + " "
                      + timeoutInSeconds
                      + " "
                      + args);

        double responseTime = tracker.elapsedTimeInMillis();

        if (exitStatus != 0) {
          scriptoutput = er.getOutString();
          serviceStatus =
              logDown(
                  Level.DEBUG,
                  script
                      + " failed with exit code "
                      + exitStatus
                      + ". Standard out: "
                      + scriptoutput);
        }
        if (er.isMaxRunTimeExceeded()) {

          serviceStatus = logDown(Level.DEBUG, script + " failed. Timeout exceeded");

        } else {
          if (exitStatus == 0) {
            scriptoutput = er.getOutString();
            scripterror = er.getErrString();
            if (!scriptoutput.equals("")) log.debug(script + " output  = " + scriptoutput);
            else log.debug(script + " returned no output");
            if (!scripterror.equals("")) log.debug(script + " error = " + scripterror);
            if (strBannerMatch == null || strBannerMatch.equals("*")) {

              serviceStatus = PollStatus.available(responseTime);

            } else {
              if (scriptoutput.indexOf(strBannerMatch) > -1) {
                serviceStatus = PollStatus.available(responseTime);
              } else {
                serviceStatus =
                    PollStatus.unavailable(
                        script
                            + "banner not contained in output banner='"
                            + strBannerMatch
                            + "' output='"
                            + scriptoutput
                            + "'");
              }
            }
          }
        }

      } catch (ArrayIndexOutOfBoundsException e) {

        serviceStatus = logDown(Level.DEBUG, script + " ArrayIndexOutOfBoundsException", e);

      } catch (IOException e) {

        serviceStatus =
            logDown(
                Level.DEBUG, "IOException occurred. Check for proper operation of " + script, e);

      } catch (Throwable e) {

        serviceStatus = logDown(Level.DEBUG, script + "Exception occurred", e);
      }
    }

    //
    // return the status of the service
    //
    log.debug("poll: GP - serviceStatus= " + serviceStatus + "  " + hostAddress);
    return serviceStatus;
  }
  /**
   * This method is used to determine if the named interface is included in the passed package
   * definition. If the interface belongs to the package then a value of true is returned. If the
   * interface does not belong to the package a false value is returned.
   *
   * <p><strong>Note: </strong>Evaluation of the interface against a package filter will only work
   * if the IP is already in the database.
   *
   * @param iface The interface to test against the package.
   * @param pkg The package to check for the inclusion of the interface.
   * @return True if the interface is included in the package, false otherwise.
   */
  public synchronized boolean interfaceInPackage(String iface, Package pkg) {
    final InetAddress ifaceAddr = addr(iface);
    ThreadCategory log = log();

    boolean filterPassed = false;

    // get list of IPs in this package
    List<InetAddress> ipList = m_pkgIpMap.get(pkg);
    if (ipList != null && ipList.size() > 0) {
      filterPassed = ipList.contains(ifaceAddr);
    }

    if (log.isDebugEnabled())
      log.debug(
          "interfaceInPackage: Interface "
              + iface
              + " passed filter for package "
              + pkg.getName()
              + "?: "
              + filterPassed);

    if (!filterPassed) return false;

    //
    // Ensure that the interface is in the specific list or
    // that it is in the include range and is not excluded
    //
    boolean has_specific = false;
    boolean has_range_include = false;
    boolean has_range_exclude = false;

    // if there are NO include ranges then treat act as if the user include
    // the range 0.0.0.0 - 255.255.255.255
    has_range_include = pkg.getIncludeRangeCount() == 0 && pkg.getSpecificCount() == 0;

    for (IncludeRange rng : pkg.getIncludeRangeCollection()) {
      if (isInetAddressInRange(iface, rng.getBegin(), rng.getEnd())) {
        has_range_include = true;
        break;
      }
    }

    byte[] addr = toIpAddrBytes(iface);

    for (String spec : pkg.getSpecificCollection()) {
      byte[] speca = toIpAddrBytes(spec);
      if (new ByteArrayComparator().compare(speca, addr) == 0) {
        has_specific = true;
        break;
      }
    }

    Enumeration<String> eurl = pkg.enumerateIncludeUrl();
    while (!has_specific && eurl.hasMoreElements()) {
      has_specific = interfaceInUrl(iface, eurl.nextElement());
    }

    for (ExcludeRange rng : pkg.getExcludeRangeCollection()) {
      if (isInetAddressInRange(iface, rng.getBegin(), rng.getEnd())) {
        has_range_exclude = true;
        break;
      }
    }

    return has_specific || (has_range_include && !has_range_exclude);
  }
  /**
   * Check the timer tasks. Reset any of the timer tasks if they need to be reset (indicated by
   * their being set to null on timer task completion). If the events counter has exceeded
   * maxEventsBeforeResend, send data out and reset timers
   */
  public synchronized void checkTimerTasksOnEventReceipt() {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    if (log.isDebugEnabled())
      log.debug(
          "checkTimerTasksOnEventReceipt: Checking if timer tasks need to be reset or data needs to be sent out");

    // cancel user timer
    boolean ret = m_userTask.cancel();
    if (log.isDebugEnabled())
      log.debug("checkTimerTasksOnEventReceipt: " + USERTIMER + " cancelled: " + ret);

    // Check the counter to see if timers need to be started afresh
    if (m_counter == -1) {
      m_counter = 0;

      //
      // set timers
      //

      // set the low threshold timer task
      if (m_lowTtask == null) {
        try {

          m_timer.schedule((m_lowTtask = new RTCTimerTask(LOWT_TASK)), m_lowThresholdInterval);
          if (log.isDebugEnabled())
            log.debug("checkTimerTasksOnEventReceipt: " + LOWT_TASK + " scheduled");
        } catch (IllegalStateException isE) {
          log.error("checkTimerTasksOnEventReceipt: Illegal State adding new RTCTimerTask", isE);
        }
      }

      // set the high threshold timer task only if currently null
      if (m_highTtask == null) {
        try {
          m_timer.schedule((m_highTtask = new RTCTimerTask(HIGHT_TASK)), m_highThresholdInterval);
          if (log.isDebugEnabled())
            log.debug("checkTimerTasksOnEventReceipt: " + HIGHT_TASK + " scheduled");
        } catch (IllegalStateException isE) {
          log.error("checkTimerTasksOnEventReceipt: Illegal State adding new RTCTimerTask", isE);
        }
      }
    }

    if (MAX_EVENTS_BEFORE_RESEND > 0 && m_counter >= MAX_EVENTS_BEFORE_RESEND) {
      if (log.isDebugEnabled())
        log.debug(
            "checkTimerTasksOnEventReceipt: max events before resend limit reached, resetting timers");

      // send the category information out and reset all timers
      if (m_lowTtask != null) {
        ret = m_lowTtask.cancel();
        if (log.isDebugEnabled())
          log.debug("checkTimerTasksOnEventReceipt: " + LOWT_TASK + " cancelled: " + ret);

        m_lowTtask = null;
      }

      if (m_highTtask != null) {
        ret = m_highTtask.cancel();
        if (log.isDebugEnabled())
          log.debug("checkTimerTasksOnEventReceipt: " + HIGHT_TASK + " cancelled: " + ret);
        m_highTtask = null;
      }

      if (log.isDebugEnabled())
        log.debug(
            "checkTimerTasksOnEventReceipt: max events before resend limit reached, sending data to listeners");

      m_dataSender.notifyToSend();

      if (log.isDebugEnabled())
        log.debug(
            "checkTimerTasksOnEventReceipt: max events before resend limit reached, datasender notified to send data");

      m_counter = -1;
    } else if (m_counter != 0) {
      // reset the low threshold timer since getting here means
      // we got an event before the low threshold timer
      // went off
      if (m_lowTtask != null) {
        ret = m_lowTtask.cancel();
        if (log.isDebugEnabled())
          log.debug("checkTimerTasksOnEventReceipt: " + LOWT_TASK + " cancelled: " + ret);
        m_lowTtask = null;
      }

      try {
        m_timer.schedule((m_lowTtask = new RTCTimerTask(LOWT_TASK)), m_lowThresholdInterval);
        if (log.isDebugEnabled())
          log.debug("checkTimerTasksOnEventReceipt: " + LOWT_TASK + " scheduled");
      } catch (IllegalStateException isE) {
        log.error("checkTimerTasksOnEventReceipt: Illegal State adding new RTCTimerTask", isE);
      }
    }
  }
  /**
   * Handles a completed task.
   *
   * <p>If the low threshold or high threshold timers expire, send category data out and set both
   * timer(task)s to null so they can be reset when the next event comes in
   *
   * <p>
   *
   * <p>If the user refresh timer is the one that expired, send category data out and reset the user
   * timer(task)
   *
   * <p>
   *
   * @param tt the task that is finishing.
   */
  private synchronized void timerTaskComplete(RTCTimerTask tt) {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    if (log.isDebugEnabled())
      log.debug("TimerTask \'" + tt.getID() + "\' complete, status: " + getStatus());

    if (tt.getID().equals(LOWT_TASK)) {
      // cancel user timer
      boolean ret = m_userTask.cancel();
      if (log.isDebugEnabled()) log.debug("timerTaskComplete: " + USERTIMER + " cancelled: " + ret);

      // send out the info and reset both timers
      if (m_highTtask != null) {
        ret = m_highTtask.cancel();
        if (log.isDebugEnabled())
          log.debug("timerTaskComplete: " + HIGHT_TASK + " cancelled: " + ret);

        m_highTtask = null;
      }

      if (isRunning()) {
        m_dataSender.notifyToSend();
      }

      m_lowTtask = null;

      m_counter = -1;

      // reset the user timer
      m_timer.schedule((m_userTask = new RTCTimerTask(USERTIMER)), 0, m_userRefreshInterval);
      if (log.isDebugEnabled()) log.debug("timerTaskComplete: " + USERTIMER + " scheduled");
    } else if (tt.getID().equals(HIGHT_TASK)) {
      // cancel user timer
      boolean ret = m_userTask.cancel();
      if (log.isDebugEnabled()) log.debug("timerTaskComplete: " + USERTIMER + " cancelled: " + ret);

      // send the category information out reset all timers
      if (m_lowTtask != null) {
        ret = m_lowTtask.cancel();
        if (log.isDebugEnabled())
          log.debug("timerTaskComplete: " + LOWT_TASK + " cancelled: " + ret);

        m_lowTtask = null;
      }

      if (isRunning()) {
        m_dataSender.notifyToSend();
      }

      m_highTtask = null;

      m_counter = -1;

      // reset the user timer
      m_timer.schedule((m_userTask = new RTCTimerTask(USERTIMER)), 0, m_userRefreshInterval);
      if (log.isDebugEnabled()) log.debug("timerTaskComplete: " + USERTIMER + " scheduled");
    } else if (tt.getID().equals(USERTIMER)) {
      // send if not pasued
      if (isRunning()) {
        m_dataSender.notifyToSend();
      }
    }
  }
Example #22
0
  /**
   * Test to see if the passed host-port pair is the endpoint for an SMTP server. If there is an
   * SMTP server at that destination then a value of true is returned from the method. Otherwise a
   * false value is returned to the caller.
   *
   * @param host The remote host to connect to.
   * @param port The remote port on the host.
   * @return True if server supports SMTP on the specified port, false otherwise
   */
  private boolean isServer(InetAddress host, int port, int retries, int timeout) {
    // get a log to send errors
    //
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    boolean isAServer = false;
    for (int attempts = 0; attempts <= retries && !isAServer; attempts++) {
      Socket socket = null;
      try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), timeout);
        socket.setSoTimeout(timeout);
        log.debug("SmtpPlugin: connected to host: " + host + " on port: " + port);

        // Allocate a line reader
        //
        BufferedReader lineRdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // Read responses from the server. The initial line should just
        // be a banner, but go ahead and check for multiline response.
        //
        String result = null;
        do {
          result = lineRdr.readLine();

        } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

        if (result == null || result.length() == 0) {
          log.info("Received truncated response from SMTP server " + InetAddressUtils.str(host));
          continue;
        }

        // Tokenize the last line result
        //
        StringTokenizer t = new StringTokenizer(result);
        int rc = Integer.parseInt(t.nextToken());
        if (rc == 220) {
          //
          // Send the HELO command
          //
          String cmd = "HELO " + LOCALHOST_NAME + "\r\n";
          socket.getOutputStream().write(cmd.getBytes());

          // Response from HELO command may be a multi-line response
          // (but
          // most likely will be single-line)..
          // We are expecting to get a response with an integer return
          // code in the first token. We can't ge sure that the first
          // response will give us what we want. Consider the
          // following
          // reponse for example:
          //
          // 250-First line
          // 250-Second line
          // 250 Requested mail action okay, completed
          //
          // In this case the final line of the response contains the
          // return
          // code we are looking for.
          do {
            result = lineRdr.readLine();

          } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

          if (result == null || result.length() == 0) {
            log.info("Received truncated response from SMTP server " + InetAddressUtils.str(host));
            continue;
          }

          t = new StringTokenizer(result);
          rc = Integer.parseInt(t.nextToken());
          if (rc == 250) {
            //
            // Send the QUIT command
            //
            cmd = "QUIT\r\n";
            socket.getOutputStream().write(cmd.getBytes());

            // Response from QUIT command may be a multi-line
            // response.
            // We are expecting to get a response with an integer
            // return
            // code in the first token. We can't ge sure that the
            // first
            // response will give us what we want. Consider the
            // following
            // reponse for example:
            //
            // 221-First line
            // 221-Second line
            // 221 <domain> Service closing transmission channel.
            //
            // In this case the final line of the response contains
            // the return
            // code we are looking for.
            do {
              result = lineRdr.readLine();

            } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

            if (result == null || result.length() == 0) {
              log.info(
                  "Received truncated response from SMTP server " + InetAddressUtils.str(host));
              continue;
            }

            t = new StringTokenizer(result);
            rc = Integer.parseInt(t.nextToken());

            if (rc == 221) isAServer = true;
          }
        }
      } catch (NumberFormatException e) {
        log.info(
            "SmtpPlugin: received invalid result code from server " + InetAddressUtils.str(host),
            e);
        isAServer = false;
      } catch (ConnectException cE) {
        // Connection refused!! Continue to retry.
        //
        log.debug("SmtpPlugin: connection refused to " + InetAddressUtils.str(host) + ":" + port);
        isAServer = false;
      } catch (NoRouteToHostException e) {
        // No route to host!! No need to perform retries.
        e.fillInStackTrace();
        log.info(
            "SmtpPlugin: Unable to test host "
                + InetAddressUtils.str(host)
                + ", no route available",
            e);
        isAServer = false;
        throw new UndeclaredThrowableException(e);
      } catch (InterruptedIOException e) {
        log.debug(
            "SmtpPlugin: did not connect to host within timeout: "
                + timeout
                + " attempt: "
                + attempts);
        isAServer = false;
      } catch (IOException e) {
        log.info("SmtpPlugin: Error communicating with host " + InetAddressUtils.str(host), e);
        isAServer = false;
      } catch (Throwable t) {
        log.warn(
            "SmtpPlugin: Undeclared throwable exception caught contacting host "
                + InetAddressUtils.str(host),
            t);
        isAServer = false;
      } finally {
        try {
          if (socket != null) socket.close();
        } catch (IOException e) {
        }
      }
    }

    //
    // return the success/failure of this
    // attempt to contact an SMTP server.
    //
    return isAServer;
  }
  /**
   * Private utility method used by the getMibObjectList() method. This method takes a group name
   * and a list of MibObject objects as arguments and adds all of the MibObjects associated with the
   * group to the object list. If the passed group consists of any additional sub-groups, then this
   * method will be called recursively for each sub-group until the entire
   * log.debug("processGroupName: adding MIB objects from group: " + groupName); group is processed.
   *
   * @param cName Collection name
   * @param groupName Name of the group to process
   * @param ifType Interface type
   * @param mibObjectList List of MibObject objects being built.
   */
  private void processGroupName(
      final String cName,
      final String groupName,
      final int ifType,
      final List<MibObject> mibObjectList) {
    ThreadCategory log = log();

    // Using the collector name retrieve the group map
    final Map<String, Group> groupMap = getCollectionGroupMap(getContainer()).get(cName);

    // Next use the groupName to access the Group object
    final Group group = groupMap.get(groupName);

    // Verify that we have a valid Group object...generate
    // warning message if not...
    if (group == null) {
      log.warn(
          "DataCollectionConfigFactory.processGroupName: unable to retrieve group information for group name '"
              + groupName
              + "': check DataCollection.xml file.");
      return;
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "processGroupName:  processing group: "
              + groupName
              + " groupIfType: "
              + group.getIfType()
              + " ifType: "
              + ifType);
    }

    // Process any sub-groups contained within this group
    for (final String includeGroup : group.getIncludeGroupCollection()) {
      processGroupName(cName, includeGroup, ifType, mibObjectList);
    }

    // Add this group's objects to the object list provided
    // that the group's ifType string does not exclude the
    // provided ifType parm.
    //
    // ifType parm of -1 indicates that only node-level
    // objects are to be added
    //
    // Any other ifType parm value must be compared with
    // the group's ifType value to verify that they match
    // (if group's ifType is "all" then the objects will
    // automatically be added.
    final String ifTypeStr = String.valueOf(ifType);
    String groupIfType = group.getIfType();

    boolean addGroupObjects = false;
    if (ifType == NODE_ATTRIBUTES) {
      if (groupIfType.equals("ignore")) {
        addGroupObjects = true;
      }
    } else {
      if (groupIfType.equals("all")) {
        addGroupObjects = true;
      } else if ("ignore".equals(groupIfType)) {
        // Do nothing
      } else if (ifType == ALL_IF_ATTRIBUTES) {
        addGroupObjects = true;
      } else {
        // First determine if the group's ifType value contains
        // a single type value or a list of values. In the case
        // of a list the ifType values will be delimited by commas.
        boolean isList = false;
        if (groupIfType.indexOf(',') != -1) isList = true;

        // Next compare the provided ifType parameter with the
        // group's ifType value to determine if the group's OIDs
        // should be added to the MIB object list.
        //
        // If the group ifType value is a single value then only
        // a simple comparison is needed to see if there is an
        // exact match.
        //
        // In the case of the group ifType value being a list
        // of ifType values it is more complicated...each comma
        // delimited substring which starts with the provided
        // ifType parm must be extracted and compared until an
        // EXACT match is found..
        if (!isList) {
          if (ifTypeStr.equals(groupIfType)) addGroupObjects = true;
        } else {
          int tmpIndex = groupIfType.indexOf(ifTypeStr);
          while (tmpIndex != -1) {
            groupIfType = groupIfType.substring(tmpIndex);

            // get substring starting at tmpIndex to
            // either the end of the groupIfType string
            // or to the first comma after tmpIndex
            final int nextComma = groupIfType.indexOf(',');

            String parsedType = null;
            if (nextComma == -1) // No comma, this is last type
            // value
            {
              parsedType = groupIfType;
            } else // Found comma
            {
              parsedType = groupIfType.substring(0, nextComma);
            }
            if (ifTypeStr.equals(parsedType)) {
              addGroupObjects = true;
              break;
            }

            // No more commas indicates no more ifType values to
            // compare...we're done
            if (nextComma == -1) break;

            // Get next substring and reset tmpIndex to
            // once again point to the first occurrence of
            // the ifType string parm.
            groupIfType = groupIfType.substring(nextComma + 1);
            tmpIndex = groupIfType.indexOf(ifTypeStr);
          }
        }
      }
    }

    if (addGroupObjects) {
      if (log.isDebugEnabled()) {
        log.debug(
            "processGroupName: OIDs from group '"
                + group.getName()
                + ":"
                + group.getIfType()
                + "' are included for ifType: "
                + ifType);
      }
      processObjectList(groupName, groupIfType, group.getMibObjCollection(), mibObjectList);
    } else {
      if (log.isDebugEnabled())
        log.debug(
            "processGroupName: OIDs from group '"
                + group.getName()
                + ":"
                + group.getIfType()
                + "' are excluded for ifType: "
                + ifType);
    }
  }
  /**
   * This method maps an OSS/J AlarmValue to OpenNMS alarm
   *
   * @param onmsAlarm OnmsAlarm object to be populated
   * @param alarmValue OSS/J AlarmValue data to use to populate OnmsAlarm
   * @param almUpdateBehaviour - determines how to treat the node name of the new alarm must be of
   *     value; <code>USE_TYPE_INSTANCE</code> - populate nodeID with node having same asset type
   *     and instance data as alarm or <code>SPECIFY_OUTSTATION</code> - populate nodeID with node
   *     having same nodeLabel as defaultUpdateNodeLabel
   * @param defaultUpdateNodeLabel name of node to be updated if
   *     almUpdateBehaviour==SPECIFY_OUTSTATION
   * @return the OnmsAlarm populated with OSS/J NotifyNewAlarmEvent data
   * @throws java.lang.IllegalArgumentException if any.
   * @throws javax.oss.UnsupportedAttributeException if any.
   */
  public OnmsAlarm populateOnmsAlarmFromOssjAlarm(
      OnmsAlarm onmsAlarm,
      AlarmValue alarmValue,
      Integer almUpdateBehaviour,
      String defaultUpdateNodeLabel)
      throws IllegalArgumentException, UnsupportedAttributeException {
    ThreadCategory log = getLog();
    String logheader =
        "\t\t" + this.getClass().getSimpleName() + "populateOnmsAlarmFromOssjAlarm():";

    try {
      String ossPrimaryKey = alarmValue.getAlarmKey().getAlarmPrimaryKey();
      String applicationDN = alarmValue.getAlarmKey().getApplicationDN();
      if (log.isDebugEnabled())
        log.debug(
            logheader
                + " - AlarmPrimaryKey: "
                + ossPrimaryKey
                + " ApplictionDN: "
                + applicationDN
                + " alarmRaisedTime: "
                + alarmValue.getAlarmRaisedTime());
      if ((applicationDN == null)
          || (applicationDN.equals(""))
          || (ossPrimaryKey == null)
          || (ossPrimaryKey.equals(""))) {
        log.error(logheader + " ApplicatioDN or PrimaryKey not set");
      } else {
        if (log.isDebugEnabled())
          log.debug(
              logheader + ": trying to find existing alarm using getCurrentAlarmForUniqueKey");

        onmsAlarm = ossDao.getCurrentAlarmForUniqueKey(applicationDN, ossPrimaryKey);
        if (onmsAlarm != null) { // already an alarm with this unique id - log error
          log.error(logheader + " Alarm Already exists with this Unique ID");
        } else {
          onmsAlarm = new OnmsAlarm();

          onmsAlarm.setUei(ossjAlarmTypeToUei(alarmValue.getAlarmType()));
          onmsAlarm.setX733AlarmType(
              (alarmValue.getAlarmType() == null) ? "" : alarmValue.getAlarmType());
          onmsAlarm.setX733ProbableCause(alarmValue.getProbableCause());

          onmsAlarm.setTTicketState(null); // needed?
          onmsAlarm.setTTicketId(""); // needed?
          onmsAlarm.setQosAlarmState("");
          onmsAlarm.setSuppressedUser(""); // needed?
          onmsAlarm.setSuppressedUntil(new Date()); // needed?
          onmsAlarm.setSuppressedTime(new Date()); // needed?

          OnmsSeverity onmsseverity;
          try {
            onmsseverity = ossjSeveritytoOnmsSeverity(alarmValue.getPerceivedSeverity());
          } catch (IllegalArgumentException iae) {
            log.error(
                logheader + " problem setting severity used default:'WARNING'. Exception:" + iae);
            onmsseverity = OnmsSeverity.WARNING;
          }
          onmsAlarm.setSeverity(onmsseverity);

          OnmsServiceType service = new OnmsServiceType();
          service.setId(new Integer(-1));
          onmsAlarm.setServiceType(new OnmsServiceType()); // needed?

          onmsAlarm.setReductionKey(
              ":managedObjectInstance:"
                  + alarmValue.getManagedObjectInstance()
                  + ":managedObjectType:"
                  + alarmValue.getManagedObjectClass()
                  + ":ossPrimaryKey:-"
                  + ossPrimaryKey
                  + ":applicationDN:-"
                  + applicationDN); // must be unique because of alarm_reductionkey_idx

          onmsAlarm.setOssPrimaryKey(ossPrimaryKey);
          onmsAlarm.setOperInstruct(alarmValue.getProposedRepairActions());

          // defaultvalue if search fails - will update node with ID 1
          OnmsNode node = new OnmsNode(); // TODO remove ossDao.makeExtendedOnmsNode();
          node.setId(new Integer(1)); // node id cannot be null
          onmsAlarm.setNode(node); //

          if (almUpdateBehaviour == null) {
            log.error(
                logheader
                    + ": This receiver's alarmUpdateBehaviour is not set: defaulting to update nodeID:1");
          } else {
            if (log.isDebugEnabled())
              log.debug(
                  logheader
                      + " alarmUpdateBehaviour:"
                      + almUpdateBehaviour
                      + " "
                      + getAlarmUpdateBehaviourForInt(almUpdateBehaviour));

            if (almUpdateBehaviour.equals(SPECIFY_OUTSTATION)) {
              // this will look for first match of node label to callingAer.getName()
              // and set node id to this value.

              if (log.isDebugEnabled())
                log.debug(
                    logheader
                        + " SPECIFY_OUTSTATION looking for node with nodelabel:"
                        + defaultUpdateNodeLabel);
              try {
                // TODO temp remove ?
                try {
                  node = ossDao.findNodeByLabel(defaultUpdateNodeLabel);
                } catch (Throwable ex) {
                  log.error(
                      logheader
                          + " alarmUpdateBehaviour.equals(USE_TYPE_INSTANCE) Problem looking up Node "
                          + ex);
                }

                if (node != null) {
                  if (log.isDebugEnabled())
                    log.debug(
                        logheader
                            + " alarmUpdateBehaviour.equals(SPECIFY_OUTSTATION):"
                            + "NODE FOUND for this name:"
                            + defaultUpdateNodeLabel
                            + " setting node id to NodeLabel:"
                            + node.getLabel()
                            + " NodeID:"
                            + node.getId());
                  onmsAlarm.setNode(
                      node); // maps into FIRST instance of node with the same managedObjectInstance
                  // and managedObjectType
                } else {
                  log.error(
                      logheader
                          + " alarmUpdateBehaviour.equals(SPECIFY_OUTSTATION):"
                          + "NODE NOT FOUND for this name:"
                          + defaultUpdateNodeLabel
                          + " setting node id to default NodeID: 1");
                  node = new OnmsNode(); // TODO remove ossDao.makeExtendedOnmsNode();
                  node.setId(new Integer(1)); // node id cannot be null
                  onmsAlarm.setNode(node); //
                }
              } catch (Throwable ex) {
                log.error(
                    logheader
                        + " alarmUpdateBehaviour.equals(USE_TYPE_INSTANCE) Problem looking up Node for alarm Set to default nodeID:1"
                        + ex);
              }

            } else if (almUpdateBehaviour.equals(USE_TYPE_INSTANCE)) {
              // this will look for first match of node Managed object Instance and Managed Object
              // type
              // and set node id to this value.
              String managedObjectType = alarmValue.getManagedObjectClass();
              String managedObjectInstance = alarmValue.getManagedObjectInstance();

              if (log.isDebugEnabled())
                log.debug(
                    logheader
                        + " USE_TYPE_INSTANCE looking for node with managedObjectType:"
                        + managedObjectType
                        + " managedObjectInstance:"
                        + managedObjectInstance);
              try {
                node = ossDao.findNodeByInstanceAndType(managedObjectInstance, managedObjectType);

                if (node != null) {
                  if (log.isDebugEnabled())
                    log.debug(
                        logheader
                            + " alarmUpdateBehaviour.equals(USE_TYPE_INSTANCE):"
                            + "NODE FOUND for this RX Name:"
                            + defaultUpdateNodeLabel
                            + " setting node id to NodeLabel:"
                            + node.getLabel()
                            + " NodeID:"
                            + node.getId());
                  onmsAlarm.setNode(
                      node); // maps into FIRST instance of node with the same managedObjectInstance
                  // and managedObjectType
                } else {
                  log.error(
                      logheader
                          + " alarmUpdateBehaviour.equals(USE_TYPE_INSTANCE):"
                          + "NODE NOT FOUND for this managedObjectType:"
                          + managedObjectType
                          + " managedObjectInstance:"
                          + managedObjectInstance
                          + " setting node id to default NodeID: 1");
                  node = new OnmsNode(); // TODO remove ossDao.makeExtendedOnmsNode();
                  node.setId(new Integer(1)); // node id cannot be null
                  onmsAlarm.setNode(node); //
                }
              } catch (Throwable ex) {
                log.error(
                    logheader
                        + " alarmUpdateBehaviour.equals(USE_TYPE_INSTANCE) Problem looking up Node for alarm Set to default nodeID:1"
                        + ex);
              }
            } else {
              log.error(
                  logheader
                      + " Invalid value for alarmUpdateBehaviour:"
                      + almUpdateBehaviour
                      + " "
                      + getAlarmUpdateBehaviourForInt(almUpdateBehaviour)
                      + " defaulting to update nodeID:1");
            }
          }

          onmsAlarm.setMouseOverText(""); // needed?
          onmsAlarm.setManagedObjectType(alarmValue.getManagedObjectClass());
          onmsAlarm.setManagedObjectInstance(alarmValue.getManagedObjectInstance());
          onmsAlarm.setLogMsg(alarmValue.getSpecificProblem());

          // NOTE - this has no effect here as .setLastEvent nulls value
          // alarm.setLastEventTime(nnae.getEventTime());

          //					TODO REMOVED - DO NOT CREATE EVENT WITH HIBERNATE AlarmDAo
          //					OnmsEvent event= new OnmsEvent();
          //					//event.setId(new Integer(1));  // This is NOT set since unique constraint in
          // alarms table on Events table
          //					onmsAlarm.setLastEvent(event);

          onmsAlarm.setIpAddr(InetAddressUtils.getLocalHostAddress()); // needed?
          onmsAlarm.setId(null); // set null as updating alarm
          onmsAlarm.setFirstEventTime(alarmValue.getAlarmRaisedTime());
          onmsAlarm.setLastEventTime(alarmValue.getAlarmChangedTime());

          //					TODO removed - do create distpoller with hibernate dao
          //					onmsAlarm.setDistPoller(new OnmsDistPoller("undefined","localhost")); //simple
          // constructor
          onmsAlarm.setDistPoller(distPollerDao.get("localhost"));

          onmsAlarm.setDescription(
              alarmValue.getAdditionalText()); // TODO need Qosd Not to generate this if remote
          onmsAlarm.setCounter(new Integer(1));
          onmsAlarm.setApplicationDN(applicationDN);
          onmsAlarm.setAlarmType(new Integer(1)); // set to raise alarm
          // alarm.setAlarmAckUser(arg0);
          // alarm.setAlarmAckTime(arg0);

          if (log.isDebugEnabled()) log.debug(logheader + ": Creating Alarm: ");
        }
      }
    } catch (Throwable e) {
      log.error(logheader + " Error : ", e);
    }
    return onmsAlarm;
  }