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:com.alibaba.jstorm.utils.JStormUtils.java

public static void redirectOutput(String file) throws Exception {

    System.out.println("Redirect output to " + file);

    FileOutputStream workerOut = new FileOutputStream(new File(file));

    PrintStream ps = new PrintStream(new BufferedOutputStream(workerOut), true);
    System.setOut(ps);/*  w ww  . j a  va  2  s.  c  om*/
    System.setErr(ps);

    LOG.info("Successfully redirect System.out to " + file);

}

From source file:com.jug.MoMA.java

/**
 * Created and shows the console window and redirects System.out and
 * System.err to it.// w  ww .j  av  a  2s. c om
 */
private void initConsoleWindow() {
    frameConsoleWindow = new JFrame(String.format("%s Console Window", this.VERSION_STRING));
    // frameConsoleWindow.setResizable( false );
    consoleWindowTextArea = new JTextArea();
    consoleWindowTextArea.setLineWrap(true);
    consoleWindowTextArea.setWrapStyleWord(true);

    final int centerX = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2;
    final int centerY = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2;
    frameConsoleWindow.setBounds(centerX - GUI_CONSOLE_WIDTH / 2, centerY - GUI_HEIGHT / 2, GUI_CONSOLE_WIDTH,
            GUI_HEIGHT);
    final JScrollPane scrollPane = new JScrollPane(consoleWindowTextArea);
    //      scrollPane.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
    scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0));
    frameConsoleWindow.getContentPane().add(scrollPane);

    final OutputStream out = new OutputStream() {

        private final PrintStream original = new PrintStream(System.out);

        @Override
        public void write(final int b) throws IOException {
            updateConsoleTextArea(String.valueOf((char) b));
            original.print(String.valueOf((char) b));
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            updateConsoleTextArea(new String(b, off, len));
            original.print(new String(b, off, len));
        }

        @Override
        public void write(final byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    final OutputStream err = new OutputStream() {

        private final PrintStream original = new PrintStream(System.out);

        @Override
        public void write(final int b) throws IOException {
            updateConsoleTextArea(String.valueOf((char) b));
            original.print(String.valueOf((char) b));
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            updateConsoleTextArea(new String(b, off, len));
            original.print(new String(b, off, len));
        }

        @Override
        public void write(final byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(err, true));
}

From source file:org.hyperic.hq.bizapp.agent.client.AgentClient.java

private void redirectOutputs(Properties bootProp) {
    if (this.redirectedOutputs) {
        return;//w  ww .  ja v  a2 s. co  m
    }
    this.redirectedOutputs = true;

    try {
        System.setErr(newLogStream("SystemErr", bootProp));
        System.setOut(newLogStream("SystemOut", bootProp));
    } catch (Exception e) {
        e.printStackTrace(SYSTEM_ERR);
    }
}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

/**
 * Fernflower converts JAR files to a zipped decompiled JAR file then
 * it unzips the JAR file./*from w  w w  . j  a  v a  2  s. c  o  m*/
 */
private JSONObject fern_flower() {// https://github.com/fesh0r/fernflower

    m_srcFernFolder.mkdirs();

    Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {

            LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString());
            m_progressStream.putStream("Uncaught exception: " + t.getName());
            m_progressStream.putStream("Uncaught exception: " + e.toString());
        }
    };

    m_fern_time = System.currentTimeMillis(); // Save start time for tracking

    m_fernThread = new Thread(m_threadGroup, new Runnable() {
        @Override
        public void run() {

            File inputJarFile = null;
            String inputJarFileName = "";

            for (int i = 0; i < m_dexFileNames.length; i++) {

                inputJarFileName = m_dexFileNames[i] + ".jar";
                OmniFile inputJarOmniFile = new OmniFile(m_volumeId, m_appFolderPath + inputJarFileName);
                inputJarFile = inputJarOmniFile.getStdFile();

                if (inputJarFile.exists() && inputJarFile.isFile()) {

                    boolean success = true;
                    try {
                        m_progressStream.putStream("Fernflower starting: " + inputJarFileName);
                        PrintStream printStream = new PrintStream(m_progressStream);
                        System.setErr(printStream);
                        System.setOut(printStream);
                        OmniFile fernLog = new OmniFile(m_volumeId,
                                m_srcFernFolderPath + "/" + m_dexFileNames[i] + "_log.txt");
                        PrintStream logStream = new PrintStream(fernLog.getOutputStream());
                        PrintStreamLogger logger = new PrintStreamLogger(logStream);

                        final Map<String, Object> mapOptions = new HashMap<>();
                        ConsoleDecompiler decompiler = new ConsoleDecompiler(m_srcFernFolder.getStdFile(),
                                mapOptions, logger);
                        decompiler.addSpace(inputJarFile, true);

                        m_progressStream
                                .putStream("Fernflower decompiler.addSpace complete: " + inputJarFileName);
                        decompiler.decompileContext();
                        m_progressStream.putStream(
                                "Fernflower decompiler.decompileContext complete: " + inputJarFileName);

                        String decompiledJarFilePath = m_srcFernFolderPath + "/" + inputJarFileName;
                        OmniFile decompiledJarFile = new OmniFile(m_volumeId, decompiledJarFilePath);
                        success = OmniZip.unzipFile(decompiledJarFile, m_srcFernFolder, null, null);
                        decompiledJarFile.delete();

                        if (success) {
                            m_progressStream
                                    .putStream("Fernflower decompiler.unpack complete: " + inputJarFileName);
                        } else {
                            m_progressStream
                                    .putStream("Fernflower decompiler.unpack failed: " + inputJarFileName);
                        }
                    } catch (Exception e) {
                        String str = LogUtil.logException(LogUtil.LogType.FERNFLOWER, e);
                        m_progressStream.putStream("Fernflower exception " + inputJarFileName);
                        m_progressStream.putStream(str);
                        success = false;
                    }
                    /**
                     * Look for the classes.jar file and unzip it
                     */
                    if (!success) {

                        OmniFile of = new OmniFile(m_volumeId, m_srcFernFolderPath + "/classes.jar");
                        if (of.exists()) {

                            ApkZipUtil.unzip(of, m_srcFernFolder, m_progressStream);
                            m_progressStream.putStream(
                                    "Fernflower utility unzip complete with errors: " + inputJarFileName);
                        } else {
                            m_progressStream.putStream("File does not exist: " + of.getAbsolutePath());
                        }
                    }
                }
            }
            m_progressStream.putStream("Fernflower complete: " + TimeUtil.deltaTimeHrMinSec(m_fern_time));
            m_fern_time = 0;

        }
    }, FERN_THREAD, STACK_SIZE);

    m_fernThread.setPriority(Thread.MAX_PRIORITY);
    m_fernThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    m_fernThread.start();

    //                String processStatus = getThreadStatus( true, m_fernThread);
    //                String url = OmniHash.getHashedServerUrl( m_ctx, m_volumeId, m_srcFernFolderPath);

    String processKey = "fern_thread";
    String urlKey = "fern_url";

    return processWrapper(processKey, urlKey);
}

