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.meresco.triplestore.TransactionLogTest.java

@Test
public void testFailingCommit() throws Exception {
    final List<Boolean> committed = new ArrayList<Boolean>();
    class MyTransactionLog extends TransactionLog {
        public MyTransactionLog(Triplestore tripleStore, File baseDir) throws Exception {
            super(tripleStore, baseDir);
        }//w w w  . j  a v a  2 s  . c  o  m

        void commit_do(TransactionItem tsItem) throws IOException {
            committed.add(true);
            super.commit_do(tsItem);
            if (committed.size() < 3) {
                return;
            }
            ArrayList<String> files = super.getTransactionItemFiles();
            String filedata = Utils.read(new File(super.transactionLogDir, files.get(0)));
            assertTrue(filedata.contains("record.rdf"));
            throw new RuntimeException("An error message");
        }
    }
    transactionLog = new MyTransactionLog(tsMock, tempdir);
    transactionLog.init();
    addFilesToTransactionLog();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(stderr);
    PrintStream orig_stderr = System.err;
    System.setErr(ps);
    try {
        transactionLog.writeTransactionItem("add", "record.rdf", "data");
        fail("Should raise an Exception");
    } catch (Error e) {
    } finally {
        System.setErr(orig_stderr);
    }
    ArrayList<String> files = transactionLog.getTransactionItemFiles();
    String filedata = Utils.read(new File(transactionLog.transactionLogDir, files.get(0)));
    assertTrue(filedata.contains("testRecord.rdf"));
    assertTrue(filedata.contains("record.rdf"));//Transaction is saved but the server will crash
    assertEquals(3, countTransactionItems(files.get(0)));
    assertTrue(stderr.toString(), stderr.toString().contains("An error message"));
}

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

/**
 * Test TaskManager failure and also if the vcores are set correctly (see issue FLINK-2213).
 *//*from  www.java2  s  .c o m*/
