예제 #1
0
 /**
  * The main method responsible for starting the coadunation base.
  *
  * @param args the command line arguments
  */
 public static void main() {
   try {
     String logFile = System.getProperty("Log.File");
     if (logFile.endsWith("properties")) {
       System.out.println("Initing the log file from properties.");
       PropertyConfigurator.configure(logFile);
     } else if (logFile.endsWith("xml")) {
       System.out.println("Initing the log file from xml.");
       DOMConfigurator.configure(logFile);
     } else {
       System.out.println("Using the basic configuration.");
       BasicConfigurator.configure();
     }
     System.out.println("Start");
     Runner runner = new Runner();
     ShutdownHook shutdownHook = new ShutdownHook();
     Runtime.getRuntime().addShutdownHook(shutdownHook);
     System.out.println("Core initialization complete");
     System.out.println("Waiting for deployment to complete");
     shutdownHook.monitor();
     runner.shutdown();
     shutdownHook.notifyOfCompletion();
     log.info("Shut down complete");
   } catch (Exception ex) {
     System.out.println("Failed to run the Coadunation base [" + ex.getMessage() + "]");
     ex.printStackTrace(System.out);
     System.exit(-1);
   }
 }
  static {
    String logfile = System.getProperty("gov.nih.nci.evs.browser.NCImlog4jProperties");
    System.out.println("NCIM Logger prop file = [" + logfile + "]");

    InputStream log4JConfig = null;
    try {
      log4JConfig = new FileInputStream(logfile);
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(log4JConfig);

      DOMConfigurator.configure(doc.getDocumentElement());
      isInit = true;
    } catch (ParserConfigurationException e) {
      System.out.println("*** Error: Failed to parse log4j configuration file!");
      e.printStackTrace();
    } catch (SAXException e) {
      System.out.println("*** SAX Error: Failed to parse log4j configuration file!");
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("*** IO Error: log4j configuration file!");
      e.printStackTrace();
    } finally {
      try {
        log4JConfig.close();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
예제 #3
0
  public void testDomConfigurator() throws Exception {

    // Configuration with configuration-file
    DOMConfigurator.configure("./src/org/apache/log4j/jdbcplus/examples/test/log4j_test.xml");

    this.doLogging();
  }
예제 #4
0
  @Test
  public void run01() {

    DOMConfigurator.configure("log4j.xml");

    Log.startTestCase("VerifyMenuLinks_01");

    Samples_Page SamplesPage = new Samples_Page(null);
    SamplesPage.getSamplesPage();

    Log.info("Page Title : " + Wrapper.getTitle("Samples - SPI"));
    Log.info("Page url : " + Wrapper.getURL());

    Icons_Page IconsPage = new Icons_Page(null);
    IconsPage.getIconsPage();

    Log.info("Page Title : " + Wrapper.getTitle("Icons - SPI"));
    Log.info("Page url : " + Wrapper.getURL());

    Iris_Page IrisPage = new Iris_Page(null);
    IrisPage.getIrisPage();

    Log.info("Page Title : " + Wrapper.getTitle("Sources - SPI"));
    Log.info("Page url : " + Wrapper.getURL());

    Home_Page homepage = new Home_Page(null);
    homepage.getHomePage();

    Log.info("Page Title : " + Wrapper.getTitle("SPI"));
    Log.info("Page url : " + Wrapper.getURL());

    Log.endTestCase("VerifyMenuLinks_01");
  }
예제 #5
0
  public void testAppenders() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4j.xml"));

    AsyncCoalescingStatisticsAppender appender =
        (AsyncCoalescingStatisticsAppender)
            Logger.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");

    // log from a bunch of threads
    TestLoggingThread[] testThreads = new TestLoggingThread[10];
    for (int i = 0; i < testThreads.length; i++) {
      testThreads[i] = new TestLoggingThread();
      testThreads[i].start();
    }

    for (TestLoggingThread testThread : testThreads) {
      testThread.join();
    }

    // close the output appender, which prevents us from returning until this method completes.
    appender.close();

    // simple verification ensures that the total number of logged messages is correct.
    // tagName  avg           min     max     std dev       count, which is group 1
    String regex = "tag\\d\\s*\\d+\\.\\d\\s*\\d+\\s*\\d+\\s*\\d+\\.\\d\\s*(\\d+)";
    Pattern statLinePattern = Pattern.compile(regex);
    Scanner scanner = new Scanner(new File("target/statisticsLog.log"));

    int totalCount = 0;
    while (scanner.findWithinHorizon(statLinePattern, 0) != null) {
      totalCount += Integer.parseInt(scanner.match().group(1));
    }
    assertEquals(testThreads.length * TestLoggingThread.STOP_WATCH_COUNT, totalCount);
  }
예제 #6
0
  // test for http://jira.codehaus.org/browse/PERFFORJ-22
  public void testFlushOnShutdown() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4j-shutdownbug.xml"));

    // make a bunch of logs, but not enough to go over the timeslice.
    for (int i = 0; i < 5; i++) {
      StopWatch stopWatch = new Log4JStopWatch("tag1");
      Thread.sleep(10 * i);
      stopWatch.stop();
    }

    // at this point none of the file appenders will have written anything because they haven't been
    // flushed
    assertEquals("", FileUtils.readFileToString(new File("target/stats-shutdownbug.log")));
    assertEquals("", FileUtils.readFileToString(new File("target/graphs-shutdownbug.log")));

    // now, to simulate shutdown, get the async appender and run the shutdown hook. We need to use
    // reflection
    // because the shutdown hook is private.
    AsyncCoalescingStatisticsAppender appender =
        (AsyncCoalescingStatisticsAppender)
            Logger.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");
    Field shutdownField = appender.getClass().getDeclaredField("shutdownHook");
    shutdownField.setAccessible(true);
    Thread shutdownHook = (Thread) shutdownField.get(appender);
    shutdownHook.run();

    // now there should be data in the files
    assertFalse("".equals(FileUtils.readFileToString(new File("target/stats-shutdownbug.log"))));
    assertFalse("".equals(FileUtils.readFileToString(new File("target/graphs-shutdownbug.log"))));
  }
예제 #7
0
  // http://jira.codehaus.org/browse/PERFFORJ-21
  public void testAppendersTimesliceOver() throws Exception {
    // need to do immediateflush on the fileappender since close will not be called
    DOMConfigurator.configure(getClass().getResource("log4j-timeslicebug.xml"));

    AsyncCoalescingStatisticsAppender appender =
        (AsyncCoalescingStatisticsAppender)
            Logger.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");

    // log from a bunch of threads
    TestLoggingThread[] testThreads = new TestLoggingThread[10];
    for (int i = 0; i < testThreads.length; i++) {
      testThreads[i] = new TestLoggingThread();
      testThreads[i].start();
    }

    for (TestLoggingThread testThread : testThreads) {
      testThread.join();
    }

    // we should see all the logging after waiting this long
    Thread.sleep(2 * appender.getTimeSlice());

    // simple verification ensures that the total number of logged messages is correct.
    // tagName  avg           min     max     std dev       count, which is group 1
    String regex = "tag\\d+\\s*\\d+\\.\\d\\s*\\d+\\s*\\d+\\s*\\d+\\.\\d\\s*(\\d+)";
    Pattern statLinePattern = Pattern.compile(regex);
    Scanner scanner = new Scanner(new File("target/statisticsLog-timeslicebug.log"));

    int totalCount = 0;
    while (scanner.findWithinHorizon(statLinePattern, 0) != null) {
      totalCount += Integer.parseInt(scanner.match().group(1));
    }
    assertEquals(testThreads.length * TestLoggingThread.STOP_WATCH_COUNT, totalCount);
  }
예제 #8
0
 /**
  * Initialize log4j logging using the Tolven appender specification.
  *
  * <p>Note: This method should <i>not</i> be called within an environment such as JBoss that has a
  * separate log4j configuration. In that case, the TolvenLogger will use the appender
  * configuration supplied by that environment.
  *
  * @param log4jConfiguration The name of the file containing the log4j configuration. If null, the
  *     a file named tolven-log4j.xml on the classpath will be used.
  * @param logFilename The name of the log file. This file will be created if it does not already
  *     exist. If null, a default file named <code>${user.dir}/tolven.log</code> will be used.
  */
 public static void initialize(String log4jConfiguration, String logFilename) {
   try {
     File logFile;
     if (logFilename != null) {
       logFile = new File(logFilename);
     } else {
       logFile = new File(DEFAULT_LOG_FILE);
     }
     System.setProperty(LOG_FILE_PROPERTY, logFile.getAbsolutePath());
     logFile.getParentFile().mkdirs();
     logFile.createNewFile();
     defaultInitialize();
     Logger.getRootLogger()
         .info(
             "Start log4j - Configuration: "
                 + log4jConfiguration
                 + ", logFileName: "
                 + logFile.getAbsolutePath());
     BasicConfigurator.resetConfiguration();
     URL configURL;
     try {
       configURL = new URL(log4jConfiguration);
     } catch (Exception e) {
       configURL = Loader.getResource(log4jConfiguration);
     }
     DOMConfigurator.configure(configURL);
   } catch (Exception e) {
     throw new RuntimeException(
         "Exception while initializing Tolven log4j. log4jConfiguration: "
             + log4jConfiguration
             + " logFilename: "
             + logFilename,
         e);
   }
 }
  @Override
  public void init(Map params, File configDir) throws DataProviderException {
    String logConfig = (String) params.get("log_config");
    if (logConfig != null) {
      File logConfigFile = new File(configDir, logConfig);
      String logRefresh = (String) params.get("log_config_refresh_seconds");
      if (logRefresh != null) {
        DOMConfigurator.configureAndWatch(
            logConfigFile.getAbsolutePath(), Integer.parseInt(logRefresh) * 1000);
      } else {
        DOMConfigurator.configure(logConfigFile.getAbsolutePath());
      }
    } // else the bridge to logback is expected

    logger = Logger.getLogger(Constants.LOGGER_CAT);

    logger.info("Adapter Logger start.");

    // Read the Adapter Set name, which is supplied by the Server as a parameter
    String adapterSetId = (String) params.get("adapters_conf.id");

    // Put a reference to this instance on a static map
    // to be read by the Metadata Adapter
    feedMap.put(adapterSetId, this);

    logger.info("DartDataAdapter ready");
  }
예제 #10
0
  public static void initCore() throws InitializationFailedException {
    java.security.Security.setProperty("networkaddress.cache.ttl", "0");
    if (System.getProperty("unicorn.home") == null) {
      try {
        URL frameworkDir = Framework.class.getResource("Framework.class");
        if (frameworkDir.getProtocol() != "jar") {
          File unicornHome = new File(frameworkDir.toURI());
          for (int i = 0; i < 6; i++) unicornHome = unicornHome.getParentFile();
          System.setProperty("unicorn.home", unicornHome.getAbsolutePath());
        }
      } catch (URISyntaxException e) {
        throw new InitializationFailedException(e.getMessage(), e);
      }
    }

    // Log4j initialization attempt
    URL log4jURL = Framework.class.getResource("/unicorn_log4j.xml");
    if (log4jURL != null) {
      DOMConfigurator.configure(log4jURL);
      logger.info("OK - Log4j successfully initialized");
      logger.debug("> Used log4j.xml file: " + log4jURL.toString());
    } else {
      logger.warn("Log4j config file \"log4j.xml\" could not be found in classpath.");
      logger.warn("Log4j will not be initialized");
    }
  }
예제 #11
0
  protected void setUp() throws Exception {
    if (!isConfigured()) {
      DOMConfigurator.configure("log4j.xml");
      iConfigured = true;
    }
    configProperties = new Properties();
    try {
      configProperties.load(
          TestBase.class.getClassLoader().getResourceAsStream("config.properties"));
    } catch (IOException e) {
      e.printStackTrace();
    }

    useRemote = Boolean.parseBoolean(configProperties.getProperty("use_remote"));

    bro = configProperties.getProperty("browser");
    chromeDriver = configProperties.getProperty("chromedriver");
    ieDriver = configProperties.getProperty("iedriver");

    if (useRemote) {
      File profileDir = new File(getClass().getResource("/seleniumProfile").getFile());
      FirefoxProfile profile = new FirefoxProfile(profileDir);
      DesiredCapabilities capabilities = DesiredCapabilities.firefox();
      capabilities.setCapability(FirefoxDriver.PROFILE, profile);
      capabilities.setCapability("binary", "/usr/bin/firefox");
      String remoteUrl = configProperties.getProperty("selenium_remote_url");
      driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
      ((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
    } else {
      if (bro.toLowerCase().equals("firefox")) {

        File profileDir = null;
        profileDir = new File(getClass().getResource("/seleniumProfile").getFile());
        FirefoxProfile profile = new FirefoxProfile(profileDir);
        driver = new FirefoxDriver(profile);
      }
      if (bro.toLowerCase().equals("chrome")) {
        System.setProperty("webdriver.chrome.driver", chromeDriver);
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.default_directory", "target");
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);
        caps.setCapability(ChromeOptions.CAPABILITY, options);
        driver = new ChromeDriver(caps);
      }
      if (bro.toLowerCase().equals("ie")) {
        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(
            InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        System.setProperty("webdriver.ie.driver", ieDriver);
        capabilities.setCapability("ignoreZoomSetting", true);
        capabilities.setCapability("nativeEvents", false);
        driver = new InternetExplorerDriver(capabilities);
      }
    }
    int timeout = Integer.parseInt(configProperties.getProperty("driver_timeout"));
    driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
  }
 static {
   try {
     DOMConfigurator.configure(PathUtils.getRealPath("classpath:log4j.xml"));
     CONFIGS.load(new FileInputStream(PathUtils.getRealPath("classpath:sstk.properties")));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
예제 #13
0
 /** Class constructor. Initialise variables: MaxHits = 3; similarityMinScore = 1.0; */
 public DBpediaLookup() {
   DOMConfigurator.configure("logger.xml");
   MaxHits = 3;
   similarityMinScore = 1.0;
   similartityAlgorithm = new Levenshtein();
   doubleCheckSimilarity = false;
   obligatoryClass = false;
 }
예제 #14
0
  public void testAsync() throws Exception {
    // Configuration with configuration-file
    DOMConfigurator.configure("./src/org/apache/log4j/jdbcplus/examples/test/log4j_async.xml");

    for (int i = 0; i < 1; i++) {
      this.doLogging();
    }
  }
 @BeforeClass
 public static void initH2() {
   try {
     DeleteDbFiles.execute("", "JPADroolsFlow", true);
     h2Server = Server.createTcpServer(new String[0]);
     h2Server.start();
   } catch (final SQLException e) {
     throw new RuntimeException("can't start h2 server db", e);
   }
   DOMConfigurator.configure(SingleSessionCommandServiceTest.class.getResource("/log4j.xml"));
 }
예제 #16
0
 /**
  * Initialize logs
  *
  * @since 5.4.2
  */
 public void initLogs() {
   File logFile = getLogConfFile();
   try {
     System.out.println("Try to configure logs with " + logFile);
     System.setProperty(org.nuxeo.common.Environment.NUXEO_LOG_DIR, getLogDir().getPath());
     DOMConfigurator.configure(logFile.toURI().toURL());
     log.info("Logs successfully configured.");
   } catch (MalformedURLException e) {
     log.error("Could not initialize logs with " + logFile, e);
   }
 }
 @BeforeClass
 public static void init() throws IOException {
   File propertyFile =
       new File("src/test/config/bes_media_file_log_batch_update_unittest.properties");
   FileInputStream in = new FileInputStream(propertyFile);
   properties = new Properties();
   properties.load(in);
   in.close();
   System.getProperties().put("log4j.defaultInitOverride", "true");
   DOMConfigurator.configure(properties.getProperty("log4j.config.file.path"));
 }
예제 #18
0
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		if (args.length < 2) {
			System.err
					.println("Usage: <program> -<input-method> [input-parameters] -<output-method> [output-parameters]");
		} else {
			DOMConfigurator.configure(DecathlonCalculator.class.getResource("log4j.xml"));
			DecathlonCalculator c = new DecathlonCalculator(args);
			c.process();
		}

	}
예제 #19
0
 static {
   ResourceBundle resourceBundle = null;
   try {
     String log4j = System.getProperty("log4j.configuration");
     DOMConfigurator.configure(log4j);
     System.out.println("->Logging configured (log4j.properties)");
   } catch (MissingResourceException e) {
     System.out.println("Missing resource : log4j.properties");
     System.out.println("Iris not started - see log file");
     System.exit(0);
   }
 }
예제 #20
0
파일: Main.java 프로젝트: cawka/DSMS_NBC
  public static void main(String[] args)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
    DOMConfigurator.configure("logger.xml");

    Configuration conf = new Configuration();
    conf.configure(new File("configuation.xml"));
    conf.getEngineDefaults().getThreading().setListenerDispatchPreserveOrder(false);

    conf.addEventTypeAutoName(Main.class.getPackage().getName());

    init(conf);

    EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(conf);
    String statement = "CREATE WINDOW trainSet.win:length(1000) as select * from InputTuple";
    epService.getEPAdministrator().createEPL(statement);

    statement = "INSERT INTO trainSet SELECT * FROM InputTuple";
    epService.getEPAdministrator().createEPL(statement);

    ////////// TASK 1. Performing Naive Bayes Classification over a data stream

    StreamClassifier classifier = new StreamClassifier(conf);
    classifier.verticalizeTuples(_fieldNames);
    EPStatement stmt = classifier.run(_fieldNames.length + 1);

    /////////// TASK 2. Periodically check quality of the classifier

    PeriodicChecker checker = new PeriodicChecker(conf, stmt);
    checker.run(
        "2 seconds", 100, 0.9); // every two seconds test last 100 tuples to satisfy threshold 0.7

    //////////

    _log.info("started");

    // emulate a continuous input
    AdapterInputSource adapterInputSource = new AdapterInputSource(new File("simulation.csv"));

    CSVInputAdapterSpec spec = new CSVInputAdapterSpec(adapterInputSource, "InputTuple");
    spec.setEventsPerSec(400);
    spec.setLooping(true);
    spec.setUsingEngineThread(true);

    (new CSVInputAdapter(epService, spec)).start();

    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    _log.info("stopped");
  }
예제 #21
0
  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
      String appPath = config.getServletContext().getRealPath("");
      // 是否为开发mode
      debug = "true".equals(config.getInitParameter("development"));
      // 读取log4j.xml配置文件
      DOMConfigurator.configure(appPath + "/WEB-INF/log4j.xml");

      logger.info("Starting JForum. Debug mode is " + debug);
      //
      ConfigLoader.startSystemglobals(appPath);
      // 启动缓存引擎
      ConfigLoader.startCacheEngine();

      // Configure the template engine
      Configuration templateCfg = new Configuration();
      templateCfg.setTemplateUpdateDelay(2);
      templateCfg.setSetting("number_format", "#");
      templateCfg.setSharedVariable("startupTime", new Long(new Date().getTime()));

      // Create the default template loader
      String defaultPath = SystemGlobals.getApplicationPath() + "/templates";
      FileTemplateLoader defaultLoader = new FileTemplateLoader(new File(defaultPath));

      String extraTemplatePath = SystemGlobals.getValue(ConfigKeys.FREEMARKER_EXTRA_TEMPLATE_PATH);

      if (StringUtils.isNotBlank(extraTemplatePath)) {
        // An extra template path is configured, we need a MultiTemplateLoader
        FileTemplateLoader extraLoader = new FileTemplateLoader(new File(extraTemplatePath));
        TemplateLoader[] loaders = new TemplateLoader[] {extraLoader, defaultLoader};
        MultiTemplateLoader multiLoader = new MultiTemplateLoader(loaders);
        templateCfg.setTemplateLoader(multiLoader);
      } else {
        // An extra template path is not configured, we only need the default loader
        templateCfg.setTemplateLoader(defaultLoader);
      }
      // 载入模块
      ModulesRepository.init(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR));

      this.loadConfigStuff();

      if (!this.debug) {
        templateCfg.setTemplateUpdateDelay(3600);
      }

      JForumExecutionContext.setTemplateConfig(templateCfg);
    } catch (Exception e) {
      throw new ForumStartupException("Error while starting JForum", e);
    }
  }
