List of usage examples for java.lang System setErr
public static void setErr(PrintStream err)
From source file:org.openanzo.test.client.cli.TestCommandLineInterface.java
/** * Isolates a java method call to the command line interface's main method. Mock System in, out and error are put around the method call and System.exit's * are managed and their status captured. * // w ww . ja va 2 s .c o m * The System out, error and exit status are returned. * */ private TestCommandResult runCommandTest(String command, InputStream input) throws Exception { InputStream defaultInput = System.in; PrintStream defaultOutput = System.out; PrintStream defaultError = System.err; SecurityManager defaultSecurityManager = System.getSecurityManager(); int status = -1; String output = null; String error = null; try { System.setIn(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(new PrintStream(out))); ByteArrayOutputStream err = new ByteArrayOutputStream(); System.setErr(new PrintStream(new PrintStream(err))); System.setSecurityManager(new ExitStatusManager()); try { CommandLineInterface.main(command.split("\\s+")); } catch (ExitStatusException e) { status = e.getStatus(); } output = out.toString("UTF-8"); error = err.toString("UTF-8"); } finally { System.setIn(defaultInput); System.setOut(defaultOutput); System.setErr(defaultError); System.setSecurityManager(defaultSecurityManager); } return new TestCommandResult(output, error, status); }
From source file:ro.nextreports.designer.NextReports.java
private void redirectOutput() { if (Globals.getConfig().getBoolean("console.redirect", false)) { try {//from w w w.j a va 2 s . co m String file = Globals.getConfig().getString("console.file", Globals.USER_DATA_DIR + File.separator + "/logs/console.log"); if (file.startsWith("./")) { file = file.substring(1); } file = Globals.USER_DATA_DIR + file; LOG.info("Redirect output to '" + file + "'"); OutputStream os = new BufferedOutputStream(new FileOutputStream(file, true)); PrintStream ps = new PrintStream(os); System.setOut(ps); System.setErr(ps); } catch (FileNotFoundException e) { e.printStackTrace(); LOG.error(e.getMessage(), e); } } }
From source file:edu.stanford.epadd.launcher.Splash.java
public static void main(String args[]) throws Exception { Splash splash = null;// w w w .ja v a2s .co m boolean headless = (System.getProperty("muse.mode.server") != null); if (!headless) splash = new Splash(); else { System.out.println("Muse running in headless mode!"); browserOpen = false; } tellUser(splash, "Setting up logging..."); setupLogging(); basicSetup(args); BASE_URL = "http://localhost:" + PORT + "/" + WEBAPP_NAME; MUSE_CHECK_URL = BASE_URL + "/js/muse.js"; // for quick check of existing muse or successful start up. BASE_URL may take some time to run and may not always be available now that we set dirAllowed to false and public mode does not serve /muse. tellUser(splash, "Log file: " + debugFile + "***\n"); out.println("Starting up ePADD on the local computer at " + BASE_URL + ", " + formatDateLong(new GregorianCalendar())); out.println("***For troubleshooting information, see this file: " + debugFile + "***\n"); out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = " + System.getProperty("user.home")); out.println("Memory status at the beginning: " + getMemoryStats()); if (Runtime.getRuntime().maxMemory() / MB < 512) aggressiveWarn( "You are probably running ePADD without enough memory. \nIf you launched ePADD from the command line, you can increase memory with an option like java -Xmx1g", 2000); tellUser(splash, "Memory: " + getMemoryStats()); // handle frequent error of user trying to launch another server when its already on // server.start() usually takes a few seconds to return // after that it takes a few seconds for the webapp to deploy // ignore any exceptions along the way and assume not if we can't prove it is alive boolean urlAlive = false; try { urlAlive = isURLAlive(MUSE_CHECK_URL); } catch (Exception e) { out.println("Exception: e"); e.printStackTrace(out); } boolean disableStart = false; if (urlAlive) { out.println("Oh! ePADD already running at: " + BASE_URL + ", will shut it down!"); tellUser(splash, "ePADD already running at: " + BASE_URL + ", will shut it down!"); killRunningServer(BASE_URL); boolean killed = false; int N_KILL_TRIES = 20, N_KILL_PERIOD_MILLIS = 3000; // check every 3 secs 20 times (total 1 minute) for the previous epadd to die // if it doesn't die after a minute, fail for (int i = 0; i < N_KILL_TRIES; i++) { try { Thread.sleep(N_KILL_PERIOD_MILLIS); } catch (InterruptedException ie) { } out.println("Checking " + MUSE_CHECK_URL); tellUser(splash, "Checking " + MUSE_CHECK_URL); try { urlAlive = isURLAlive(MUSE_CHECK_URL); } catch (Exception e) { out.println("Exception: " + e); e.printStackTrace(out); } if (!urlAlive) break; } if (!urlAlive) { out.println("Good. Shutdown succeeded, will restart"); tellUser(splash, "Good. Shutdown succeeded, we'll restart ePADD."); } else { String message = "Previously running ePADD still alive despite attempt to shut it down, disabling fresh restart!\n"; message += "If you just want to use the previous instance of ePADD, please go to " + BASE_URL; message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching ePADD again.\n"; aggressiveWarn(message, 2000); tellUser(splash, "Sorry, unable to kill previous ePADD. Quitting!"); try { Thread.sleep(10000); } catch (InterruptedException ie) { } if (splash != null) splash.close(); return; } } // else // out.println ("Muse not already alive at URL: ..." + URL); if (!disableStart) { setupResources(); out.println("Starting ePADD at URL: ..." + BASE_URL); tellUser(splash, "Starting ePADD at " + BASE_URL); server.start(); PrintStream debugOut1 = err; try { File f = new File(debugFile); if (f.exists()) f.delete(); // particular problem on windows :-( debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8"); } catch (IOException ioe) { out.println("Warning: failed to delete debug file " + debugFile + " : " + ioe); } final PrintStream debugOut = debugOut1; Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { shutdownSessions(); server.stop(); server.destroy(); debugOut.close(); } catch (Exception e) { e.printStackTrace(); } } })); boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS); if (success) { try { int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. tellUser(splash, "Setting up shutdown port..."); new ShutdownThread(server, shutdownPort).start(); // this will start a non-daemon thread that keeps the process alive out.println("Listening for ePADD shutdown message on port " + shutdownPort); tellUser(splash, "Listening for ePADD shutdown message on port " + shutdownPort); } catch (Exception e) { out.println( "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows"); } try { setupSystemTrayIcon(); } catch (Exception e) { out.println("Unable to setup system tray icon: " + e); e.printStackTrace(err); } // open browser window if (browserOpen) { preferredBrowser = null; // launch a browser here try { String link; link = "http://localhost:" + PORT + "/muse/index.jsp"; if (startPage != null) { // startPage has to be absolute link = "http://localhost:" + PORT + "/muse/" + startPage; } if (baseDir != null) link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir launchBrowser(link, splash); } catch (Exception e) { out.println( "Warning: Unable to launch browser due to exception (use the -n option to prevent ePADD from trying to launch a browser):"); e.printStackTrace(out); } } } else { out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n"); tellUser(splash, "SORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING"); } savedSystemOut = out; savedSystemErr = err; System.setOut(debugOut); System.setErr(debugOut); if (splash != null) splash.close(); } // program should not halt here, as ShutdownThread is running as a non-daemon thread. // splashDemo.closeWindow(); }
From source file:ai.grakn.test.graql.shell.GraqlShellIT.java
private String testShell(String input, ByteArrayOutputStream berr, String... args) throws Exception { args = specifyUniqueKeyspace(args);/*from ww w . j a v a2s . c o m*/ InputStream in = new ByteArrayInputStream(input.getBytes()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new TeeOutputStream(bout, trueOut)); // Intercept stderr, but make sure it is still printed using the TeeOutputStream PrintStream err = new PrintStream(new TeeOutputStream(berr, trueErr)); try { System.out.flush(); System.err.flush(); System.setIn(in); System.setOut(out); System.setErr(err); GraqlShell.runShell(args, expectedVersion, historyFile); } catch (Exception e) { System.setErr(trueErr); e.printStackTrace(); err.flush(); fail(berr.toString()); } finally { resetIO(); } out.flush(); err.flush(); return bout.toString(); }
From source file:edu.umd.cs.buildServer.BuildServerDaemon.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); Options options = getOptions();/*from w w w.j a v a 2s . c om*/ CommandLine line; try { line = parser.parse(options, args); } catch (Exception e) { printHelp(options); return; } if (line.hasOption("help")) { printHelp(options); return; } String[] remainingArgs = line.getArgs(); Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); Protocol.registerProtocol("easyhttps", easyhttps); BuildServerDaemon buildServer = new BuildServerDaemon(); if (line.hasOption("config")) { String c = line.getOptionValue("config"); buildServer.setConfigFile(c); } else if (remainingArgs.length == 1) buildServer.setConfigFile(remainingArgs[0]); boolean once = line.hasOption("once"); if (line.hasOption("submission")) { once = true; buildServer.getConfig().setProperty(DEBUG_SPECIFIC_SUBMISSION, line.getOptionValue("submission")); if (line.hasOption("testSetup")) buildServer.getConfig().setProperty(DEBUG_SPECIFIC_TESTSETUP, line.getOptionValue("testSetup")); if (line.hasOption("skipDownload")) buildServer.getConfig().setProperty(DEBUG_SKIP_DOWNLOAD, "true"); } else if (line.hasOption("testSetup")) { throw new IllegalArgumentException( "You can only specify a specific test setup if you also specify a specific submission"); } if (line.hasOption("projectNum")) { buildServer.getConfig().setProperty(DEBUG_SPECIFIC_PROJECT, line.getOptionValue("projectNum")); } if (line.hasOption("quiet")) buildServer.setQuiet(true); if (line.hasOption("verify")) buildServer.setVerifyOnly(); if (line.hasOption("course")) { buildServer.getConfig().setProperty(DEBUG_SPECIFIC_COURSE, line.getOptionValue("course")); } if (line.hasOption("logLevel")) buildServer.getConfig().setProperty(LOG4J_THRESHOLD, line.getOptionValue("logLevel")); if (line.hasOption("downloadOnly")) { System.out.println("Setting download only"); buildServer.setDownloadOnly(true); once = true; } if (once) { buildServer.getConfig().setProperty(LOG_DIRECTORY, "console"); buildServer.setDoNotLoop(true); buildServer.getConfig().setProperty(DEBUG_PRESERVE_SUBMISSION_ZIPFILES, "true"); } buildServer.initConfig(); Logger log = buildServer.getLog(); /** Redirect standard out and err to dev null, since clover * writes to standard out and error */ PrintStream systemOut = System.out; PrintStream systemErr = System.err; if (buildServer.isQuiet()) { System.setOut(new PrintStream(new DevNullOutputStream())); System.setErr(new PrintStream(new DevNullOutputStream())); } try { buildServer.executeServerLoop(); if (log != null) log.info("Shutting down"); System.out.println("Shutting down"); timedSystemExit0(); } catch (Throwable e) { buildServer.clearMyPidFile(); if (log != null) log.fatal("BuildServerDaemon got fatal exception; waiting for cron to restart me: ", e); e.printStackTrace(systemErr); System.exit(1); } if (buildServer.isQuiet()) { System.setOut(systemOut); System.setErr(systemErr); } }
From source file:geva.Main.AbstractRun.java
protected void setOutput() { String stdOut = ""; String stdErr = ""; try {/*from w ww . ja va 2 s .c o m*/ String key = Constants.STDOUT; String value = this.properties.getProperty(key); if (value != null) { if (!value.equals("")) { stdOut = System.getProperty("user.dir") + System.getProperty("file.separator") + value + ".out"; } } key = Constants.STDERR; value = this.properties.getProperty(key); if (value != null) { if (!value.equals("")) { stdErr = System.getProperty("user.dir") + System.getProperty("file.separator") + value + ".err"; } } if (!stdOut.equals("")) { logger.info("Redirecting stdOut to " + stdOut); FileOutputStream fos = new FileOutputStream(stdOut, true); PrintStream ps = new PrintStream(fos); System.setOut(ps); } if (!stdErr.equals("")) { logger.info("Redirecting stdErr to " + stdErr); FileOutputStream fos = new FileOutputStream(stdErr, true); PrintStream ps = new PrintStream(fos); System.setErr(ps); } } catch (Exception e) { logger.error(" std output exception", e); } }
From source file:org.apache.flink.yarn.YarnTestBase.java
/** * The test has been passed once the "terminateAfterString" has been seen. * @param args Command line arguments for the runner * @param terminateAfterString the runner is searching the stdout and stderr for this string. as soon as it appears, the test has passed * @param failOnPatterns The runner is searching stdout and stderr for the pattern (regexp) specified here. If one appears, the test has failed * @param type Set the type of the runner * @param expectedReturnValue Expected return code from the runner. * @param checkLogForTerminateString If true, the runner checks also the log4j logger for the terminate string *///from w w w . java 2 s .c o m protected void runWithArgs(String[] args, String terminateAfterString, String[] failOnPatterns, RunTypes type, int expectedReturnValue, boolean checkLogForTerminateString) { LOG.info("Running with args {}", Arrays.toString(args)); outContent = new ByteArrayOutputStream(); errContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); System.setErr(new PrintStream(errContent)); // we wait for at most three minutes final int START_TIMEOUT_SECONDS = 180; final long deadline = System.currentTimeMillis() + (START_TIMEOUT_SECONDS * 1000); Runner runner = new Runner(args, type, expectedReturnValue); runner.start(); boolean expectedStringSeen = false; boolean testPassedFromLog4j = false; do { sleep(1000); String outContentString = outContent.toString(); String errContentString = errContent.toString(); if (failOnPatterns != null) { for (String failOnString : failOnPatterns) { Pattern pattern = Pattern.compile(failOnString); if (pattern.matcher(outContentString).find() || pattern.matcher(errContentString).find()) { LOG.warn("Failing test. Output contained illegal string '" + failOnString + "'"); sendOutput(); // stopping runner. runner.sendStop(); Assert.fail("Output contained illegal string '" + failOnString + "'"); } } } // check output for the expected terminateAfterString. if (checkLogForTerminateString) { LoggingEvent matchedEvent = UtilsTest.getEventContainingString(terminateAfterString); if (matchedEvent != null) { testPassedFromLog4j = true; LOG.info("Found expected output in logging event {}", matchedEvent); } } if (outContentString.contains(terminateAfterString) || errContentString.contains(terminateAfterString) || testPassedFromLog4j) { expectedStringSeen = true; LOG.info("Found expected output in redirected streams"); // send "stop" command to command line interface LOG.info("RunWithArgs: request runner to stop"); runner.sendStop(); // wait for the thread to stop try { runner.join(30000); } catch (InterruptedException e) { LOG.warn("Interrupted while stopping runner", e); } LOG.warn("RunWithArgs runner stopped."); } else { // check if thread died if (!runner.isAlive()) { // leave loop: the runner died, so we can not expect new strings to show up. break; } } } while (runner.getRunnerError() == null && !expectedStringSeen && System.currentTimeMillis() < deadline); sendOutput(); if (runner.getRunnerError() != null) { // this lets the test fail. throw new RuntimeException("Runner failed", runner.getRunnerError()); } Assert.assertTrue("During the timeout period of " + START_TIMEOUT_SECONDS + " seconds the " + "expected string did not show up", expectedStringSeen); LOG.info("Test was successful"); }
From source file:org.apache.flink.yarn.YarnTestBase.java
protected static void sendOutput() { System.setOut(originalStdout); System.setErr(originalStderr); LOG.info("Sending stdout content through logger: \n\n{}\n\n", outContent.toString()); LOG.info("Sending stderr content through logger: \n\n{}\n\n", errContent.toString()); }
From source file:stg.pr.engine.CProcessRequestEngine.java
/** * Constructor of the class.//from www.ja v a 2 s .c om * <p> * This constructor accepts a String variable that has the path of the init * file that has the path of all the property files that have to be loaded. * The engine only accesses properties from the pr.properties file. However * if the processes, that have to be executed, require any more property * files, then the path of these files can also be mentioned in this init * file * </p> * * <p> * <ul> * <li> * Once the property file is loaded using the CSettings class, all the * attributes that the engine might access are retrieved and initialized to * the corresponding private member variables</li> * * <li> * The max size defined for both the log files are checked, against the * respective buffer sizes, to see that max size's specified are greater * than the buffer sizes</li> * * <li> * Engine log file is initialized and a database connection pool is created</li> * * <li> * A Shutdown hook is added that listens for a termination event for eg: * CTRL-C Once the event occurs appropriate action is taken to release * resources.</li> * </ul> * </p> * * @param pstrInitFile * String path of the init file that has the path of all the * property files that have to be loaded * @param pstrLoggerFile * Log4J.properties file. * @throws Exception * */ private CProcessRequestEngine(String pstrInitFile, String pstrLoggerFile, int iRebootCntr) throws Exception { try { PropertyConfigurator.configure(pstrLoggerFile); CSettings.getInstance().load(pstrInitFile); objEngineLogger_.log(LogLevel.NOTICE, info.toString()); context_ = new PREContextImpl(); context_.setPREinfo(info); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Initializing Engine"); } setRebootCounter(iRebootCntr); // System.setProperty("java.util.prefs.PreferencesFactory", // "stg.utils.prefs.PREPreferencesFactoryImpl"); // System.setProperty("java.util.prefs.PreferencesFactory.file", // CSettings.get("pr.java.util.prefs.PreferencesFactory.file", // null)); // try { // installLic(); // always install the license so that if the // // license is changed in between it will get // // reflected. // licContent_ = readLicense(); // LicenseVerifier.verify(licContent_); // objEngineLogger_.log(LogLevel.NOTICE, "Licensed to " // + licContent_.getHolder().getName() + " for usage of " // + licContent_.getConsumerAmount() + " threads."); // objEngineLogger_.log(LogLevel.NOTICE, "Valid up to " // + licContent_.getNotAfter()); // Day now = new Day(); // objEngineLogger_.log(LogLevel.NOTICE, "Days remaining " // + Math.abs(now.daysBetween(licContent_.getNotAfter()))); // } catch (LicenseContentException lce) { // generateLicenseRequest(); // objEngineLogger_.log(LogLevel.FATAL, "Invalid license."); //// System.err.println(lce.getLocalizedMessage()); // throw new Exception(lce.getLocalizedMessage()); // } catch (Exception e2) { // objEngineLogger_.log(LogLevel.FATAL, "Invalid license."); // generateLicenseRequest(); //// System.err.println(e2.getLocalizedMessage()); // throw new Exception(e2.getLocalizedMessage()); // } lStuckThreadMonitorInterval_ = Math .abs(Long.parseLong(CSettings.get("pr.stuckthreadmonitorinterval", "0"))); if (lStuckThreadMonitorInterval_ <= 0) { throw new IllegalArgumentException( "Property stuckthreadmonitorinterval should be greater than zero"); } if (objEngineLogger_.isEnabledFor(LogLevel.FINEST)) { objEngineLogger_.log(LogLevel.FINEST, "Redirecting System.out and System.err to log4j"); } System.setErr( new PrintStream(new LoggingOutputStream(Logger.getLogger("System.err"), Level.WARN), true)); System.setOut( new PrintStream(new LoggingOutputStream(Logger.getLogger("System.out"), Level.INFO), true)); } catch (Exception e) { throw e; } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("CLASSPATH=" + System.getProperty("java.class.path")); } strReqLogFilePath_ = CSettings.get("pr.requestlogfilepath"); strReqLogFileUrl_ = CSettings.get("pr.requestlogfileurl"); strReqLogFileExtension_ = CSettings.get("pr.requestlogfileextension"); paramSimpleDateFormat_ = new SimpleDateFormat(CSettings.get("pr.paramdateformat")); paramSimpleTimeFormat_ = new SimpleDateFormat(CSettings.get("pr.paramtimeformat")); paramSimpleDateTimeFormat_ = new SimpleDateFormat(CSettings.get("pr.paramdatetimeformat")); strParamArrValueDelim_ = CSettings.get("pr.paramarrvaluedelim"); FILTER_CONDITION = CSettings.get("pr.requesttypefilter", "XYZ"); if (!FILTER_CONDITION.equals("INCLUDE") && !FILTER_CONDITION.equals("EXCLUDE")) { throw new CProcessRequestEngineException( "Invalid FILTER type specified for property requesttypefilter."); } iStandAloneMaximumThread_ = CSettings.getInteger("pr.standalonemaxiumthreads"); iGroupMaximumThread_ = CSettings.getInteger("pr.groupmaxiumthreads"); if (iStandAloneMaximumThread_ <= 0) { throw new CProcessRequestEngineException("Invalid maximum threads for StandAlone engine configured."); } if (iGroupMaximumThread_ <= 0) { throw new CProcessRequestEngineException("Invalid maximum threads for Group engine configured."); } String strRequestTypes = CSettings.get("pr.processrequesttype", null); if (strRequestTypes == null) { throw new CProcessRequestEngineException( "Invalid processrequesttype defined. There must be a default value."); } StringTokenizer tokenizer = new StringTokenizer(strRequestTypes, ","); StringBuffer buffer = new StringBuffer(); while (tokenizer.hasMoreTokens()) { buffer.append("'"); buffer.append(tokenizer.nextElement()); buffer.append("'"); buffer.append(","); } buffer.deleteCharAt(buffer.length() - 1); if (FILTER_CONDITION.equals("INCLUDE")) { FILTER_CONDITION = "req_type IN (" + buffer.toString() + ")"; } else { FILTER_CONDITION = "req_type NOT IN (" + buffer.toString() + ")"; } try { (CCustomClassLoaderFactory.getInstance()).getClassLoader(this); // dummy call As this is a SingleTon Factory Pattern } catch (Exception e) { throw e; // throw new CProcessRequestEngineException("ClassLoader: " + // e.getMessage()); } iMaximumFetchSizeAtATime_ = Math.abs( Integer.parseInt(CSettings.get("pr.maximumfetchsizeinsinglefetch", CSettings.get("pr.dbcon")))); iThreadCounter_ = new AtomicInteger(1); iGrpThreadCounter_ = new AtomicInteger(1); setRebootMaxCounter(Integer.parseInt(CSettings.get("pr.rebootmaxcounter", "-1"))); setRebootSleepTime(Long.parseLong(CSettings.get("pr.sleepbeforereboottime", "5"))); hmWhereCondition_ = new HashMap<String, String>(); hmWhereCondition_.put("getScheduledTime", " <= "); bGroupEngineToBeStarted_ = ((CSettings.get("pr.groupengine", "OFF").equals("OFF")) ? false : true); httpserver_ = new CHttpServer(); // instantiate http server // bEngineTerminationConfirmed_ = false; vectorThreads_ = new Vector<Thread>(); // Inital size will be equal to // the total threads vectorThreadsGroup_ = new Vector<Thread>(); // =================== "" // ======================= // These NET properties are available only in JDK1.4.x and above. // Added by Kedar on July 31, 2004 .....SouthField Detroit USA System.setProperty("http.keepAlive", CSettings.get("pr.http.keepAlive", "true")); System.setProperty("http.maxConnections", CSettings.get("pr.http.maxConnections", "5")); System.setProperty("sun.net.client.defaultConnectTimeout", CSettings.get("pr.sun.net.client.defaultConnectTimeout", "10000")); System.setProperty("sun.net.client.defaultReadTimeout", CSettings.get("pr.sun.net.client.defaultReadTimeout", "10000")); try { jobMonitorEscalationTimeInterval_ = Math .abs(Integer.parseInt(CSettings.get("pr.jobmonitorescalationtimeinterval", "30"))); } catch (NumberFormatException e) { objEngineLogger_.error("Invalid value specified for jobmonitorescalationtimeinterval in properties."); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Defaulting jobmonitorescalationtimeinterval to 30 minutes."); } jobMonitorEscalationTimeInterval_ = 30; } /* * Anonymous inner class passed as a parameter to addShutdownHook This * thread is registered with the JVM, and the JVM starts this just * before shutting down. For eg: when u try to abort by pressing Ctrl-C. * Hence run method is called and in turn terminateEngine method is * called where resources are released. */ if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Add ShutDown Hook ...."); } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("ShutDown Hook Added...."); objEngineLogger_.info("Initializing Connection Pool ...."); } Class<?> c = Class.forName( CSettings.get("pr.dataSourceFactory", "stg.pr.engine.datasource.defaultimpl.PREDataSourceFactory")); Object obj = c.newInstance(); if (obj instanceof IDataSourceFactory) { dataSourceFactory_ = (IDataSourceFactory) obj; if (!dataSourceFactory_.initialize(new File(CSettings.get("pr.dataSourceFactoryConfigFile")))) { throw new CProcessRequestEngineException("Could not initialize the data source factory."); } } else { throw new CProcessRequestEngineException("Class does not implement IDataSource"); } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Initiating the cluster using the configuration from file " + System.getProperty("hazelcast.config")); } Config config = ConfigLoader.load(System.getProperty("hazelcast.config")); Hazelcast.init(config); loadStartupClasses(); for (Entry<String, Service> entry : services_.entrySet()) { Service service = entry.getValue(); if (service instanceof Singleton<?>) { Singleton<?> singleton = (Singleton<?>) service; context_.addSingletonIfAbsent(entry.getKey(), singleton); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Service " + entry.getKey() + ":" + entry.getValue().getClass().getName() + "made available to the context.. "); } } else { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Service " + entry.getKey() + ":" + entry.getValue().getClass().getName() + "is unavailable to the context.. "); } } } startWebServer(); // if (CSettings.get("pr.reportService", "OFF").equalsIgnoreCase("ON")) { // if (objEngineLogger_.isInfoEnabled()) { // objEngineLogger_.info("Starting the Report Services."); // } // try { // EngineConfig reportConfig = new EngineConfig(); // reportConfig.setBIRTHome(CSettings.get("pr.birt.home")); // reportConfig.setLogConfig(CSettings.get("pr.birt.log.dir"), // java.util.logging.Level.parse(CSettings // .get("pr.birt.log.level"))); // reportConfig.setProperty("ThreadPoolServiceSize", CSettings // .getInt("pr.birt.threadpoolsize", 3)); // reportService = ReportService.getService(reportConfig); // if (objEngineLogger_.isEnabledFor(LogLevel.NOTICE)) { // objEngineLogger_.log(LogLevel.NOTICE, // "Report Services started"); // } // } catch (ReportServiceException e) { // objEngineLogger_.fatal("Report Service exception encountered", // e); // if (objEngineLogger_.isEnabledFor(LogLevel.NOTICE)) { // objEngineLogger_.log(LogLevel.NOTICE, // "Unable to start the report services."); // } // } // } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Engine Initialized"); } // This thread is now assigned upfront as in the Terminate engine if // called from Reboot Sequence then // the shutdown hook has to be removed from the Runtime instance. tInterrupt_ = new Thread("shutdown") { public void run() { objEngineLogger_.log(LogLevel.NOTICE, "ShutDown Hook In Running mode."); terminateEngine(); } }; Runtime.getRuntime().addShutdownHook(tInterrupt_); }
From source file:com.github.trugath.jdalvikvm.VirtualMachineTest.java
private VirtualMachine run(final byte[] dexFileContent, final String mainClassName, final boolean runInNewThread) { lines.clear();/*from w w w . j ava 2 s . c om*/ final PrintStream oldErr = System.err; final PrintStream newOutAndErr = new PrintStream(new NullOutputStream()) { public synchronized void println(Object o) { println("" + o); } public void println(int x) { println("" + x); } public void println(long l) { println("" + l); } public void println(float f) { println("" + f); } public void println(double d) { println("" + d); } public synchronized void println(String x) { lines.add(x); } }; System.setOut(newOutAndErr); System.setErr(newOutAndErr); final VirtualMachine vm = new VirtualMachine() { protected void error(Throwable e) { System.setErr(oldErr); e.printStackTrace(); System.setErr(newOutAndErr); } }; vm.load(dexFileContent); if (runInNewThread) { new java.lang.Thread() { public void run() { vm.run(mainClassName, new String[0]); } }.start(); } else { vm.run(mainClassName, new String[0]); } return vm; }