/** {@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}
   *
   * <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");
      }
    }
  }
  /** 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);
    }
  }
 /**
  * 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);
     }
   }
 }
  /*
   * 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");
    }
  }
 /**
  * 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;
 }
  /**
   * {@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 + "\"");
    }
  }
  /**
   * 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;
  }
  /** 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");
  }
 /** Constructor for DefaultReportWrapperService. */
 public DefaultReportWrapperService() {
   String oldPrefix = ThreadCategory.getPrefix();
   ThreadCategory.setPrefix(LOG4J_CATEGORY);
   log = ThreadCategory.getInstance(DefaultReportWrapperService.class);
   ThreadCategory.setPrefix(oldPrefix);
 }
 private static ThreadCategory log() {
   return ThreadCategory.getInstance(SnmpAssetProvisioningAdapter.class);
 }
Example #13
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;
  }
 /**
  * log
  *
  * @return a {@link org.opennms.core.utils.ThreadCategory} object.
  */
 protected ThreadCategory log() {
   return ThreadCategory.getInstance(this.getClass());
 }
Example #15
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;
  }
Example #16
0
/**
 * Encapsulates all querying functionality for outages.
 *
 * @author <A HREF="mailto:[email protected]">Lawrence Karnowski </A>
 * @author <A HREF="mailto:[email protected]">Jason Johns </A>
 */
public class OutageFactory extends Object {

  /** Constant <code>log</code> */
  protected static final ThreadCategory log = ThreadCategory.getInstance("OutageFactory");

  /** Private constructor so this class cannot be instantiated. */
  private OutageFactory() {}

  /**
   * Return the count of current outages.
   *
   * <p>Note: This method has been optimized for the simplest query.
   *
   * @return a int.
   * @throws java.sql.SQLException if any.
   */
  public static int getOutageCount() throws SQLException {
    int outageCount = 0;
    final Connection conn = Vault.getDbConnection();
    final DBUtils d = new DBUtils(OutageFactory.class, conn);

    try {
      final Statement stmt = conn.createStatement();
      d.watch(stmt);

      final ResultSet rs =
          stmt.executeQuery(
              "SELECT COUNT(OUTAGEID) AS OUTAGECOUNT 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 "
                  + "WHERE IFREGAINEDSERVICE IS NULL "
                  + "AND (NODE.NODETYPE != 'D' AND IPINTERFACE.ISMANAGED != 'D' AND IFSERVICES.STATUS != 'D') ");
      d.watch(rs);

      if (rs.next()) {
        outageCount = rs.getInt("OUTAGECOUNT");
      }
    } finally {
      d.cleanUp();
    }

    return outageCount;
  }

  /**
   * Count the number of outages for a given outage type.
   *
   * @param outageType a {@link org.opennms.web.outage.OutageType} object.
   * @param filters an array of org$opennms$web$filter$Filter objects.
   * @return a int.
   * @throws java.sql.SQLException if any.
   */
  public static int getOutageCount(OutageType outageType, Filter[] filters) throws SQLException {
    if (outageType == null || filters == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    int outageCount = 0;
    final Connection conn = Vault.getDbConnection();
    final DBUtils d = new DBUtils(OutageFactory.class, conn);

    try {
      StringBuffer select =
          new StringBuffer(
              "SELECT COUNT(OUTAGEID) AS OUTAGECOUNT 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.NOTIFYID "
                  + "WHERE (NODE.NODETYPE != 'D' AND IPINTERFACE.ISMANAGED != 'D' AND IFSERVICES.STATUS != 'D') "
                  + "AND ");
      select.append(outageType.getClause());

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

      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);

      if (rs.next()) {
        outageCount = rs.getInt("OUTAGECOUNT");
      }
    } finally {
      d.cleanUp();
    }

    return outageCount;
  }

  /**
   * getOutage
   *
   * @param outageId a int.
   * @return a {@link org.opennms.web.outage.Outage} object.
   * @throws java.sql.SQLException if any.
   */
  public static Outage getOutage(int outageId) throws SQLException {
    Outage outage = null;
    final Connection conn = Vault.getDbConnection();
    final DBUtils d = new DBUtils(OutageFactory.class, conn);

    try {
      final PreparedStatement stmt =
          conn.prepareStatement(
              "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 "
                  + "LEFT OUTER JOIN SERVICE USING(SERVICEID) "
                  + "LEFT OUTER JOIN NOTIFICATIONS ON SVCLOSTEVENTID=NOTIFICATIONS.EVENTID "
                  + "WHERE OUTAGEID=?");
      d.watch(stmt);
      stmt.setInt(1, outageId);

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

      Outage[] outages = rs2Outages(rs);

      if (outages != null && outages.length > 0) {
        outage = outages[0];
      }
    } finally {
      d.cleanUp();
    }

    return outage;
  }

