List of usage examples for java.util.logging ConsoleHandler ConsoleHandler
public ConsoleHandler()
From source file:org.rzo.yajsw.app.WrapperManagerImpl.java
public void init(String[] args, ClassLoader wrapperClassLoader) { /*//from w w w. j av a 2 s .c o m * System.out.println(Scheduler.class.getClassLoader()); * System.out.println(Configuration.class.getClassLoader()); * System.out.flush(); try { Thread.sleep(10000); } catch * (InterruptedException e1) { // TODO Auto-generated catch block * e1.printStackTrace(); } */ ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(wrapperClassLoader); instance = this; String outFile = System.getProperty("wrapper.teeName"); String outPath = System.getProperty("wrapper.tmpPath"); String vStr = System.getProperty("wrapper.console.visible"); boolean visible = vStr != null && vStr.equals("true"); if (outFile != null) { teeSystemStreams(outFile, outPath, visible); } logJavaInfo(args); String preScript = System.getProperty("wrapper.app.pre.script"); if (preScript != null & !"".equals(preScript)) { Logger logger = new MyLogger(); logger.addHandler(new ConsoleHandler()); Script script = ScriptFactory.createScript(preScript, "", null, new String[0], null); if (script != null) script.execute(); } YajswConfigurationImpl config = new YajswConfigurationImpl(); //config.setDebug(false); config.init(); try { _overrideStdErr = config.getBoolean("wrapper.java.dump.override", false); } catch (Exception ex) { System.out.println("Error getting wrapper.java.dump.override " + ex.getMessage()); } String mainClassName = config.getString("wrapper.java.app.mainclass"); String jarName = config.getString("wrapper.java.app.jar"); String groovyScript = config.getString("wrapper.groovy"); if (mainClassName == null && jarName == null && groovyScript == null) mainClassName = config.getString("wrapper.app.parameter.1"); if (jarName == null && mainClassName == null && groovyScript == null) { System.out.println("missing main class name or jar file or groovy file. please check configuration"); return; } if (jarName != null) { mainMethod = loadJar(jarName); } else if (mainClassName != null) try { Class cls = ClassLoader.getSystemClassLoader().loadClass(mainClassName);// Class.forName(mainClassName, // currentContext); mainMethod = cls.getDeclaredMethod("main", new Class[] { String[].class }); } catch (Exception e) { System.out.println("error finding main method in class: " + mainClassName + " : " + e.getMessage()); // log.throwing(WrapperMain.class.getName(), "main", e); e.printStackTrace(); return; } else _groovyScript = groovyScript; String stopConfig = config.getString("wrapper.stop.conf"); if (stopConfig != null) { File f = new File(stopConfig); _externalStop = true; } System.out.println("external stop " + _externalStop); exitOnMainTerminate = config.getInt("wrapper.exit_on_main_terminate", DEFAULT_EXIT_ON_MAIN_TERMINATE); exitOnException = config.getInt("wrapper.exit_on_main_exception", DEFAULT_EXIT_ON_MAIN_EXCEPTION); mainMethodArgs = getAppParam((Configuration) config); setConfiguration((Configuration) config); if (_config.getBoolean("wrapper.java.jmx", false)) registerMBean(config); String control = _config.getString("wrapper.control", DEFAULT_CONTROL); if ("TIGHT".equals(control) || "APPLICATION".equals(control)) _haltAppOnWrapper = true; Thread.currentThread().setContextClassLoader(currentClassLoader); setKey(_config.getString("wrapper.key")); // setDebug(true); setPort(_config.getInt("wrapper.port")); setPingInterval(_config.getInt("wrapper.ping.interval", Constants.DEFAULT_PING_INTERVAL)); _startupTimeout = _config.getInt("wrapper.startup.timeout", DEFAULT_STARTUP_TIMEOUT) * 1000; _debug = _config.getBoolean("wrapper.debug", false); }
From source file:majordodo.task.BrokerTestUtils.java
@Before public void brokerTestUtilsBefore() throws Exception { // Setup exception handler Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override//from w w w.j a v a 2s .co m public void uncaughtException(Thread t, Throwable e) { System.err.println("uncaughtException from thread " + t.getName() + ": " + e); e.printStackTrace(); unhandledExceptions.add(e); } }); // Setup Logger System.out.println("Setup logger to level " + logLevel.getName()); java.util.logging.LogManager.getLogManager().reset(); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(logLevel); ch.setFormatter(new Formatter() { @Override public String format(LogRecord record) { return "" + new java.sql.Timestamp(record.getMillis()) + " " + record.getLevel() + " [" + getThreadName(record.getThreadID()) + "<" + record.getThreadID() + ">] " + record.getLoggerName() + ": " + formatMessage(record) + "\n"; } }); java.util.logging.Logger.getLogger("").setLevel(logLevel); java.util.logging.Logger.getLogger("").addHandler(ch); // Initialize groupsMap groupsMap.clear(); groupsMap.put(userId, group); // Setup workdir Path mavenTargetDir = Paths.get("target").toAbsolutePath(); workDir = Files.createTempDirectory(mavenTargetDir, "test" + System.nanoTime()); if (startBroker) { broker = new Broker(brokerConfig, new FileCommitLog(workDir, workDir, 1024 * 1024), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker.startAsWritable(); server = new NettyChannelAcceptor(broker.getAcceptor()); server.start(); } if (startReplicatedBrokers) { zkServer = new ZKTestEnv(folderZk.getRoot().toPath()); zkServer.startBookie(); // Broker 1 broker1 = new Broker(broker1Config, new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(), folderSnapshots.newFolder().toPath(), BrokerHostData.formatHostdata( new BrokerHostData(broker1Host, broker1Port, "", false, null)), false), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker1.startAsWritable(); server1 = new NettyChannelAcceptor(broker1.getAcceptor(), broker1Host, broker1Port); server1.start(); // Broker 2 broker2 = new Broker(broker2Config, new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(), folderSnapshots.newFolder().toPath(), BrokerHostData.formatHostdata( new BrokerHostData(broker2Host, broker2Port, "", false, null)), false), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker2.start(); server2 = new NettyChannelAcceptor(broker2.getAcceptor(), broker2Host, broker2Port); server2.start(); // Broker locator brokerLocator = new ZKBrokerLocator(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath()); } }
From source file:com.bluexml.side.integration.standalone.GenerateModelHelper.java
/** * Init {@link Logger}s associated to package * com.bluexml.side.Integration.standAlone * /* w w w .j a v a2 s . com*/ * @param baseLevel * the level above which logs will be displayed on the console * @return the base {@link Logger} managing the package */ public static Logger initLogger(Level baseLevel) { if (baseLevel == null) { baseLevel = Level.INFO; } if (baseLogger == null) { Logger logger = Logger.getLogger("com.bluexml.side"); // $NON-NLS-1$ ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(new ConsoleSimpleFormatter()); logger.setUseParentHandlers(false); logger.addHandler(handler); baseLogger = logger; consoleHandler = handler; } baseLogger.setLevel(baseLevel); consoleHandler.setLevel(baseLevel); return baseLogger; }
From source file:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java
/** * /*from w w w .j av a 2 s. co m*/ * * @throws Exception * ? */ private void init() throws Exception { /* xsocket - FINE ??? ? ? ? ? */ if (XSOCKET_DEBUG) { xsocket_log.setLevel(Level.ALL); } else { xsocket_log.setLevel(Level.INFO); } ConsoleHandler console = new ConsoleHandler(); if (XSOCKET_DEBUG) { console.setLevel(Level.ALL); } else { console.setLevel(Level.INFO); } xsocket_log.addHandler(console); /* xsocket - FINE ??? ? ? ? ? */ initLogger(); initFilter(); initStorage(); InetAddress ia = InetAddress.getByName(HOST); if (ia == null) { ia = InetAddress.getLocalHost(); } /* ? ( ) - Receive Buffer Size ? */ Map<String, Object> options = new HashMap<String, Object>(); // - 2014.04.29 - ? - START - Multiplexing? . // options.put(IConnection.SO_REUSEADDR, true); // options.put(IConnection.SO_LINGER, "5"); // ? ?? (? ? ? ) // options.put(IConnection.SO_KEEPALIVE, true); // options.put(IConnection.TCP_NODELAY, true); // options.put(IConnection.SO_RCVBUF, XNDiscConfig.INIT_BUFFER_SIZE); // options.put(IConnection.SO_SNDBUF, XNDiscConfig.INIT_BUFFER_SIZE); // - 2014.04.29 - ? - END - Multiplexing? . /* SERVER? ? ? */ /* workerpool (?? ? ? )? ?. */ /* ? ? workerpool? ? ? workerpool ? ?. ? 100. */ System.setProperty(XNDiscUtils.XSOCKET_WORKER_POOL_MIN_SIZE, SIZE_WORKER_POOL); /* workerpool? ?. ? 4 */ System.setProperty(XNDiscUtils.XSOCKET_WORKER_POOL_MIN_SIZE, MIN_SIZE_WORKER_POOL); /* ? ? (NIO Selectors)? . ? 2 ? ?. */ System.setProperty(XNDiscUtils.XSOKET_DISPATCHER_INIT_COUNT, DISPATCHER_INIT_COUNT); /* ?? ? ?? */ /* , ?? ?? ?. ? ?? . */ System.setProperty(XNDiscUtils.XSOCKET_DISPATCHER_MAX_HANDLE, DISPATCHER_MAX_HANDLES); /* ? ? ? ?? ?? ? . ? false. */ System.setProperty(XNDiscUtils.XSOCKET_SERVER_READ_BUFFER_USEDIRECT, READ_BUFFER_USEDIRECT); // - 2014.04.25 - ByteBuffer Direct - START System.setProperty(XNDiscUtils.XSOCKET_CLIENT_READ_BUFFER_USEDIRECT, READ_BUFFER_USEDIRECT); System.setProperty(XNDiscUtils.XSOCKET_WRITE_BUFFER_USEDIRECT, READ_BUFFER_USEDIRECT); // - 2014.04.25 - ByteBuffer Direct - END // - 2014.04.29 - - START System.setProperty(XNDiscUtils.XSOCKET_SUPPRESS_SYNC_FLUSH_WARNING, "true"); System.setProperty(XNDiscUtils.XSOCKET_SUPPRESS_REUSE_BUFFER_WARNING, "true"); // or FlushMode.SYNC (GET ? ) System.setProperty(XNDiscUtils.XSOCKET_SUPPRESS_SYNC_FLUSH_COMPLETION_HANDLER_WARNING, "true"); System.setProperty(XNDiscUtils.XSOCKET_DISPATCHER_BYPASSING_WRITE_ALLOWED, "true"); // - 2014.04.29 - - END /* (NIO SelectionKey)? ? true ? ?? detach?. ?? ??? . false. */ System.setProperty(XNDiscUtils.XSOCKET_DISPATCHER_DETACH_HANDLE_ON_NO_OPS, DETACH_HANDLE_NO_OPERATION); /* ? ?? ? ?? ? ? (1024 * 16) */ Integer mapped_bytebuffer_maxsize = 1024 * XNDiscConfig.getInt(XNDiscConfig.TRANSFER_MAPPED_BYTE_BUFFER_MAXSIZE, 16); System.setProperty(XNDiscUtils.XSOCKET_TRANFER_MAPPED_BYTEBUFFER_MAX_SIZE, mapped_bytebuffer_maxsize.toString()); /* ? Sever - SSL ? ? Connection? ? ?! */ if (USE_SSL) { this.server = new Server(ia, PORT, options, new MultiplexedProtocolAdapter(new XNDiscHandler(storage, logger)), XNDiscSSLContextFactory.getSSLContext(), true); // this.server = new Server(ia, PORT, options, new XNDiscHandler(storage, logger), XNDiscSSLContextFactory.getSSLContext(), true); } else { this.server = new Server(ia, PORT, options, new MultiplexedProtocolAdapter(new XNDiscHandler(storage, logger)), null, false); // this.server = new Server(ia, PORT, options, new XNDiscHandler(storage, logger), null, false); } /* ThreadPool? ? , Cached ? ? ??? ? ? ? ?. */ /* SERVER? ? ? (? Fixed) */ /* ? : ? ? ?? Runtime.availableProcessors() ? ? ?? ??? */ /* newFixedThreadPool ? ? ? corePoolSize, maximumPoolSize . ? */ /* newCachedThreadPool ? corePoolSize = 0, maximumPoolSize Integer.MAX_VALUE . ? 1 */ if (WORKER_POOL_TYPE.equals("C")) { this.server.setWorkerpool(Executors.newCachedThreadPool(new XNDiscThreadFactory(true))); } else { if (XNDiscConfig.getBoolean(XNDiscConfig.MULTIPLICATION_THREAD_AVAILABLE_PROCESSORS)) { WORKER_THREAD_POOL = Runtime.getRuntime().availableProcessors() * WORKER_THREAD_POOL; } this.server .setWorkerpool(Executors.newFixedThreadPool(WORKER_THREAD_POOL, new XNDiscThreadFactory(true))); } this.server.setFlushmode(FlushMode.ASYNC); }
From source file:de.phillme.PhotoSorter.java
private void initLogging() { System.setProperty("java.util.logging.SimpleFormatter.format", "%5$s %n"); LOGGER.setLevel(Level.INFO);// ww w .j av a 2 s .c o m ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(new SimpleFormatter()); handler.setLevel(Level.INFO); LOGGER.addHandler(handler); LOGGER.setUseParentHandlers(false); }
From source file:com.cisco.oss.foundation.logging.FoundationLogger.java
private static void setupJULSupport(URL resource) { boolean julSupportEnabled = Boolean.valueOf(log4jConfigProps .getProperty(FoundationLoggerConstants.Foundation_JUL_SUPPORT_ENABLED.toString(), "false")); if (julSupportEnabled) { String appenderRef = log4jConfigProps .getProperty(FoundationLoggerConstants.Foundation_JUL_APPENDER_REF.toString()); if (StringUtils.isBlank(appenderRef)) { Enumeration allAppenders = Logger.getRootLogger().getAllAppenders(); while (allAppenders.hasMoreElements()) { Appender appender = (Appender) allAppenders.nextElement(); if (appender instanceof FileAppender) { appenderRef = appender.getName(); getLogger(FoundationLogger.class) .info("*** Using '" + appenderRef + "' as the Java util logging appender ref ***"); System.err.println( "*** Using '" + appenderRef + "' as the Java util logging appender ref ***"); break; }//w ww. j a v a 2 s .com } } if (StringUtils.isBlank(appenderRef)) { throw new IllegalArgumentException( "Java util support was enabled but couldn't find a matching appender under the '" + FoundationLoggerConstants.Foundation_JUL_APPENDER_REF.toString() + "' key."); } Handler handler = null; Appender appender = Logger.getRootLogger().getAppender(appenderRef); if (appender == null) { Enumeration allAppenders = Logger.getRootLogger().getAllAppenders(); while (allAppenders.hasMoreElements()) { Appender tempAppender = (Appender) allAppenders.nextElement(); if (tempAppender instanceof AsyncAppender) { AsyncAppender asyncAppender = (AsyncAppender) tempAppender; Enumeration asyncAppenderAllAppenders = asyncAppender.getAllAppenders(); while (asyncAppenderAllAppenders.hasMoreElements()) { Appender asyncTempAppender = (Appender) asyncAppenderAllAppenders.nextElement(); if (appenderRef.equals(asyncTempAppender.getName())) { appender = asyncTempAppender; break; } } if (appender != null) { break; } } } } if (appender instanceof FileAppender) { try { handler = new FileHandler(((FileAppender) appender).getFile()); } catch (IOException e) { throw new IllegalArgumentException( "IOException encountered when trying to setup jul logging: " + e, e); } } else if (appender instanceof ConsoleAppender) { handler = new ConsoleHandler(); } else { getLogger(FoundationLogger.class) .error("got a reference to an unsupported appender: " + appenderRef); } if (handler != null) { // System.setProperty("java.util.logging.config.file",resource.getPath()); java.util.logging.LogManager.getLogManager().reset(); try { java.util.logging.LogManager.getLogManager().readConfiguration(resource.openStream()); } catch (IOException e) { throw new IllegalArgumentException( "IOException encountered when trying to read log4j properties file: " + e, e); } handler.setLevel(java.util.logging.Level.FINEST); handler.setFormatter(new FoundationLogFormatter()); java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger(""); rootLogger.addHandler(handler); rootLogger.setLevel(java.util.logging.Level.SEVERE); Properties julLoggerSubset = getPropertiesSubset("jul.logger"); if (!julLoggerSubset.isEmpty()) { Set<Object> keySet = julLoggerSubset.keySet(); for (Object key : keySet) { java.util.logging.Logger logger = java.util.logging.Logger.getLogger((String) key); logger.setLevel(java.util.logging.Level.parse((String) julLoggerSubset.get(key))); } } } } }
From source file:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java
@Test public void buildShellScriptAcrossRestart() throws Exception { Assume.assumeFalse("TODO not sure how to write a corresponding batch script", Functions.isWindows()); story.addStep(new Statement() { @SuppressWarnings("SleepWhileInLoop") @Override/*from www . j a v a 2 s.co m*/ public void evaluate() throws Throwable { Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName()); LOGGER.setLevel(Level.FINE); Handler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); LOGGER.addHandler(handler); // Cannot use regular JenkinsRule.createSlave due to JENKINS-26398. // Nor can we can use JenkinsRule.createComputerLauncher, since spawned commands are killed by CommandLauncher somehow (it is not clear how; apparently before its onClosed kills them off). DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1", Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList()); story.j.jenkins.addNode(s); startJnlpProc(); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "demo"); File f1 = new File(story.j.jenkins.getRootDir(), "f1"); File f2 = new File(story.j.jenkins.getRootDir(), "f2"); new FileOutputStream(f1).close(); p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + " sh 'touch \"" + f2 + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2 + "\"'\n" + " echo 'OK, done'\n" + "}", true)); WorkflowRun b = p.scheduleBuild2(0).waitForStart(); while (!f2.isFile()) { Thread.sleep(100); } assertTrue(b.isBuilding()); killJnlpProc(); } }); story.addStep(new Statement() { @Override public void evaluate() throws Throwable { WorkflowJob p = (WorkflowJob) story.j.jenkins.getItem("demo"); WorkflowRun b = p.getLastBuild(); assertTrue(b.isBuilding()); // TODO occasionally fails; log ends with: Running: Allocate node : Body : Start (no shell step in sight) startJnlpProc(); // Have to relaunch JNLP agent, since the Jenkins port has changed, and we cannot force JenkinsRule to reuse the same port as before. File f1 = new File(story.j.jenkins.getRootDir(), "f1"); File f2 = new File(story.j.jenkins.getRootDir(), "f2"); assertTrue(f2.isFile()); assertTrue(f1.delete()); while (f2.isFile()) { Thread.sleep(100); } story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b)); story.j.assertLogContains("finished waiting", b); story.j.assertLogContains("OK, done", b); killJnlpProc(); } }); }
From source file:org.apache.qpid.amqp_1_0.client.Util.java
protected Util(String[] args) { CommandLineParser cmdLineParse = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "show this help message and exit"); options.addOption(OptionBuilder.withLongOpt("host").withDescription("host to connect to (default 0.0.0.0)") .hasArg(true).withArgName("HOST").create('H')); options.addOption(//from w w w. jav a2s. com OptionBuilder.withLongOpt("username").withDescription("username to use for authentication") .hasArg(true).withArgName("USERNAME").create('u')); options.addOption( OptionBuilder.withLongOpt("password").withDescription("password to use for authentication") .hasArg(true).withArgName("PASSWORD").create('w')); options.addOption(OptionBuilder.withLongOpt("port").withDescription("port to connect to (default 5672)") .hasArg(true).withArgName("PORT").create('p')); options.addOption(OptionBuilder.withLongOpt("frame-size").withDescription("specify the maximum frame size") .hasArg(true).withArgName("FRAME_SIZE").create('f')); options.addOption(OptionBuilder.withLongOpt("container-name").withDescription("Container name").hasArg(true) .withArgName("CONTAINER_NAME").create('C')); options.addOption(OptionBuilder.withLongOpt("ssl").withDescription("Use SSL").create('S')); options.addOption( OptionBuilder.withLongOpt("remote-hostname").withDescription("hostname to supply in the open frame") .hasArg(true).withArgName("HOST").create('O')); if (hasBlockOption()) options.addOption( OptionBuilder.withLongOpt("block").withDescription("block until messages arrive").create('b')); if (hasCountOption()) options.addOption( OptionBuilder.withLongOpt("count").withDescription("number of messages to send (default 1)") .hasArg(true).withArgName("COUNT").create('c')); if (hasModeOption()) options.addOption(OptionBuilder.withLongOpt("acknowledge-mode") .withDescription("acknowledgement mode: AMO|ALO|EO (At Least Once, At Most Once, Exactly Once") .hasArg(true).withArgName("MODE").create('k')); if (hasSubjectOption()) options.addOption(OptionBuilder.withLongOpt("subject").withDescription("subject message property") .hasArg(true).withArgName("SUBJECT").create('s')); if (hasSingleLinkPerConnectionMode()) options.addOption(OptionBuilder.withLongOpt("single-link-per-connection") .withDescription("acknowledgement mode: AMO|ALO|EO (At Least Once, At Most Once, Exactly Once") .hasArg(false).create('Z')); if (hasFilterOption()) options.addOption(OptionBuilder.withLongOpt("filter") .withDescription("filter, e.g. exact-subject=hello; matching-subject=%.a.#").hasArg(true) .withArgName("<TYPE>=<VALUE>").create('F')); if (hasTxnOption()) { options.addOption("x", "txn", false, "use transactions"); options.addOption( OptionBuilder.withLongOpt("batch-size").withDescription("transaction batch size (default: 1)") .hasArg(true).withArgName("BATCH-SIZE").create('B')); options.addOption(OptionBuilder.withLongOpt("rollback-ratio") .withDescription("rollback ratio - must be between 0 and 1 (default: 0)").hasArg(true) .withArgName("RATIO").create('R')); } if (hasLinkDurableOption()) { options.addOption("d", "durable-link", false, "use a durable link"); } if (hasStdInOption()) options.addOption("i", "stdin", false, "read messages from stdin (one message per line)"); options.addOption( OptionBuilder.withLongOpt("trace").withDescription("trace logging specified categories: RAW, FRM") .hasArg(true).withArgName("TRACE").create('t')); if (hasSizeOption()) options.addOption( OptionBuilder.withLongOpt("message-size").withDescription("size to pad outgoing messages to") .hasArg(true).withArgName("SIZE").create('z')); if (hasResponseQueueOption()) options.addOption( OptionBuilder.withLongOpt("response-queue").withDescription("response queue to reply to") .hasArg(true).withArgName("RESPONSE_QUEUE").create('r')); if (hasLinkNameOption()) { options.addOption(OptionBuilder.withLongOpt("link").withDescription("link name").hasArg(true) .withArgName("LINK").create('l')); } if (hasWindowSizeOption()) { options.addOption(OptionBuilder.withLongOpt("window-size").withDescription("credit window size") .hasArg(true).withArgName("WINDOW-SIZE").create('W')); } CommandLine cmdLine = null; try { cmdLine = cmdLineParse.parse(options, args); } catch (ParseException e) { printUsage(options); System.exit(-1); } if (cmdLine.hasOption('h') || cmdLine.getArgList().isEmpty()) { printUsage(options); System.exit(0); } _host = cmdLine.getOptionValue('H', "0.0.0.0"); _remoteHost = cmdLine.getOptionValue('O', null); String portStr = cmdLine.getOptionValue('p', "5672"); String countStr = cmdLine.getOptionValue('c', "1"); _useSSL = cmdLine.hasOption('S'); if (hasWindowSizeOption()) { String windowSizeStr = cmdLine.getOptionValue('W', "100"); _windowSize = Integer.parseInt(windowSizeStr); } if (hasSubjectOption()) { _subject = cmdLine.getOptionValue('s'); } if (cmdLine.hasOption('u')) { _username = cmdLine.getOptionValue('u'); } if (cmdLine.hasOption('w')) { _password = cmdLine.getOptionValue('w'); } if (cmdLine.hasOption('F')) { _filter = cmdLine.getOptionValue('F'); } _port = Integer.parseInt(portStr); _containerName = cmdLine.getOptionValue('C'); if (hasBlockOption()) _block = cmdLine.hasOption('b'); if (hasLinkNameOption()) _linkName = cmdLine.getOptionValue('l'); if (hasLinkDurableOption()) _durableLink = cmdLine.hasOption('d'); if (hasCountOption()) _count = Integer.parseInt(countStr); if (hasStdInOption()) _useStdIn = cmdLine.hasOption('i'); if (hasSingleLinkPerConnectionMode()) _useMultipleConnections = cmdLine.hasOption('Z'); if (hasTxnOption()) { _useTran = cmdLine.hasOption('x'); _batchSize = Integer.parseInt(cmdLine.getOptionValue('B', "1")); _rollbackRatio = Double.parseDouble(cmdLine.getOptionValue('R', "0")); } if (hasModeOption()) { _mode = AcknowledgeMode.ALO; if (cmdLine.hasOption('k')) { _mode = AcknowledgeMode.valueOf(cmdLine.getOptionValue('k')); } } if (hasResponseQueueOption()) { _responseQueue = cmdLine.getOptionValue('r'); } _frameSize = Integer.parseInt(cmdLine.getOptionValue('f', "65536")); if (hasSizeOption()) { _messageSize = Integer.parseInt(cmdLine.getOptionValue('z', "-1")); } String categoriesList = cmdLine.getOptionValue('t'); String[] categories = categoriesList == null ? new String[0] : categoriesList.split("[, ]"); for (String cat : categories) { if (cat.equalsIgnoreCase("FRM")) { FRAME_LOGGER.setLevel(Level.FINE); Formatter formatter = new Formatter() { @Override public String format(final LogRecord record) { return "[" + record.getMillis() + " FRM]\t" + record.getMessage() + "\n"; } }; for (Handler handler : FRAME_LOGGER.getHandlers()) { FRAME_LOGGER.removeHandler(handler); } Handler handler = new ConsoleHandler(); handler.setLevel(Level.FINE); handler.setFormatter(formatter); FRAME_LOGGER.addHandler(handler); } else if (cat.equalsIgnoreCase("RAW")) { RAW_LOGGER.setLevel(Level.FINE); Formatter formatter = new Formatter() { @Override public String format(final LogRecord record) { return "[" + record.getMillis() + " RAW]\t" + record.getMessage() + "\n"; } }; for (Handler handler : RAW_LOGGER.getHandlers()) { RAW_LOGGER.removeHandler(handler); } Handler handler = new ConsoleHandler(); handler.setLevel(Level.FINE); handler.setFormatter(formatter); RAW_LOGGER.addHandler(handler); } } _args = cmdLine.getArgs(); }
From source file:LineageSimulator.java
public static void main(String[] args) { Options options = new Options(); // commands/*from w w w . j a va2 s .co m*/ //options.addOption("simulate", false, "Simulate lineage trees"); //options.addOption("sample", false, "Sample from the simulated trees"); //options.addOption("evaluate", false, "Evaluate trees"); // tree simulation options.addOption("t", "nTrees", true, "Number of trees to simulate (default: 100)"); options.addOption("i", "nIter", true, "Number of tree growth iterations (default: 50)"); options.addOption("snv", "probSNV", true, "Per node probablity of generating a descendant cell population with an acquired SNV during a tree growth iteration (default: 0.15)"); options.addOption("cnv", "probCNV", true, "Per node probablity of generating a descendant cell population with an acquired CNV during a tree growth iteration (default: 0.02)"); options.addOption("probDeath", true, "Probablity of a cell population death in each tree growth iteration (default: 0.06)"); options.addOption("maxPopulationSize", true, "Max size of a cell population (default: 1000000)"); options.addOption("minNodes", true, "Minimum number of undead cell population nodes in a valid tree, tree growth will continue beyond the defined number of iterations until this value is reached (default: 10)"); options.addOption("maxNodes", true, "Maximum number of undead cell population nodes in a tree, tree growth will stop after the iteration in which this value is reached/first surpassed (default: 1000)"); // sampling Option samplesOption = new Option("s", "nSamples", true, "Number of samples to collect, accepts multiple values, e.g. 5 10 15 (default: 5)"); samplesOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(samplesOption); Option covOption = new Option("c", "coverage", true, "Simulated coverage to generate the VAFs, accepts multiple values, e.g. 500 1000 (default: 1000)"); covOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(covOption); options.addOption("maxSubclones", true, "Max number of subclones per sample (default: 5)"); options.addOption("sampleSize", true, "Number of cells per sample (default: 100000)"); options.addOption("e", true, "Sequencing error (default: 0.001)"); options.addOption("minNC", true, "Minimum percentage of normal contamination per sample; the percentage will be randomly generated from the range [minNC maxNC] for each sample (default: 0)"); options.addOption("maxNC", true, "Maximum percentage of normal contamination per sample; if maxNC < minNC, maxNC will be automatically set to minNC; the percentage will be randomly generated from the range [minNC maxNC] for each sample (default: 20)"); //options.addOption("localized", false, "Enable localized sampling (default: random sampling)"); //options.addOption("mixSubclone", false, "With localized sampling, add an additional subclone from a different subtree to each sample; by default, the sample is localized to a single disjoint subtree"); // input/output/display options.addOption("dir", "outputDir", true, "Directory where the output files should be created [required]"); options.addOption("dot", false, "Produce DOT files for the simulated trees"); options.addOption("sdot", "sampledDot", false, "Produce DOT files for the simulated trees with indicated samples"); options.addOption("sampleProfile", false, "Output VAF file includes an additional column with the binary sample profile for each SNV"); // other options.addOption("v", "verbose", false, "Verbose mode"); options.addOption("h", "help", false, "Print usage"); // display order ArrayList<Option> optionsList = new ArrayList<Option>(); optionsList.add(options.getOption("dir")); optionsList.add(options.getOption("t")); optionsList.add(options.getOption("i")); optionsList.add(options.getOption("snv")); optionsList.add(options.getOption("cnv")); optionsList.add(options.getOption("probDeath")); optionsList.add(options.getOption("maxPopulationSize")); optionsList.add(options.getOption("minNodes")); optionsList.add(options.getOption("maxNodes")); optionsList.add(options.getOption("s")); optionsList.add(options.getOption("c")); optionsList.add(options.getOption("maxSubclones")); optionsList.add(options.getOption("sampleSize")); optionsList.add(options.getOption("e")); optionsList.add(options.getOption("minNC")); optionsList.add(options.getOption("maxNC")); optionsList.add(options.getOption("dot")); optionsList.add(options.getOption("sdot")); optionsList.add(options.getOption("sampleProfile")); optionsList.add(options.getOption("v")); optionsList.add(options.getOption("h")); CommandLineParser parser = new BasicParser(); CommandLine cmdLine = null; HelpFormatter hf = new HelpFormatter(); hf.setOptionComparator(new OptionComarator<Option>(optionsList)); try { cmdLine = parser.parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); hf.printHelp(PROG_NAME, options); System.exit(-1); } Args params = new Args(); if (cmdLine.hasOption("dir")) { params.simPath = cmdLine.getOptionValue("dir") + "/" + SIMULATION_DATA_DIR; } else { System.err.println("Required parameter: output directory path [-dir]"); hf.printHelp(PROG_NAME, options); System.exit(-1); } if (cmdLine.hasOption("t")) { Parameters.NUM_TREES = Integer.parseInt(cmdLine.getOptionValue("t")); } if (cmdLine.hasOption("i")) { Parameters.NUM_ITERATIONS = Integer.parseInt(cmdLine.getOptionValue("i")); } if (cmdLine.hasOption("snv")) { Parameters.PROB_SNV = Double.parseDouble(cmdLine.getOptionValue("snv")); } if (cmdLine.hasOption("cnv")) { Parameters.PROB_CNV = Double.parseDouble(cmdLine.getOptionValue("cnv")); } if (cmdLine.hasOption("probDeath")) { Parameters.PROB_DEATH = Double.parseDouble(cmdLine.getOptionValue("probDeath")); } if (cmdLine.hasOption("maxPopulationSize")) { Parameters.MAX_POPULATION_SIZE = Integer.parseInt(cmdLine.getOptionValue("maxPopulationSize")); } if (cmdLine.hasOption("minNodes")) { Parameters.MIN_NUM_NODES = Integer.parseInt(cmdLine.getOptionValue("minNodes")); if (Parameters.MIN_NUM_NODES < 1) { System.err.println("Minimum number of nodes [-minNodes] must be at least 1"); System.exit(-1); } } if (cmdLine.hasOption("maxNodes")) { Parameters.MAX_NUM_NODES = Integer.parseInt(cmdLine.getOptionValue("maxNodes")); if (Parameters.MAX_NUM_NODES < 1 || Parameters.MAX_NUM_NODES < Parameters.MIN_NUM_NODES) { System.err.println( "Maximum number of nodes [-maxNodes] must be at least 1 and not less than [-minNodes]"); System.exit(-1); } } if (cmdLine.hasOption("s")) { String[] samples = cmdLine.getOptionValues("s"); Parameters.NUM_SAMPLES_ARRAY = new int[samples.length]; for (int i = 0; i < samples.length; i++) { Parameters.NUM_SAMPLES_ARRAY[i] = Integer.parseInt(samples[i]); } } if (cmdLine.hasOption("c")) { String[] cov = cmdLine.getOptionValues("c"); Parameters.COVERAGE_ARRAY = new int[cov.length]; for (int i = 0; i < cov.length; i++) { Parameters.COVERAGE_ARRAY[i] = Integer.parseInt(cov[i]); } } if (cmdLine.hasOption("maxSubclones")) { Parameters.MAX_NUM_SUBCLONES = Integer.parseInt(cmdLine.getOptionValue("maxSubclones")); } if (cmdLine.hasOption("sampleSize")) { Parameters.NUM_CELLS_PER_SAMPLE = Integer.parseInt(cmdLine.getOptionValue("sampleSize")); } if (cmdLine.hasOption("e")) { Parameters.SEQUENCING_ERROR = Double.parseDouble(cmdLine.getOptionValue("e")); } if (cmdLine.hasOption("minNC")) { Parameters.MIN_PERCENT_NORMAL_CONTAMINATION = Double.parseDouble(cmdLine.getOptionValue("minNC")); } if (cmdLine.hasOption("maxNC")) { Parameters.MAX_PERCENT_NORMAL_CONTAMINATION = Double.parseDouble(cmdLine.getOptionValue("maxNC")); } if (Parameters.MAX_PERCENT_NORMAL_CONTAMINATION < Parameters.MIN_PERCENT_NORMAL_CONTAMINATION) { Parameters.MAX_PERCENT_NORMAL_CONTAMINATION = Parameters.MIN_PERCENT_NORMAL_CONTAMINATION; } /*if(cmdLine.hasOption("localized")) { Parameters.LOCALIZED_SAMPLING = true; } if(cmdLine.hasOption("mixSubclone")) { Parameters.MIX_NBR_SUBTREE_SUBCLONE = true; }*/ if (cmdLine.hasOption("dot")) { params.generateDOT = true; } if (cmdLine.hasOption("sampledDot")) { params.generateSampledDOT = true; } if (cmdLine.hasOption("sampleProfile")) { params.outputSampleProfile = true; } if (cmdLine.hasOption("h")) { new HelpFormatter().printHelp(" ", options); } // logger ConsoleHandler h = new ConsoleHandler(); h.setFormatter(new LogFormatter()); h.setLevel(Level.INFO); logger.setLevel(Level.INFO); if (cmdLine.hasOption("v")) { h.setLevel(Level.FINEST); logger.setLevel(Level.FINEST); } logger.addHandler(h); logger.setUseParentHandlers(false); // validate settings if (Parameters.PROB_SNV + Parameters.PROB_CNV + Parameters.PROB_DEATH > 1) { System.err.println("The sum of SSNV, CNV, and cell death probabilities cannot exceed 1"); hf.printHelp(PROG_NAME, options); System.exit(-1); } simulateLineageTrees(params); }
From source file:eu.asterics.mw.services.AstericsErrorHandling.java
/** * This method creates the logger. Actually there are 4 types of loggers: * "severe": logs fatal errors i.e. errors that prevent the ARE from functioning * "warning": logs errors other than fatal e.g. component errors * "info": logs informative messages//from w w w .ja v a 2s. c om * "fine": logs debugging messages * * Each logger by default also logs all messages with severity level higher than its own. * E.g. the warning logger logs warning and severe messages, the info logger logs info, * warning and severe messages etc. The same applies to the consoleHandler, i.e. by * setting its level to info, the console will also print severe and warning messages * along with info messages */ public Logger getLogger() { if (logger == null) { logger = Logger.getLogger("AstericsLogger"); FileHandler warningFileHandler, severeFileHandler, infoFileHandler, fineFileHandler; ConsoleHandler consoleHandler; try { //cleanup before starting: logger.setUseParentHandlers(false); // remove and handlers that will be replaced Handler[] handlers = logger.getHandlers(); for (Handler handler : handlers) { if (handler.getClass() == ConsoleHandler.class) logger.removeHandler(handler); } File logFolder = new File(System.getProperty(LOG_PATH_PROPERTY, ResourceRegistry.TMP_FOLDER)); if (!logFolder.exists()) { FileUtils.forceMkdir(logFolder); } //Create handlers severeFileHandler = new FileHandler(new File(logFolder, "asterics_logger_severe.log").getPath(), true); warningFileHandler = new FileHandler(new File(logFolder, "asterics_logger_warning.log").getPath(), true); infoFileHandler = new FileHandler(new File(logFolder, "asterics_logger.log").getPath(), true); fineFileHandler = new FileHandler(new File(logFolder, "asterics_logger_fine.log").getPath(), true); consoleHandler = new ConsoleHandler(); //Set report level of handlers severeFileHandler.setLevel(Level.SEVERE); warningFileHandler.setLevel(Level.WARNING); infoFileHandler.setLevel(Level.INFO); fineFileHandler.setLevel(Level.FINE); //The consoleHandler prints log messaged to the console. Its //severety level can be adjusted accordingly. String level = getLoggerLevel(); switch (level) { case "INFO": consoleHandler.setLevel(Level.INFO); break; case "WARNING": consoleHandler.setLevel(Level.WARNING); break; case "FINE": consoleHandler.setLevel(Level.FINE); break; case "SEVERE": consoleHandler.setLevel(Level.SEVERE); break; default: consoleHandler.setLevel(Level.INFO); break; } //Add handlers to the logger logger.addHandler(warningFileHandler); logger.addHandler(severeFileHandler); logger.addHandler(infoFileHandler); logger.addHandler(fineFileHandler); logger.addHandler(consoleHandler); //Create formatters for the handlers (optional) severeFileHandler.setFormatter(new SimpleFormatter()); warningFileHandler.setFormatter(new SimpleFormatter()); infoFileHandler.setFormatter(new SimpleFormatter()); fineFileHandler.setFormatter(new SimpleFormatter()); consoleHandler.setFormatter(new SimpleFormatter()); logger.setLevel(Level.ALL); logger.setUseParentHandlers(false); } catch (SecurityException e) { System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: " + e.getMessage()); } catch (IOException e) { //logger.warning(this.getClass().getName()+ // ": Error creating AstericsLogger: "+e.getMessage()); System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: " + e.getMessage()); } } return logger; }