/** {@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;
  }
  /** {@inheritDoc} */
  @Override
  public DeliveryOptions getDeliveryOptions(String reportId, String userId) {
    DeliveryOptions options = new DeliveryOptions();

    options.setFormat(ReportFormat.HTML);
    options.setPersist(true);
    options.setSendMail(false);

    UserManager userFactory = UserFactory.getInstance();

    try {
      String emailAddress = userFactory.getEmail(userId);
      if (emailAddress != null) {
        options.setMailTo(emailAddress);
      }
    } catch (MarshalException e) {
      log.error("marshal exception trying to set destination email address", e);
    } catch (ValidationException e) {
      log.error("validation exception trying to set destination email address", e);
    } catch (IOException e) {
      log.error("IO exception trying to set destination email address", e);
    } catch (NullPointerException e) { // See NMS-5111 for more details.
      log.warn("the user " + userId + " does not have any email configured.");
    }

    options.setInstanceId(reportId + " " + userId);

    return options;
  }
  /** {@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.
   */
  @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");
      }
    }
  }
 @Override
 public void handleTimeout(InetAddress address, EchoPacket request) {
   String oldPrefix = ThreadCategory.getPrefix();
   try {
     ThreadCategory.setPrefix(m_prefix);
     m_cb.handleTimeout(address, request);
   } finally {
     ThreadCategory.setPrefix(oldPrefix);
   }
 }
 @Override
 public void handleResponse(InetAddress address, EchoPacket response) {
   String oldPrefix = ThreadCategory.getPrefix();
   try {
     ThreadCategory.setPrefix(m_prefix);
     m_cb.handleResponse(address, response);
   } finally {
     ThreadCategory.setPrefix(oldPrefix);
   }
 }
  /** 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();
    }
  }
  /*
   * 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");
    }
  }
 private void mailReport(DeliveryOptions deliveryOptions, ByteArrayOutputStream outputStream) {
   try {
     JavaMailer jm = new JavaMailer();
     jm.setTo(deliveryOptions.getMailTo());
     jm.setSubject(deliveryOptions.getInstanceId());
     jm.setMessageText("Here is your report from the OpenNMS report service.");
     jm.setInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
     switch (deliveryOptions.getFormat()) {
       case HTML:
         jm.setInputStreamName(deliveryOptions.getInstanceId() + ".htm");
         jm.setInputStreamContentType("text/html");
         break;
       case PDF:
         jm.setInputStreamName(deliveryOptions.getInstanceId() + ".pdf");
         jm.setInputStreamContentType("application/pdf");
         break;
       case SVG:
         jm.setInputStreamName(deliveryOptions.getInstanceId() + ".pdf");
         jm.setInputStreamContentType("application/pdf");
         break;
       default:
         jm.setInputStreamName(deliveryOptions.getInstanceId() + ".htm");
         jm.setInputStreamContentType("text/html");
     }
     jm.mailSend();
   } catch (JavaMailerException e) {
     log.error("Caught JavaMailer exception sending report", e);
   }
 }
 /** {@inheritDoc} */
 public void render(
     String reportId, String location, ReportFormat format, OutputStream outputStream) {
   try {
     getReportService(reportId).render(reportId, location, format, outputStream);
   } catch (ReportException e) {
     log.error("failed to render report", e);
   }
 }
 /** {@inheritDoc} */
 public ReportParameters getParameters(String reportId) {
   try {
     return getReportService(reportId).getParameters(reportId);
   } catch (ReportException e) {
     log.error("Report Exception when retrieving report parameters", e);
   }
   return null;
 }
  /** {@inheritDoc} */
  @Override
  public void run(
      ReportParameters parameters,
      ReportMode mode,
      DeliveryOptions deliveryOptions,
      String reportId) {

    if (!deliveryOptions.getPersist()) {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      BufferedOutputStream bout = new BufferedOutputStream(out);
      try {
        getReportService(reportId)
            .runAndRender(
                parameters.getReportParms(mode), reportId, deliveryOptions.getFormat(), bout);
      } catch (ReportException reportException) {
        log.error("failed to run or render report: " + reportId, reportException);
      }
      mailReport(deliveryOptions, out);
    } else {
      String outputPath;
      try {
        outputPath = getReportService(reportId).run(parameters.getReportParms(mode), reportId);
        ReportCatalogEntry catalogEntry = new ReportCatalogEntry();
        catalogEntry.setReportId(reportId);
        catalogEntry.setTitle(deliveryOptions.getInstanceId());
        catalogEntry.setLocation(outputPath);
        catalogEntry.setDate(new Date());
        m_reportStoreService.save(catalogEntry);
        if (deliveryOptions.getMailTo().length() != 0) {
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          BufferedOutputStream bout = new BufferedOutputStream(out);
          getReportService(reportId)
              .render(reportId, outputPath, deliveryOptions.getFormat(), bout);
          mailReport(deliveryOptions, out);
        }
      } catch (ReportException reportException) {
        log.error("failed to run or render report: " + reportId, reportException);
      }
    }
  }
 /**
  * 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;
  }
 /**
  * Retrieves a current record from the database based upon the key fields of <em>nodeID</em> and
  * <em>ipAddr</em>. If the record cannot be found then a null reference is returned.
  *
  * @param nid The node id key
  * @param addr The ip address.
  * @param ifIndex The interface index.
  * @return The loaded entry or null if one could not be found.
  */
 public static DbIpInterfaceEntry get(int nid, InetAddress addr, int ifIndex) throws SQLException {
   Connection db = null;
   try {
     db = DataSourceFactory.getInstance().getConnection();
     return get(db, nid, addr, ifIndex);
   } finally {
     try {
       if (db != null) {
         db.close();
       }
     } catch (SQLException e) {
       ThreadCategory.getInstance(DbIpInterfaceEntry.class)
           .warn("Exception closing JDBC connection", e);
     }
   }
 }