  /**
   * Return all unresolved outages sorted by the default sort style, outage identifier.
   *
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutages() throws SQLException {
    return OutageFactory.getOutages(
        SortStyle.DEFAULT_SORT_STYLE, OutageType.CURRENT, new Filter[0], -1, -1);
  }

  /**
   * Return all unresolved outages sorted by the given sort style.
   *
   * @param sortStyle a {@link org.opennms.web.outage.SortStyle} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutages(SortStyle sortStyle) throws SQLException {
    return OutageFactory.getOutages(sortStyle, OutageType.CURRENT, new Filter[0], -1, -1);
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by the given sort style.
   *
   * @param sortStyle a {@link org.opennms.web.outage.SortStyle} object.
   * @param outType a {@link org.opennms.web.outage.OutageType} object.
   * @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) throws SQLException {
    return OutageFactory.getOutages(sortStyle, outType, new Filter[0], -1, -1);
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by the given sort style.
   *
   * @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)
      throws SQLException {
    return OutageFactory.getOutages(sortStyle, outType, filters, -1, -1);
  }

  /**
   * 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;
  }

  /**
   * Return all current outages sorted by time for the given node.
   *
   * @param nodeId a int.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForNode(int nodeId, ServletContext servletContext)
      throws SQLException {
    return (getOutagesForNode(
        nodeId, SortStyle.DEFAULT_SORT_STYLE, OutageType.CURRENT, servletContext));
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by given sort style for the
   * given node.
   *
   * @param nodeId a int.
   * @param sortStyle a {@link org.opennms.web.outage.SortStyle} object.
   * @param outType a {@link org.opennms.web.outage.OutageType} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForNode(
      int nodeId, SortStyle sortStyle, OutageType outType, ServletContext servletContext)
      throws SQLException {
    if (sortStyle == null || outType == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    Filter[] filters = new Filter[] {new NodeFilter(nodeId, servletContext)};
    return (OutageFactory.getOutages(sortStyle, outType, filters));
  }

  /**
   * Return all unresolved notices for the given interface.
   *
   * @param nodeId a int.
   * @param ipAddress a {@link java.lang.String} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForInterface(
      int nodeId, String ipAddress, ServletContext servletContext) throws SQLException {
    return (getOutagesForInterface(
        nodeId, ipAddress, SortStyle.DEFAULT_SORT_STYLE, OutageType.CURRENT, servletContext));
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by given sort style for the
   * given interface.
   *
   * @param nodeId a int.
   * @param ipAddress a {@link java.lang.String} object.
   * @param sortStyle a {@link org.opennms.web.outage.SortStyle} object.
   * @param outType a {@link org.opennms.web.outage.OutageType} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForInterface(
      int nodeId,
      String ipAddress,
      SortStyle sortStyle,
      OutageType outType,
      ServletContext servletContext)
      throws SQLException {
    if (ipAddress == null || sortStyle == null || outType == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    Filter[] filters =
        new Filter[] {new NodeFilter(nodeId, servletContext), new InterfaceFilter(ipAddress)};
    return (OutageFactory.getOutages(sortStyle, outType, filters));
  }

  /**
   * Return all outages (optionally only unresolved notices) sorted by id for the given interface.
   *
   * @deprecated Replaced by {@link " #getOutagesForInterface(int,String,SortStyle,OutageType)
   *     getOutagesForInterface(int,String,SortStyle,OutageType)"}
   * @param nodeId a int.
   * @param ipAddress a {@link java.lang.String} object.
   * @param includeResolved a boolean.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForInterface(
      int nodeId, String ipAddress, boolean includeResolved, ServletContext servletContext)
      throws SQLException {
    if (ipAddress == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    OutageType outageType = includeResolved ? OutageType.BOTH : OutageType.CURRENT;
    Outage[] outages =
        getOutagesForInterface(
            nodeId, ipAddress, SortStyle.DEFAULT_SORT_STYLE, outageType, servletContext);

    return outages;
  }

  /**
   * Return all unacknowledged notices sorted by time for that have the given IP address, regardless
   * of what node they belong to.
   *
   * @param ipAddress a {@link java.lang.String} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForInterface(String ipAddress) throws SQLException {
    return (getOutagesForInterface(ipAddress, SortStyle.DEFAULT_SORT_STYLE, OutageType.CURRENT));
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by given sort style for the
   * given IP address.
   *
   * @param ipAddress a {@link java.lang.String} object.
   * @param sortStyle a {@link org.opennms.web.outage.SortStyle} object.
   * @param outType a {@link org.opennms.web.outage.OutageType} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForInterface(
      String ipAddress, SortStyle sortStyle, OutageType outType) throws SQLException {
    if (ipAddress == null || sortStyle == null || outType == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    Filter[] filters = new Filter[] {new InterfaceFilter(ipAddress)};
    return (OutageFactory.getOutages(sortStyle, outType, filters));
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by id that have the given IP
   * address, regardless of what node they belong to.
   *
   * @deprecated Replaced by {@link " #getOutagesForInterface(String,SortStyle,OutageType)
   *     getOutagesForInterface(String,SortStyle,OutageType)"}
   * @param ipAddress a {@link java.lang.String} object.
   * @param includeResolved a boolean.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForInterface(String ipAddress, boolean includeResolved)
      throws SQLException {
    if (ipAddress == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    OutageType outageType = includeResolved ? OutageType.BOTH : OutageType.CURRENT;
    Outage[] outages = getOutagesForInterface(ipAddress, SortStyle.DEFAULT_SORT_STYLE, outageType);

    return outages;
  }

  /**
   * Return all unresolved outages sorted by time for the given service.
   *
   * @param nodeId a int.
   * @param ipAddress a {@link java.lang.String} object.
   * @param serviceId a int.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForService(
      int nodeId, String ipAddress, int serviceId, ServletContext servletContext)
      throws SQLException {
    return (getOutagesForService(
        nodeId,
        ipAddress,
        serviceId,
        SortStyle.DEFAULT_SORT_STYLE,
        OutageType.CURRENT,
        servletContext));
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by given sort style for the
   * given service.
   *
   * @param nodeId a int.
   * @param ipAddress a {@link java.lang.String} object.
   * @param serviceId a int.
   * @param sortStyle a {@link org.opennms.web.outage.SortStyle} object.
   * @param outType a {@link org.opennms.web.outage.OutageType} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForService(
      int nodeId,
      String ipAddress,
      int serviceId,
      SortStyle sortStyle,
      OutageType outType,
      ServletContext servletContext)
      throws SQLException {
    if (ipAddress == null || sortStyle == null || outType == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    Filter[] filters =
        new Filter[] {
          new NodeFilter(nodeId, servletContext),
          new InterfaceFilter(ipAddress),
          new ServiceFilter(serviceId, servletContext)
        };
    return (OutageFactory.getOutages(sortStyle, outType, filters));
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by time for the given service.
   *
   * @deprecated Replaced by {@link " #getOutagesForService(int,String,int,SortStyle,OutageType)
   *     getOutagesForInterface(int,String,int,SortStyle,OutageType)"}
   * @param nodeId a int.
   * @param ipAddress a {@link java.lang.String} object.
   * @param serviceId a int.
   * @param includeResolved a boolean.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForService(
      int nodeId,
      String ipAddress,
      int serviceId,
      boolean includeResolved,
      ServletContext servletContext)
      throws SQLException {
    if (ipAddress == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    OutageType outageType = includeResolved ? OutageType.BOTH : OutageType.CURRENT;
    Outage[] outages =
        getOutagesForService(
            nodeId, ipAddress, serviceId, SortStyle.DEFAULT_SORT_STYLE, outageType, servletContext);

    return outages;
  }

  /**
   * Return all unresolved outages sorted by time for the given service type, regardless of what
   * node or interface they belong to.
   *
   * @param serviceId a int.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForService(int serviceId, ServletContext servletContext)
      throws SQLException {
    return (getOutagesForService(
        serviceId, SortStyle.DEFAULT_SORT_STYLE, OutageType.CURRENT, servletContext));
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by given sort style for the
   * given service identifier.
   *
   * @param serviceId a int.
   * @param sortStyle a {@link org.opennms.web.outage.SortStyle} object.
   * @param outType a {@link org.opennms.web.outage.OutageType} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForService(
      int serviceId, SortStyle sortStyle, OutageType outType, ServletContext servletContext)
      throws SQLException {
    if (sortStyle == null || outType == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    Filter[] filters = new Filter[] {new ServiceFilter(serviceId, servletContext)};
    return (OutageFactory.getOutages(sortStyle, outType, filters));
  }

  /**
   * Return all outages (optionally only unresolved outages) sorted by id for the given service
   * type, regardless of what node or interface they belong to.
   *
   * @deprecated Replaced by {@link " #getOutagesForService(int,SortStyle,OutageType)
   *     getOutagesForInterface(int,SortStyle,OutageType)"}
   * @param serviceId a int.
   * @param includeResolved a boolean.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  public static Outage[] getOutagesForService(
      int serviceId, boolean includeResolved, ServletContext servletContext) throws SQLException {
    OutageType outageType = includeResolved ? OutageType.BOTH : OutageType.CURRENT;
    Outage[] outages =
        getOutagesForService(serviceId, SortStyle.DEFAULT_SORT_STYLE, outageType, servletContext);

    return outages;
  }

  /**
   * Convenience method for translating a <code>java.sql.ResultSet</code> containing outage
   * information into an array of <code>Outage</code> objects.
   *
   * @param rs a {@link java.sql.ResultSet} object.
   * @return an array of {@link org.opennms.web.outage.Outage} objects.
   * @throws java.sql.SQLException if any.
   */
  protected static Outage[] rs2Outages(ResultSet rs) throws SQLException {
    Outage[] outages = null;
    List<Outage> list = new ArrayList<Outage>();

    // FIXME: Don't reuse the "element" variable for multiple objects.
    while (rs.next()) {
      Outage outage = new Outage();

      Object element = null;
      int intElement = -1;

      // cannot be null
      outage.outageId = rs.getInt("outageid");
      outage.nodeId = rs.getInt("nodeid");
      outage.ipAddress = rs.getString("ipaddr");
      outage.serviceId = rs.getInt("serviceid");

      // cannot be null
      element = rs.getTimestamp("iflostservice");
      outage.lostServiceTime = new java.util.Date(((Timestamp) element).getTime());

      // can be null
      outage.hostname = rs.getString("iphostname"); // from ipinterface
      // table

      // can be null
      outage.nodeLabel = rs.getString("nodelabel"); // from node table

      // can be null
      outage.serviceName = rs.getString("servicename"); // from service
      // table

      // can be null
      element = rs.getTimestamp("ifregainedservice");
      if (element != null) {
        outage.regainedServiceTime = new java.util.Date(((Timestamp) element).getTime());
      }

      // can be null
      intElement = rs.getInt("svcLostEventID");
      if (!rs.wasNull()) {
        outage.lostServiceEventId = Integer.valueOf(intElement);
      }

      // can be null
      intElement = rs.getInt("svcRegainedEventID");
      if (!rs.wasNull()) {
        outage.regainedServiceEventId = Integer.valueOf(intElement);
      }

      // can be null
      intElement = rs.getInt("notifyid");
      if (!rs.wasNull()) {
        outage.lostServiceNotificationId = Integer.valueOf(intElement);
      }

      // can be null
      outage.lostServiceNotificationAcknowledgedBy = rs.getString("answeredby");

      list.add(outage);
    }

    outages = list.toArray(new Outage[list.size()]);

    return outages;
  }
}
 private static ThreadCategory log() {
   return ThreadCategory.getInstance(DefaultKscReportService.class);
 }
Example #18
0
 private final ThreadCategory log() {
   return ThreadCategory.getInstance(ThresholdEntity.class);
 }
  /**
   * 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();
      }
    }
  }
  /**
   * {@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;
  }
 private ThreadCategory log() {
   return ThreadCategory.getInstance(getClass());
 }
 /** Method to get the QoSDrx's logger from OpenNMS */
 private static ThreadCategory getLog() {
   return ThreadCategory.getInstance(OnmsAlarmOssjMapper.class);
 }
 /**
  * log
  *
  * @return a {@link org.opennms.core.utils.ThreadCategory} object.
  */
 public final ThreadCategory log() {
   return ThreadCategory.getInstance(LatencyThresholder.class);
 }