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:net.dv8tion.jda.core.utils.SimpleLog.java

/**
 * Will duplicate the output-streams to the specified Files.
 * This will catch everything that is sent to sout and serr (even stuff not logged via SimpleLog).
 *
 * @param std/*from  www .jav  a  2  s  .  c om*/
 *      The file to use for System.out logging, or null to not LOG System.out to a file
 * @param err
 *      The file to use for System.err logging, or null to not LOG System.err to a file
 * @throws java.io.IOException
 *      If an IO error is encountered while dealing with the file. Most likely
 *      to be caused by a lack of permissions when creating the log folders or files.
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void addFileLogs(File std, File err) throws IOException {
    if (std != null) {
        if (origStd == null)
            origStd = System.out;
        if (!std.getAbsoluteFile().getParentFile().exists()) {
            std.getAbsoluteFile().getParentFile().mkdirs();
        }
        if (!std.exists()) {
            std.createNewFile();
        }
        FileOutputStream fOut = new FileOutputStream(std, true);
        System.setOut(new PrintStream(new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                origStd.write(b);
                fOut.write(b);
            }
        }));
        if (stdOut != null)
            stdOut.close();
        stdOut = fOut;
    } else if (origStd != null) {
        System.setOut(origStd);
        stdOut.close();
        origStd = null;
    }
    if (err != null) {
        if (origErr == null)
            origErr = System.err;
        if (!err.getAbsoluteFile().getParentFile().exists()) {
            err.getAbsoluteFile().getParentFile().mkdirs();
        }
        if (!err.exists()) {
            err.createNewFile();
        }
        FileOutputStream fOut = new FileOutputStream(err, true);
        System.setErr(new PrintStream(new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                origErr.write(b);
                fOut.write(b);
            }
        }));
        if (errOut != null)
            errOut.close();
        errOut = fOut;
    } else if (origErr != null) {
        System.setErr(origErr);
        errOut.close();
        origErr = null;
    }
}

From source file:org.apache.hive.beeline.TestSchemaTool.java

@Override
protected void tearDown() throws Exception {
    File metaStoreDir = new File(testMetastoreDB);
    if (metaStoreDir.exists()) {
        FileUtils.forceDeleteOnExit(metaStoreDir);
    }//from w  w w.  j  av a 2s  . co m
    System.setOut(outStream);
    System.setErr(errStream);
    if (conn != null) {
        conn.close();
    }
}

From source file:com.github.jessemull.microflex.stat.statbigdecimal.MeanBigDecimalWeightsTest.java

/**
 * Generates random objects and numbers for testing.
 *///from   w  w  w. j av a 2 s.c  om
@BeforeClass
public static void setUp() {

    if (error) {

        System.setErr(new PrintStream(new OutputStream() {
            public void write(int x) {
            }
        }));

    }

    for (int j = 0; j < array.length; j++) {

        PlateBigDecimal plate = RandomUtil.randomPlateBigDecimal(rows, columns, minValue, maxValue, length,
                "Plate1-" + j);

        array[j] = plate;
    }

    for (int j = 0; j < arrayIndices.length; j++) {

        PlateBigDecimal plateIndices = RandomUtil.randomPlateBigDecimal(rows, columns, minValue, maxValue,
                lengthIndices, "Plate1-" + j);

        arrayIndices[j] = plateIndices;
    }

    for (int i = 0; i < weights.length; i++) {
        double randomDouble = random.nextDouble();
        weights[i] = new BigDecimal(randomDouble + "", contextWeights).doubleValue();
    }

    for (int i = 0; i < weightsIndices.length; i++) {
        double randomDouble = random.nextDouble();
        weightsIndices[i] = new BigDecimal(randomDouble + "", contextWeights).doubleValue();
    }
}

From source file:org.owasp.dependencycheck.cli.CliParserTest.java

/**
 * Test of parse method with jar and cpe args, of class CliParser.
 *
 * @throws Exception thrown when an exception occurs.
 *//*from   w ww . ja va  2  s .com*/
