예제 #1
0
  /** @see HttpServlet#HttpServlet() */
  @Override
  public void init(ServletConfig config) throws ServletException {

    String log4jLocation = config.getInitParameter("log4j-properties-location");

    ServletContext sc = config.getServletContext();

    if (log4jLocation == null) {

      BasicConfigurator.configure();
    } else {
      String webAppPath = sc.getRealPath("/");
      String log4jProp = webAppPath + log4jLocation;
      File output = new File(log4jProp);

      if (output.exists()) {

        PropertyConfigurator.configure(log4jProp);
      } else {

        BasicConfigurator.configure();
      }
    }

    super.init(config);
  }
예제 #2
0
  public static void main(String[] args) throws IOException, InterruptedException {
    BasicConfigurator.resetConfiguration();
    BasicConfigurator.configure();

    NioInvokerServerExample.main(args);
    Thread.sleep(200);
    NioInvokerClientExample.main(args);
  }
  public void init(ServletConfig config) throws ServletException {
    System.out.println("CabServer Log4JInitServlet is initializing log4j");
    String log4jLocation = config.getInitParameter("log4j-properties-location");

    ServletContext sc = config.getServletContext();

    if (log4jLocation == null) {
      System.err.println(
          "*** CabServer No log4j-properties-location init param, "
              + "so initializing log4j with BasicConfigurator");
      BasicConfigurator.configure();
    } else {
      String webAppPath = sc.getRealPath("/");
      String log4jProp = webAppPath + log4jLocation;
      File yoMamaYesThisSaysYoMama = new File(log4jProp);
      if (yoMamaYesThisSaysYoMama.exists()) {
        System.out.println("CabServer Initializing log4j with: " + log4jProp);
        PropertyConfigurator.configure(log4jProp);
      } else {
        System.err.println(
            "*** CabServer "
                + log4jProp
                + " file not found, so "
                + "initializing log4j with BasicConfigurator");
        BasicConfigurator.configure();
      }
    }
    super.init(config);

    String constantsLocation = config.getInitParameter("constants-properties-location");

    try {

      Properties props = new Properties();
      InputStream stream = sc.getResourceAsStream(constantsLocation);
      props.load(stream);
      stream.close();

      Iterator keyIterator = props.keySet().iterator();
      while (keyIterator.hasNext()) {
        String key = (String) keyIterator.next();
        String value = (String) props.getProperty(key);
        // System.out.println("key:" + key + " value: " + value);
        ConfigDetails.constants.put(key, value);
      }

      Iterator it = ConfigDetails.constants.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry) it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #4
0
 public Mary4To5VoiceConverter(List<VoiceComponentDescription> voiceDescriptions, File voiceZip) {
   voiceDescription = null;
   mary4Zip = voiceZip;
   for (VoiceComponentDescription d : voiceDescriptions) {
     if (d.getPackageFilename().equals(mary4Zip.getName())) {
       voiceDescription = d;
       break;
     }
   }
   if (voiceDescription == null) {
     throw new IllegalArgumentException(
         "No matching voice description for file " + mary4Zip.getName());
   }
   if (!MaryUtils.isLog4jConfigured()) {
     BasicConfigurator.configure();
   }
   logger = Logger.getLogger(this.getClass());
   logger.info(
       voiceDescription.getName()
           + " "
           + voiceDescription.getVersion()
           + " ("
           + voiceDescription.getLocale()
           + " "
           + voiceDescription.getGender()
           + ")");
 }
예제 #5
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);
   }
 }
예제 #6
0
 private void initLogger(ServletConfig config) {
   final String log4jconfig = config.getInitParameter("log4j-properties-location");
   ServletContext context = config.getServletContext();
   if (log4jconfig == null) {
     BasicConfigurator.configure();
   } else {
     String appPath = context.getRealPath("/");
     String log4jpath = appPath + log4jconfig;
     if (new File(log4jpath).exists()) {
       PropertyConfigurator.configure(log4jpath);
       log = Logger.getLogger(this.getClass().getName());
     } else {
       BasicConfigurator.configure();
     }
   }
 }
