Exemplo n.º 1
0
  /** {@inheritDoc} */
  @Override
  public byte[] render(final String inputFileName, final Resource xsltResource)
      throws ReportRenderException {
    try {
      return Logging.withPrefix(
          LOG4J_CATEGORY,
          new Callable<byte[]>() {
            @Override
            public byte[] call() throws Exception {
              LOG.debug(
                  "Rendering {} with XSL File {} to byte array",
                  inputFileName,
                  xsltResource.getDescription());

              ByteArrayOutputStream outputStream = null;
              try {
                outputStream = new ByteArrayOutputStream();
                render(inputFileName, outputStream, xsltResource);
                return outputStream.toByteArray();
              } finally {
                IOUtils.closeQuietly(outputStream);
              }
            }
          });
    } catch (final Exception e) {
      if (e instanceof ReportRenderException) throw (ReportRenderException) e;
      throw new ReportRenderException("Failed to render " + inputFileName, e);
    }
  }
Exemplo n.º 2
0
  /** {@inheritDoc} */
  @Override
  public void render(
      final InputStream inputStream, final OutputStream outputStream, final Resource xsltResource)
      throws ReportRenderException {
    try {
      Logging.withPrefix(
          LOG4J_CATEGORY,
          new Callable<Void>() {
            @Override
            public Void call() throws Exception {
              LOG.debug(
                  "Rendering InputStream with XSL File {} to OutputStream",
                  xsltResource.getDescription());

              FileInputStream xslt = null;
              Reader xsl = null;
              Reader xml = null;
              try {
                xslt = new FileInputStream(xsltResource.getFile());
                xsl = new InputStreamReader(xslt, "UTF-8");
                xml = new InputStreamReader(inputStream, "UTF-8");
                render(xml, outputStream, xsl);
                return null;
              } finally {
                IOUtils.closeQuietly(xml);
                IOUtils.closeQuietly(xsl);
                IOUtils.closeQuietly(xslt);
              }
            }
          });
    } catch (final Exception e) {
      if (e instanceof ReportRenderException) throw (ReportRenderException) e;
      throw new ReportRenderException(e);
    }
  }
  /** {@inheritDoc} */
  @Override
  public String run(final Map<String, Object> reportParms, final String reportId) {
    try {
      return Logging.withPrefix(
          LOG4J_CATEGORY,
          new Callable<String>() {
            @Override
            public String call() throws Exception {
              AvailabilityCalculator calculator;
              String reportFileName = null;

              LOG.debug("running OpenNMS database report {}", reportId);

              if (m_configDao.getType(reportId).equalsIgnoreCase(CAL_TYPE)) {
                calculator = m_calendarCalculator;
                LOG.debug("Calendar report format selected");
              } else {
                calculator = m_classicCalculator;
                LOG.debug("Classic report format selected");
              }

              calculator.setCategoryName((String) reportParms.get("reportCategory"));

              LOG.debug(
                  "set availability calculator report category to: {}",
                  calculator.getCategoryName());

              calculator.setPeriodEndDate((Date) reportParms.get("endDate"));

              LOG.debug(
                  "set availability calculator end date to: {}", calculator.getPeriodEndDate());

              calculator.setLogoURL(m_configDao.getLogo(reportId));

              // have the calculator calculate everything to enable any of the
              // templates to work
              // This has changed since the last version
              // This will have some performance impact.

              calculator.setReportFormat("all");

              LOG.debug("Starting Availability Report Calculations");
              try {
                calculator.calculate();
                reportFileName = calculator.writeXML();
              } catch (AvailabilityCalculationException ce) {
                LOG.error("Unable to calculate report data ", ce);
              }

              return reportFileName;
            }
          });
    } catch (final Exception e) {
      LOG.warn("An error occurred while running report {}", reportId, e);
    }
    return null;
  }
  private void render(
      final String id,
      final InputStream inputStream,
      final ReportFormat format,
      final OutputStream outputStream) {
    Logging.withPrefix(
        LOG4J_CATEGORY,
        new Runnable() {
          @Override
          public void run() {
            try {
              Resource xsltResource;
              ReportRenderer renderer;

              switch (format) {
                case HTML:
                  LOG.debug("rendering as HTML");
                  renderer = new HTMLReportRenderer();
                  xsltResource = new UrlResource(m_configDao.getHtmlStylesheetLocation(id));
                  break;
                case PDF:
                  LOG.debug("rendering as PDF");
                  renderer = new PDFReportRenderer();
                  xsltResource = new UrlResource(m_configDao.getPdfStylesheetLocation(id));
                  break;
                case SVG:
                  LOG.debug("rendering as PDF with embedded SVG");
                  renderer = new PDFReportRenderer();
                  xsltResource = new UrlResource(m_configDao.getSvgStylesheetLocation(id));
                  break;
                default:
                  LOG.debug("rendering as HTML as no valid format found");
                  renderer = new HTMLReportRenderer();
                  xsltResource = new UrlResource(m_configDao.getHtmlStylesheetLocation(id));
              }

              final String baseDir = System.getProperty("opennms.report.dir");
              renderer.setBaseDir(baseDir);
              renderer.render(inputStream, outputStream, xsltResource);
              outputStream.flush();

            } catch (final Exception e) {
              LOG.error("An error occurred rendering to {} format.", format.name(), e);
            }
          }
        });
  }
