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:com.jug.MotherMachine.java

/**
 * Created and shows the console window and redirects System.out and
 * System.err to it./*from   w  w  w.  j  a  va  2  s  . com*/
 */
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:org.apache.hadoop.hbase.mapreduce.TestImportExport.java

/**
 * test main method. Import should print help and call System.exit
 *//*from  w w w  .j  ava2  s .  c om*/
@Test
public void testImportMain() throws Exception {
    PrintStream oldPrintStream = System.err;
    SecurityManager SECURITY_MANAGER = System.getSecurityManager();
    LauncherSecurityManager newSecurityManager = new LauncherSecurityManager();
    System.setSecurityManager(newSecurityManager);
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    String[] args = {};
    System.setErr(new PrintStream(data));
    try {
        System.setErr(new PrintStream(data));
        Import.main(args);
        fail("should be SecurityException");
    } catch (SecurityException e) {
        assertEquals(-1, newSecurityManager.getExitCode());
        assertTrue(data.toString().contains("Wrong number of arguments:"));
        assertTrue(data.toString().contains("-Dimport.bulk.output=/path/for/output"));
        assertTrue(data.toString().contains("-Dimport.filter.class=<name of filter class>"));
        assertTrue(data.toString().contains("-Dimport.bulk.output=/path/for/output"));
        assertTrue(data.toString().contains("-Dmapreduce.reduce.speculative=false"));
    } finally {
        System.setErr(oldPrintStream);
        System.setSecurityManager(SECURITY_MANAGER);
    }
}

From source file:com.mirth.connect.server.Mirth.java

private void initializeLogging() {
    // Route all System.err messages to log4j error
    System.setErr(new PrintStream(new LogOutputStream()));
    // Route all java.util.logging.Logger output to log4j
    JuliToLog4JService.getInstance().start();

    // Add a custom filter to appenders to suppress SAXParser warnings introduced in 7u40 (MIRTH-3548)
    for (Enumeration<?> en = Logger.getRootLogger().getAllAppenders(); en.hasMoreElements();) {
        ((Appender) en.nextElement()).addFilter(new MirthLog4jFilter());
    }//  ww w .  ja  v  a  2s .  c  o m
}

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

/**
 * Sets up StdErr and StdOut to be 'tee'd' to files. 
 */// w  ww  . j a v a 2 s . 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:edu.stanford.muse.launcher.Splash.java

