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:org.apache.mrql.QueryTest.java

private int queryAndCompare(File query, File resultDir) throws Exception {
    System.err.println("Testing " + query);
    Translator.global_reset();//from   w  w  w  . j  av  a 2 s .  c o  m
    String qname = query.getName();
    qname = qname.substring(0, qname.length() - 5);
    String resultFile = resultDir.getAbsolutePath() + "/" + qname + ".txt";
    boolean exists = new File(resultFile).exists();
    if (exists)
        System.setOut(new PrintStream(resultDir.getAbsolutePath() + "/" + qname + "_result.txt"));
    else
        System.setOut(new PrintStream(resultFile));
    Config.max_bag_size_print = -1;
    Config.testing = true;
    MRQL.evaluate("store NaN := -1;");
    MRQLLex scanner = new MRQLLex(new FileInputStream(query));
    MRQLParser parser = new MRQLParser(scanner);
    parser.setScanner(scanner);
    MRQLLex.reset();
    parser.parse();
    PrintStream errorStream = System.err;
    int i;
    if (exists && (i = compare(resultFile, resultDir.getAbsolutePath() + "/" + qname + "_result.txt")) > 0) {
        return i;
    } else if (exists) {
        return 0;
    } else {
        return 0;
    }
}

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

/**
 * Test of printVersionInfo, of class CliParser.
 *
 * @throws Exception thrown when an exception occurs.
 *//*from  w ww  .java  2 s .  c  om*/
@Test
public void testParse_printVersionInfo() throws Exception {

    PrintStream out = System.out;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));

    CliParser instance = new CliParser();
    instance.printVersionInfo();
    try {
        baos.flush();
        String text = (new String(baos.toByteArray())).toLowerCase();
        String[] lines = text.split(System.getProperty("line.separator"));
        Assert.assertEquals(1, lines.length);
        Assert.assertTrue(text.contains("version"));
        Assert.assertTrue(!text.contains("unknown"));
    } catch (IOException ex) {
        System.setOut(out);
        Assert.fail("CliParser.printVersionInfo did not write anything to system.out.");
    } finally {
        System.setOut(out);
    }
}

From source file:com.enioka.jqm.tools.JqmEngine.java

/**
 * Starts the engine/*from   www .jav  a2  s .  c  o  m*/
 * 
 * @param nodeName
 *            the name of the node to start, as in the NODE table of the database.
 * @throws JqmInitError
 */
void start(String nodeName) {
    if (nodeName == null || nodeName.isEmpty()) {
        throw new IllegalArgumentException("nodeName cannot be null or empty");
    }

    // Set thread name - used in audits
    Thread.currentThread().setName("JQM engine;;" + nodeName);
    Helpers.setLogFileName(nodeName);

    // Log: we are starting...
    jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting");
    jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by "
            + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version "
            + System.getProperty("java.vm.version"));

    // JNDI first - the engine itself uses JNDI to fetch its connections!
    Helpers.registerJndiIfNeeded();

    // Database connection
    EntityManager em = Helpers.getNewEm();

    // Node configuration is in the database
    node = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    // Check if double-start
    long toWait = (long) (1.1 * Long.parseLong(Helpers.getParameter("internalPollingPeriodMs", "60000", em)));
    if (node.getLastSeenAlive() != null
            && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) {
        long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis();
        throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000
                + " seconds ago. Either stop the other node, or if it already stopped, please wait "
                + (toWait - r) / 1000 + " seconds");
    }

    // Prevent very quick multiple starts by immediately setting the keep-alive
    em.getTransaction().begin();
    node.setLastSeenAlive(Calendar.getInstance());
    em.getTransaction().commit();

    // Only start if the node configuration seems OK
    Helpers.checkConfiguration(nodeName, em);

    // Log parameters
    Helpers.dumpParameters(em, node);

    // Log level
    Helpers.setLogLevel(node.getRootLogLevel());

    // Log multicasting (& log4j stdout redirect)
    GlobalParameter gp1 = em
            .createQuery("SELECT g FROM GlobalParameter g WHERE g.key = :k", GlobalParameter.class)
            .setParameter("k", "logFilePerLaunch").getSingleResult();
    if ("true".equals(gp1.getValue()) || "both".equals(gp1.getValue())) {
        RollingFileAppender a = (RollingFileAppender) Logger.getRootLogger().getAppender("rollingfile");
        MultiplexPrintStream s = new MultiplexPrintStream(System.out, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setOut(s);
        ((ConsoleAppender) Logger.getRootLogger().getAppender("consoleAppender"))
                .setWriter(new OutputStreamWriter(s));
        s = new MultiplexPrintStream(System.err, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setErr(s);
    }

    // Remote JMX server
    if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0
            && node.getJmxServerPort() > 0) {
        JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns());
    } else {
        jqmlogger.info(
                "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined");
    }

    // Jetty
    this.server = new JettyServer();
    this.server.start(node, em);

    // JMX
    if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName());
            mbs.registerMBean(this, name);
        } catch (Exception e) {
            throw new JqmInitError("Could not create JMX beans", e);
        }
        jqmlogger.info("JMX management bean for the engine was registered");
    } else {
        loadJmxBeans = false;
        jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero");
    }

    // Security
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManagerPayload());
    }
    jqmlogger.info("Security manager was registered");

    // Cleanup
    purgeDeadJobInstances(em, this.node);

    // Force Message EMF load
    em.createQuery("SELECT m FROM Message m WHERE 1=0", Message.class).getResultList();

    // Pollers
    syncPollers(em, this.node);
    jqmlogger.info("All required queues are now polled");

    // Internal poller (stop notifications, keepalive)
    intPoller = new InternalPoller(this);
    Thread t = new Thread(intPoller);
    t.start();

    // Kill notifications
    killHook = new SignalHandler(this);
    Runtime.getRuntime().addShutdownHook(killHook);

    // Done
    em.close();
    em = null;
    latestNodeStartedName = node.getName();
    jqmlogger.info("End of JQM engine initialization");
}