@Test(timeout = 100000) // timeout after 100 seconds
public void testTaskManagerFailure() {
    LOG.info("Starting testTaskManagerFailure()");
    Runner runner = startWithArgs(
            new String[] { "-j", flinkUberjar.getAbsolutePath(), "-t", flinkLibFolder.getAbsolutePath(), "-n",
                    "1", "-jm", "768", "-tm", "1024", "-s", "3", // set the slots 3 to check if the vCores are set properly!
                    "-nm", "customName", "-Dfancy-configuration-value=veryFancy",
                    "-Dyarn.maximum-failed-containers=3", "-D" + ConfigConstants.YARN_VCORES + "=2" },
            "Number of connected TaskManagers changed to 1. Slots available: 3", RunTypes.YARN_SESSION);

    Assert.assertEquals(2, getRunningContainers());

    // ------------------------ Test if JobManager web interface is accessible -------

    YarnClient yc = null;
    try {
        yc = YarnClient.createYarnClient();
        yc.init(yarnConfiguration);
        yc.start();

        List<ApplicationReport> apps = yc.getApplications(EnumSet.of(YarnApplicationState.RUNNING));
        Assert.assertEquals(1, apps.size()); // Only one running
        ApplicationReport app = apps.get(0);
        Assert.assertEquals("customName", app.getName());
        String url = app.getTrackingUrl();
        if (!url.endsWith("/")) {
            url += "/";
        }
        if (!url.startsWith("http://")) {
            url = "http://" + url;
        }
        LOG.info("Got application URL from YARN {}", url);

        String response = TestBaseUtils.getFromHTTP(url + "taskmanagers/");

        JsonNode parsedTMs = new ObjectMapper().readTree(response);
        ArrayNode taskManagers = (ArrayNode) parsedTMs.get("taskmanagers");
        Assert.assertNotNull(taskManagers);
        Assert.assertEquals(1, taskManagers.size());
        Assert.assertEquals(3, taskManagers.get(0).get("slotsNumber").asInt());

        // get the configuration from webinterface & check if the dynamic properties from YARN show up there.
        String jsonConfig = TestBaseUtils.getFromHTTP(url + "jobmanager/config");
        Map<String, String> parsedConfig = WebMonitorUtils.fromKeyValueJsonArray(jsonConfig);

        Assert.assertEquals("veryFancy", parsedConfig.get("fancy-configuration-value"));
        Assert.assertEquals("3", parsedConfig.get("yarn.maximum-failed-containers"));
        Assert.assertEquals("2", parsedConfig.get(ConfigConstants.YARN_VCORES));

        // -------------- FLINK-1902: check if jobmanager hostname/port are shown in web interface
        // first, get the hostname/port
        String oC = outContent.toString();
        Pattern p = Pattern.compile("Flink JobManager is now running on ([a-zA-Z0-9.-]+):([0-9]+)");
        Matcher matches = p.matcher(oC);
        String hostname = null;
        String port = null;
        while (matches.find()) {
            hostname = matches.group(1).toLowerCase();
            port = matches.group(2);
        }
        LOG.info("Extracted hostname:port: {} {}", hostname, port);

        Assert.assertEquals("unable to find hostname in " + jsonConfig, hostname,
                parsedConfig.get(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY));
        Assert.assertEquals("unable to find port in " + jsonConfig, port,
                parsedConfig.get(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY));

        // test logfile access
        String logs = TestBaseUtils.getFromHTTP(url + "jobmanager/log");
        Assert.assertTrue(logs.contains("Starting YARN ApplicationMaster"));
        Assert.assertTrue(logs.contains("Starting JobManager"));
        Assert.assertTrue(logs.contains("Starting JobManager Web Frontend"));
    } catch (Throwable e) {
        LOG.warn("Error while running test", e);
        Assert.fail(e.getMessage());
    }

    // ------------------------ Kill container with TaskManager and check if vcores are set correctly -------

    // find container id of taskManager:
    ContainerId taskManagerContainer = null;
    NodeManager nodeManager = null;
    UserGroupInformation remoteUgi = null;
    NMTokenIdentifier nmIdent = null;
    try {
        remoteUgi = UserGroupInformation.getCurrentUser();
    } catch (IOException e) {
        LOG.warn("Unable to get curr user", e);
        Assert.fail();
    }
    for (int nmId = 0; nmId < NUM_NODEMANAGERS; nmId++) {
        NodeManager nm = yarnCluster.getNodeManager(nmId);
        ConcurrentMap<ContainerId, Container> containers = nm.getNMContext().getContainers();
        for (Map.Entry<ContainerId, Container> entry : containers.entrySet()) {
            String command = Joiner.on(" ").join(entry.getValue().getLaunchContext().getCommands());
            if (command.contains(YarnTaskManager.class.getSimpleName())) {
                taskManagerContainer = entry.getKey();
                nodeManager = nm;
                nmIdent = new NMTokenIdentifier(taskManagerContainer.getApplicationAttemptId(), null, "", 0);
                // allow myself to do stuff with the container
                // remoteUgi.addCredentials(entry.getValue().getCredentials());
                remoteUgi.addTokenIdentifier(nmIdent);
            }
        }
        sleep(500);
    }

    Assert.assertNotNull("Unable to find container with TaskManager", taskManagerContainer);
    Assert.assertNotNull("Illegal state", nodeManager);

    yc.stop();

    List<ContainerId> toStop = new LinkedList<ContainerId>();
    toStop.add(taskManagerContainer);
    StopContainersRequest scr = StopContainersRequest.newInstance(toStop);

    try {
        nodeManager.getNMContext().getContainerManager().stopContainers(scr);
    } catch (Throwable e) {
        LOG.warn("Error stopping container", e);
        Assert.fail("Error stopping container: " + e.getMessage());
    }

    // stateful termination check:
    // wait until we saw a container being killed and AFTERWARDS a new one launched
    boolean ok = false;
    do {
        LOG.debug("Waiting for correct order of events. Output: {}", errContent.toString());

        String o = errContent.toString();
        int killedOff = o.indexOf("Container killed by the ApplicationMaster");
        if (killedOff != -1) {
            o = o.substring(killedOff);
            ok = o.indexOf("Launching TaskManager") > 0;
        }
        sleep(1000);
    } while (!ok);

    // send "stop" command to command line interface
    runner.sendStop();
    // wait for the thread to stop
    try {
        runner.join(1000);
    } catch (InterruptedException e) {
        LOG.warn("Interrupted while stopping runner", e);
    }
    LOG.warn("stopped");

    // ----------- Send output to logger
    System.setOut(originalStdout);
    System.setErr(originalStderr);
    String oC = outContent.toString();
    String eC = errContent.toString();
    LOG.info("Sending stdout content through logger: \n\n{}\n\n", oC);
    LOG.info("Sending stderr content through logger: \n\n{}\n\n", eC);

    // ------ Check if everything happened correctly
    Assert.assertTrue("Expect to see failed container", eC.contains("New messages from the YARN cluster"));

    Assert.assertTrue("Expect to see failed container",
            eC.contains("Container killed by the ApplicationMaster"));

    Assert.assertTrue("Expect to see new container started",
            eC.contains("Launching TaskManager") && eC.contains("on host"));

    // cleanup auth for the subsequent tests.
    remoteUgi.getTokenIdentifiers().remove(nmIdent);

    LOG.info("Finished testTaskManagerFailure()");
}

