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.proteus.jsmodify.JSExecutionTracer.java

public static void postCrawling(CallGraphAnalyzer callGraphAnalyzer) {
    try {/*ww w  .j  a v a 2 s.co  m*/
        // Add closing bracket
        PrintStream oldOut = System.out;
        System.setOut(output);
        System.out.println(" ");
        System.out.println("}");
        System.setOut(oldOut);

        /* close the output file */
        output.close();

        //            extraxtTraceObjects();
    } catch (Exception e) {
        e.printStackTrace();
    }

    extraxtTraceObjects(); // TODO

    // TODO
    InteractionGraph.getInstance().handleGraphAfterTermination();

    System.out.println("********************************");
    System.out.println("********************************");

    // TODO TODO TODO TODO
    System.out.println("+++++++++++++++++++++++");
    System.out.println("DYNAMIC");
    System.out.println(InteractionGraph.getInstance().getDynamicFunctions().keySet().toString());
    System.out.println("++++++++++++++++STATIC");
    System.out.println(InteractionGraph.getInstance().getStaticFunctions().keySet().toString());
    System.out.println("+++++++++++++++++++++++");
    // TODO TODO TODO TODO

    Set<String> keys = JSModifyProxyPlugin.JSCodeMultiMap.keySet();
    for (String key : keys) {
        System.out.println("key: " + key);
        System.out.println(JSModifyProxyPlugin.JSCodeMultiMap.get(key).size());

        String fileScript = "";

        Iterator<String> itr = JSModifyProxyPlugin.JSCodeMultiMap.get(key).iterator();
        while (itr.hasNext()) {
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            System.out.println("///////////////////////////////////////////////");
            System.out.println("KEY: " + key);
            System.out.println("///////////////////////////////////////////////");
            fileScript = fileScript + " \n " + itr.next();
            //            System.out.println(itr.next());
            //            TestWala.getCallGraph(itr.next());
            /*****
            Graph<CGNode> callGraph = callGraphAnalyzer.getCallGraph(itr.next(), key);
            System.out.println("<><><><> " + callGraph.getNumberOfNodes());
            *****/
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO
            // TODO TODO TODO TODO TODO TODO TODO TODO 
            // TODO TODO TODO TODO TODO TODO TODO TODO 
            // TODO TODO TODO TODO TODO TODO TODO TODO 
            // TODO TODO TODO TODO TODO TODO TODO TODO 
            //////////////            Iteractor<CGNode> nodeItr = PrunedCFG<I, IBasicBlock<I>>
            // TODO TODO TODO TODO TODO TODO TODO TODO 
            // TODO TODO TODO TODO TODO TODO TODO TODO 
            // TODO TODO TODO TODO TODO TODO TODO TODO 
            // TODO TODO TODO TODO TODO TODO TODO TODO 
        }

        if (!fileScript.isEmpty()) {
            //            TestWala.getCallGraph(fileScript);
            ////////////////////// TODO removed this to complete dynamic part
            //////////////////////////////////            TestWala.getCallGraphAndSlicer(fileScript); // TODO TODO TODO
        }

        System.out.println("------------");
        //         System.out.println("values: " + JSModifyProxyPlugin.JSCodeMultiMap.get(key));
    }

}

From source file:functionaltests.TagCommandsFunctTest.java

@Test
public void testListTaskStatesUnknownJob() throws Exception {
    typeLine("taskstates(" + NOT_EXISTENT_JOBID + ", 'unknownTag')");

    runCli();//from   w ww . j  av a  2 s.  c  o m

    String out = this.capturedOutput.toString();
    System.setOut(stdOut);
    System.out.println("------------- testListTaskStatesUnknownJob:");
    System.out.println(out);
    assertTrue(out.contains("error"));
    assertTrue(!out.contains("T1#1"));
    assertTrue(!out.contains("Print1#1"));
    assertTrue(!out.contains("Print2#1"));
    assertTrue(!out.contains("T2#1"));
    assertTrue(!out.contains("T1#2"));
    assertTrue(!out.contains("Print1#2"));
    assertTrue(!out.contains("Print2#2"));
    assertTrue(!out.contains("T2#2"));
}

From source file:org.codehaus.mojo.exec.ExecMojoTest.java

/**
 * //  w w w. ja  v  a2 s .c  o  m
 * @param pom the pom file
 * @param goal the goal to execute
 * @return output from System.out during mojo execution
 * @throws Exception if any exception occurs
 */