public static void main(String args[]) throws Exception {
    Splash splash = null;/*from   ww w  .  j a  va 2  s.c  o 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:org.meresco.triplestore.TransactionLogTest.java

@Test
public void testCorruptedCurrentFileInTransactionLog() throws Exception {
    String currentData = "<transaction_item>\n" + "    <action>add</action>\n"
            + "    <identifier>test1.rdf</identifier>\n" + "    <filedata>ignored</filedata>\n"
            + "<transaction_item>\n" + "    <action>add</action>\n" + "    <identifier>test2.rdf</identifier>\n"
            + "    <filedata>ignored</filedata>\n" + "</transaction_item>\n";

    Utils.write(transactionLog.transactionLogFilePath, currentData);

    OutputStream os = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(os);
    PrintStream err = System.err;
    System.setErr(ps);
    try {//from   w  w w .j a  va2s.  c o m
        transactionLog.recoverTripleStore();
        fail("Should fail");
    } catch (TransactionLogException e) {
        assertEquals("Corrupted transaction_item in " + transactionLog.transactionLogFilePath.getAbsolutePath()
                + " at line 9. This should never occur.", e.getMessage());
        assertTrue(os.toString(),
                os.toString().contains("XML document structures must start and end within the same entity."));
    } finally {
        System.setErr(err);
    }
    assertEquals(0, tsMock.actions.size());
}

From source file:net.pms.PMS.java

/**
 * Initialisation procedure for PMS.//from w  ww  .j ava 2 s  .c  o  m
 * @return true if the server has been initialized correctly. false if the server could
 * not be set to listen on the UPnP port.
 * @throws Exception
 */
private boolean init() throws Exception {
    // The public VERSION field is deprecated.
    // This is a temporary fix for backwards compatibility
    VERSION = getVersion();

    // call this as early as possible
    displayBanner();

    AutoUpdater autoUpdater = null;
    if (Build.isUpdatable()) {
        String serverURL = Build.getUpdateServerURL();
        autoUpdater = new AutoUpdater(serverURL, getVersion());
    }

    registry = createSystemUtils();

    if (!isHeadless()) {
        frame = new LooksFrame(autoUpdater, configuration);
    } else {
        logger.info("GUI environment not available");
        logger.info("Switching to console mode");
        frame = new DummyFrame();
    }

    /*
     * we're here:
     *
     *     main() -> createInstance() -> init()
     *
     * which means we haven't created the instance returned by get()
     * yet, so the frame appender can't access the frame in the
     * standard way i.e. PMS.get().getFrame(). we solve it by
     * inverting control ("don't call us; we'll call you") i.e.
     * we notify the appender when the frame is ready rather than
     * e.g. making getFrame() static and requiring the frame
     * appender to poll it.
     *
     * XXX an event bus (e.g. MBassador or Guava EventBus
     * (if they fix the memory-leak issue)) notification
     * would be cleaner and could support other lifecycle
     * notifications (see above).
     */
    FrameAppender.setFrame(frame);

    configuration.addConfigurationListener(new ConfigurationListener() {
        @Override
        public void configurationChanged(ConfigurationEvent event) {
            if ((!event.isBeforeUpdate())
                    && PmsConfiguration.NEED_RELOAD_FLAGS.contains(event.getPropertyName())) {
                frame.setReloadable(true);
            }
        }
    });

    frame.setStatusCode(0, Messages.getString("PMS.130"), "connect_no-220.png");
    RendererConfiguration.loadRendererConfigurations(configuration);
    logger.info("Checking MPlayer font cache. It can take a minute or so.");
    checkProcessExistence("MPlayer", true, null, configuration.getMplayerPath(), "dummy");

    if (Platform.isWindows()) {
        checkProcessExistence("MPlayer", true, configuration.getTempFolder(), configuration.getMplayerPath(),
                "dummy");
    }

    logger.info("Done!");

    // check the existence of Vsfilter.dll
    if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
        logger.info("Found AviSynth plugins dir: " + registry.getAvsPluginsDir().getAbsolutePath());
        File vsFilterdll = new File(registry.getAvsPluginsDir(), "VSFilter.dll");
        if (!vsFilterdll.exists()) {
            logger.info(
                    "VSFilter.dll is not in the AviSynth plugins directory. This can cause problems when trying to play subtitled videos with AviSynth");
        }
    }

    // Check if VLC is found
    String vlcVersion = registry.getVlcVersion();
    String vlcPath = registry.getVlcPath();

    if (vlcVersion != null && vlcPath != null) {
        logger.info("Found VLC version " + vlcVersion + " at: " + vlcPath);

        Version vlc = new Version(vlcVersion);
        Version requiredVersion = new Version("2.0.2");

        if (vlc.compareTo(requiredVersion) <= 0) {
            logger.error("Only VLC versions 2.0.2 and above are supported");
        }
    }

    // check if Kerio is installed
    if (registry.isKerioFirewall()) {
        logger.info("Detected Kerio firewall");
    }

    // force use of specific dvr ms muxer when it's installed in the right place
    File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe");
    if (dvrsMsffmpegmuxer.exists()) {
        configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
    }

    // disable jaudiotagger logging
    LogManager.getLogManager()
            .readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes()));

    // wrap System.err
    System.setErr(new PrintStream(new SystemErrWrapper(), true));

    server = new HTTPServer(configuration.getServerPort());

    /*
     * XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
     * can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
     *
     * XXX: if a plugin requires initialization/notification even earlier than
     * this, then a new external listener implementing a new callback should be added
     * e.g. StartupListener.registeredExtensions()
     */
    try {
        ExternalFactory.lookup();
    } catch (Exception e) {
        logger.error("Error loading plugins", e);
    }

    // a static block in Player doesn't work (i.e. is called too late).
    // this must always be called *after* the plugins have loaded.
    // here's as good a place as any
    Player.initializeFinalizeTranscoderArgsListeners();

    // Initialize a player factory to register all players
    PlayerFactory.initialize(configuration);

    // Instantiate listeners that require registered players.
    ExternalFactory.instantiateLateListeners();

    // Any plugin-defined players are now registered, create the GUI view.
    frame.addEngines();

    boolean binding = false;

    try {
        binding = server.start();
    } catch (BindException b) {
        logger.info("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: "
                + b.getMessage());
        logger.info("Maybe another process is running or the hostname is wrong.");
    }

    new Thread("Connection Checker") {
        @Override
        public void run() {
            try {
                Thread.sleep(7000);
            } catch (InterruptedException e) {
            }

            if (foundRenderers.isEmpty()) {
                frame.setStatusCode(0, Messages.getString("PMS.0"), "messagebox_critical-220.png");
            } else {
                frame.setStatusCode(0, Messages.getString("PMS.18"), "apply-220.png");
            }
        }
    }.start();

    if (!binding) {
        return false;
    }

    // initialize the cache
    if (configuration.getUseCache()) {
        initializeDatabase(); // XXX: this must be done *before* new MediaLibrary -> new MediaLibraryFolder
        mediaLibrary = new MediaLibrary();
        logger.info("A tiny cache admin interface is available at: http://" + server.getHost() + ":"
                + server.getPort() + "/console/home");
    }

    // XXX: this must be called:
    //     a) *after* loading plugins i.e. plugins register root folders then RootFolder.discoverChildren adds them
    //     b) *after* mediaLibrary is initialized, if enabled (above)
    getRootFolder(RendererConfiguration.getDefaultConf());

    frame.serverReady();

    // UPNPHelper.sendByeBye();
    Runtime.getRuntime().addShutdownHook(new Thread("PMS Listeners Stopper") {
        @Override
        public void run() {
            try {
                for (ExternalListener l : ExternalFactory.getExternalListeners()) {
                    l.shutdown();
                }
                UPNPHelper.shutDownListener();
                UPNPHelper.sendByeBye();
                logger.debug("Forcing shutdown of all active processes");
                for (Process p : currentProcesses) {
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ise) {
                        logger.trace("Forcing shutdown of process: " + p);
                        ProcessUtil.destroy(p);
                    }
                }
                get().getServer().stop();
                Thread.sleep(500);
            } catch (InterruptedException e) {
                logger.debug("Caught exception", e);
            }
        }
    });

    UPNPHelper.sendAlive();
    logger.trace("Waiting 250 milliseconds...");
    Thread.sleep(250);
    UPNPHelper.listen();

    return true;
}

