Example usage for java.lang System setErr

List of usage examples for java.lang System setErr

Introduction

In this page you can find the example usage for java.lang System setErr.

Prototype

public static void setErr(PrintStream err) 

Source Link

Document

Reassigns the "standard" error output stream.

Usage

From source file:org.apache.maven.cli.CopyOfMavenCli.java

/**
 * configure logging//from   w w  w .j  a va 2  s  .  c o m
 */
private void logging(CliRequest cliRequest) {
    cliRequest.debug = cliRequest.commandLine.hasOption(CLIManager.DEBUG);
    cliRequest.quiet = !cliRequest.debug && cliRequest.commandLine.hasOption(CLIManager.QUIET);
    cliRequest.showErrors = cliRequest.debug || cliRequest.commandLine.hasOption(CLIManager.ERRORS);

    slf4jLoggerFactory = LoggerFactory.getILoggerFactory();
    Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration(slf4jLoggerFactory);

    if (cliRequest.debug) {
        cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_DEBUG);
        slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.DEBUG);
    } else if (cliRequest.quiet) {
        cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_ERROR);
        slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.ERROR);
    }
    // else fall back to default log level specified in conf
    // see http://jira.codehaus.org/browse/MNG-2570

    if (cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
        File logFile = new File(cliRequest.commandLine.getOptionValue(CLIManager.LOG_FILE));
        logFile = resolveFile(logFile, cliRequest.workingDirectory);

        // redirect stdout and stderr to file
        try {
            PrintStream ps = new PrintStream(new FileOutputStream(logFile));
            System.setOut(ps);
            System.setErr(ps);
        } catch (FileNotFoundException e) {
            //
            // Ignore
            //
        }
    }

    slf4jConfiguration.activate();

    plexusLoggerManager = new Slf4jLoggerManager();
    slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
}

From source file:eu.irreality.age.SwingAetheriaGameLoaderInterface.java