예제 #7
0
  // This function  will set the request status in the "userrequest" table
  public Boolean setStatus(String status, int requestId) {

    BasicConfigurator.configure();
    logger.info("Entered setStatus method of ChangeRequestStatusDAO");
    Boolean isStatusCommit = false;
    int result = 0;
    conn = Util.connect();
    String query = "UPDATE userrequest  SET STATUS=? WHERE REQUEST_ID = ?";
    try {
      PreparedStatement pstmt = conn.prepareStatement(query);
      pstmt.setString(1, status);
      pstmt.setInt(2, requestId);
      result = pstmt.executeUpdate();
      if (result > 0) {
        conn.commit();
        isStatusCommit = true;
      }
      logger.info("Exit setBookASessionDetails method of BookASessionDAO");
    } catch (SQLException e) {
      logger.error(
          "setBookASessionDetails method of BookASessionDAO threw error:" + e.getMessage());
      e.printStackTrace();
    } finally {
      try {
        conn.close();
      } catch (SQLException e) {
        logger.error(
            "setBookASessionDetails method of BookASessionDAO threw error:" + e.getMessage());
        e.printStackTrace();
      }
    }
    return isStatusCommit;
  }
예제 #8
0
  @BeforeClass
  public static void oneTimeSetup() {
    // Format logger output
    BasicConfigurator.configure();
    ((PatternLayout)
            ((Appender) Logger.getRootLogger().getAllAppenders().nextElement()).getLayout())
        .setConversionPattern("[%30.30t] %-30.30c{1} %-5p %m%n");

    Logger.getRootLogger().setLevel(Level.INFO);

    // To add appender that logs to a log file in addition to Console
    //        Layout layout = (PatternLayout)((Appender)
    // Logger.getRootLogger().getAllAppenders().nextElement()).getLayout();
    //        FileAppender appender;
    //        try
    //        {
    //            appender = new FileAppender(layout, "test.log", true);
    //            Logger.getRootLogger().addAppender(appender);
    //        }
    //        catch (IOException e)
    //        {
    //            // TODO Auto-generated catch block
    //            e.printStackTrace();
    //        }
  }
예제 #9
0
  public static void main(String[] args) throws Exception {

    BasicConfigurator.configure();

    String username = "******";

    final String TWITTER_OAUTH_KEY = "";
    final String TWITTER_OAUTH_SECRET = "";
    final String ACCESS_TOKEN = "";
    final String ACCESS_TOKEN_SECRET = "";

    OAuthSignpostClient oauth =
        new OAuthSignpostClient(
            TWITTER_OAUTH_KEY, TWITTER_OAUTH_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    TwitterClient twitter = new TwitterClient(username, oauth);

    Connection conn =
        DriverManager.getConnection("jdbc:postgresql://juergenbickert.de:5432/smsd?user=smsd");
    conn.setAutoCommit(false);
    conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

    SmsProvider smsProvider = new SmsProvider(conn);

    TwitterTask task = new TwitterTask(twitter, smsProvider);
    task.setAppend(" #tmn12");

    ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);

    pool.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS);
  }
예제 #10
0
  public static void main(String[] args) throws FileNotFoundException {
    BasicConfigurator.configure();
    Logger.getRootLogger().setLevel(Level.WARN);

    Mib2Events convertor = new Mib2Events();

    convertor.parseCli(args);
    try {
      convertor.convert();
    } catch (FileNotFoundException e) {
      printError(convertor.getMibLocation(), e);
      System.exit(1);
    } catch (IOException e) {
      printError(convertor.getMibLocation(), e);
    } catch (MibLoaderException e) {
      e.getLog().printTo(System.err);
      System.exit(1);
    }

    if (convertor.getMib().getLog().warningCount() > 0) {
      convertor.getMib().getLog().printTo(System.err);
    }

    PrintStream out = System.out;
    out.println(
        "<!-- Start of auto generated data from MIB: " + convertor.getMib().getName() + " -->");
    try {
      convertor.printEvents(out);
    } catch (Throwable e) {
      printError(convertor.getMibLocation(), e);
      System.exit(1);
    }
    out.println(
        "<!-- End of auto generated data from MIB: " + convertor.getMib().getName() + " -->");
  }
예제 #11
0
  public static void main(String[] args) throws IOException, UIMAException, SimilarityException {
    /** Setup logger */
    org.apache.log4j.BasicConfigurator.configure();

    /** Run the code for the English tasks */
    new CommentwiseSimilarity().runForEnglish();
  }