protected String execute(File pom, String goal) throws Exception {

    ExecMojo mojo;
    mojo = (ExecMojo) lookupMojo(goal, pom);

    setUpProject(pom, mojo);

    MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");

    // why isn't this set up by the harness based on the default-value? TODO get to bottom of this!
    // setVariableValueToObject( mojo, "includeProjectDependencies", Boolean.TRUE );
    // setVariableValueToObject( mojo, "killAfter", new Long( -1 ) );

    assertNotNull(mojo);
    assertNotNull(project);

    // trap System.out
    PrintStream out = System.out;
    StringOutputStream stringOutputStream = new StringOutputStream();
    System.setOut(new PrintStream(stringOutputStream));
    // ensure we don't log unnecessary stuff which would interfere with assessing success of tests
    mojo.setLog(new DefaultLog(new ConsoleLogger(Logger.LEVEL_ERROR, "exec:exec")));

    try {
        mojo.execute();
    } catch (Throwable e) {
        e.printStackTrace(System.err);
        fail(e.getMessage());
    } finally {
        System.setOut(out);
    }

    return stringOutputStream.toString();
}

From source file:org.apache.maven.cli.CopyOfMavenCli.java

public int doMain(String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr) {
    PrintStream oldout = System.out;
    PrintStream olderr = System.err;

    try {/* w  ww.  j  av  a  2s  . co  m*/
        if (stdout != null) {
            System.setOut(stdout);
        }
        if (stderr != null) {
            System.setErr(stderr);
        }

        CliRequest cliRequest = new CliRequest(args, classWorld);
        cliRequest.workingDirectory = workingDirectory;

        return doMain(cliRequest);
    } finally {
        System.setOut(oldout);
        System.setErr(olderr);
    }
}

From source file:org.apache.hive.hplsql.TestHplsqlLocal.java

/**
 * Run a test file//from  w  ww .  java 2  s.  co m
 */
void run(String testFile) throws Exception {
    System.setOut(new PrintStream(out));
    Exec exec = new Exec();
    String[] args = { "-f", "src/test/queries/local/" + testFile + ".sql", "-trace" };
    exec.run(args);
    String s = getTestOutput(out.toString()).trim();
    FileUtils.writeStringToFile(new java.io.File("target/tmp/log/" + testFile + ".out.txt"), s);
    String t = FileUtils
            .readFileToString(new java.io.File("src/test/results/local/" + testFile + ".out.txt"), "utf-8")
            .trim();
    System.setOut(null);
    Assert.assertEquals(s, t);
}

From source file:net.hasor.maven.ExecMojoTest.java

/**
 * @return output from System.out during mojo execution
 *//*  w  w w .j  a  v a2 s  .  c  o  m*/
private String execute(File pom, String goal) throws Exception {

    ExecMojo mojo;
    mojo = (ExecMojo) lookupMojo(goal, pom);

    setUpProject(pom, mojo);

    MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");

    // why isn't this set up by the harness based on the default-value?   get to bottom of this!
    // setVariableValueToObject( mojo, "includeProjectDependencies", Boolean.TRUE );
    // setVariableValueToObject( mojo, "killAfter", new Long( -1 ) );

    assertNotNull(mojo);
    assertNotNull(project);

    // trap System.out
    PrintStream out = System.out;
    StringOutputStream stringOutputStream = new StringOutputStream();
    System.setOut(new PrintStream(stringOutputStream));
    // ensure we don't log unnecessary stuff which would interfere with assessing success of tests
    mojo.setLog(new DefaultLog(new ConsoleLogger(Logger.LEVEL_ERROR, "exec:exec")));

    try {
        mojo.execute();
    } catch (Throwable e) {
        e.printStackTrace(System.err);
        fail(e.getMessage());
    } finally {
        System.setOut(out);
    }

    return stringOutputStream.toString();
}

From source file:com.cisco.dvbu.ps.deploytool.dao.wsapi.VCSWSDAOImpl.java