public static void redirectStandardError(String file) {
    File f = new File(file);
    if (!f.exists()) {
        if (!f.getParentFile().exists()) {
            if (!f.getParentFile().mkdirs()) {
                System.err.println(
                        "Could not redirect standard error to " + file + ": unable to create directories.");
                return;
            }/*  ww  w . j  a  v  a2 s  .co  m*/
        }
    }
    //{f.getParentFile().exists()
    try {
        System.setErr(new PrintStream(new FileOutputStream(f, true)));
        System.err.println("[" + new Date() + "]");
    } catch (FileNotFoundException e) {
        System.err.println("Could not redirect standard error to " + file + ":");
        e.printStackTrace();
    }
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.ReusableAFMavenCli.java

public int doMain(AFCliRequest cliRequest, ClassWorld classWorld) {

    PrintStream originalOut = System.out;
    PrintStream originalErr = System.err;
    try {//from   w  w  w . j a  v  a  2s.  co m
        initialize(cliRequest);
        cli(cliRequest);
        logging(cliRequest);
        version(cliRequest);
        properties(cliRequest);
        reusableContainer = container(cliRequest, classWorld);
        commands(cliRequest);//ok
        configure(cliRequest);
        toolchains(cliRequest);
        populateRequest(cliRequest);
        repository(cliRequest);
        return execute(cliRequest);
    } catch (ExitException e) {
        //e.printStackTrace();
        e.getStackTrace();
        return e.exitCode;
    } catch (UnrecognizedOptionException e) {
        //e.printStackTrace();
        e.getStackTrace();
        return 1;
    } catch (BuildAbort e) {
        //e.printStackTrace();
        e.getStackTrace();
        AFCLIReportingUtils.showError(reusableSlf4jLogger, "ABORTED", e, cliRequest.isShowErrors());
        return 2;
    } catch (Exception e) {
        //e.printStackTrace();
        e.getStackTrace();
        AFCLIReportingUtils.showError(reusableSlf4jLogger, "Error executing Maven.", e,
                cliRequest.isShowErrors());

        return 1;
    } finally {
        System.setOut(originalOut);
        System.setErr(originalErr);
    }
}

From source file:com.cisco.dvbu.ps.deploytool.dao.wsapi.VCSWSDAOImpl.java

public void vcsExportCommand(String prefix, String arguments, String vcsIgnoreMessages, String propertyFile)
        throws CompositeException {

    String identifier = "VCSWSDAOImpl.vcsExportCommand"; // some unique identifier that characterizes this invocation.
    String actionName = "EXPORT";

    try {//  ww w  .  j a v a2s  .  c  o  m
        boolean preserveQuotes = false;
        boolean initArgsList = true;
        List<String> argsList = new ArrayList<String>();
        argsList = CommonUtils.parseArguments(argsList, initArgsList, arguments, preserveQuotes, propertyFile);
        String[] args = argsList.toArray(new String[0]);

        /*
         * 2014-02-14 (mtinius): Removed the PDTool Archive capability
         */
        //         ExportCommand.startCommand(null, null, args);
        /*
         * 2014-02-14 (mtinius): Added security manager around the Composite native Archive code because
         *                    it has System.out.println and System.exit commands.  Need to trap both.
         */
        String maskedargsList = CommonUtils.getArgumentListMasked(argsList);
        if (logger.isDebugEnabled()) {
            logger.debug(identifier + "(prefix, arguments, vcsIgnoreMessages, propertyFile).  prefix=" + prefix
                    + "  arguments=[" + maskedargsList + "]" + "  vcsIgnoreMessages=" + vcsIgnoreMessages
                    + "  propertyFile=" + propertyFile);
        }

        // Get the existing security manager
        SecurityManager sm = System.getSecurityManager();
        PrintStream originalOut = System.out;
        PrintStream originalErr = System.err;
        String command = "ExportCommand.startCommand";
        try {
            // Get the offset location of the java.policy file [offset from PDTool home].
            String javaPolicyOffset = CommonConstants.javaPolicy;
            String javaPolicyLocation = CommonUtils.extractVariable(prefix,
                    CommonUtils.getFileOrSystemPropertyValue(propertyFile, "PROJECT_HOME_PHYSICAL"),
                    propertyFile, true) + javaPolicyOffset;
            // Set the java security policy
            System.getProperties().setProperty("java.security.policy", javaPolicyLocation);

            // Create a new System.out Logger
            Logger exportLogger = Logger.getLogger(ExportCommand.class);
            System.setOut(new PrintStream(new LogOutputStream(exportLogger, Level.INFO)));
            System.setErr(new PrintStream(new LogOutputStream(exportLogger, Level.ERROR)));
            // Create a new security manager
            System.setSecurityManager(new NoExitSecurityManager());

            // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
            if (CommonUtils.isExecOperation()) {
                // Invoke the Composite native export command.
                ExportCommand.startCommand(null, null, args);
            } else {
                logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                        + "] WAS NOT PERFORMED.\n");
            }
        } catch (NoExitSecurityExceptionStatusNonZero nesesnz) {
            String error = identifier + ":: Exited with exception from System.exit(): " + command
                    + "(null, null, " + maskedargsList + ")";
            logger.error(error);
            throw new CompositeException(error);
        } catch (NoExitSecurityExceptionStatusZero nesezero) {
            if (logger.isDebugEnabled()) {
                logger.debug(identifier + ":: Exited successfully from System.exit(): " + command
                        + "(null, null, " + maskedargsList + ")");
            }
        } finally {
            System.setSecurityManager(sm);
            System.setOut(originalOut);
            System.setErr(originalErr);
        }

    } catch (Exception e) {
        if (resolveExecCommandLineError(prefix, e.getMessage().toString(), vcsIgnoreMessages)) {
            ApplicationException applicationException = new ApplicationException(
                    "ExportCommand execution returned an error=" + e.getMessage().toString());
            if (logger.isErrorEnabled()) {
                logger.error(applicationException);
            }
            throw applicationException;
        }
    }
}