From source file:io.dockstore.client.cli.nested.AbstractEntryClient.java

private void launchWdl(String entry, final List<String> args) {
    boolean isLocalEntry = false;
    if (args.contains("--local-entry")) {
        isLocalEntry = true;/*from w  ww.  j a  va2s.c o  m*/
    }
    final String json = reqVal(args, "--json");

    Main main = new Main();
    File parameterFile = new File(json);

    final SourceFile wdlFromServer;
    try {
        // Grab WDL from server and store to file
        final File tempDir = Files.createTempDir();
        File tmp;
        if (!isLocalEntry) {
            wdlFromServer = getDescriptorFromServer(entry, "wdl");
            File tempDescriptor = File.createTempFile("temp", ".wdl", tempDir);
            Files.write(wdlFromServer.getContent(), tempDescriptor, StandardCharsets.UTF_8);
            downloadDescriptors(entry, "wdl", tempDir);

            tmp = resolveImportsForDescriptor(tempDir, tempDescriptor);
        } else {
            tmp = new File(entry);
        }

        // Get list of input files
        Bridge bridge = new Bridge();
        Map<String, String> wdlInputs = bridge.getInputFiles(tmp);

        // Convert parameter JSON to a map
        WDLFileProvisioning wdlFileProvisioning = new WDLFileProvisioning(this.getConfigFile());
        Gson gson = new Gson();
        String jsonString = FileUtils.readFileToString(parameterFile, StandardCharsets.UTF_8);
        Map<String, Object> inputJson = gson.fromJson(jsonString, HashMap.class);

        // Download files and change to local location
        // Make a new map of the inputs with updated locations
        final String workingDir = Paths.get(".").toAbsolutePath().normalize().toString();
        System.out.println("Creating directories for run of Dockstore launcher in current working directory: "
                + workingDir);
        Map<String, Object> fileMap = wdlFileProvisioning.pullFiles(inputJson, wdlInputs);

        // Make new json file
        String newJsonPath = wdlFileProvisioning.createUpdatedInputsJson(inputJson, fileMap);

        final List<String> wdlRun = Lists.newArrayList(tmp.getAbsolutePath(), newJsonPath);
        final scala.collection.immutable.List<String> wdlRunList = scala.collection.JavaConversions
                .asScalaBuffer(wdlRun).toList();

        // run a workflow
        System.out.println("Calling out to Cromwell to run your workflow");

        // save the output stream
        PrintStream savedOut = System.out;
        PrintStream savedErr = System.err;

        // capture system.out and system.err
        ByteArrayOutputStream stdoutCapture = new ByteArrayOutputStream();
        System.setOut(new PrintStream(stdoutCapture, true, StandardCharsets.UTF_8.toString()));
        ByteArrayOutputStream stderrCapture = new ByteArrayOutputStream();
        System.setErr(new PrintStream(stderrCapture, true, StandardCharsets.UTF_8.toString()));

        final int run = main.run(wdlRunList);

        System.out.flush();
        System.err.flush();
        String stdout = stdoutCapture.toString(StandardCharsets.UTF_8);
        String stderr = stderrCapture.toString(StandardCharsets.UTF_8);

        System.setOut(savedOut);
        System.setErr(savedErr);
        System.out.println("Cromwell exit code: " + run);

        LauncherCWL.outputIntegrationOutput(workingDir, ImmutablePair.of(stdout, stderr),
                stdout.replaceAll("\n", "\t"), stderr.replaceAll("\n", "\t"), "Cromwell");

        // capture the output and provision it
        final String wdlOutputTarget = optVal(args, "--wdl-output-target", null);
        if (wdlOutputTarget != null) {
            // grab values from output JSON
            Map<String, String> outputJson = gson.fromJson(stdout, HashMap.class);
            System.out.println("Provisioning your output files to their final destinations");
            final List<String> outputFiles = bridge.getOutputFiles(tmp);
            for (String outFile : outputFiles) {
                // find file path from output
                final File resultFile = new File(outputJson.get(outFile));
                FileProvisioning.FileInfo new1 = new FileProvisioning.FileInfo();

                new1.setUrl(wdlOutputTarget + "/" + resultFile.getParentFile().getName() + "/"
                        + resultFile.getName());
                new1.setLocalPath(resultFile.getAbsolutePath());
                System.out.println("Uploading: " + outFile + " from " + resultFile + " to : " + new1.getUrl());
                FileProvisioning fileProvisioning = new FileProvisioning(this.getConfigFile());
                fileProvisioning.provisionOutputFile(new1, resultFile.getAbsolutePath());
            }
        } else {
            System.out.println("Output files left in place");
        }
    } catch (ApiException ex) {
        exceptionMessage(ex, "", API_ERROR);
    } catch (IOException ex) {
        exceptionMessage(ex, "", IO_ERROR);
    }
}

