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.kie.workbench.common.services.backend.compiler.impl.external339.AFMavenCli.java

protected void logging(AFCliRequest cliRequest) {
    cliRequest.setDebug(cliRequest.getCommandLine().hasOption(CLIManager.DEBUG));
    cliRequest.setQuiet(!cliRequest.isDebug() && cliRequest.getCommandLine().hasOption(CLIManager.QUIET));
    cliRequest.setShowErrors(cliRequest.isDebug() || cliRequest.getCommandLine().hasOption(CLIManager.ERRORS));

    slf4jLoggerFactory = LoggerFactory.getILoggerFactory();
    Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration(slf4jLoggerFactory);
    if (cliRequest.isDebug()) {
        cliRequest.getRequest().setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_DEBUG);
        slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.DEBUG);
    } else if (cliRequest.isQuiet()) {
        cliRequest.getRequest().setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_ERROR);
        slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.ERROR);
    }//from w  ww  .  j av a 2 s  . c  o m

    if (cliRequest.getCommandLine().hasOption(CLIManager.LOG_FILE)) {
        File logFile = new File(cliRequest.getCommandLine().getOptionValue(CLIManager.LOG_FILE).trim());
        logFile = resolveFile(logFile, cliRequest.getWorkingDirectory());

        try {
            PrintStream ps = new PrintStream(new FileOutputStream(logFile));
            System.setOut(ps);
            System.setErr(ps);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        }
    }

    slf4jConfiguration.activate();

    plexusLoggerManager = new Slf4jLoggerManager();
    slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
}

From source file:fr.gouv.culture.vitam.droid.DroidHandler.java

/**
 * Check one InputStream/*w w w.j  a  v  a  2 s . c o  m*/
 * 
 * @param in
 * @param argument
 * @return a List of DroidFileFOrmat
 * @throws CommandExecutionException
 */
public List<DroidFileFormat> checkFileFormat(InputStream in, VitamArgument argument)
        throws CommandExecutionException {
    String path = "";
    String slash = File.separator;
    String slash1 = slash;

    path = "";
    ResultPrinter resultPrinter = new ResultPrinter(vitamBinarySignatureIdentifier,
            containerSignatureDefinitions, path, slash, slash1, argument.archive, argument.checkSubFormat);

    // change System.out
    PrintStream oldOut = System.out;
    DroidFileFormatOutputStream out = new DroidFileFormatOutputStream(
            vitamBinarySignatureIdentifier.getSigFile(), argument);
    PrintStream newOut = new PrintStream(out, true);
    try {
        System.setOut(newOut);
        realCheck(in, resultPrinter);
    } finally {
        // reset System.out
        System.setOut(oldOut);
        newOut.close();
        newOut = null;
    }
    return out.getResult();
}

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

/**
 * configure logging//from  w  ww .j av  a2s .c  om
 */