From source file:org.apache.hadoop.hbase.mapreduce.TestImportExport.java

/**
 * test main method. Export should print help and call System.exit
 *//*from www  .  ja v  a2s . c o  m*/
@Test
public void testExportMain() throws Exception {
    PrintStream oldPrintStream = System.err;
    SecurityManager SECURITY_MANAGER = System.getSecurityManager();
    LauncherSecurityManager newSecurityManager = new LauncherSecurityManager();
    System.setSecurityManager(newSecurityManager);
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    String[] args = {};
    System.setErr(new PrintStream(data));
    try {
        System.setErr(new PrintStream(data));
        Export.main(args);
        fail("should be SecurityException");
    } catch (SecurityException e) {
        assertEquals(-1, newSecurityManager.getExitCode());
        assertTrue(data.toString().contains("Wrong number of arguments:"));
        assertTrue(data.toString()
                .contains("Usage: Export [-D <property=value>]* <tablename> <outputdir> [<versions> "
                        + "[<starttime> [<endtime>]] [^[regex pattern] or [Prefix] to filter]]"));
        assertTrue(data.toString().contains("-D hbase.mapreduce.scan.column.family=<familyName>"));
        assertTrue(data.toString().contains("-D hbase.mapreduce.include.deleted.rows=true"));
        assertTrue(data.toString().contains("-Dhbase.client.scanner.caching=100"));
        assertTrue(data.toString().contains("-Dmapreduce.map.speculative=false"));
        assertTrue(data.toString().contains("-Dmapreduce.reduce.speculative=false"));
        assertTrue(data.toString().contains("-Dhbase.export.scanner.batch=10"));
    } finally {
        System.setErr(oldPrintStream);
        System.setSecurityManager(SECURITY_MANAGER);
    }
}

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

/**
 * This method returns once the "startedAfterString" has been seen.
 *///from   w  ww.ja  va 2 s  .co m
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:com.esri.geoevent.test.performance.ui.OrchestratorController.java

private void redirectSystemOutAndErrToTextArea() {
    OutputStream out = new OutputStream() {
        @Override/*from   www.j a  va  2  s.com*/
        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));
}