예제 #22
0
  public static void main(String[] args) {
    try {
      if ((new File(GUI.LOG_CONFIG_FILE)).exists()) {
        DOMConfigurator.configure(GUI.LOG_CONFIG_FILE);
      } else {
        DOMConfigurator.configure(GUI.class.getResource("/" + GUI.LOG_CONFIG_FILE));
      }
    } catch (AccessControlException e) {
      BasicConfigurator.configure();
    }

    if (args.length > 0) {
      /* Generate executable JAR */
      if (args.length != 2) {
        throw new RuntimeException("Usage: [input .csc] [output .jar]");
      }
      generate(new File(args[0]), new File(args[1]));
    } else {
      /* Run simulation */
      execute();
    }
  }
  public GeorchestraConfiguration(String context) {

    this.contextName = context;
    globalDatadir = System.getProperty("georchestra.datadir");
    if (globalDatadir != null) {
      contextDataDir =
          new File(
                  String.format("%s%s%s%s", globalDatadir, File.separator, context, File.separator))
              .getAbsolutePath();

      // Simple check that the path exists
      if (new File(contextDataDir).exists() == false) {
        contextDataDir = null;
        return;
      }
      // loads the application context property file
      FileInputStream propsFis = null;
      try {
        try {
          // application-context
          propsFis = new FileInputStream(new File(contextDataDir, context + ".properties"));
          InputStreamReader isr = new InputStreamReader(propsFis, "UTF8");
          applicationSpecificProperties.load(isr);
        } finally {
          if (propsFis != null) {
            propsFis.close();
          }
        }
      } catch (Exception e) {
        activated = false;
        return;
      }

      // log4j configuration
      File log4jProperties =
          new File(contextDataDir, "log4j" + File.separator + "log4j.properties");
      File log4jXml = new File(contextDataDir, "log4j" + File.separator + "log4j.xml");
      String log4jConfigurationFile = null;
      if (log4jProperties.exists()) {
        log4jConfigurationFile = log4jProperties.getAbsolutePath();
        PropertyConfigurator.configure(log4jConfigurationFile);
      } else if (log4jXml.exists()) {
        log4jConfigurationFile = log4jXml.getAbsolutePath();
        DOMConfigurator.configure(log4jConfigurationFile);
      }
      // everything went well
      activated = true;
    }
  }