From source file:com.netspective.sparx.navigate.NavigationControllerServlet.java

protected void executAntBuild(ServletConfig servletConfig, File buildFile, String target)
        throws ServletException {
    log.debug("Executing Ant build " + buildFile + " target " + target);

    org.apache.tools.ant.Project antProject = AntProject.getConfiguredProject(buildFile);
    antProject.setProperty("app.home", servletConfig.getServletContext().getRealPath("/"));
    antProject.setProperty("app.init-count", Long.toString(getInitializationCount()));

    Properties servletOptionsProps = servletOptions.setProperties(new Properties(), "app.servlet-options",
            false);//from w  ww.  j  a v  a  2s.  c  o  m
    for (Iterator i = servletOptionsProps.keySet().iterator(); i.hasNext();) {
        String propName = (String) i.next();
        antProject.setProperty(propName, servletOptionsProps.getProperty(propName));
    }

    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
    PrintStream pstream = new PrintStream(ostream);

    BuildLogger logger = new NoBannerLogger();
    logger.setMessageOutputLevel(org.apache.tools.ant.Project.MSG_INFO);
    logger.setOutputPrintStream(pstream);
    logger.setErrorPrintStream(pstream);

    PrintStream saveOut = System.out;
    PrintStream saveErr = System.err;
    System.setOut(pstream);
    System.setErr(pstream);

    antProject.addBuildListener(logger);
    Exception exceptionThrown = null;
    try {
        Vector targets = new Vector();
        if (target != null) {
            String[] targetNames = TextUtils.getInstance().split(target, ",", true);
            for (int i = 0; i < targetNames.length; i++)
                targets.add(targetNames[i]);
        } else
            targets.add(antProject.getDefaultTarget());
        antProject.executeTargets(targets);
    } catch (Exception e) {
        exceptionThrown = e;
    }

    if (exceptionThrown != null) {
        log.error(ostream.toString());
        log.error("Error running ant build file " + buildFile + " target " + target, exceptionThrown);
    } else
        log.debug(ostream.toString());

    int extnPos = buildFile.getName().lastIndexOf('.');
    String nameNoExtn = extnPos != -1 ? buildFile.getName().substring(0, extnPos) : buildFile.getName();
    File logFile = servletOptions.getInitUsingAntLogFile() != null
            ? new File(servletOptions.getInitUsingAntLogFile())
            : new File(buildFile.getParentFile(), nameNoExtn + ".log");

    FileOutputStream fos = null;
    PrintWriter logWriter = null;
    try {
        fos = new FileOutputStream(logFile.getAbsolutePath(), logFile.exists());
        logWriter = new PrintWriter(fos);
        logWriter.println("-----------------------------------------------------------------------------");
        logWriter.println("Started build at " + SimpleDateFormat.getDateTimeInstance().format(new Date())
                + " in Servlet " + getServletName() + " (Context " + getServletContext().getServletContextName()
                + ", BuildFile " + buildFile.getAbsolutePath() + ")");
        logWriter.write(ostream.toString());
        if (exceptionThrown != null)
            logWriter.write(TextUtils.getInstance().getStackTrace(exceptionThrown));
        logWriter.println("Ended build at " + SimpleDateFormat.getDateTimeInstance().format(new Date())
                + " in Servlet " + getServletName() + " (Context " + getServletContext().getServletContextName()
                + ", BuildFile " + buildFile.getAbsolutePath() + ")");
    } catch (IOException e) {
        throw new ServletException(e);
    } finally {
        logWriter.close();
        try {
            fos.close();
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }

    System.setOut(saveOut);
    System.setErr(saveErr);
}

From source file:mil.dod.th.ose.junit4xmltestrunner.ant.XMLJUnitResultFormatter.java

public void cleanup() {
    System.setOut(m_OldStdOut);
    System.setErr(m_OldStdErr);
}

From source file:org.apache.hadoop.hive.metastore.tools.TestSchemaToolForMetastore.java

/**
 * Test schema upgrade//from   w w w  .  java 2  s  .  c o  m
 */
@Test
public void testSchemaUpgrade() throws Exception {
    boolean foundException = false;
    // Initialize 1.2.0 schema
    execute(new SchemaToolTaskInit(), "-initSchemaTo 1.2.0");
    // verify that driver fails due to older version schema
    try {
        schemaTool.verifySchemaVersion();
    } catch (HiveMetaException e) {
        // Expected to fail due to old schema
        foundException = true;
    }
    if (!foundException) {
        throw new Exception("Hive operations shouldn't pass with older version schema");
    }

    // Generate dummy pre-upgrade script with errors
    String invalidPreUpgradeScript = writeDummyPreUpgradeScript(0, "upgrade-2.3.0-to-3.0.0.derby.sql",
            "foo bar;");
    // Generate dummy pre-upgrade scripts with valid SQL
    String validPreUpgradeScript0 = writeDummyPreUpgradeScript(1, "upgrade-2.3.0-to-3.0.0.derby.sql",
            "CREATE TABLE schema_test0 (id integer);");
    String validPreUpgradeScript1 = writeDummyPreUpgradeScript(2, "upgrade-2.3.0-to-3.0.0.derby.sql",
            "CREATE TABLE schema_test1 (id integer);");

    // Capture system out and err
    schemaTool.setVerbose(true);
    OutputStream stderr = new ByteArrayOutputStream();
    PrintStream errPrintStream = new PrintStream(stderr);
    System.setErr(errPrintStream);
    OutputStream stdout = new ByteArrayOutputStream();
    PrintStream outPrintStream = new PrintStream(stdout);
    System.setOut(outPrintStream);

    // Upgrade schema from 0.7.0 to latest
    execute(new SchemaToolTaskUpgrade(), "-upgradeSchemaFrom 1.2.0");

    // Verify that the schemaTool ran pre-upgrade scripts and ignored errors
    Assert.assertTrue(stderr.toString().contains(invalidPreUpgradeScript));
    Assert.assertTrue(stderr.toString().contains("foo"));
    Assert.assertFalse(stderr.toString().contains(validPreUpgradeScript0));
    Assert.assertFalse(stderr.toString().contains(validPreUpgradeScript1));
    Assert.assertTrue(stdout.toString().contains(validPreUpgradeScript0));
    Assert.assertTrue(stdout.toString().contains(validPreUpgradeScript1));

    // Verify that driver works fine with latest schema
    schemaTool.verifySchemaVersion();
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibResourcesAj.java

/**
 * png?//from   www. java 2 s . c  om
 * brut.androlib.res.AndrolibResources
 * public void aaptPackage(File apkFile, File manifest, File resDir, File rawDir, File assetDir, File[] include)
 */
@Around("execution(* brut.androlib.res.AndrolibResources.aaptPackage(..))"
        + "&& args(apkFile, manifest, resDir, rawDir, assetDir, include)")
public void aaptPackage_around(ProceedingJoinPoint joinPoint, File apkFile, File manifest, File resDir,
        File rawDir, File assetDir, File[] include) throws Throwable {
    /**
     * ?10,?
     */
    int max = 10;
    PrintStream olderr = System.err;
    String lastErrInfo = null;
    while (max-- > 0) {

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos)) {
            System.setErr(ps);
            try {
                joinPoint.proceed(joinPoint.getArgs());
                System.setErr(olderr);
                /**
                 * ????
                 */
                fuckNotDefinedRes_clearAddRes(apkFile);
                break;
            } catch (Throwable e) {
                System.setErr(olderr);

                String errStr = new String(baos.toByteArray());

                /**
                 * ?,?,
                 */
                if (errStr.equals(lastErrInfo)) {
                    throw new ShakaException(errStr, e);
                }
                lastErrInfo = errStr;

                String rootDir = manifest.getParentFile().getAbsolutePath();

                boolean bContinue = fuckNotDefinedRes(errStr, rootDir);

                if (checkPng(errStr, rootDir)) {
                    bContinue = true;
                }

                if (horizontalScrollView_check(errStr)) {
                    bContinue = true;
                }

                if (bContinue) {
                    continue;
                } else {
                    throw new ShakaException(errStr, e);
                }
            } finally {
                System.setErr(olderr);
            }
        }
    }

}

