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:functionaltests.TagCommandsFunctTest.java

@Test
public void testListJobTaskIdsWithUnknownTag() throws Exception {
    typeLine("listtasks(" + jobId.longValue() + ", 'unknownTag')");

    runCli();/*from ww w . ja v  a2  s.  c  om*/

    String out = this.capturedOutput.toString();
    System.setOut(stdOut);
    System.out.println("------------- testListJobTaskIdsWithUnknownTag:");
    System.out.println(out);
    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.codelibs.robot.extractor.impl.TikaExtractor.java

@Override
public ExtractData getText(final InputStream inputStream, final Map<String, String> params) {
    if (inputStream == null) {
        throw new RobotSystemException("The inputstream is null.");
    }//  w  w  w.j  a  v a  2 s  .  co  m

    File tempFile = null;
    try {
        tempFile = File.createTempFile("tikaExtractor-", ".out");
    } catch (final IOException e) {
        throw new ExtractException("Could not create a temp file.", e);
    }

    try {
        try (OutputStream out = new FileOutputStream(tempFile)) {
            CopyUtil.copy(inputStream, out);
        }

        InputStream in = new FileInputStream(tempFile);

        final PrintStream originalOutStream = System.out;
        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outStream, true));
        final PrintStream originalErrStream = System.err;
        final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
        System.setErr(new PrintStream(errStream, true));
        try {
            final String resourceName = params == null ? null : params.get(TikaMetadataKeys.RESOURCE_NAME_KEY);
            final String contentType = params == null ? null : params.get(HttpHeaders.CONTENT_TYPE);
            String contentEncoding = params == null ? null : params.get(HttpHeaders.CONTENT_ENCODING);

            // password for pdf
            String pdfPassword = params == null ? null : params.get(ExtractData.PDF_PASSWORD);
            if (pdfPassword == null && params != null) {
                pdfPassword = getPdfPassword(params.get(ExtractData.URL), resourceName);
            }

            final Metadata metadata = createMetadata(resourceName, contentType, contentEncoding, pdfPassword);

            final Parser parser = new DetectParser();
            final ParseContext parseContext = new ParseContext();
            parseContext.set(Parser.class, parser);

            final StringWriter writer = new StringWriter(initialBufferSize);
            parser.parse(in, new BodyContentHandler(writer), metadata, parseContext);

            String content = normalizeContent(writer);
            if (StringUtil.isBlank(content)) {
                if (resourceName != null) {
                    IOUtils.closeQuietly(in);
                    if (logger.isDebugEnabled()) {
                        logger.debug("retry without a resource name: {}", resourceName);
                    }
                    in = new FileInputStream(tempFile);
                    final Metadata metadata2 = createMetadata(null, contentType, contentEncoding, pdfPassword);
                    final StringWriter writer2 = new StringWriter(initialBufferSize);
                    parser.parse(in, new BodyContentHandler(writer2), metadata2, parseContext);
                    content = normalizeContent(writer2);
                }
                if (StringUtil.isBlank(content) && contentType != null) {
                    IOUtils.closeQuietly(in);
                    if (logger.isDebugEnabled()) {
                        logger.debug("retry without a content type: {}", contentType);
                    }
                    in = new FileInputStream(tempFile);
                    final Metadata metadata3 = createMetadata(null, null, contentEncoding, pdfPassword);
                    final StringWriter writer3 = new StringWriter(initialBufferSize);
                    parser.parse(in, new BodyContentHandler(writer3), metadata3, parseContext);
                    content = normalizeContent(writer3);
                }

                if (readAsTextIfFailed && StringUtil.isBlank(content)) {
                    IOUtils.closeQuietly(in);
                    if (logger.isDebugEnabled()) {
                        logger.debug("read the content as a text.");
                    }
                    if (contentEncoding == null) {
                        contentEncoding = Constants.UTF_8;
                    }
                    BufferedReader br = null;
                    try {
                        br = new BufferedReader(
                                new InputStreamReader(new FileInputStream(tempFile), contentEncoding));
                        final StringWriter writer4 = new StringWriter(initialBufferSize);
                        String line;
                        while ((line = br.readLine()) != null) {
                            writer4.write(line.replaceAll("\\p{Cntrl}", " ").replaceAll("\\s+", " ").trim());
                            writer4.write(' ');
                        }
                        content = writer4.toString().trim();
                    } catch (final Exception e) {
                        logger.warn("Could not read " + tempFile.getAbsolutePath(), e);
                    } finally {
                        IOUtils.closeQuietly(br);
                    }
                }
            }
            final ExtractData extractData = new ExtractData(content);

            final String[] names = metadata.names();
            Arrays.sort(names);
            for (final String name : names) {
                extractData.putValues(name, metadata.getValues(name));
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Result: metadata: {}", metadata);
            }

            return extractData;
        } catch (final TikaException e) {
            if (e.getMessage().indexOf("bomb") >= 0) {
                throw e;
            }
            final Throwable cause = e.getCause();
            if (cause instanceof SAXException) {
                final Extractor xmlExtractor = robotContainer.getComponent("xmlExtractor");
                if (xmlExtractor != null) {
                    IOUtils.closeQuietly(in);
                    in = new FileInputStream(tempFile);
                    return xmlExtractor.getText(in, params);
                }
            }
            throw e;
        } finally {
            IOUtils.closeQuietly(in);
            if (originalOutStream != null) {
                System.setOut(originalOutStream);
            }
            if (originalErrStream != null) {
                System.setErr(originalErrStream);
            }
            try {
                if (logger.isInfoEnabled()) {
                    final byte[] bs = outStream.toByteArray();
                    if (bs.length != 0) {
                        logger.info(new String(bs, outputEncoding));
                    }
                }
                if (logger.isWarnEnabled()) {
                    final byte[] bs = errStream.toByteArray();
                    if (bs.length != 0) {
                        logger.warn(new String(bs, outputEncoding));
                    }
                }
            } catch (final Exception e) {
                // NOP
            }
        }
    } catch (final Exception e) {
        throw new ExtractException("Could not extract a content.", e);
    } finally {
        if (tempFile != null && !tempFile.delete()) {
            logger.warn("Failed to delete " + tempFile.getAbsolutePath());
        }
    }
}