예제 #12
0
 /** Loads the configuration for log4j from the file log4j.properties */
 public void configureLogging() {
   // BasicConfigurator is used to quickly configure the package log4j
   // Add a ConsoleAppender that uses PatternLayout using the
   // PatternLayout.TTCC_CONVERSION_PATTERN
   // and prints to System.out to the root category.
   BasicConfigurator.configure();
   // Configure log4j by the url : log4j.properties.
   String fileName = "log4j_" + Configuration.instance().getLogLevel() + ".properties";
   System.out.println("Loading logging configuration file: " + fileName);
   URL url = Main.class.getResource(fileName);
   if (url == null) {
     System.out.println(
         "Logging configuration file not found - loading file: log4j_off.properties");
     url = Main.class.getResource("log4j_off.properties"); // $NON-NLS-1$
     if (url == null) {
       System.err.println("No logging configuration found");
       return;
     }
   }
   // PropertyConfigurator allows the configuration of log4j from an
   // external file
   // It will read configuration options from URL url.
   PropertyConfigurator.configure(url);
   LOG = Logger.getLogger(Configuration.class);
 }
예제 #13
0
파일: Main.java 프로젝트: nologic/nabs
  public static void main(String[] argv) throws Exception {
    Layout layout = new PatternLayout("%d{HH:mm:ss} %-5p: %m%n");
    appender = new EunomiaAppender(layout, System.out);
    BasicConfigurator.configure(appender);
    logger = Logger.getLogger(Main.class);

    try {
      Config.setGlobalName("receptor");
    } catch (Exception e) {
      logger.error("Unable to open configurations database: " + e.getMessage());
      logger.error("\tIs there another instance already running?");
      System.exit(1);
    }

    logger.info("Start up");

    String startScript = "init.esh";
    if (argv.length > 0) {
      startScript = argv[0];
    }

    // Execute Start up script.
    runStartupScript(new File(startScript));

    try {
      ModuleHandle handle = ModuleManager.v().startModule_PROC("streamStatus");
      if (handle != null) {
        StateManager.v().addGlobalInstance(handle);
        ModuleManager.v().addDefaultConnect(handle);
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("Unable to load streamStatus module");
    }
  }
예제 #14
0
  public void testOmittedJudge() throws IOException, ScoreException {
    final String config =
        "sessionTitle: noManipTarget\n"
            + "rounds: 3\n"
            + "timeLimit: 5\n"
            + "roles: trader, manipulator\n"
            + "players: trader1, manip1, judge1\n"
            + "trader1.role: trader\n"
            + "manip1.role: manipulator\n"
            + "manip1.target: 60\n"
            + "initialHint: Trading has not started yet.\n"
            + "actualValue: 50, 50, 50\n"
            + "endowment.trader: 200\n"
            + "endowment.manipulator: 200\n"
            + "tickets.trader: 30\n"
            + "tickets.manipulator: 30\n"
            + "scoringFactor.manipulator: 0\n"
            + "scoringConstant.manipulator: 0\n";

    StringWriter stringWriter = new StringWriter();
    WriterAppender appender =
        new WriterAppender(
            new PatternLayout("%d{yyyy/MM/dd hh:mm:ss} %6p - %12c{1} - %m\n"), stringWriter);
    BasicConfigurator.configure(appender);

    setupSession(config);
    assertREMatches(".*ERROR.*", stringWriter.toString());
    assertMatches("Judge role required if manipulators are used.", session.getErrorMessage());
  }
예제 #15
0
 public static void initLogger() {
   if (!isLoggerInitialized) {
     BasicConfigurator.configure();
     Logger.getRootLogger().setLevel(Level.INFO);
     isLoggerInitialized = true;
   }
 }
예제 #16
0
  public static void main(String a[]) throws Exception {
    BasicConfigurator.configure();
    ICommentService service = CommentServiceFactory.getCommentService();

    /*
    Comment tmp = service.getComment(42590);
    System.out.println(tmp);
    System.out.println(tmp.getText());
    System.out.println(tmp.getText().indexOf("href="));
    System.out.println(isBlacklisted(tmp.getText()));*/
    /// *
    List<Comment> comments = service.getComments();

    System.out.println("Got " + comments.size() + " comments to check");
    int bots = 0;
    List<Integer> toDelete = new ArrayList<Integer>();
    for (Comment c : comments) {
      boolean bot = AntispamUtil.detectBot(c);
      if (bot) {
        bots++;
        System.out.println(c);
        toDelete.add(c.getId());
      }
    }
    service.deleteComments(toDelete);
    System.out.println("Detected " + bots + " bot comments");
    // */
  }
  @Test
  public void duplicateRecord() throws Exception {

    BasicConfigurator.configure();

    /*ObjectId id = null;

    Registration registration = new Registration();
    registration.setId(new ObjectId());
    registration.setOrgName("UniqueNotion");
    registration.setOrgPrefix("UN");
    registration.setEmail("*****@*****.**");
    registration.setContact("+31647608916");
    registration.setCreatedBy("Parag2");
    registration.setCreateTimestamp(new Date());
    id = service.add(registration);
    registration = new Registration();
    registration.setId(new ObjectId());
    registration.setOrgName("UniqueNotion");
    registration.setOrgPrefix("UN");
    registration.setEmail("*****@*****.**");
    registration.setContact("+31647608916");
    registration.setCreatedBy("Parag2");
    registration.setCreateTimestamp(new Date());
    id = service.add(registration);
    logger.debug("log.id =" + id);

    registration = (Registration) service.get(id);
    logger.debug("registration = " + registration);*/
    // Assert.assertNull(registration);
  }
예제 #18
0
  /**
   * @param args
   * @throws HarnessException
   */
  public static void main(String[] args) throws HarnessException {

    // Configure log4j using the basic configuration
    BasicConfigurator.configure();

    // Use the pre-provisioned global admin account to send a basic request
    ZimbraAdminAccount.GlobalAdmin().soapSend("<GetVersionInfoRequest xmlns='urn:zimbraAdmin'/>");
    if (!ZimbraAdminAccount.GlobalAdmin().soapMatch("//admin:GetVersionInfoResponse", null, null))
      throw new HarnessException("GetVersionInfoRequest did not return GetVersionInfoResponse");

    // Create a new global admin account
    String domain =
        ZimbraSeleniumProperties.getStringProperty("server.host", "qa60.lab.zimbra.com");
    ZimbraAdminAccount admin =
        new ZimbraAdminAccount("admin" + System.currentTimeMillis() + "@" + domain);
    admin.provision(); // Create the account (CreateAccountRequest)
    admin.authenticate(); // Authenticate the account (AuthRequest)

    // Send a basic request as the new admin account
    admin.soapSend("<GetServiceStatusRequest xmlns='urn:zimbraAdmin'/>");
    if (!admin.soapMatch("//admin:GetServiceStatusResponse", null, null))
      throw new HarnessException("GetServiceStatusRequest did not return GetServiceStatusResponse");

    logger.info("Done!");
  }
  @Test
  public void appenderStoresMessages() {
    MemoryAppender appender = new MemoryAppender();
    BasicConfigurator.configure(appender);

    Logger logger = Logger.getLogger(TEST_CATEGORY);
    logger.setLevel(Level.ERROR);

    logger.error(TEST_MESSAGE);

    LinkedList<LoggingEvent> events = appender.getEvents();
    assertEquals(1, events.size());

    LoggingEvent event = events.getFirst();
    assertEquals(Level.ERROR, event.getLevel());
    assertEquals(TEST_CATEGORY, event.getLoggerName());
    assertEquals(TEST_MESSAGE, event.getMessage());
    assertEquals(TEST_LOCATION, event.getLocationInformation().getClassName());

    appender.clear();
    assertEquals(0, events.size());

    logger.error(TEST_MESSAGE);
    assertEquals(1, appender.getEvents().size());
  }
예제 #20
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);
   }
 }
  /** @param args */
  public static void main(String[] args) throws Exception {
    BasicConfigurator.configure();
    Logger.getLogger("org.eclipse.emf.teneo").setLevel(Level.INFO);
    Logger.getLogger("org.hibernate").setLevel(Level.WARN);

    DatabaseSetupData setupData = new DatabaseSetupData();

    if (args != null && args.length > 0) {
      setupData.setSchemaFileName(args[0]);
      if (args.length > 1) {
        setupData.setDatabaseName(args[1]);
      }
    }

    if (!DatabaseSetupUtil.testServerConnection(setupData)) {
      throw new RuntimeException("Unable to connect to running server");
    }

    if (DatabaseSetupUtil.checkDatabaseExists(setupData)) {
      throw new RuntimeException("Database: '" + setupData.getDatabaseName() + "' exists!");
    }

    // documentation
    DatabaseSetupUtil.generateSchemaFile(setupData);
    DatabaseSetupUtil.generateHibernateMapping(setupData);

    // create live database
    DatabaseSetupUtil.createDatabase(setupData);

    // create seed data and initial dairy record
    DatabaseSetupUtil setupUtil = new DatabaseSetupUtil(setupData);
    setupUtil.intializeDairyDatabase("registration #", "licensee name");
  }
  public WarehouseReportPDF(ReportGateway gw) {
    super(gw);

    BasicConfigurator.configure();

    doc = null;
  }