@Test
public void testParse_unknown() throws Exception {

    String[] args = { "-unknown" };

    PrintStream out = System.out;
    PrintStream err = System.err;
    ByteArrayOutputStream baos_out = new ByteArrayOutputStream();
    ByteArrayOutputStream baos_err = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos_out));
    System.setErr(new PrintStream(baos_err));

    CliParser instance = new CliParser();

    try {
        instance.parse(args);
    } catch (ParseException ex) {
        Assert.assertTrue(ex.getMessage().contains("Unrecognized option"));
    }
    Assert.assertFalse(instance.isGetVersion());
    Assert.assertFalse(instance.isGetHelp());
    Assert.assertFalse(instance.isRunScan());
}

From source file:VASSAL.launch.Launcher.java

protected Launcher(String[] args) {
    if (instance != null)
        throw new IllegalStateException();
    instance = this;

    LaunchRequest lreq = null;/*  www.  j  a  va2s.c  o  m*/
    try {
        lreq = LaunchRequest.parseArgs(args);
    } catch (LaunchRequestException e) {
        System.err.println("VASSAL: " + e.getMessage());
        System.exit(1);
    }

    lr = lreq;

    // Note: We could do more sanity checking of the launch request
    // in standalone mode, but we don't bother because this is meant
    // only for debugging, not for normal use. If you pass nonsense
    // arguments (e.g., '-e' to the Player), don't expect it to work.
    final boolean standalone = lr.standalone;

    /*
        // parse the command line args now if we're standalone, since they
        // could be messed up and so we'll bail before setup
        LaunchRequest lr = null;
        if (standalone) {
          // Note: We could do more sanity checking of the launch request
          // in standalone mode, but we don't bother because this is meant
          // only for debugging, not for normal use. If you pass nonsense
          // arguments (e.g., '-e' to the Player), don't expect it to work.
          try {
            lr = LaunchRequest.parseArgs(args);
          }
          catch (LaunchRequestException e) {
            System.err.println("VASSAL: " + e.getMessage());
            System.exit(1);
          }
        }
    */

    // start the error log and setup system properties
    final StartUp start = SystemUtils.IS_OS_MAC_OSX ? new MacOSXStartUp() : new StartUp();

    start.startErrorLog();

    // log everything which comes across our stderr
    System.setErr(new PrintStream(new LoggedOutputStream(), true));

    logger.info(getClass().getSimpleName());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
    start.initSystemProperties();

    // if we're not standalone, contact the module manager for instructions
    if (!standalone) {
        try {
            final int port = Integer.parseInt(System.getProperty("VASSAL.port"));

            final InetAddress lo = InetAddress.getByName(null);
            final Socket cs = new Socket(lo, port);

            ipc = new IPCMessenger(cs);

            ipc.addEventListener(CloseRequest.class, new CloseRequestListener());

            ipc.start();

            ipc.send(new StartedNotice(Info.getInstanceID()));
        } catch (IOException e) {
            // What we've got here is failure to communicate.
            ErrorDialog.show(e, "Error.communication_error",
                    Resources.getString(getClass().getSimpleName() + ".app_name"));
            System.exit(1);
        }
    }

    createMenuManager();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                launch();
            } catch (ExtensionsLoader.LoadExtensionException e2) {
                warn(e2);
            } catch (IOException e1) {
                warn(e1);
            }
        }

        private void warn(Exception e1) {
            if (ipc == null) {
                // we are standalone, so warn the user directly
                ErrorDialog.showDetails(e1, ThrowableUtils.getStackTrace(e1), "Error.module_load_failed",
                        e1.getMessage());
            } else {
                // we have a manager, so pass the load failure back to it
                try {
                    ipc.send(new AbstractLaunchAction.NotifyOpenModuleFailed(lr, e1));
                } catch (IOException e2) {
                    // warn the user directly as a last resort
                    ErrorDialog.showDetails(e1, ThrowableUtils.getStackTrace(e1), "Error.module_load_failed",
                            e1.getMessage());

                    ErrorDialog.show(e2, "Error.communication_error",
                            Resources.getString(getClass().getSimpleName() + ".app_name"));
                }
            }

            System.exit(1);
        }
    });
}