public void vcsImportCommand(String prefix, String arguments, String vcsIgnoreMessages, String propertyFile)
        throws CompositeException {

    String identifier = "VCSWSDAOImpl.vcsImportCommand"; // some unique identifier that characterizes this invocation.
    String actionName = "IMPORT";

    try {//from  w  w w  . j  a v  a2  s .  c om
        boolean preserveQuotes = false;
        boolean initArgsList = true;
        List<String> argsList = new ArrayList<String>();

        // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
        //   If so then force a no operation to happen by performing a -printcontents for pkg_import
        // mtinius-2016-04-14: commented out until a full analysis can be done.
        //if (CommonUtils.isExecOperation() && !arguments.toLowerCase().contains("-printcontents")) 
        //   arguments = arguments + " -printcontents";

        // Parse the arguments
        argsList = CommonUtils.parseArguments(argsList, initArgsList, arguments, preserveQuotes, propertyFile);
        String[] args = argsList.toArray(new String[0]);

        /*
         * 2014-02-14 (mtinius): Removed the PDTool Archive capability
         */
        //         ImportCommand.startCommand(null, null, args);
        /*
         * 2014-02-14 (mtinius): Added security manager around the Composite native Archive code because
         *                    it has System.out.println and System.exit commands.  Need to trap both.
         */
        String maskedargsList = CommonUtils.getArgumentListMasked(argsList);
        if (logger.isDebugEnabled()) {
            logger.debug(identifier + "(prefix, arguments, vcsIngoreMessages, propertyFile).  prefix=" + prefix
                    + "  arguments=[" + maskedargsList + "]" + "  vcsIgnoreMessages=" + vcsIgnoreMessages
                    + "  propertyFile=" + propertyFile);
        }

        // Get the existing security manager
        SecurityManager sm = System.getSecurityManager();
        PrintStream originalOut = System.out;
        PrintStream originalErr = System.err;
        String command = "ImportCommand.startCommand";
        try {
            // Get the offset location of the java.policy file [offset from PDTool home].
            String javaPolicyOffset = CommonConstants.javaPolicy;
            String javaPolicyLocation = CommonUtils.extractVariable(prefix,
                    CommonUtils.getFileOrSystemPropertyValue(propertyFile, "PROJECT_HOME_PHYSICAL"),
                    propertyFile, true) + javaPolicyOffset;
            // Set the java security policy
            System.getProperties().setProperty("java.security.policy", javaPolicyLocation);

            // Create a new System.out Logger
            Logger exportLogger = Logger.getLogger(ImportCommand.class);
            System.setOut(new PrintStream(new LogOutputStream(exportLogger, Level.INFO)));
            System.setErr(new PrintStream(new LogOutputStream(exportLogger, Level.ERROR)));
            // Create a new security manager
            System.setSecurityManager(new NoExitSecurityManager());

            // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
            if (CommonUtils.isExecOperation()) {
                // Invoke the Composite native import command.
                ImportCommand.startCommand(null, null, args);
            } else {
                logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                        + "] WAS NOT PERFORMED.\n");
            }
        } catch (NoExitSecurityExceptionStatusNonZero nesesnz) {
            String error = identifier + ":: Exited with exception from System.exit(): " + command
                    + "(null, null, " + maskedargsList + ")";
            logger.error(error);
            throw new CompositeException(error);
        } catch (NoExitSecurityExceptionStatusZero nesezero) {
            if (logger.isDebugEnabled()) {
                logger.debug(identifier + ":: Exited successfully from System.exit(): " + command
                        + "(null, null, " + maskedargsList + ")");
            }
        } finally {
            System.setSecurityManager(sm);
            System.setOut(originalOut);
            System.setErr(originalErr);
        }

    } catch (Exception e) {
        if (resolveExecCommandLineError(prefix, e.getMessage().toString(), vcsIgnoreMessages)) {
            ApplicationException applicationException = new ApplicationException(
                    "ImportCommand execution returned an error=" + e.getMessage().toString());
            if (logger.isErrorEnabled()) {
                logger.error(applicationException);
            }
            throw applicationException;
        }
    }
}

From source file:com.eviware.loadui.launcher.LoadUILauncher.java

/**
 * Initiates and starts the OSGi runtime.
 *//*from   w w w  .j a  v  a  2 s. c o m*/