예제 #23
0
  public void testMissingPlayer() throws IOException, ScoreException {
    final String config =
        "sessionTitle: noManipTarget\n"
            + "rounds: 3\n"
            + "timeLimit: 5\n"
            + "roles: traderA, traderB\n"
            + "players: trader1, trader2, trader3\n"
            + "trader1.role: traderA\n"
            +
            //                "trader2.role: traderB\n" +
            "trader3.role: traderA\n"
            + "initialHint: Trading has not started yet.\n"
            + "actualValue: 50, 50, 50\n"
            + "endowment.traderA: 200\n"
            + "endowment.traderB: 300\n"
            + "tickets.traderA: 10\n"
            + "tickets.traderB: 20\n";

    StringWriter stringWriter = new StringWriter();
    WriterAppender appender =
        new WriterAppender(
            new PatternLayout("%d{yyyy/MM/dd hh:mm:ss} %6p - %12c{1} - %m\n"), stringWriter);
    BasicConfigurator.configure(appender);

    setupSession(config);
    assertREMatches(".*ERROR.*", stringWriter.toString());
    assertMatches("player 'trader2' has no assigned Role.", session.getErrorMessage());

    session.startNextRound();
    Trader trader3 = (Trader) session.getPlayer("trader3");
    assertNotNull(trader3);
  }