private void logging(CliRequest cliRequest) {
    cliRequest.debug = cliRequest.commandLine.hasOption(CLIManager.DEBUG);
    cliRequest.quiet = !cliRequest.debug && cliRequest.commandLine.hasOption(CLIManager.QUIET);
    cliRequest.showErrors = cliRequest.debug || cliRequest.commandLine.hasOption(CLIManager.ERRORS);

    slf4jLoggerFactory = LoggerFactory.getILoggerFactory();
    Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration(slf4jLoggerFactory);

    if (cliRequest.debug) {
        cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_DEBUG);
        slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.DEBUG);
    } else if (cliRequest.quiet) {
        cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_ERROR);
        slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.ERROR);
    }
    // else fall back to default log level specified in conf
    // see https://issues.apache.org/jira/browse/MNG-2570

    if (cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
        File logFile = new File(cliRequest.commandLine.getOptionValue(CLIManager.LOG_FILE));
        logFile = resolveFile(logFile, cliRequest.workingDirectory);

        // redirect stdout and stderr to file
        try {
            PrintStream ps = new PrintStream(new FileOutputStream(logFile));
            System.setOut(ps);
            System.setErr(ps);
        } catch (FileNotFoundException e) {
            //
            // Ignore
            //
        }
    }

    slf4jConfiguration.activate();

    plexusLoggerManager = new Slf4jLoggerManager();
    slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
}

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

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

    String identifier = "VCSWSDAOImpl.vcsDiffMergerCommand"; // some unique identifier that characterizes this invocation.
    String actionName = "DIFF";

    try {//ww w.ja  va 2  s  . c o m
        boolean preserveQuotes = false;
        boolean initArgsList = true;
        List<String> argsList = new ArrayList<String>();
        argsList = CommonUtils.parseArguments(argsList, initArgsList, arguments, preserveQuotes, propertyFile);

        String[] args = argsList.toArray(new String[0]);

        /*
         * 2014-06-30 (mtinius): Removed the PDTool Diffmerger capability
         */
        //         DiffMerger.startCommand(null, null, args);
        /*
         * 2014-06-30 (mtinius): Added security manager around the Composite native Diffmerger 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, vcsIgnoreMessages, 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 = "DiffMerger.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(DiffMerger.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 DiffMerger command.
                DiffMerger.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(
                    "DiffMerger execution returned an error=" + e.getMessage().toString());
            if (logger.isErrorEnabled()) {
                logger.error(applicationException);
            }
            throw applicationException;
        }
    }
}

From source file:de.haber.xmind2latex.XMindToLatexExporterConfigurationTest.java

@Test
public void testVersion() {
    String[] args = new String[] { "-" + VERSION };
    ByteArrayOutputStream result = new ByteArrayOutputStream();

    PrintStream out = new PrintStream(result);
    PrintStream old_out = System.out;
    System.setOut(out);
    try {//w  ww  . ja va2  s .co  m
        XMindToLatexExporter exp = CliParameters.build(args);
        assertNull(exp);
        String resultContent = new String(result.toByteArray());
        assertFalse(resultContent.isEmpty());
        assertTrue(resultContent.contains("version"));
    } catch (Exception e) {
        e.printStackTrace();
        fail("ParseException expected.");
        // this is expected
    } finally {
        System.setOut(old_out);
        try {
            result.close();
        } catch (IOException e) {
            fail(e.getMessage());
        }
    }
}

From source file:io.druid.cli.PullDependencies.java

private DefaultTeslaAether getAetherClient() {
    /*/* w  w  w  .j a va 2 s .c  om*/
    DefaultTeslaAether logs a bunch of stuff to System.out, which is annoying.  We choose to disable that
    unless debug logging is turned on.  "Disabling" it, however, is kinda bass-ackwards.  We copy out a reference
    to the current System.out, and set System.out to a noop output stream.  Then after DefaultTeslaAether has pulled
    The reference we swap things back.
            
    This has implications for other things that are running in parallel to this.  Namely, if anything else also grabs
    a reference to System.out or tries to log to it while we have things adjusted like this, then they will also log
    to nothingness.  Fortunately, the code that calls this is single-threaded and shouldn't hopefully be running
    alongside anything else that's grabbing System.out.  But who knows.
    */

    final List<String> remoteUriList = Lists.newArrayList();
    if (!noDefaultRemoteRepositories) {
        remoteUriList.addAll(DEFAULT_REMOTE_REPOSITORIES);
    }
    remoteUriList.addAll(remoteRepositories);

    List<Repository> remoteRepositories = Lists.newArrayList();
    for (String uri : remoteUriList) {
        try {
            URI u = new URI(uri);
            Repository r = new Repository(uri);

            if (u.getUserInfo() != null) {
                String[] auth = u.getUserInfo().split(":", 2);
                if (auth.length == 2) {
                    r.setUsername(auth[0]);
                    r.setPassword(auth[1]);
                } else {
                    log.warn(
                            "Invalid credentials in repository URI, expecting [<user>:<password>], got [%s] for [%s]",
                            u.getUserInfo(), uri);
                }
            }
            remoteRepositories.add(r);
        } catch (URISyntaxException e) {
            throw Throwables.propagate(e);
        }
    }

    if (log.isTraceEnabled() || log.isDebugEnabled()) {
        return new DefaultTeslaAether(localRepository,
                remoteRepositories.toArray(new Repository[remoteRepositories.size()]));
    }

    PrintStream oldOut = System.out;
    try {
        System.setOut(new PrintStream(new OutputStream() {
            @Override
            public void write(int b) throws IOException {

            }

            @Override
            public void write(byte[] b) throws IOException {

            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {

            }
        }, false, StringUtils.UTF8_STRING));
        return new DefaultTeslaAether(localRepository,
                remoteRepositories.toArray(new Repository[remoteRepositories.size()]));
    } catch (UnsupportedEncodingException e) {
        // should never happen
        throw new IllegalStateException(e);
    } finally {
        System.setOut(oldOut);
    }
}

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

private static void redirectStandardStreams() throws FileNotFoundException {
    in = System.in;/* w  ww  .j  a  v a  2 s .  co m*/
    out = System.out;
    err = System.err;
    System.setIn(new ByteArrayInputStream(new byte[0]));
    boolean isDebug = Boolean.getBoolean("jdt.ls.debug");
    if (isDebug) {
        String id = "jdt.ls-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        File workspaceFile = root.getRawLocation().makeAbsolute().toFile();
        File rootFile = new File(workspaceFile, ".metadata");
        rootFile.mkdirs();
        File outFile = new File(rootFile, ".out-" + id + ".log");
        FileOutputStream stdFileOut = new FileOutputStream(outFile);
        System.setOut(new PrintStream(stdFileOut));
        File errFile = new File(rootFile, ".error-" + id + ".log");
        FileOutputStream stdFileErr = new FileOutputStream(errFile);
        System.setErr(new PrintStream(stdFileErr));
    } else {
        System.setOut(new PrintStream(new ByteArrayOutputStream()));
        System.setErr(new PrintStream(new ByteArrayOutputStream()));
    }
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.ReusableAFMavenCli.java

protected void logging(AFCliRequest cliRequest) {
    cliRequest.setDebug(cliRequest.getCommandLine().hasOption(CLIManager.DEBUG));
    cliRequest.setQuiet(!cliRequest.isDebug() && cliRequest.getCommandLine().hasOption(CLIManager.QUIET));
    cliRequest.setShowErrors(cliRequest.isDebug() || cliRequest.getCommandLine().hasOption(CLIManager.ERRORS));

    slf4jLoggerFactory = LoggerFactory.getILoggerFactory();
    Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration(slf4jLoggerFactory);
    if (cliRequest.isDebug()) {
        cliRequest.getRequest().setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_DEBUG);
        slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.DEBUG);
    } else if (cliRequest.isQuiet()) {
        cliRequest.getRequest().setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_ERROR);
        slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.ERROR);
    }/*  w ww  .  ja  va 2  s.  c  om*/

    if (cliRequest.getCommandLine().hasOption(CLIManager.LOG_FILE)) {
        File logFile = new File(cliRequest.getCommandLine().getOptionValue(CLIManager.LOG_FILE).trim());
        logFile = resolveFile(logFile, cliRequest.getWorkingDirectory());

        try {
            PrintStream ps = new PrintStream(new FileOutputStream(logFile));
            System.setOut(ps);
            System.setErr(ps);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        }
    }

    slf4jConfiguration.activate();

    plexusLoggerManager = new Slf4jLoggerManager();
    reusableSlf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
}