From source file:org.eclipse.jdt.ls.core.internal.JDTUtilsTest.java

@Test
public void testIgnoredUnknownSchemes() {
    PrintStream originalOut = System.out;
    try {// w ww.j  a  va 2  s  .c o m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(baos, true));
        System.out.flush();
        JDTUtils.resolveCompilationUnit("inmemory:///foo/bar/Clazz.java");

        assertEquals("", baos.toString());

    } finally {
        System.setOut(originalOut);
    }
}

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

/**
 * The whole test suite started./*  ww w.  jav a2 s.c  om*/
 */
public void startTestSuite(final String name) // NOCHECKSTYLE: no documentation, file modified from 3rd party
{
    m_Doc = getDocumentBuilder().newDocument();
    m_RootElement = m_Doc.createElement(TESTSUITE);
    m_RootElement.setAttribute(ATTR_NAME, name);

    //add the timestamp
    final String timestamp = DateUtils.format(new Date(), DateUtils.ISO8601_DATETIME_PATTERN);
    m_RootElement.setAttribute(TIMESTAMP, timestamp);
    //and the hostname.
    m_RootElement.setAttribute(HOSTNAME, getHostname());

    // Output properties
    final Element propsElement = m_Doc.createElement(PROPERTIES);
    m_RootElement.appendChild(propsElement);
    final Properties props = System.getProperties();
    if (props != null) {
        final Enumeration<?> e = props.propertyNames();
        while (e.hasMoreElements()) {
            final String propName = (String) e.nextElement();
            final Element propElement = m_Doc.createElement(PROPERTY);
            propElement.setAttribute(ATTR_NAME, propName);
            propElement.setAttribute(ATTR_VALUE, props.getProperty(propName));
            propsElement.appendChild(propElement);
        }
    }

    m_OldStdOut = System.out;
    System.setOut(new PrintStream(m_TeeOutStream));
    m_OldStdErr = System.err;
    System.setErr(new PrintStream(m_TeeErrStream));
}

From source file:org.apache.hadoop.hive.ql.io.orc.TestFixAcidKeyIndex.java

void runFixIndex(Path orcFile, File outFile) throws Exception {
    // Run with --recover and save the output to a file so it can be checked.
    PrintStream origOut = System.out;
    FileOutputStream myOut = new FileOutputStream(outFile);

    System.setOut(new PrintStream(myOut));
    String[] checkArgs = new String[] { "--recover", orcFile.toString() };
    FixAcidKeyIndex.main(checkArgs);//  ww  w . j  a  v  a 2  s .  c o  m
    System.out.flush();
    System.setOut(origOut);
}