public class LogPrefixPreservingPingResponseCallback implements PingResponseCallback {
  private final PingResponseCallback m_cb;
  private final String m_prefix = ThreadCategory.getPrefix();

  public LogPrefixPreservingPingResponseCallback(PingResponseCallback cb) {
    m_cb = cb;
  }

  @Override
  public void handleError(InetAddress address, EchoPacket request, Throwable t) {
    String oldPrefix = ThreadCategory.getPrefix();
    try {
      ThreadCategory.setPrefix(m_prefix);
      m_cb.handleError(address, request, t);
    } finally {
      ThreadCategory.setPrefix(oldPrefix);
    }
  }

  @Override
  public void handleResponse(InetAddress address, EchoPacket response) {
    String oldPrefix = ThreadCategory.getPrefix();
    try {
      ThreadCategory.setPrefix(m_prefix);
      m_cb.handleResponse(address, response);
    } finally {
      ThreadCategory.setPrefix(oldPrefix);
    }
  }

  @Override
  public void handleTimeout(InetAddress address, EchoPacket request) {
    String oldPrefix = ThreadCategory.getPrefix();
    try {
      ThreadCategory.setPrefix(m_prefix);
      m_cb.handleTimeout(address, request);
    } finally {
      ThreadCategory.setPrefix(oldPrefix);
    }
  }
}
  /**
   * {@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;
  }
 /** Constructor for DefaultReportWrapperService. */
 public DefaultReportWrapperService() {
   String oldPrefix = ThreadCategory.getPrefix();
   ThreadCategory.setPrefix(LOG4J_CATEGORY);
   log = ThreadCategory.getInstance(DefaultReportWrapperService.class);
   ThreadCategory.setPrefix(oldPrefix);
 }
  /**
   * 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);
      }
    }
  }
  /**
   * 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);
  }
  /** 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");
  }
  /**
   * 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);
    }
  }
 private static ThreadCategory log() {
   return ThreadCategory.getInstance(SnmpAssetProvisioningAdapter.class);
 }
 private static ThreadCategory log() {
   return ThreadCategory.getInstance(DefaultKscReportService.class);
 }
  /**
   * 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;
  }
  /** {@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;
  }
  /**
   * 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;
    }
  }
  /**
   * {@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 ThreadCategory log() {
   return ThreadCategory.getInstance(getClass());
 }