From source file:de.haber.xmind2latex.XMindToLatexExporterConfigurationTest.java

@Test
public void testConfigureHelp1() {
    File in = new File("src/test/resources/content.xml");
    File result = new File("target/testout/helpmsg.txt");
    result.delete();//from   ww w.j a va  2  s. c  om
    result.getParentFile().mkdirs();

    String[] args = new String[] { "-i", in.getPath(), "-h" };
    try {
        result.createNewFile();
        FileOutputStream os = new FileOutputStream(result);
        PrintStream out = new PrintStream(os);
        PrintStream old_out = System.out;
        System.setOut(out);
        CliParameters.build(args);
        String resultContent = FileUtils.readFileToString(result);
        assertFalse(resultContent.isEmpty());
        assertTrue(resultContent.contains("usage: xmind2latex"));
        System.setOut(old_out);
        os.close();
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:org.apache.druid.cli.PullDependencies.java

@SuppressForbidden(reason = "System#out")
private DefaultTeslaAether getAetherClient() {
    /*/* w w w.j  a v a 2 s . com*/
    DefaultTeslaAether logs a bunch of stuff to System.out, which is annoying.  We choose to disable that
    unless debug logging is turned on.  "Disabling" it, however, is kinda bass-ackwards.  We copy out a reference
    to the current System.out, and set System.out to a noop output stream.  Then after DefaultTeslaAether has pulled
    The reference we swap things back.
            
    This has implications for other things that are running in parallel to this.  Namely, if anything else also grabs
    a reference to System.out or tries to log to it while we have things adjusted like this, then they will also log
    to nothingness.  Fortunately, the code that calls this is single-threaded and shouldn't hopefully be running
    alongside anything else that's grabbing System.out.  But who knows.
    */

    final List<String> remoteUriList = Lists.newArrayList();
    if (!noDefaultRemoteRepositories) {
        remoteUriList.addAll(DEFAULT_REMOTE_REPOSITORIES);
    }
    remoteUriList.addAll(remoteRepositories);

    List<Repository> remoteRepositories = Lists.newArrayList();
    for (String uri : remoteUriList) {
        try {
            URI u = new URI(uri);
            Repository r = new Repository(uri);

            if (u.getUserInfo() != null) {
                String[] auth = u.getUserInfo().split(":", 2);
                if (auth.length == 2) {
                    r.setUsername(auth[0]);
                    r.setPassword(auth[1]);
                } else {
                    log.warn(
                            "Invalid credentials in repository URI, expecting [<user>:<password>], got [%s] for [%s]",
                            u.getUserInfo(), uri);
                }
            }
            remoteRepositories.add(r);
        } catch (URISyntaxException e) {
            throw Throwables.propagate(e);
        }
    }

    if (log.isTraceEnabled() || log.isDebugEnabled()) {
        return createTeslaAether(remoteRepositories);
    }

    PrintStream oldOut = System.out;
    try {
        System.setOut(new PrintStream(new OutputStream() {
            @Override
            public void write(int b) {

            }

            @Override
            public void write(byte[] b) {

            }

            @Override
            public void write(byte[] b, int off, int len) {

            }
        }, false, StringUtils.UTF8_STRING));
        return createTeslaAether(remoteRepositories);
    } catch (UnsupportedEncodingException e) {
        // should never happen
        throw new IllegalStateException(e);
    } finally {
        System.setOut(oldOut);
    }
}