From source file:org.jkiss.dbeaver.core.application.DBeaverApplication.java

private void stopDebugWriter() {
    if (oldSystemOut != null)
        System.setOut(oldSystemOut);
    if (oldSystemErr != null)
        System.setErr(oldSystemErr);

    if (debugWriter != null) {
        IOUtils.close(debugWriter);/*  www  .  j  a  va 2 s  . c o  m*/
        debugWriter = null;
    }
}

From source file:eu.cassandra.platform.gui.GUI.java

/**
 * Redirects output streams to the GUI.//w ww . j  av a  2  s  . c o  m
 */
@SuppressWarnings("unused")
private void redirectSystemStreams() {
    OutputStream out = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            updateTextArea(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            updateTextArea(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };
    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(out, true));
}

From source file:org.codehaus.mojo.antlr.AbstractAntlrMojo.java

protected void performGeneration(GenerationPlan plan, Artifact antlrArtifact) throws MojoExecutionException {
    if (!plan.getGenerationDirectory().getParentFile().exists()) {
        plan.getGenerationDirectory().getParentFile().mkdirs();
    }//from   w  w w . j a  va2s.  co  m

    // ----------------------------------------------------------------------
    // Wrap arguments
    // Note: grammar file should be last
    // ----------------------------------------------------------------------

    List arguments = new LinkedList();
    addArgIf(arguments, debug, "-debug");
    addArgIf(arguments, diagnostic, "-diagnostic");
    addArgIf(arguments, trace, "-trace");
    addArgIf(arguments, traceParser, "-traceParser");
    addArgIf(arguments, traceLexer, "-traceLexer");
    addArgIf(arguments, traceTreeParser, "-traceTreeParser");

    addArgs(arguments);

    arguments.add("-o");
    arguments.add(plan.getGenerationDirectory().getPath());

    if (plan.getCollectedSuperGrammarIds().size() > 0) {
        arguments.add("-glib");
        StringBuffer buffer = new StringBuffer();
        Iterator ids = plan.getCollectedSuperGrammarIds().iterator();
        while (ids.hasNext()) {
            buffer.append(new File(sourceDirectory, (String) ids.next()));
            if (ids.hasNext()) {
                buffer.append(';');
            }
        }
        arguments.add(buffer.toString());
    }

    arguments.add(plan.getSource().getPath());

    String[] args = (String[]) arguments.toArray(new String[arguments.size()]);

    if (plan.getImportVocabTokenTypesDirectory() != null
            && !plan.getImportVocabTokenTypesDirectory().equals(plan.getGenerationDirectory())) {
        // we need to spawn a new process to properly set up PWD
        CommandLine commandLine = new CommandLine("java");
        commandLine.addArgument("-classpath", false);
        commandLine.addArgument(generateClasspathForProcessSpawning(antlrArtifact), true);
        commandLine.addArgument("antlr.Tool", false);
        commandLine.addArguments(args, true);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(plan.getImportVocabTokenTypesDirectory());
        try {
            executor.execute(commandLine);
        } catch (IOException e) {
            getLog().warn("Error spawning process to execute antlr tool : " + e.getMessage());
        }

        return;
    }

    // ----------------------------------------------------------------------
    // Call Antlr
    // ----------------------------------------------------------------------

    if (getLog().isDebugEnabled()) {
        getLog().debug("antlr args=\n" + StringUtils.join(args, "\n"));
    }

    boolean failedSetManager = false;
    SecurityManager oldSm = null;
    try {
        oldSm = System.getSecurityManager();
        System.setSecurityManager(NoExitSecurityManager.INSTANCE);
    } catch (SecurityException ex) {
        // ANTLR-12
        oldSm = null;
        failedSetManager = true;
        // ignore, in embedded environment the security manager can already be set.
        // in such a case assume the exit call is handled properly..
        getLog().warn("Cannot set custom SecurityManager. "
                + "Antlr's call to System.exit() can cause application shutdown "
                + "if not handled by the current SecurityManager.");
    }

    String originalUserDir = null;
    if (plan.getImportVocabTokenTypesDirectory() != null) {
        originalUserDir = System.getProperty("user.dir");
        System.setProperty("user.dir", plan.getImportVocabTokenTypesDirectory().getPath());
    }

    PrintStream oldErr = System.err;

    OutputStream errOS = new StringOutputStream();
    PrintStream err = new PrintStream(errOS);
    System.setErr(err);

    try {
        executeAntlrInIsolatedClassLoader((String[]) arguments.toArray(new String[0]), antlrArtifact);
    } catch (SecurityException e) {
        if (e.getMessage().equals("exitVM-0")
                || e.getClass().getName().equals("org.netbeans.core.execution.ExitSecurityException")) // netbeans
                                                                                                                                             // IDE Sec
                                                                                                                                             // Manager.
        {
            // ANTLR-12
            // now basically every secutiry manager could set different message, how to handle in generic way?
            // probably only by external execution
            // / in case of NetBeans SecurityManager, it's not possible to distinguish exit codes, rather swallow
            // than fail.
            getLog().debug(e);
        } else {
            throw new MojoExecutionException(
                    "Antlr execution failed: " + e.getMessage() + "\n Error output:\n" + errOS, e);
        }
    } finally {
        if (originalUserDir != null) {
            System.setProperty("user.dir", originalUserDir);
        }
        if (!failedSetManager) {
            System.setSecurityManager(oldSm);
        }
        System.setErr(oldErr);
        System.err.println(errOS.toString());
    }
}