Exemplo n.º 5
0
  /** {@inheritDoc} */
  @Override
  public void render(
      final String inputFileName, final String outputFileName, final Resource xsltResource)
      throws ReportRenderException {
    try {
      Logging.withPrefix(
          LOG4J_CATEGORY,
          new Callable<Void>() {
            @Override
            public Void call() throws Exception {

              LOG.debug(
                  "Rendering {} with XSL File {} to {} with base directory of {}",
                  m_baseDir,
                  inputFileName,
                  xsltResource.getDescription(),
                  outputFileName);

              FileInputStream in = null, xslt = null;
              FileOutputStream out = null;
              Reader xsl = null, xml = null;
              try {

                xslt = new FileInputStream(xsltResource.getFile());
                xsl = new InputStreamReader(xslt, "UTF-8");
                in = new FileInputStream(m_baseDir + "/" + inputFileName);
                xml = new InputStreamReader(in, "UTF-8");

                out = new FileOutputStream(new File(m_baseDir + "/" + outputFileName));

                render(xml, out, xsl);
                return null;
              } finally {
                IOUtils.closeQuietly(xml);
                IOUtils.closeQuietly(xsl);
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(xslt);
              }
            }
          });
    } catch (final Exception e) {
      if (e instanceof ReportRenderException) throw (ReportRenderException) e;
      throw new ReportRenderException(e);
    }
  }
 /** {@inheritDoc} */
 @Override
 public void render(
     final String id,
     final String location,
     final ReportFormat format,
     final OutputStream outputStream) {
   Logging.withPrefix(
       LOG4J_CATEGORY,
       new Runnable() {
         @Override
         public void run() {
           FileInputStream inputStream = null;
           try {
             inputStream = new FileInputStream(location);
             render(id, inputStream, format, outputStream);
           } catch (final FileNotFoundException e) {
             LOG.error("could not open input file", e);
           }
         }
       });
 }
  /** {@inheritDoc} */
  @Override
  public boolean validate(final Map<String, Object> reportParms, final String reportID) {
    try {
      return Logging.withPrefix(
          LOG4J_CATEGORY,
          new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
              if (!reportParms.containsKey("endDate")) {
                LOG.error("report parameters should contain parameter endDate");
                return false;
              }

              if (!(reportParms.get("endDate") instanceof Date)) {
                LOG.error("report parameters 'endDate' should be a Date");
                return false;
              }

              if (!reportParms.containsKey("reportCategory")) {
                LOG.error("report parameters should contain parameter reportCategory");
                return false;
              }

              if (!(reportParms.get("reportCategory") instanceof String)) {
                LOG.error("report parameter 'reportCategory' should be a String");
                return false;
              }

              return true;
            }
          });
    } catch (final Exception e) {
      LOG.error("And unknown error occurred.", e);
      return false;
    }
  }