From source file:com.cyberway.issue.io.arc.ARCWriterTest.java

protected void lengthTooShort(String name, boolean compress, boolean strict) throws IOException {
    CorruptibleARCWriter writer = createArcWithOneRecord(name, compress);
    // Add some bytes on the end to mess up the record.
    String content = getContent();
    ByteArrayInputStream bais = getBais(content + "SOME TRAILING BYTES");
    writeRecord(writer, SOME_URL, "text/html", content.length(), bais);
    writer.setEndJunk("SOME TRAILING BYTES".getBytes());
    writeRecord(writer, SOME_URL, "text/html", content.length(), getBais(content));
    writer.close();//from w w  w  . jav a2 s  .c om

    // Catch System.err into a byte stream.
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    System.setErr(new PrintStream(os));

    ARCReader r = ARCReaderFactory.get(writer.getFile());
    r.setStrict(strict);
    int count = iterateRecords(r);
    assertTrue("Count wrong " + count, count == 4);

    // Make sure we get the warning string which complains about the
    // trailing bytes.
    String err = os.toString();
    assertTrue("No message " + err, err.startsWith("WARNING") && (err.indexOf("Record ENDING at") > 0));
}

From source file:org.apache.easyant.core.EasyAntMain.java

/**
 * Process command line arguments. When ant is started from Launcher, launcher-only arguments do not get passed
 * through to this routine.//from  w  w w  . j ava  2s .  c om
 *
 * @since Ant 1.6
 */