From source file:Alias2.java

public void dispose() {
    System.setOut(console);
    System.setErr(err);
    System.setIn(stdin);
}

From source file:dibl.Main.java

private void showUsage() {
    final String jarFileName = new java.io.File(
            getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
    final String usage = "java -jar " + jarFileName + " [options] stitches [tuples]";
    final String header = "Transform a bobbin lace svg template into a variant." + NEW_LINE + "options:";
    final String footer = "Rotate is flip along X + Y." + NEW_LINE //
            + "The stitches and tuples arguments are either a file or a multiline string." + NEW_LINE //
            + "Tuples argument make garbage diagrams of non pair travesal templates.";
    final PrintStream saved = System.out;
    System.setOut(System.err);
    new HelpFormatter().printHelp(usage, header, options, footer);
    System.setOut(saved);/*from   w ww .  jav a2 s .  co  m*/
}

From source file:org.apache.flink.client.program.Client.java

public OptimizedPlan getOptimizedPlan(PackagedProgram prog, int parallelism)
        throws CompilerException, ProgramInvocationException {
    Thread.currentThread().setContextClassLoader(prog.getUserCodeClassLoader());
    if (prog.isUsingProgramEntryPoint()) {
        return getOptimizedPlan(prog.getPlanWithJars(), parallelism);
    } else if (prog.isUsingInteractiveMode()) {
        // temporary hack to support the optimizer plan preview
        OptimizerPlanEnvironment env = new OptimizerPlanEnvironment(this.compiler);
        if (parallelism > 0) {
            env.setDegreeOfParallelism(parallelism);
        }/*w w w .ja  va  2s . c om*/
        env.setAsContext();

        // temporarily write syser and sysout to bytearray.
        PrintStream originalOut = System.out;
        PrintStream originalErr = System.err;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(baos));
        ByteArrayOutputStream baes = new ByteArrayOutputStream();
        System.setErr(new PrintStream(baes));
        try {
            ContextEnvironment.disableLocalExecution();
            prog.invokeInteractiveModeForExecution();
        } catch (ProgramInvocationException e) {
            throw e;
        } catch (Throwable t) {
            // the invocation gets aborted with the preview plan
            if (env.optimizerPlan != null) {
                return env.optimizerPlan;
            } else {
                throw new ProgramInvocationException("The program caused an error: ", t);
            }
        } finally {
            System.setOut(originalOut);
            System.setErr(originalErr);
            System.err.println(baes);
            System.out.println(baos);
        }

        throw new ProgramInvocationException(
                "The program plan could not be fetched. The program silently swallowed the control flow exceptions.\n"
                        + "System.err: " + StringEscapeUtils.escapeHtml4(baes.toString()) + " \n"
                        + "System.out: " + StringEscapeUtils.escapeHtml4(baos.toString()) + " \n");
    } else {
        throw new RuntimeException();
    }
}

From source file:org.apache.hadoop.hive.cli.TestCliDriverMethods.java

public void testRun() throws Exception {
    // clean history
    String historyDirectory = System.getProperty("user.home");
    if ((new File(historyDirectory)).exists()) {
        File historyFile = new File(historyDirectory + File.separator + ".hivehistory");
        historyFile.delete();/*w w w  .ja v a  2s . co m*/
    }
    HiveConf configuration = new HiveConf();
    configuration.setBoolVar(ConfVars.HIVE_SESSION_HISTORY_ENABLED, true);
    PrintStream oldOut = System.out;
    ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
    System.setOut(new PrintStream(dataOut));
    PrintStream oldErr = System.err;
    ByteArrayOutputStream dataErr = new ByteArrayOutputStream();
    System.setErr(new PrintStream(dataErr));
    CliSessionState ss = new CliSessionState(configuration);
    CliSessionState.start(ss);
    String[] args = {};

    try {
        new FakeCliDriver().run(args);
        assertTrue(dataOut.toString(), dataOut.toString().contains("test message"));
        assertTrue(dataErr.toString(), dataErr.toString().contains("Hive history file="));
        assertTrue(dataErr.toString(), dataErr.toString().contains("File: fakeFile is not a file."));
        dataOut.reset();
        dataErr.reset();

    } finally {
        System.setOut(oldOut);
        System.setErr(oldErr);

    }

}