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.pentaho.di.kitchen.KitchenIT.java

@Test
public void testFileJobsExecution() throws Exception {
    String file = this.getClass().getResource("Job.kjb").getFile();
    String[] args = new String[] { "/file:" + file };
    oldOut = System.out;/*from   w  w  w.  j a  va  2s.co  m*/
    oldErr = System.err;
    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
    try {
        Kitchen.main(args);
    } catch (SecurityException e) {
        System.setOut(oldOut);
        System.setErr(oldErr);
        System.out.println(outContent);
        assertFalse(outContent.toString().contains("result=[false]"));
        assertFalse(outContent.toString().contains("ERROR"));
    }
}

From source file:edu.cmu.cs.lti.ark.fn.data.prep.ParsePreparation.java

public static void runExternalCommand(String command) {
    String s;/*from  w w w .ja  v  a 2 s  .co  m*/
    try {
        Process p = Runtime.getRuntime().exec(command);
        PrintStream errStream = System.err;
        System.setErr(System.out);
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
        p.destroy();
        System.setErr(errStream);
    } catch (IOException e) {
        System.out.println("exception happened - here's what I know: ");
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:brooklyn.util.stream.ThreadLocalPrintStream.java

/** installs a thread local print stream to System.err if one is not already set;
 * caller may then #capture and #captureTee on it.
 * @return the ThreadLocalPrintStream which System.err is using */
public synchronized static ThreadLocalPrintStream stderr() {
    PrintStream oldErr = System.err;
    if (oldErr instanceof ThreadLocalPrintStream)
        return (ThreadLocalPrintStream) oldErr;
    ThreadLocalPrintStream newErr = new ThreadLocalPrintStream(System.err);
    System.setErr(newErr);
    return newErr;
}

From source file:org.marketcetera.util.file.WriterWrapperTest.java

private void testStandardErrorStreamUnicode() throws Exception {
    PrintStream stdErrSave = System.err;
    CloseableRegistry r = new CloseableRegistry();
    ByteArrayOutputStream stdErrByteArray = new ByteArrayOutputStream();
    try {/*from www. ja  v  a 2s  . c o  m*/
        r.register(stdErrByteArray);
        PrintStream stdErr = new PrintStream(stdErrByteArray);
        r.register(stdErr);
        System.setErr(stdErr);
        WriterWrapper wrapper = new WriterWrapper(SpecialNames.STANDARD_ERROR, SignatureCharset.UTF8_UTF8);
        r.register(wrapper);
        assertTrue(wrapper.getSkipClose());
        assertNotNull(wrapper.getWriter());
        wrapper.getWriter().write(COMBO);
    } finally {
        System.setErr(stdErrSave);
        r.close();
    }
    assertArrayEquals(ArrayUtils.addAll(Signature.UTF8.getMark(), COMBO_UTF8), stdErrByteArray.toByteArray());
}

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;
        }/*from  www  .  ja v a  2s  . c o  m*/
    });
}

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.");
    }/*from   w w  w.  j  a  v  a 2s  .c om*/

    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:org.tinygroup.jspengine.compiler.JspRuntimeContext.java

/**
 * Create a JspRuntimeContext for a web application context.
 * //from   ww w.  j  av  a2  s. c  om
 * Loads in any previously generated dependencies from file.
 * 
 * @param context
 *            ServletContext for web application
 */
public JspRuntimeContext(ServletContext context, Options options) {

    System.setErr(new SystemLogHandler(System.err));

    this.context = context;
    this.options = options;

    int hashSize = options.getInitialCapacity();
    jsps = new ConcurrentHashMap<String, JspServletWrapper>(hashSize);

    bytecodes = new ConcurrentHashMap<String, byte[]>(hashSize);
    bytecodeBirthTimes = new ConcurrentHashMap<String, Long>(hashSize);

    // Get the parent class loader
    parentClassLoader = Thread.currentThread().getContextClassLoader();
    if (parentClassLoader == null) {
        parentClassLoader = this.getClass().getClassLoader();
    }

    if (log.isTraceEnabled()) {
        if (parentClassLoader != null) {
            log.trace(Localizer.getMessage("jsp.message.parent_class_loader_is", parentClassLoader.toString()));
        } else {
            log.trace(Localizer.getMessage("jsp.message.parent_class_loader_is", "<none>"));
        }
    }

    initClassPath();

    if (context instanceof org.tinygroup.jspengine.servlet.JspCServletContext) {
        return;
    }

    if (Constants.IS_SECURITY_ENABLED) {
        initSecurity();
    }

    // If this web application context is running from a
    // directory, start the background compilation thread
    String appBase = context.getRealPath("/");
    if (!options.getDevelopment() && appBase != null && options.getCheckInterval() > 0) {
        if (appBase.endsWith(File.separator)) {
            appBase = appBase.substring(0, appBase.length() - 1);
        }
        String directory = appBase.substring(appBase.lastIndexOf(File.separator));
        threadName = threadName + "[" + directory + "]";
        threadStart();
    }
}

From source file:runtime.starter.MPJYarnWrapper.java

public void run() {

    try {//w  w  w . ja v  a  2 s  . com
        clientSock = new Socket(serverName, ioServerPort);
    } catch (UnknownHostException exp) {
        System.err.println("Unknown Host Exception, Host not found");
        exp.printStackTrace();
    } catch (IOException exp) {
        exp.printStackTrace();
    }

    // Redirecting Output Stream 
    try {
        System.setOut(new PrintStream(clientSock.getOutputStream(), true));
        System.setErr(new PrintStream(clientSock.getOutputStream(), true));
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        c = Class.forName(className);
    } catch (ClassNotFoundException exp) {
        exp.printStackTrace();
    }

    try {
        String[] arvs = new String[3];

        if (appArgs != null) {
            arvs = new String[3 + appArgs.length];
        }
        arvs[0] = rank;
        arvs[1] = portInfo;
        arvs[2] = deviceName;

        if (appArgs != null) {
            for (int i = 0; i < appArgs.length; i++) {
                arvs[3 + i] = appArgs[i];
            }
        }

        InetAddress localaddr = InetAddress.getLocalHost();
        String hostName = localaddr.getHostName();

        System.out.println("Starting process <" + rank + "> on <" + hostName + ">");

        Method m = c.getMethod("main", new Class[] { arvs.getClass() });
        m.setAccessible(true);
        int mods = m.getModifiers();

        if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
            throw new NoSuchMethodException("main");
        }

        m.invoke(null, new Object[] { arvs });

        System.out.println("Stopping process <" + rank + "> on <" + hostName + ">");

        System.out.println("EXIT");//Stopping IOThread

        try {
            clientSock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception ioe) {
        ioe.printStackTrace();
    }

}

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

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