private void processArgs(CommandLine line) {
    String searchForThis;
    PrintStream logTo = null;

    if (line.hasOption("help")) {
        printUsage();
        return;
    }
    if (easyAntConfiguration.getMsgOutputLevel() >= Project.MSG_VERBOSE || line.hasOption("version")) {
        printVersion();
        if (line.hasOption("version")) {
            return;
        }
    }
    if (line.hasOption("showMemoryDetails")) {
        easyAntConfiguration.setShowMemoryDetails(true);
    }
    if (line.hasOption("diagnostics")) {
        Diagnostics.doReport(System.out, easyAntConfiguration.getMsgOutputLevel());
        return;
    }
    if (line.hasOption("quiet")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_WARN);
    }
    if (line.hasOption("verbose")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_VERBOSE);
    }
    if (line.hasOption("debug")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_DEBUG);
    }
    if (line.hasOption("noinput")) {
        easyAntConfiguration.setAllowInput(false);
    }
    if (line.hasOption("logfile")) {
        try {
            File logFile = new File(line.getOptionValue("logfile"));
            logTo = new PrintStream(new FileOutputStream(logFile));
            isLogFileUsed = true;
        } catch (IOException ioe) {
            String msg = "Cannot write on the specified log file. "
                    + "Make sure the path exists and you have write " + "permissions.";
            throw new BuildException(msg);
        } catch (ArrayIndexOutOfBoundsException aioobe) {
            String msg = "You must specify a log file when " + "using the -log argument";
            throw new BuildException(msg);
        }
    }
    if (line.hasOption("buildmodule")) {
        File buildModule = new File(line.getOptionValue("buildmodule").replace('/', File.separatorChar));
        easyAntConfiguration.setBuildModule(buildModule);
    }
    if (line.hasOption("buildfile")) {
        File buildFile = new File(line.getOptionValue("buildfile").replace('/', File.separatorChar));
        easyAntConfiguration.setBuildFile(buildFile);
    }
    if (line.hasOption("buildconf")) {
        easyAntConfiguration.getActiveBuildConfigurations().add(line.getOptionValue("buildconf"));
    }

    File easyantConfFile = null;

    if (line.hasOption("configfile")) {
        easyantConfFile = new File(line.getOptionValue("configfile").replace('/', File.separatorChar));
    } else {
        // if no command line switch is specified check the default location

        File easyantHome = new File(
                System.getProperty(EasyAntMagicNames.EASYANT_HOME).replace('/', File.separatorChar));
        File defaultGlobalEasyantConfFile = new File(easyantHome,
                EasyAntConstants.DEFAULT_GLOBAL_EASYANT_CONF_FILE);

        if (defaultGlobalEasyantConfFile.exists()) {
            easyantConfFile = defaultGlobalEasyantConfFile;
        }
    }

    if (easyantConfFile != null) {
        try {
            easyAntConfiguration = EasyantConfigurationFactory.getInstance()
                    .createConfigurationFromFile(easyAntConfiguration, easyantConfFile.toURI().toURL());
        } catch (Exception e) {
            throw new BuildException(e);
        }
    }

    if (line.hasOption("listener")) {
        easyAntConfiguration.getListeners().add(line.getOptionValue("listener"));
    }
    if (line.hasOption("D")) {
        easyAntConfiguration.getDefinedProps().putAll(line.getOptionProperties("D"));
    }
    if (line.hasOption("logger")) {
        if (easyAntConfiguration.getLoggerClassname() != null) {
            throw new BuildException("Only one logger class may be specified.");
        }
        easyAntConfiguration.setLoggerClassname(line.getOptionValue("logger"));
    }
    if (line.hasOption("inputhandler")) {
        if (easyAntConfiguration.getInputHandlerClassname() != null) {
            throw new BuildException("Only one input handler class may " + "be specified.");
        }
        easyAntConfiguration.setInputHandlerClassname(line.getOptionValue("inputhandler"));
    }
    if (line.hasOption("emacs")) {
        easyAntConfiguration.setEmacsMode(true);
    }
    if (line.hasOption("projecthelp")) {
        // set the flag to display the targets and quit
        projectHelp = true;
    }
    if (line.hasOption("find")) {
        // eat up next arg if present, default to module.ivy
        if (line.getOptionValues("find").length > 0) {
            searchForThis = line.getOptionValue("find");

        } else {
            searchForThis = EasyAntConstants.DEFAULT_BUILD_MODULE;
        }
        easyAntConfiguration.setBuildModule(new File(searchForThis));
        easyAntConfiguration.setBuildModuleLookupEnabled(true);
    }
    if (line.hasOption("propertyfile")) {
        propertyFiles.add(line.getOptionValue("propertyfile"));
    }
    if (line.hasOption("keep-going")) {
        easyAntConfiguration.setKeepGoingMode(true);
    }
    if (line.hasOption("offline")) {
        easyAntConfiguration.setOffline(true);
    }
    if (line.hasOption("nice")) {
        easyAntConfiguration.setThreadPriority(Integer.decode(line.getOptionValue("nice")));

        if (easyAntConfiguration.getThreadPriority() < Thread.MIN_PRIORITY
                || easyAntConfiguration.getThreadPriority() > Thread.MAX_PRIORITY) {
            throw new BuildException("Niceness value is out of the range 1-10");
        }
    }
    if (line.hasOption("autoproxy")) {
        easyAntConfiguration.setProxy(true);
    }
    if (!line.getArgList().isEmpty()) {
        for (Object o : line.getArgList()) {
            String target = (String) o;
            easyAntConfiguration.getTargets().add(target);
        }
    }

    // Load the property files specified by -propertyfile
    loadPropertyFiles();

    if (logTo != null) {
        easyAntConfiguration.setOut(logTo);
        easyAntConfiguration.setErr(logTo);
        System.setOut(easyAntConfiguration.getOut());
        System.setErr(easyAntConfiguration.getErr());
    }
    readyToRun = true;
}