From source file:org.apache.solr.hadoop.MapReduceIndexerToolArgumentParserTest.java

@After
public void tearDown() throws Exception {
    super.tearDown();
    System.setOut(oldSystemOut);
    System.setErr(oldSystemErr);
}

From source file:de.uni.bremen.monty.moco.CompileTestProgramsTest.java

@Test
public void compileProgramTest() throws IOException, InterruptedException {
    final PrintStream bufferOut = System.out;
    final PrintStream bufferErr = System.err;
    final ByteArrayOutputStream outStream = setStdout();
    final ByteArrayOutputStream errorStream = setStdErr(file);

    if (inputFileExists(file)) {
        System.setProperty("testrun.readFromFile", changeFileExtension(file, ".input"));
    }/*from ww  w  .j av a  2 s .c  om*/
    Main.main(new String[] { "-e", file.getAbsolutePath() });

    if (outputFileExists(file)) {
        assertThat(getOutput(errorStream), is(isEmptyString()));
        assertThat(getOutput(outStream), is(expectedResultFromFile(file)));
    } else {
        // chop the last char to not contain /n in the string
        assertThat(StringUtils.chop(getOutput(errorStream)), is(expectedErrorFromFile(file)));
        assertThat(getOutput(outStream), is(isEmptyString()));
    }
    System.clearProperty("testrun.readFromFile");
    System.setOut(bufferOut);
    System.setErr(bufferErr);
}

From source file:downloadwebpages.DownloadWebpages.java

/**
 * create a gui to mimic the output console
 *//*from   ww  w .j  av  a  2  s .  c  o m*/
private void createGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame();
    frame.add(new JLabel(" Output"), BorderLayout.NORTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // add JTextArea to show console
    JTextArea ta = new JTextArea(30, 50);
    TextAreaOutputStream taos = new TextAreaOutputStream(ta, 60);
    PrintStream ps = new PrintStream(taos);
    System.setOut(ps);
    System.setErr(ps);

    frame.add(new JScrollPane(ta));
    frame.pack();
    frame.setVisible(true);
}

From source file:org.apache.taverna.scufl2.wfdesc.TestConvertToWfdesc.java

private void help(String argName) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream outBuf = new PrintStream(out);

    ByteArrayOutputStream err = new ByteArrayOutputStream();
    PrintStream errBuf = new PrintStream(err);

    try {//  www . j a  v  a  2 s  .  c o  m
        System.setOut(outBuf);
        System.setErr(errBuf);
        ConvertToWfdesc.main(new String[] { argName });
    } finally {
        restoreStd();
    }
    out.flush();
    out.close();
    err.flush();
    err.close();

    assertEquals(0, err.size());
    String help = out.toString("utf-8");
    //      System.out.println(help);
    assertTrue(help.contains("scufl2-to-wfdesc"));
    assertTrue(help.contains("\nIf no arguments are given"));
}

From source file:de.fau.cs.osr.hddiff.perfsuite.RunFcDiff.java

private String runFcDiff(File fileA, File fileB, File fileDiff) throws IOException {
    PrintStream oldOut = System.out;
    PrintStream oldErr = System.err;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        try {//from  w  ww. j  a va  2 s  . c om
            try (PrintStream ps = new PrintStream(baos)) {
                System.setOut(ps);
                System.setErr(ps);

                fc.xml.diff.Diff.main(new String[] { fileA.getAbsolutePath(), fileB.getAbsolutePath(),
                        fileDiff.getAbsolutePath() });
            } finally {
                System.setOut(oldOut);
                System.setErr(oldErr);
            }
        } catch (Exception e) {
            throw new FcDiffException(new String(baos.toByteArray()), e);
        }

        return new String(baos.toByteArray());
    }
}