From source file:org.kchine.rpf.PoolUtils.java

public static void redirectIO() {
    final JTextArea area = new JTextArea();
    JFrame f = new JFrame("out/err");
    f.add(new JScrollPane(area), BorderLayout.CENTER);
    f.pack();/*from  w  w w  .  j a v a 2  s. c o m*/
    f.setVisible(true);
    f.setSize(500, 500);
    f.setLocation(100, 100);

    PrintStream ps = new PrintStream(new OutputStream() {
        public void write(final int b) throws IOException {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    area.setText(area.getText() + new String(new byte[] { (byte) b }));
                }
            });
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    area.setCaretPosition(area.getText().length());
                    area.repaint();
                }
            });
        }

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

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    area.setText(area.getText() + new String(b));
                }
            });
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    area.setCaretPosition(area.getText().length());
                    area.repaint();
                }
            });
        }

        public void write(byte[] b, int off, int len) throws IOException {
            final byte[] r = new byte[len];
            for (int i = 0; i < len; ++i)
                r[i] = b[off + i];

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    area.setText(area.getText() + new String(r));
                }
            });
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    area.setCaretPosition(area.getText().length());
                    area.repaint();
                }
            });
        }
    });
    System.setOut(ps);
    System.setErr(ps);
}

From source file:com.ibm.bi.dml.test.integration.AutomatedTestBase.java

public void setExpectedStdErr(String expectedLine) {
    this.expectedStdErr = expectedLine;
    originalErrStreamStd = System.err;
    iExpectedStdErrState = 1;/*from  w  w  w .j  a  v  a2  s  .  c o m*/
    System.setErr(new PrintStream(new ExpectedErrorStream()));
}

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