From source file:edu.umn.natsrl.ticas.plugin.srte.SRTEMainPanel.java

/**
 * Redirect output into log box//  ww w. j  av  a2 s . co m
 */
public void redirectOutput() {
    backupOut = System.out;
    backupErr = System.err;
    //reset Area
    jTextArea1.setText("");
    // redirect System.out and System.err to log textbox
    StringOutputStream sos = new StringOutputStream(this.jTextArea1);
    System.setOut(new PrintStream(sos));
    System.setErr(new PrintStream(sos));
}

From source file:org.archive.io.arc.ARCWriterTest.java

protected void lengthTooShort(String name, boolean compress, boolean strict) throws IOException {
    CorruptibleARCWriter writer = null;/*from   ww  w .j a  va 2 s. co m*/
    try {
        writer = createArcWithOneRecord(name, compress);
        // Add some bytes on the end to mess up the record.
        String content = getContent();
        ByteArrayInputStream bais = getBais(content + "SOME TRAILING BYTES");
        writeRecord(writer, SOME_URL, "text/html", content.length(), bais);
        writer.setEndJunk("SOME TRAILING BYTES".getBytes());
        writeRecord(writer, SOME_URL, "text/html", content.length(), getBais(content));
    } finally {
        Closeables.close(writer, true);
    }

    // Catch System.err into a byte stream.
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PrintStream origErr = System.err;
    ARCReader r = null;
    try {
        System.setErr(new PrintStream(os));

        r = ARCReaderFactory.get(writer.getFile());
        r.setStrict(strict);
        int count = iterateRecords(r);
        assertTrue("Count wrong " + count, count == 4);

        // Make sure we get the warning string which complains about the
        // trailing bytes.
        String err = os.toString();
        assertTrue("No message " + err, err.startsWith("WARNING") && (err.indexOf("Record STARTING at") > 0));
        r.close();
    } finally {
        Closeables.close(r, true);
        System.setErr(origErr);
    }
}