private JasperPrint runAndRender(Report report) throws Exception, JRException {
    JasperPrint jasperPrint = new JasperPrint();

    JasperReport jasperReport =
        JasperCompileManager.compileReport(
            System.getProperty("opennms.home")
                + File.separator
                + "etc"
                + File.separator
                + "report-templates"
                + File.separator
                + report.getReportTemplate());

    if (report.getReportEngine().equals("jdbc")) {
      Connection connection = DataSourceFactory.getDataSource().getConnection();
      jasperPrint =
          JasperFillManager.fillReport(
              jasperReport, paramListToMap(report.getParameterCollection()), connection);
      connection.close();
    } else if (report.getReportEngine().equals("opennms")) {
      LogUtils.errorf(this, "Sorry the OpenNMS Data source engine is not yet available");
      jasperPrint = null;
    } else {
      LogUtils.errorf(this, "Unknown report engine: %s ", report.getReportEngine());
      jasperPrint = null;
    }

    return jasperPrint;
  }
Example #2
0
  protected void setUp() throws Exception {
    super.setUp();
    MockUtil.println("------------ Begin Test " + this + " --------------------------");
    MockLogAppender.setupLogging();

    if (m_runSupers) {

      createMockNetwork();

      populateDatabase();

      DataSourceFactory.setInstance(m_db);

      SnmpPeerFactory.setInstance(
          new SnmpPeerFactory(new ByteArrayResource(getSnmpConfig().getBytes())));

      if (isStartEventd()) {
        m_eventdIpcMgr = new EventIpcManagerDefaultImpl();

        JdbcEventdServiceManager eventdServiceManager = new JdbcEventdServiceManager();
        eventdServiceManager.setDataSource(m_db);
        eventdServiceManager.afterPropertiesSet();

        /*
         * Make sure we specify a full resource path since "this" is
         * the unit test class, which is most likely in another package.
         */
        File configFile =
            ConfigurationTestUtils.getFileForResource(
                this, "/org/opennms/netmgt/mock/eventconf.xml");
        DefaultEventConfDao eventConfDao = new DefaultEventConfDao();
        eventConfDao.setConfigResource(new FileSystemResource(configFile));
        eventConfDao.afterPropertiesSet();
        EventconfFactory.setInstance(eventConfDao);

        EventExpander eventExpander = new EventExpander();
        eventExpander.setEventConfDao(eventConfDao);
        eventExpander.afterPropertiesSet();

        JdbcEventWriter jdbcEventWriter = new JdbcEventWriter();
        jdbcEventWriter.setEventdServiceManager(eventdServiceManager);
        jdbcEventWriter.setDataSource(m_db);
        jdbcEventWriter.setGetNextIdString(
            "select nextVal('eventsNxtId')"); // for HSQL: "SELECT max(eventId)+1 from events"
        jdbcEventWriter.afterPropertiesSet();

        EventIpcBroadcastProcessor eventIpcBroadcastProcessor = new EventIpcBroadcastProcessor();
        eventIpcBroadcastProcessor.setEventIpcBroadcaster(m_eventdIpcMgr);
        eventIpcBroadcastProcessor.afterPropertiesSet();

        List<EventProcessor> eventProcessors = new ArrayList<EventProcessor>(3);
        eventProcessors.add(eventExpander);
        eventProcessors.add(jdbcEventWriter);
        eventProcessors.add(eventIpcBroadcastProcessor);

        DefaultEventHandlerImpl eventHandler = new DefaultEventHandlerImpl();
        eventHandler.setEventProcessors(eventProcessors);
        eventHandler.afterPropertiesSet();

        m_eventdIpcMgr.setHandlerPoolSize(5);
        m_eventdIpcMgr.setEventHandler(eventHandler);
        m_eventdIpcMgr.afterPropertiesSet();

        m_eventProxy = m_eventdIpcMgr;

        EventIpcManagerFactory.setIpcManager(m_eventdIpcMgr);

        EventIpcManagerEventHandlerProxy proxy = new EventIpcManagerEventHandlerProxy();
        proxy.setEventIpcManager(m_eventdIpcMgr);
        proxy.afterPropertiesSet();
        List<EventHandler> eventHandlers = new ArrayList<EventHandler>(1);
        eventHandlers.add(proxy);

        TcpEventReceiver tcpEventReceiver = new TcpEventReceiver();
        tcpEventReceiver.setPort(5837);
        tcpEventReceiver.setEventHandlers(eventHandlers);

        UdpEventReceiver udpEventReceiver = new UdpEventReceiver();
        udpEventReceiver.setPort(5837);
        tcpEventReceiver.setEventHandlers(eventHandlers);

        List<EventReceiver> eventReceivers = new ArrayList<EventReceiver>(2);
        eventReceivers.add(tcpEventReceiver);
        eventReceivers.add(udpEventReceiver);

        m_eventd = new Eventd();
        m_eventd.setEventdServiceManager(eventdServiceManager);
        m_eventd.setEventReceivers(eventReceivers);
        m_eventd.setReceiver(new BroadcastEventProcessor(m_eventdIpcMgr, eventConfDao));

        m_eventd.init();
        m_eventd.start();
      }
    }

    m_transMgr = new DataSourceTransactionManager(DataSourceFactory.getInstance());
  }
  /**
   * {@inheritDoc}
   *
   * <p>Responsible for performing all necessary initialization for the specified interface in
   * preparation for thresholding.
   */
  public void initialize(ThresholdNetworkInterface iface, Map<?, ?> parameters) {
    // Get interface address from NetworkInterface
    //
    if (iface.getType() != NetworkInterface.TYPE_INET)
      throw new RuntimeException("Unsupported interface type, only TYPE_INET currently supported");
    InetAddress ipAddr = (InetAddress) iface.getAddress();
    String groupName = ParameterMap.getKeyedString(parameters, "thresholding-group", "default");

    // Get the threshold group's RRD repository path
    //
    String repository = null;
    try {
      repository = ThresholdingConfigFactory.getInstance().getRrdRepository(groupName);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException("Thresholding group '" + groupName + "' does not exist.");
    }

    // Add RRD repository as an attribute of the interface for retrieval
    // by the check() method.
    //
    iface.setAttribute(RRD_REPOSITORY_KEY, repository);

    // Get database connection in order to retrieve the nodeid and
    // ifIndex from the database for this interface.
    //
    java.sql.Connection dbConn = null;
    final DBUtils d = new DBUtils(getClass());
    try {
      dbConn = DataSourceFactory.getInstance().getConnection();
      d.watch(dbConn);
    } catch (SQLException sqlE) {
      if (log().isEnabledFor(ThreadCategory.Level.ERROR))
        log().error("initialize: Failed getting connection to the database.", sqlE);
      throw new UndeclaredThrowableException(sqlE);
    }

    // Use IP address to lookup the node id
    //
    // NOTE: All database calls wrapped in try/finally block so we make
    // certain that the connection will be closed when we are
    // finished.
    //
    int nodeId = -1;

    final String hostAddress = InetAddressUtils.str(ipAddr);
    try {
      // Prepare & execute the SQL statement to get the 'nodeid',
      // 'ifIndex' and 'isSnmpPrimary' fields from the ipInterface table.
      //
      PreparedStatement stmt = null;
      try {
        stmt = dbConn.prepareStatement(SQL_GET_NODEID);
        d.watch(stmt);
        stmt.setString(1, hostAddress); // interface address
        ResultSet rs = stmt.executeQuery();
        d.watch(rs);
        if (rs.next()) {
          nodeId = rs.getInt(1);
          if (rs.wasNull()) nodeId = -1;
        }
      } catch (SQLException sqle) {
        if (log().isDebugEnabled()) log().debug("initialize: SQL exception!!", sqle);
        throw new RuntimeException(
            "SQL exception while attempting to retrieve node id for interface " + hostAddress);
      }

      if (log().isDebugEnabled())
        log()
            .debug(
                "initialize: db retrieval info: nodeid = " + nodeId + ", address = " + hostAddress);

      if (nodeId == -1)
        throw new RuntimeException("Unable to retrieve node id for interface " + hostAddress);
    } finally {
      d.cleanUp();
    }

    // Add nodeId as an attribute of the interface for retrieval
    // by the check() method.
    //
    iface.setAttribute(NODE_ID_KEY, new Integer(nodeId));

    // Retrieve the collection of Threshold objects associated with
    // the defined thresholding group and build maps of
    // ThresholdEntity objects keyed by datasource name. The
    // datasource type of the threshold determines which
    // map the threshold entity is added to.
    //
    // Each ThresholdEntity can wrap one high Threshold and one low
    // Threshold castor-generated object for a single datasource.
    // If more than one high or more than one low threshold is defined
    // for a single datasource a warning messages is generated. Only
    // the first threshold in such a scenario will be used for thresholding.
    //

    // Create empty map for storing threshold entities
    Map<String, ThresholdEntity> thresholdMap = new HashMap<String, ThresholdEntity>();

    try {
      for (Basethresholddef thresh :
          ThresholdingConfigFactory.getInstance().getThresholds(groupName)) {
        // See if map entry already exists for this datasource
        // If not, create a new one.
        boolean newEntity = false;
        ThresholdEntity thresholdEntity = null;

        // All latency thresholds are per interface so confirm that
        // the datasource type is set to "if"
        //
        if (!thresh.getDsType().equals("if") && !thresh.getDsType().equals("expr")) {
          log()
              .warn(
                  "initialize: invalid datasource type, latency thresholder only supports interface level datasources.");
          continue; // continue with the next threshold...
        }
        try {
          BaseThresholdDefConfigWrapper wrapper =
              BaseThresholdDefConfigWrapper.getConfigWrapper(thresh);
          // First attempt to lookup the entry in the map
          thresholdEntity = thresholdMap.get(wrapper.getDatasourceExpression());

          // Found entry?
          if (thresholdEntity == null) {
            // Nope, create a new one
            newEntity = true;
            thresholdEntity = new ThresholdEntity();
          }

          try {
            thresholdEntity.addThreshold(wrapper);
          } catch (IllegalStateException e) {
            log()
                .warn(
                    "Encountered duplicate "
                        + thresh.getType()
                        + " for datasource "
                        + wrapper.getDatasourceExpression()
                        + ": "
                        + e,
                    e);
          }

          // Add new entity to the map
          if (newEntity) {
            thresholdMap.put(wrapper.getDatasourceExpression(), thresholdEntity);
          }
        } catch (ThresholdExpressionException e) {
          log().warn("Could not parse threshold expression: " + e.getMessage(), e);
        }
      }
    } catch (IllegalArgumentException e) {
      throw new RuntimeException("Thresholding group '" + groupName + "' does not exist.");
    }

    // Add threshold maps as attributes for retrieval by the check() method.
    //
    iface.setAttribute(THRESHOLD_MAP_KEY, thresholdMap);

    // Debug
    //
    if (log().isDebugEnabled()) {
      log()
          .debug(
              "initialize: dumping interface thresholds defined for "
                  + hostAddress
                  + "/"
                  + groupName
                  + ":");
      Iterator<ThresholdEntity> iter = thresholdMap.values().iterator();
      while (iter.hasNext()) log().debug(iter.next().toString());
    }

    if (log().isDebugEnabled())
      log().debug("initialize: initialization completed for " + hostAddress);
    return;
  }