예제 #24
0
  public void testCsvRenderer() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4jWCsv.xml"));

    Logger logger = Logger.getLogger("org.perf4j.CsvAppenderTest");

    for (int i = 0; i < 20; i++) {
      StopWatch stopWatch = new Log4JStopWatch(logger);
      Thread.sleep(i * 10);
      stopWatch.stop("csvTest");
    }

    // close the appender
    logger.getAppender("coalescingStatistics").close();

    // verify the statisticsLog.csv file
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (Object line : FileUtils.readLines(new File("./target/statisticsLog.csv"))) {
      String[] values = line.toString().split(",");
      // first column is the tag
      assertEquals("\"csvTest\"", values[0]);
      // next 2 columns are the dates - ensure they can be parsed
      assertTrue(dateFormat.parse(values[1]).before(dateFormat.parse(values[2])));
      // next 3 columns are mean, min and max
      double mean = Double.parseDouble(values[3]);
      int min = Integer.parseInt(values[4]);
      int max = Integer.parseInt(values[5]);
      assertTrue(mean >= min && mean <= max);
      // next column is stddev - ust make sure it's parseable
      Double.parseDouble(values[6]);
      // next column is count
      assertTrue(Integer.parseInt(values[7]) < 20);
      // final column is TPS - just make sure it's parseable
      Double.parseDouble(values[8]);
    }

    // verify the pivotedStatisticsLog.csv file
    for (Object line : FileUtils.readLines(new File("./target/pivotedStatisticsLog.csv"))) {
      String[] values = line.toString().split(",");
      // first 2 columns are the dates - ensure they can be parsed
      assertTrue(dateFormat.parse(values[0]).before(dateFormat.parse(values[1])));
      // next column is mean, ensure it can be parsed
      Double.parseDouble(values[2]);
      // last column should be empty, so make sure last char on string is comma
      assertEquals(',', line.toString().charAt(line.toString().length() - 1));
    }
  }
  @BeforeClass
  public void setUp() throws Exception {

    // Configuring Log4j logs.
    new BaseClass();
    DOMConfigurator.configure(BaseClass.bLog);
    // Setting Excel File -- Test Data xls File
    ExcelUtils.setExcelFile(
        Constant.Path_TestData + Constant.File_TestData, Constant.File_TestappNameSheet);
    // Getting the Test Case name, as it will going to use in so many places
    // The main use is to get the TestCase row from the Test Data Excel sheet
    sTestCaseName = this.toString();
    Log.info(sTestCaseName);
    sTestCaseName = Utils.getTestCaseName(this.toString());
    Log.info(sTestCaseName);
    Log.startTestCase(sTestCaseName);
    testStep = new HelperFunction();
  }