Exemplo n.º 8
0
  /** Constructor for XMPPNotificationManager. */
  protected XMPPNotificationManager() {

    Map<String, String> mdc = Logging.getCopyOfContextMap();
    try {
      mdc.put(Logging.PREFIX_KEY, LOG4J_CATEGORY);

      // Load up some properties

      File config = null;
      try {
        config = ConfigFileConstants.getFile(ConfigFileConstants.XMPP_CONFIG_FILE_NAME);
      } catch (IOException e) {
        LOG.warn("{} not readable", ConfigFileConstants.XMPP_CONFIG_FILE_NAME, e);
      }
      if (Boolean.getBoolean("useSystemXMPPConfig") || !config.canRead()) {
        this.props.putAll(System.getProperties());
      } else {
        FileInputStream fis = null;
        try {
          fis = new FileInputStream(config);
          this.props.load(fis);
        } catch (FileNotFoundException e) {
          LOG.warn("unable to load {}", config, e);
        } catch (IOException e) {
          LOG.warn("unable to load {}", config, e);
        } finally {
          IOUtils.closeQuietly(fis);
        }
      }

      xmppServer = this.props.getProperty("xmpp.server");
      String xmppServiceName = this.props.getProperty("xmpp.servicename", xmppServer);
      xmppUser = this.props.getProperty("xmpp.user");
      xmppPassword = this.props.getProperty("xmpp.pass");
      xmppPort = Integer.valueOf(this.props.getProperty("xmpp.port", XMPP_PORT));

      ConnectionConfiguration xmppConfig =
          new ConnectionConfiguration(xmppServer, xmppPort, xmppServiceName);

      boolean debuggerEnabled = Boolean.parseBoolean(props.getProperty("xmpp.debuggerEnabled"));
      xmppConfig.setDebuggerEnabled(debuggerEnabled);

      xmppConfig.setSASLAuthenticationEnabled(
          Boolean.parseBoolean(props.getProperty("xmpp.SASLEnabled", "true")));
      xmppConfig.setSelfSignedCertificateEnabled(
          Boolean.parseBoolean(props.getProperty("xmpp.selfSignedCertificateEnabled")));

      if (Boolean.parseBoolean(props.getProperty("xmpp.TLSEnabled"))) {
        xmppConfig.setSecurityMode(SecurityMode.enabled);
      } else {
        xmppConfig.setSecurityMode(SecurityMode.disabled);
      }
      if (this.props.containsKey("xmpp.truststorePassword")) {
        xmppConfig.setTruststorePassword(this.props.getProperty("xmpp.truststorePassword"));
      } else {
        xmppConfig.setTruststorePassword(TRUST_STORE_PASSWORD);
      }

      LOG.debug("XMPP Manager connection config: {}", xmppConfig.toString());

      xmpp = new XMPPConnection(xmppConfig);

      // Connect to xmpp server
      connectToServer();
    } finally {
      Logging.setContextMap(mdc);
    }
  }
Exemplo n.º 9
0
  private void generateData(
      final String categoryName,
      final Report report,
      final String format,
      final String monthFormat,
      final Date periodEndDate)
      throws IOException, MarshalException, ValidationException, Exception {

    Logging.withPrefix(
        LOG4J_CATEGORY,
        new Callable<Void>() {

          @Override
          public Void call() throws Exception {
            LOG.debug("Inside AvailabilityData");

            m_nodes = new ArrayList<Node>();

            initializeInterval(periodEndDate);

            Catinfo config = null;
            try {
              CategoryFactory.init();
              m_catFactory = CategoryFactory.getInstance();
              config = m_catFactory.getConfig();
            } catch (IOException e) {
              LOG.error("Initializing CategoryFactory", e);
              throw e;
            } catch (MarshalException e) {
              LOG.error("Initializing CategoryFactory", e);
              throw e;
            } catch (ValidationException e) {
              LOG.error("Initializing CategoryFactory", e);
              throw e;
            }

            // FIXME There's some magic in here regarding multiple categories in a report

            LOG.debug("CATEGORY {}", categoryName);

            m_catFactory.getReadLock().lock();
            try {
              if (categoryName.equals("") || categoryName.equals("all")) {
                int catCount = 0;
                LOG.debug("catCount {}", catCount);

                for (final Categorygroup cg : config.getCategorygroupCollection()) {

                  for (org.opennms.netmgt.config.categories.Category cat :
                      cg.getCategories().getCategoryCollection()) {

                    LOG.debug("CATEGORY {}", cat.getLabel());
                    catCount++;
                    populateDataStructures(cat, report, format, monthFormat, catCount);
                  }
                }
                LOG.debug("catCount {}", catCount);
              } else {
                org.opennms.netmgt.config.categories.Category cat =
                    (org.opennms.netmgt.config.categories.Category)
                        m_catFactory.getCategory(categoryName);
                LOG.debug("CATEGORY - now populating data structures {}", cat.getLabel());
                populateDataStructures(cat, report, format, monthFormat, 1);
              }

              final SimpleDateFormat simplePeriod = new SimpleDateFormat("MMMMMMMMMMM dd, yyyy");
              final String reportPeriod =
                  simplePeriod.format(new java.util.Date(m_startTime))
                      + " - "
                      + simplePeriod.format(new java.util.Date(m_endTime));
              Created created = report.getCreated();
              if (created == null) {
                created = new Created();
              }
              created.setPeriod(reportPeriod);
              report.setCreated(created);
            } finally {
              m_catFactory.getReadLock().unlock();
            }

            LOG.debug("After availCalculations");
            return null;
          }
        });
  }
  /** {@inheritDoc} */
  @Override
  public void runAndRender(
      final Map<String, Object> reportParms,
      final String reportId,
      final ReportFormat format,
      final OutputStream outputStream) {
    Logging.withPrefix(
        LOG4J_CATEGORY,
        new Runnable() {
          @Override
          public void run() {
            ByteArrayOutputStream out = null;
            BufferedOutputStream bout = null;

            try {
              out = new ByteArrayOutputStream();
              bout = new BufferedOutputStream(out);

              AvailabilityCalculator calculator;

              LOG.debug("running OpenNMS database report {}", reportId);

              if (m_configDao.getType(reportId).equalsIgnoreCase(CAL_TYPE)) {
                calculator = m_calendarCalculator;
                LOG.debug("Calendar report format selected");
              } else {
                calculator = m_classicCalculator;
                LOG.debug("Classic report format selected");
              }

              calculator.setCategoryName((String) reportParms.get("reportCategory"));

              LOG.debug(
                  "set availability calculator report category to: {}",
                  calculator.getCategoryName());

              calculator.setPeriodEndDate((Date) reportParms.get("endDate"));

              LOG.debug(
                  "set availability calculator end date to: {}", calculator.getPeriodEndDate());

              calculator.setLogoURL(m_configDao.getLogo(reportId));

              // have the calculator calculate everything to enable any of the
              // templates to work
              // This has changed since the last version
              // This will have some performance impact.

              calculator.setReportFormat("all");

              LOG.debug("Starting Availability Report Calculations");

              calculator.calculate();
              calculator.writeXML(bout);
              render(reportId, new ByteArrayInputStream(out.toByteArray()), format, outputStream);
              outputStream.flush();
            } catch (final Exception e) {
              LOG.warn("An error occurred while rendering report {}", reportId, e);
            } finally {
              IOUtils.closeQuietly(bout);
              IOUtils.closeQuietly(out);
            }
          }
        });
  }