From source file:CalendarController.java

private void startConsole(String dir) throws Exception {
    final String path = dir + "/" + CONSOLE_FILENAME;
    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
            log("Writing log to " + path);
            console = new PrintStream(new FileOutputStream(path));
            System.setOut(console);
            System.setErr(console);
            return null;
        }//www  .  j  a v a2  s  . c o  m
    });
}

From source file:gov.nih.nci.ncicb.tcga.dcc.QCLiveTestDataGeneratorSlowTest.java

/**
 * Tests the {@link QCLiveTestDataGenerator#main(String[])} with the {@link CommandLineOptionType#HELP} option type and asserts that the
 * appropriate usage information is displayed via the command line. 
 */// ww  w  . java  2  s  .c o  m
@Test
public void testHelpCommandLineArg() {

    // Call the QCLiveTestDataGenerator with the -? option to capture its output
    QCLiveTestDataGenerator.main(new String[] { '-' + CommandLineOptionType.HELP.getOptionValue().getOpt() });
    String actualOutput = outContent.toString();

    // Print the expected output to system out and capture its output
    System.setOut(new PrintStream(outContent = new ByteArrayOutputStream()));
    QCLiveTestDataGenerator.displayHelp();
    String expectedOutput = outContent.toString();

    // Compare the results
    assertEquals(expectedOutput, actualOutput);
}

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

/**
 * Test subscriptions:list command with no args. Should return no registered subscriptions.
 *
 * @throws Exception//  w w  w  .j a  v a 2 s . c o m
 */
@Test
public void testListNoArgsNoSubscriptionsFound() throws Exception {
    ListCommand listCommand = new ListCommand();

    BundleContext bundleContext = mock(BundleContext.class);
    listCommand.setBundleContext(bundleContext);
    when(bundleContext.getServiceReferences(eq(SubscriptionsCommand.SERVICE_PID), anyString()))
            .thenReturn(new ServiceReference[] {});

    PrintStream realSystemOut = System.out;

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    System.setOut(new PrintStream(buffer));

    // when
    listCommand.doExecute();

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

    // then
    assertThat(buffer.toString(), startsWith(ListCommand.RED_CONSOLE_COLOR
            + ListCommand.NO_SUBSCRIPTIONS_FOUND_MSG + ListCommand.DEFAULT_CONSOLE_COLOR));

    buffer.close();
}

From source file:nl.knaw.huygens.alexandria.dropwizard.cli.CommandIntegrationTest.java

@After
public void tearDown() throws IOException {
    System.setOut(originalOut);
    System.setErr(originalErr);/*from  w w  w . j a va2s  .co m*/
    //    System.setIn(originalIn);
    tearDownWorkDir();
}

From source file:org.apache.rocketmq.tools.command.message.ConsumeMessageCommandTest.java

@Test
public void testExecuteByCondition() throws SubCommandException {
    PrintStream out = System.out;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(bos));
    Options options = ServerUtil.buildCommandlineOptions(new Options());

    String[] subargs = new String[] { "-t mytopic", "-b localhost", "-i 0", "-n localhost:9876" };
    CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + consumeMessageCommand.commandName(), subargs,
            consumeMessageCommand.buildCommandlineOptions(options), new PosixParser());
    consumeMessageCommand.execute(commandLine, options, null);
    System.setOut(out);//  w  ww . ja  v a  2  s.  c  om
    String s = new String(bos.toByteArray());
    Assert.assertTrue(s.contains("Consume ok"));
}

From source file:net.minecraftforge.fml.relauncher.FMLLaunchHandler.java

private void redirectStdOutputToLog() {
    FMLLog.log.debug("Injecting tracing printstreams for STDOUT/STDERR.");
    System.setOut(new TracingPrintStream(LogManager.getLogger("STDOUT"), System.out));
    System.setErr(new TracingPrintStream(LogManager.getLogger("STDERR"), System.err));
}

From source file:org.apache.hadoop.yarn.client.cli.TestLogsCLI.java

@Before
public void setUp() {
    sysOutStream = new ByteArrayOutputStream();
    sysOut = new PrintStream(sysOutStream);
    System.setOut(sysOut);

    sysErrStream = new ByteArrayOutputStream();
    sysErr = new PrintStream(sysErrStream);
    System.setErr(sysErr);/*w  w  w. java  2s  .c om*/
}