예제 #26
0
  static {
    if (System.getProperty("cst.home") != null) {
      baseDir = System.getProperty("cst.home");
    } else {
      baseDir = System.getProperty("CST_HOME");
    }

    if (baseDir == null) {
      throw new ToolsStartException("CST_HOME not set");
    }

    logFile = baseDir + File.separator + CONFIGURATION + File.separator + TOOLS_LOG4J;
    if (!(new File(logFile).exists())) {
      throw new ToolsStartException(logFile + " doesn't exists");
    }

    toolsConf = baseDir + File.separator + CONFIGURATION + File.separator + CORE_CONF;
    if (!(new File(toolsConf).exists())) {
      throw new ToolsStartException(toolsConf + " doesn't exists");
    }

    outDir = baseDir + File.separator + OUT;
    if (!(new File(outDir).exists())) {
      new File(outDir).mkdir();
    }

    inputDir = baseDir + File.separator + INPUT;
    if (!(new File(inputDir).exists())) {
      throw new ToolsStartException(inputDir + " doesn't exists");
    }

    logDir = baseDir + File.separator + LOG;
    if (!(new File(logDir).exists())) {
      new File(logDir).mkdir();
    }

    System.setProperty(baseDirProps, baseDir);
    System.setProperty(inputDirProps, inputDir);
    System.setProperty(outDirProps, outDir);
    System.setProperty(logDirProps, logDir);

    DOMConfigurator.configure(logFile);
  }
 @Test
 public void categoriesMensPage() {
   DOMConfigurator.configure("log4j.xml");
   test = reportMens.startTest("CATEGORIES MENS PAGE");
   test.assignAuthor("Masihur");
   abercrombie().advertisement().clickCloseAdd();
   log.info("Advertisement Closed");
   test.log(LogStatus.INFO, "CLOSE ADVERTISEMENT", "Click to Close Advertisement");
   abercrombie().pageHeader().mensPageLink();
   log.info("Click Mens Page Link");
   test.log(LogStatus.INFO, "MENS PAGE LINK FUNCTIONALITY", "Click the Mens Page Link");
   abercrombie().mensPage().categoryMensPage();
   log.info("Ctegories of Mens Page");
   test.log(
       LogStatus.INFO, "MENS PAGE CATEGORIES", "Verify all the Categories in Mens Page Present");
   RenameFile.toBeRenamed.add(
       "TestVideos/MP_CategoriesMensPage " + dateFormat.format(new Date()) + ".avi");
   reportMens.endTest(test);
   reportMens.flush();
 }