Exemplo n.º 11
0
  /**
   * main
   *
   * @param argv an array of {@link java.lang.String} objects.
   */
  public static void main(String[] argv) {

    Logging.putPrefix(LOG4J_CATEGORY);

    Controller c = new Controller();

    for (int i = 0; i < argv.length; i++) {
      if (argv[i].equals("-h")) {
        System.out.println(
            "Usage: java org.opennms.netmgt.vmmgr.Controller " + "[<options>] <command>");
        System.out.println("Accepted options:");
        System.out.println(
            "        -t <timeout>    HTTP connection timeout in seconds.  Defaults to 30.");
        System.out.println("        -u <URL>        Alternate invoker URL.");
        System.out.println("        -v              Verbose mode.");
        System.out.println("");
        System.out.println("Accepted commands: start, stop, status");
        System.out.println("");
        System.out.println("The default invoker URL is: " + DEFAULT_INVOKER_URL);
        System.exit(0);
      } else if (argv[i].equals("-t")) {
        c.setHttpRequestReadTimeout(Integer.parseInt(argv[i + 1]) * 1000);
        i++;
      } else if (argv[i].equals("-v")) {
        c.setVerbose(true);
      } else if (argv[i].equals("-u")) {
        c.setInvokeUrl(argv[i + 1]);
        i++;
      } else if (i != (argv.length - 1)) {
        System.err.println(
            "Invalid command-line option: \"" + argv[i] + "\".  Use \"-h\" option for help.");
        System.exit(1);
      } else {
        break;
      }
    }

    if (argv.length == 0) {
      System.err.println("You must specify a command.  Use \"-h\"" + " option for help");
      System.exit(1);
    }

    c.setAuthenticator(c.createAuthenticatorUsingConfigCredentials());

    String command = argv[argv.length - 1];

    if ("start".equals(command)) {
      c.start();
    } else if ("stop".equals(command)) {
      System.exit(c.stop());
    } else if ("status".equals(command)) {
      System.exit(c.status());
    } else if ("check".equals(command)) {
      System.exit(c.check());
    } else if ("exit".equals(command)) {
      System.exit(c.exit());
    } else {
      System.err.println("Invalid command \"" + command + "\".");
      System.err.println("Use \"-h\" option for help.");
      System.exit(1);
    }
  }