Example usage for java.lang System setOut

List of usage examples for java.lang System setOut

Introduction

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

Prototype

public static void setOut(PrintStream out) 

Source Link

Document

Reassigns the "standard" output stream.

Usage

From source file:com.jug.MotherMachine.java

/**
 * Created and shows the console window and redirects System.out and
 * System.err to it.// w  w  w  .jav  a 2 s  . c om
 */
private void initConsoleWindow() {
    frameConsoleWindow = new JFrame("MotherMachine Console Window");
    //      frameConsoleWindow.setResizable( false );
    consoleWindowTextArea = new JTextArea();

    final int centerX = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2;
    final int centerY = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2;
    frameConsoleWindow.setBounds(centerX - GUI_CONSOLE_WIDTH / 2, centerY - GUI_HEIGHT / 2, GUI_CONSOLE_WIDTH,
            GUI_HEIGHT);
    final JScrollPane scrollPane = new JScrollPane(consoleWindowTextArea);
    scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0));
    frameConsoleWindow.getContentPane().add(scrollPane);

    final OutputStream out = new OutputStream() {

        private final PrintStream original = new PrintStream(System.out);

        @Override
        public void write(final int b) throws IOException {
            updateConsoleTextArea(String.valueOf((char) b));
            original.print(String.valueOf((char) b));
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            updateConsoleTextArea(new String(b, off, len));
            original.print(new String(b, off, len));
        }

        @Override
        public void write(final byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    final OutputStream err = new OutputStream() {

        private final PrintStream original = new PrintStream(System.out);

        @Override
        public void write(final int b) throws IOException {
            updateConsoleTextArea(String.valueOf((char) b));
            original.print(String.valueOf((char) b));
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            updateConsoleTextArea(new String(b, off, len));
            original.print(new String(b, off, len));
        }

        @Override
        public void write(final byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(err, true));
}

From source file:it.crs4.seal.common.SealToolParser.java

/**
 * Prints help and exits with code 3.//from   w w  w  .j  av  a  2s .  c  o  m
 */
public void defaultUsageError(String msg) {
    System.err.print("Usage error");
    if (msg != null)
        System.err.println(":  " + msg);
    System.err.print("\n");
    // XXX: redirect System.out to System.err since the simple version of
    // HelpFormatter.printHelp prints to System.out, and we're on a way to
    // a fatal exit.
    System.setOut(System.err);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("" + toolName + " [options] <in>+ <out>", options);
    System.exit(3);
}

From source file:edu.ku.brc.specify.ui.AppBase.java

/**
 * Sets up StdErr and StdOut to be 'tee'd' to files. 
 *//*from  www.j a v  a  2s.  c  o  m*/
public static void setupTeeForStdErrStdOut(final boolean doStdErr, final boolean doStdOut) {
    try {
        if (doStdOut) {
            // Tee standard output
            File file = getFullLogFilePath(OUTPUT_LOG);
            if (file != null) {
                PrintStream out = new PrintStream(new FileOutputStream(file));
                PrintStream tee = new TeeOutputStream(System.out, out);
                System.setOut(tee);
            }
        }

        if (doStdErr) {
            // Tee standard error
            File file = getFullLogFilePath(ERRORSYS_LOG);
            if (file != null) {
                PrintStream err = new PrintStream(new FileOutputStream(file));
                PrintStream tee = new TeeOutputStream(System.err, err);
                System.setErr(tee);
            }
        }

    } catch (FileNotFoundException e) {
    }
}

From source file:de.haber.xmind2latex.XMindToLatexExporterConfigurationTest.java

@Test
public void testConfigureHelp2() {
    File in = new File("src/test/resources/content.xml");
    File result = new File("target/testout/helpmsg.txt");
    result.delete();//w w  w .  j av  a  2  s.  co m
    result.getParentFile().mkdirs();

    String[] args = new String[] { "-i", in.getPath(), "-help" };
    try {
        result.createNewFile();
        FileOutputStream os = new FileOutputStream(result);
        PrintStream out = new PrintStream(os);
        PrintStream old_out = System.out;
        System.setOut(out);
        CliParameters.build(args);

        String resultContent = FileUtils.readFileToString(result);
        assertFalse(resultContent.isEmpty());
        assertTrue(resultContent.contains("usage: xmind2latex"));
        System.setOut(old_out);
        os.close();
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:MainProgram.MainProgram.java

public LogOutput() {
    setLayout(new BorderLayout());
    add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
    System.setOut(new PrintStream(taOutputStream));
}

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

public static void main(String args[]) throws Exception {
    Splash splash = null;/* w  w  w.j a v  a2 s .  co  m*/
    splash = new Splash();

    tellUser(splash, "Setting up logging...");
    setupLogging();
    tellUser(splash, "Setting up shutdown port...");
    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 muse 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) {
            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 {
                    shutdownSessions();
                    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) {
            try {
                int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

                new ShutdownThread(server, shutdownPort).start();
                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) {
                err.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();
    }
    // splashDemo.closeWindow();
}

From source file:com.esri.geoevent.test.performance.ui.OrchestratorController.java

private void redirectSystemOutAndErrToTextArea() {
    OutputStream out = new OutputStream() {
        @Override/* www.  jav a2s . c  o  m*/
        public void write(int b) throws IOException {
            Platform.runLater(() -> outputBuffer.append(String.valueOf((char) b)));
        }
    };
    System.setOut(new PrintStream(out, true));
    OutputStream err = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            Platform.runLater(() -> outputBuffer.append(String.valueOf((char) b)));
        }
    };
    System.setErr(new PrintStream(err, true));
}

From source file:org.apache.flink.yarn.YarnTestBase.java

/**
 * This method returns once the "startedAfterString" has been seen.
 *//*  w  w  w.j a va  2s  .com*/
protected Runner startWithArgs(String[] args, String startedAfterString, RunTypes type) {
    LOG.info("Running with args {}", Arrays.toString(args));

    outContent = new ByteArrayOutputStream();
    errContent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));

    final int START_TIMEOUT_SECONDS = 60;

    Runner runner = new Runner(args, type, 0);
    runner.setName("Frontend (CLI/YARN Client) runner thread (startWithArgs()).");
    runner.start();

    for (int second = 0; second < START_TIMEOUT_SECONDS; second++) {
        sleep(1000);
        // check output for correct TaskManager startup.
        if (outContent.toString().contains(startedAfterString)
                || errContent.toString().contains(startedAfterString)) {
            LOG.info("Found expected output in redirected streams");
            return runner;
        }
        // check if thread died
        if (!runner.isAlive()) {
            sendOutput();
            if (runner.getRunnerError() != null) {
                throw new RuntimeException("Runner failed with exception.", runner.getRunnerError());
            }
            Assert.fail("Runner thread died before the test was finished.");
        }
    }

    sendOutput();
    Assert.fail("During the timeout period of " + START_TIMEOUT_SECONDS + " seconds the "
            + "expected string did not show up");
    return null;
}

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.
 * //from   w  ww.  j  a  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:com.datatorrent.stram.cli.ApexCli.java

protected PrintStream suppressOutput() {
    PrintStream originalStream = System.out;
    if (raw) {//from  ww  w.  j av a2  s.  c o  m
        PrintStream dummyStream = new PrintStream(new OutputStream() {
            @Override
            public void write(int b) {
                // no-op
            }

        });
        System.setOut(dummyStream);
    }
    return originalStream;
}