public LoadUILauncher(String[] args) {
    argv = args;

    //Fix for Protection!
    String username = System.getProperty("user.name");
    System.setProperty("user.name.original", username);
    System.setProperty("user.name", username.toLowerCase());

    File externalFile = new File(WORKING_DIR, "res/buildinfo.txt");

    //Workaround for some versions of Java 6 which have a known SSL issue
    String versionString = System.getProperty("java.version", "0.0.0_00");
    try {
        if (versionString.startsWith("1.6") && versionString.contains("_")) {
            int updateVersion = Integer.parseInt(versionString.split("_", 2)[1]);
            if (updateVersion > 27) {
                log.info("Detected Java version " + versionString + ", disabling CBC Protection.");
                System.setProperty("jsse.enableCBCProtection", "false");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (externalFile.exists()) {
        try (InputStream is = new FileInputStream(externalFile)) {
            Properties buildinfo = new Properties();
            buildinfo.load(is);
            System.setProperty(LOADUI_BUILD_NUMBER, buildinfo.getProperty("build.number"));
            System.setProperty(LOADUI_BUILD_DATE, buildinfo.getProperty("build.date"));
            System.setProperty(LOADUI_NAME, buildinfo.getProperty(LOADUI_NAME, "loadUI"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.setProperty(LOADUI_BUILD_NUMBER, "unknown");
        System.setProperty(LOADUI_BUILD_DATE, "unknown");
        System.setProperty(LOADUI_NAME, "loadUI");
    }

    options = createOptions();
    CommandLineParser parser = new PosixParser();
    try {
        cmd = parser.parse(options, argv);
    } catch (ParseException e) {
        System.err.print("Error parsing commandline args: " + e.getMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("", options);

        exitInError();
        throw new RuntimeException();
    }

    if (cmd.hasOption(SYSTEM_PROPERTY_OPTION)) {
        parseSystemProperties();
    }

    initSystemProperties();

    String sysOutFilePath = System.getProperty("system.out.file");
    if (sysOutFilePath != null) {
        File sysOutFile = new File(sysOutFilePath);
        if (!sysOutFile.exists()) {
            try {
                sysOutFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            System.err.println("Writing stdout and stderr to file:" + sysOutFile.getAbsolutePath());

            final PrintStream outStream = new PrintStream(sysOutFile);
            System.setOut(outStream);
            System.setErr(outStream);

            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    outStream.close();
                }
            }));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    System.out.println("Launching " + System.getProperty(LOADUI_NAME) + " Build: "
            + System.getProperty(LOADUI_BUILD_NUMBER, "[internal]") + " "
            + System.getProperty(LOADUI_BUILD_DATE, ""));
    Main.loadSystemProperties();
    configProps = Main.loadConfigProperties();
    if (configProps == null) {
        System.err.println("There was an error loading the OSGi configuration!");
        exitInError();
    }
    Main.copySystemProperties(configProps);
}

From source file:ddf.catalog.pubsub.command.ListCommandTest.java

/**
 * Test subscriptions:list command with one subscription ID argument. Should return the one
 * matching registered subscriptions.//from w ww  .  ja  v a2s .c  om
 *
 * @throws Exception
 */
@Test
public void testListOneMatchingSubscriptionIdArg() throws Exception {
    // Setup argument captor for LDAP filter that will be passed in to getServiceReferences()
    // call
    ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);

    ListCommand listCommand = new ListCommand();

    BundleContext bundleContext = mock(BundleContext.class);
    listCommand.setBundleContext(bundleContext);

    ServiceReference mySubscription = mock(ServiceReference.class);
    when(mySubscription.getPropertyKeys()).thenReturn(new String[] { SUBSCRIPTION_ID_PROPERTY_KEY });
    when(mySubscription.getProperty(SUBSCRIPTION_ID_PROPERTY_KEY)).thenReturn(MY_SUBSCRIPTION_ID);

    ServiceReference yourSubscription = mock(ServiceReference.class);
    when(yourSubscription.getPropertyKeys()).thenReturn(new String[] { SUBSCRIPTION_ID_PROPERTY_KEY });
    when(yourSubscription.getProperty(SUBSCRIPTION_ID_PROPERTY_KEY)).thenReturn(YOUR_SUBSCRIPTION_ID);

    when(bundleContext.getServiceReferences(eq(SubscriptionsCommand.SERVICE_PID), anyString()))
            .thenReturn(new ServiceReference[] { mySubscription });

    PrintStream realSystemOut = System.out;

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    System.setOut(new PrintStream(buffer));

    // when
    listCommand.id = MY_SUBSCRIPTION_ID;
    listCommand.doExecute();

    /* cleanup */
    System.setOut(realSystemOut);

    // then
    List<String> linesWithText = getConsoleOutputText(buffer);
    assertThat(linesWithText.size(), is(3));
    assertThat(linesWithText,
            hasItems(
                    "Total subscriptions found: 1", ListCommand.CYAN_CONSOLE_COLOR
                            + ListCommand.SUBSCRIPTION_ID_COLUMN_HEADER + ListCommand.DEFAULT_CONSOLE_COLOR,
                    MY_SUBSCRIPTION_ID));

    buffer.close();

    // Verify the LDAP filter passed in when mock BundleContext.getServiceReferences() was
    // called.
    verify(bundleContext).getServiceReferences(anyString(), argument.capture());
    String expectedLdapFilter = "(" + SUBSCRIPTION_ID_PROPERTY_KEY + "=" + MY_SUBSCRIPTION_ID + ")";
    assertThat(argument.getValue(), containsString(expectedLdapFilter));
}

From source file:de.thischwa.pmcms.tool.InternalAntTool.java

/**
 * Initializes an ant project. The base directory is the current working directory.
 * //from  w  ww  .j av  a 2s. c  o m
 * @return Ant project.
 */
private static Project buildProject() {
    Project project = new Project();
    project.setBasedir(System.getProperty("user.dir"));
    project.init();
    DefaultLogger logger = new DefaultLogger();
    project.addBuildListener(logger);
    logger.setOutputPrintStream(System.out);
    logger.setErrorPrintStream(System.err);
    logger.setMessageOutputLevel(Project.MSG_VERBOSE);
    System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
    System.setErr(new PrintStream(new DemuxOutputStream(project, true)));
    project.fireBuildStarted();
    return project;
}