예제 #24
0
  private void loadParameter(Element elem) {
    logger.info("loadParameter: fileName=" + elem.getAttributeValue("file"));
    String parameterFile = elem.getAttributeValue("file");
    String absolutePath = getAbsolutePath(parameterFile);
    BasicConfigurator.configure();

    try {
      InputStream in = new FileInputStream(absolutePath);
      Properties parameter = new Properties();
      parameter.load(in);
      in.close();

      Set<Entry<Object, Object>> entrySet = parameter.entrySet();

      for (Map.Entry entry : entrySet) {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        System.out.println(key + " = " + value);
        addParam(key, value);
      }
    } catch (Exception e) {
      logger.error("Can not load parameter . ");
    }

    String newStr =
        replaceParam(elem.getAttributeValue("src1")) + replaceParam(elem.getAttributeValue("src2"));
    addParam(elem.getAttributeValue("out"), newStr);
  }
예제 #25
0
 public static void testProject(File projectFile, ProjectRunnable pr) {
   IdeMain.setTestMode(TestMode.CORE_TEST);
   Logger.setThreshold("INFO");
   org.apache.log4j.BasicConfigurator.configure();
   TestMain.configureMPS();
   final Project project = loadProject(projectFile);
   pr.execute(project);
 }
 public void setUp() throws Exception {
   EtmManager.reset();
   BasicConfigurator.configure();
   filter = new HttpRequestPerformanceFilter();
   filter.init(null);
   etmMonitor = EtmManager.getEtmMonitor();
   etmMonitor.start();
 }
예제 #27
0
  @Before
  public void setUp() {
    Logger.getRootLogger().setLevel(Level.INFO);
    Logger.getLogger("org.springframework").setLevel(Level.WARN);
    BasicConfigurator.configure();

    userId = 1;
  }
  public static void main(String[] args) throws IOException, UIMAException, SimilarityException {
    /** Setup logger */
    org.apache.log4j.BasicConfigurator.configure();
    Logger.getRootLogger().setLevel(Level.INFO);

    /** Run the code for the English tasks */
    new CommentSelectionDatasetCreatorV2().runForEnglish();
  }
예제 #29
0
  @Test
  public void testLib() {

    BasicConfigurator.configure();
    Logger log = Logger.getLogger("Logger de Test");
    log.warn("un warning");
    log.error("un error");
    assertTrue("No funciona log4j BasicConfigurator", true);
  }
예제 #30
0
 @BeforeClass
 public void setUp() throws IOException {
   BasicConfigurator.configure();
   this.fs = FileSystem.getLocal(new Configuration());
   this.path = new Path("MRJobLockTest");
   if (!this.fs.exists(this.path)) {
     this.fs.mkdirs(this.path);
   }
 }