From source file:edu.stanford.muse.launcher.Main.java

public static void main(String args[]) throws Exception {

    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    final int TIMEOUT_SECS = 60;
    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();//from   w ww  .  j a v a 2 s .co  m
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Muse batch mode", options);
        return;
    }

    boolean debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open"))
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");
    if (cmd.hasOption("search-mode"))
        searchMode = true;
    if (cmd.hasOption("amuse-mode"))
        amuseMode = true;

    System.setSecurityManager(null); // this is important
    WebAppContext webapp0 = null; // deployWarAt("root.war", "/"); // for redirecting
    String path = "/muse";
    WebAppContext webapp1 = deployWarAt("muse.war", path);
    if (webapp1 == null) {
        System.err.println("Aborting... no webapp");
        return;
    }

    // if in any debug mode, turn blurring off
    if (debug)
        webapp1.setAttribute("noblur", true);

    // we set this and its read by JSPHelper within the webapp 
    System.setProperty("muse.container", "jetty");

    // need to copy crossdomain.xml file for
    String tmp = System.getProperty("java.io.tmpdir");
    final URL url = Main.class.getClassLoader().getResource("crossdomain.xml");
    try {
        InputStream is = url.openStream();
        String file = tmp + File.separatorChar + "crossdomain.xml";
        copy_stream_to_file(is, file);
    } catch (Exception e) {
        System.err.println("Aborting..." + e);
        return;
    }
    server = new Server(PORT);
    ResourceHandler resource_handler = new ResourceHandler();
    //        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
    resource_handler.setResourceBase(tmp);

    // set the header buffer size in the connectors, default is a ridiculous 4K, which causes failures any time there is
    // is a large request, such as selecting a few hundred folders. (even for posts!)
    // usually there is only one SocketConnector, so we just put the setHeaderBufferSize in a loop.
    Connector conns[] = server.getConnectors();
    for (Connector conn : conns) {
        int NEW_BUFSIZE = 1000000;
        // out.println ("Connector " + conn + " buffer size is " + conn.getHeaderBufferSize() + " setting to " + NEW_BUFSIZE);
        conn.setHeaderBufferSize(NEW_BUFSIZE);
    }

    BASE_URL = "http://localhost:" + PORT + path;
    String 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.
    String debugFile = tmp + File.separatorChar + "debug.txt";

    HandlerList hl = new HandlerList();
    if (webapp0 != null)
        hl.setHandlers(new Handler[] { webapp1, webapp0, resource_handler });
    else
        hl.setHandlers(new Handler[] { webapp1, resource_handler });
    out.println("Starting up Muse 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 Muse without enough memory. \nIf you launched Muse from the command line, you can increase memory with an option like java -Xmx1g",
                2000);
    server.setHandler(hl);

    // 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! Muse is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running Muse still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of Muse, please go to http://localhost:9099/muse\n";
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching Muse again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting Muse at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill Muse if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.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) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for Muse 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(out);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                if (System.getProperty("muse.mode.public") != null)
                    link = "http://localhost:" + PORT + "/muse/archives/";
                else
                    link = "http://localhost:" + PORT + "/muse/index.jsp";

                if (searchMode) {
                    String u = "http://localhost:" + PORT + "/muse/search";
                    out.println("Launching URL in browser: " + u);
                    link += "?mode=search";
                } else if (amuseMode) {
                    String u = "http://localhost:" + PORT + "/muse/amuse.jsp";
                    out.println("Launching URL in browser: " + u);
                    link = u;
                } else 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

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent Muse from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!cmd.hasOption("no-shutdown")) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("Muse will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:edu.stanford.epadd.launcher.Main.java

public static void main(String args[]) throws Exception {
    setupLogging();//from w w  w .  j a  v a 2 s.  c o  m
    basicSetup(args);
    setupResources();

    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);

    // 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 is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running ePADD still alive despite attempt to kill it, 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);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting ePADD at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill ePADD if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.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) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("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) {
            System.err.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(System.err);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                link = "http://localhost:" + PORT + "/epadd/index.jsp";

                if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/epadd/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } 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);
            }
        }

        if (!noShutdown) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("ePADD will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java

@Override
public void runBare() throws Throwable
{
    String qname = getClass().getName() + "." + getName();

    // Initialize this for each test run
    _env = new HashMap<String, String>();

    PrintStream oldOut = System.out;
    PrintStream oldErr = System.err;
    PrintStream out = null;/*from w ww .ja  va 2s . com*/
    PrintStream err = null;

    boolean redirected = _output != null && _output.length() > 0;
    if (redirected)
    {
        _outputFile = new File(String.format("%s/TEST-%s.out", _output, qname));
        out = new PrintStream(new FileOutputStream(_outputFile), true);
        err = new PrintStream(String.format("%s/TEST-%s.err", _output, qname));

        System.setOut(out);
        System.setErr(err);

        if (_interleaveBrokerLog)
        {
            _testcaseOutputStream = out;
        }
        else
        {
            _testcaseOutputStream = new PrintStream(new FileOutputStream(String
                    .format("%s/TEST-%s.broker.out", _output, qname)), true);
        }
    }

    try
    {
        super.runBare();
    }
    catch (Exception e)
    {
        _logger.error("exception", e);
        throw e;
    }
    finally
    {
        stopAllBrokers();

        // reset properties used in the test
        revertSystemProperties();
        revertLoggingLevels();

        if(_brokerCleanBetweenTests)
        {
            final String qpidWork = System.getProperty("QPID_WORK");
            cleanBrokerWork(qpidWork);
            createBrokerWork(qpidWork);
        }

        _logger.info("==========  stop " + getTestName() + " ==========");

        if (redirected)
        {
            System.setErr(oldErr);
            System.setOut(oldOut);
            err.close();
            out.close();
            if (!_interleaveBrokerLog)
            {
                _testcaseOutputStream.close();
            }
        }
    }
}