예제 #28
0
파일: Main.java 프로젝트: kevx/csp
  /** @param args */
  public static void main(String[] args) {

    DOMConfigurator.configure("time_log4j.xml");

    if (args == null || args.length == 0) {
      System.out.println("请输入分组标记");
      System.exit(-1);
    }
    String mc = args[0];
    //		String mc = "CM3";
    final GroupMaker maker = new GroupMaker(mc);

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                maker.stop();
              }
            });
    maker.startup();
  }
예제 #29
0
  /**
   * Loads the configuration from the specified url location. A DOM configuration will be triggered
   * if the url ends with ".xml".
   *
   * @param url the url of the configuration source.
   * @throws Exception if the operation is unsuccessful.
   * @see hk.hku.cecid.piazza.commons.module.PersistentComponent#loading(java.net.URL)
   */
  protected void loading(URL url) throws Exception {
    if (url.getPath().toLowerCase().endsWith(".xml")) {
      Properties params = getParameters();
      if (params != null) {
        String checkConfig = params.getProperty("checkConfig");

        if (checkConfig != null) {
          if (checkConfig.equals("true")) {

            SAXReader xmlReader = new SAXReader();
            xmlReader.setEntityResolver(
                new EntityResolver() {
                  public InputSource resolveEntity(String publicId, String systemId)
                      throws SAXException, IOException {
                    return new InputSource(new ByteArrayInputStream(new byte[0]));
                  }
                });
            org.dom4j.Document doc = xmlReader.read(url);
            Node node = doc.selectSingleNode("/*[local-name()='configuration']/category/priority");
            String priority = node.valueOf("@value");
            if (!chechPriorityString(priority)) {
              throw new UtilitiesException(
                  "Log4j does not support the value for priority - " + priority);
            }

            // Node node2 = doc.selectSingleNode("/*[local-name()='configuration']/root/priority");
            String priority2 = node.valueOf("@value");
            if (!chechPriorityString(priority2)) {
              throw new UtilitiesException(
                  "Log4j does not support the value for priority - " + priority2);
            }
          }
        }
      }

      DOMConfigurator.configure(url);
    } else {
      PropertyConfigurator.configure(url);
    }
  }
예제 #30
0
  public static URL configure() {
    final String log4jConfig = System.getProperty("log4j.configuration");

    if (log4jConfig != null) {
      // Log4j environment variable found, the LogManager will take care of
      // itself, don't bother reinitializing

      // This is what the LogManager does to find the resource.

      URL configUrl = null;
      try {
        configUrl = new URL(log4jConfig);
      } catch (MalformedURLException mue) {
        configUrl = Loader.getResource(log4jConfig);
      }

      Preconditions.checkState(configUrl != null, "Invalid config URL: %s", log4jConfig);

      return configUrl;
    }

    for (final String logFile : DEFAULT_LOG_FILES) {
      final URL configUrl = Log4jConfigurator.class.getResource(logFile);
      if (configUrl != null) {
        LogManager.resetConfiguration();
        DOMConfigurator.configure(configUrl);

        final Log log = Log.findLog();
        log.info("Configured logging from '%s'", configUrl);
        return configUrl;
      }
    }

    BasicConfigurator.configure();
    final Log log = Log.findLog();
    log.warn("No logging configuration, falling back to default!");

    return null;
  }