@Test
public void testRemoteException() throws Exception {
    UserGroupInformation tmpUGI = UserGroupInformation.createUserForTesting("tmpname",
            new String[] { "mygroup" });
    MiniDFSCluster dfs = null;//www.  j av  a 2 s.  c  om
    PrintStream bak = null;
    try {
        final Configuration conf = new HdfsConfiguration();
        dfs = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
        FileSystem fs = dfs.getFileSystem();
        Path p = new Path("/foo");
        fs.mkdirs(p);
        fs.setPermission(p, new FsPermission((short) 0700));
        bak = System.err;

        tmpUGI.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                FsShell fshell = new FsShell(conf);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                PrintStream tmp = new PrintStream(out);
                System.setErr(tmp);
                String[] args = new String[2];
                args[0] = "-ls";
                args[1] = "/foo";
                int ret = ToolRunner.run(fshell, args);
                assertEquals("returned should be 1", 1, ret);
                String str = out.toString();
                assertTrue("permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });
    } finally {
        if (bak != null) {
            System.setErr(bak);
        }
        if (dfs != null) {
            dfs.shutdown();
        }
    }
}

From source file:com.adito.agent.client.Agent.java

protected static Agent initAgent(AgentArgs agentArgs) throws Throwable {
    Agent agent = new Agent(agentArgs.getAgentConfiguration());

    // Setup the output stream
    PrintStream consolePrintStream = new PrintStream(agent.getGUI().getConsole());
    System.setErr(consolePrintStream);
    System.setOut(consolePrintStream);

    System.out.println("Java version " + System.getProperty("java.version"));
    System.out.println("OS version " + System.getProperty("os.name"));

    // #ifdef DEBUG
    if (agentArgs.getLogProperties() != null) {
        File f = new File(agentArgs.getLogProperties());
        InputStream in = new FileInputStream(f);
        try {//from www . ja  v  a 2  s  . co  m
            Properties props = new Properties();
            props.load(in);
            File logfile = new File(f.getParent(), "agent.log"); //$NON-NLS-1$
            props.put("log4j.appender.logfile.File", logfile.getAbsolutePath()); //$NON-NLS-1$
            org.apache.log4j.PropertyConfigurator.configure(props);
            log = org.apache.commons.logging.LogFactory.getLog(Agent.class);
            log.info("Configured logging"); //$NON-NLS-1$
        } finally {
            in.close();
        }
    }

    Properties systemProperties = System.getProperties();
    String key;
    log.info("System properties:");
    for (Enumeration e = systemProperties.keys(); e.hasMoreElements();) {
        key = (String) e.nextElement();
        log.info("   " + key + ": " + systemProperties.getProperty(key));
    }
    // #endif

    agent.setupProxy(agentArgs.getLocalProxyURL(), agentArgs.getUserAgent(), agentArgs.getPluginProxyURL(),
            agentArgs.getReverseProxyURL());

    if (agentArgs.getBrowserCommand() != null && !agentArgs.getBrowserCommand().equals("")) { //$NON-NLS-1$

        // #ifdef DEBUG
        log.info("Setting browser to " + agentArgs.getBrowserCommand()); //$NON-NLS-1$
        // #endif
        BrowserLauncher.setBrowserCommand(agentArgs.getBrowserCommand());
    }

    return agent;
}

From source file:at.alladin.rmbt.android.main.RMBTMainActivity.java

/**
 * /*from   w ww. j  a va  2 s.  c om*/
 * @param toFile
 */
public void redirectSystemOutput(boolean toFile) {
    try {
        if (toFile) {
            Log.i(DEBUG_TAG, "redirecting sysout to file");
            //Redirecting console output and runtime exceptions to file (System.out.println)
            File f = new File(Environment.getExternalStorageDirectory(), "qosdebug");
            if (!f.exists()) {
                f.mkdir();
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmm", Locale.GERMAN);
            //PrintStream fileStream = new PrintStream(new File(f, sdf.format(new Date()) + ".txt"));
            PrintStream fileStream = new DebugPrintStream(new File(f, sdf.format(new Date()) + ".txt"));

            //System.setOut(fileStream);
            System.setErr(fileStream);
        } else {
            //Redirecting console output and runtime exceptions to default output stream
            //System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
            //System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.err)));
            Log.i(DEBUG_TAG, "redirecting sysout to default");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}