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.apache.hadoop.hdfs.TestDFSShell.java

private static String runLsr(final FsShell shell, String root, int returnvalue) throws Exception {
    System.out.println("root=" + root + ", returnvalue=" + returnvalue);
    final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    final PrintStream out = new PrintStream(bytes);
    final PrintStream oldOut = System.out;
    final PrintStream oldErr = System.err;
    System.setOut(out);//from w w  w .ja  v  a  2  s.  c o  m
    System.setErr(out);
    final String results;
    try {
        assertEquals(returnvalue, shell.run(new String[] { "-lsr", root }));
        results = bytes.toString();
    } finally {
        IOUtils.closeStream(out);
        System.setOut(oldOut);
        System.setErr(oldErr);
    }
    System.out.println("results:\n" + results);
    return results;
}

From source file:de.hybris.platform.test.TransactionTest.java

@Test
public void testNestedTAError() throws Exception {

    final AtomicBoolean storeCalled = new AtomicBoolean();
    final AtomicBoolean commitCalled = new AtomicBoolean();
    final AtomicBoolean rollbackCalled = new AtomicBoolean();

    final Transaction transaction = new DefaultTransaction() {
        @Override/*from  w ww. java2 s  .c  om*/
        public void rollback() throws TransactionException {
            rollbackCalled.set(true);
            super.rollback();
        }

        @Override
        public void commit() throws TransactionException {
            commitCalled.set(true);
            super.commit();
        }
    };
    transaction.enableDelayedStore(true);

    final EntityInstanceContext eCtx = new EntityInstanceContext() {

        @Override
        public ItemDeployment getItemDeployment() {
            return null;
        }

        @Override
        public PK getPK() {
            return PK.NULL_PK;
        }

        @Override
        public PersistencePool getPersistencePool() {
            return null;
        }

        @Override
        public void setPK(final PK pk) {
            // mock
        }
    };

    final EntityInstance mockEntity = new EntityInstance() {
        final EntityInstanceContext ctx = eCtx;

        @Override
        public PK ejbFindByPrimaryKey(final PK pkValue) throws YObjectNotFoundException {
            return null;
        }

        @Override
        public void ejbLoad() {
            // mock
        }

        @Override
        public void ejbRemove() {
            // mock
        }

        @Override
        public void ejbStore() {
            storeCalled.set(true);
            throw new IllegalArgumentException("let's rollback ;)");
        }

        @Override
        public EntityInstanceContext getEntityContext() {
            return ctx;
        }

        @Override
        public boolean needsStoring() {
            return true;
        }

        @Override
        public void setEntityContext(final EntityInstanceContext ctx) {
            // mock
        }

        @Override
        public void setNeedsStoring(final boolean needs) {
            // mock
        }

    };

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final PrintStream printstream = new PrintStream(bos);

    final PrintStream err = System.err;

    final AtomicReference<Title> itemRef = new AtomicReference<Title>();

    try {
        System.setErr(printstream);

        // outer TA
        transaction.execute(new TransactionBody() {
            @Override
            public Object execute() throws Exception {
                // inner TA
                transaction.execute(new TransactionBody() {
                    @Override
                    public Object execute() throws Exception {
                        itemRef.set(UserManager.getInstance().createTitle("T" + System.currentTimeMillis()));

                        // inject mock entity to call ejbStore upon -> throws exception
                        transaction.registerEntityInstance(mockEntity);

                        return null;
                    }

                });
                return null;
            }

        });
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException ex) {
        assertTrue(storeCalled.get());
        assertEquals("let's rollback ;)", ex.getMessage());

        assertFalse(transaction.isRunning());
        assertEquals(0, transaction.getOpenTransactionCount());
        assertNotNull(itemRef.get());
        assertFalse(itemRef.get().isAlive());

        final String errorLog = new String(bos.toByteArray());

        assertFalse(errorLog.contains("no transaction running"));
    } catch (final Exception e) {
        fail("unexpected error " + e.getMessage());
    } finally {
        System.setErr(err);
    }
}

From source file:homenetapp.HomeNetAppGui.java

private void redirectSystemStreams() {

    javax.swing.text.Style style = consoleTextPane.addStyle("Red", null);
    javax.swing.text.StyleConstants.setForeground(style, java.awt.Color.red);
    final javax.swing.text.Style redStyle = style;

    style = consoleTextPane.addStyle("White", null);
    javax.swing.text.StyleConstants.setForeground(style, java.awt.Color.white);
    final javax.swing.text.Style whiteStyle = style;

    OutputStream out = new OutputStream() {

        @Override//  w w  w .  j  av  a  2  s  . c o m
        public void write(final int b) throws IOException {
            updateTextPane(String.valueOf((char) b), whiteStyle);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            updateTextPane(new String(b, off, len), whiteStyle);
        }

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

    OutputStream err = new OutputStream() {

        @Override
        public void write(final int b) throws IOException {
            updateTextPane(String.valueOf((char) b), redStyle);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            updateTextPane(new String(b, off, len), redStyle);
        }

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

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

From source file:com.netscape.admin.certsrv.Console.java

public static void tee(String f) throws IOException {

    // Create/Open logfile.
    logfile = new PrintStream(new BufferedOutputStream(new FileOutputStream(f)), /*autoFlush=*/true);

    // Start redirecting the output.
    System.setOut(new TeeStream(System.out));
    System.setErr(new TeeStream(System.err));
}

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

@Test(timeout = 30000)
public void testSetXAttrPermission() throws Exception {
    UserGroupInformation user = UserGroupInformation.createUserForTesting("user", new String[] { "mygroup" });
    MiniDFSCluster cluster = null;//from   www .  j av a2s . co  m
    PrintStream bak = null;
    try {
        final Configuration conf = new HdfsConfiguration();
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
        cluster.waitActive();

        FileSystem fs = cluster.getFileSystem();
        Path p = new Path("/foo");
        fs.mkdirs(p);
        bak = System.err;

        final FsShell fshell = new FsShell(conf);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setErr(new PrintStream(out));

        // No permission to write xattr
        fs.setPermission(p, new FsPermission((short) 0700));
        user.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                int ret = ToolRunner.run(fshell,
                        new String[] { "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                String str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });

        int ret = ToolRunner.run(fshell, new String[] { "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
        assertEquals("Returned should be 0", 0, ret);
        out.reset();

        // No permission to read and remove
        fs.setPermission(p, new FsPermission((short) 0750));
        user.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // Read
                int ret = ToolRunner.run(fshell, new String[] { "-getfattr", "-n", "user.a1", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                String str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                // Remove
                ret = ToolRunner.run(fshell, new String[] { "-setfattr", "-x", "user.a1", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });
    } finally {
        if (bak != null) {
            System.setErr(bak);
        }
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

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

/**
 * HDFS-6374 setXAttr should require the user to be the owner of the file
 * or directory.//from ww w.ja v  a  2s.c o m
 *
 * Test to make sure that only the owner of a file or directory can set
 * or remove the xattrs.
 *
 * As user1:
 * Create a directory (/foo) as user1, chown it to user1 (and user1's group),
 * grant rwx to "other".
 *
 * As user2:
 * Set an xattr (should fail).
 *
 * As user1:
 * Set an xattr (should pass).
 *
 * As user2:
 * Read the xattr (should pass).
 * Remove the xattr (should fail).
 *
 * As user1:
 * Read the xattr (should pass).
 * Remove the xattr (should pass).
 */
@Test(timeout = 30000)
public void testSetXAttrPermissionAsDifferentOwner() throws Exception {
    final String USER1 = "user1";
    final String GROUP1 = "mygroup1";
    final UserGroupInformation user1 = UserGroupInformation.createUserForTesting(USER1,
            new String[] { GROUP1 });
    final UserGroupInformation user2 = UserGroupInformation.createUserForTesting("user2",
            new String[] { "mygroup2" });
    MiniDFSCluster cluster = null;
    PrintStream bak = null;
    try {
        final Configuration conf = new HdfsConfiguration();
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
        cluster.waitActive();

        final FileSystem fs = cluster.getFileSystem();
        fs.setOwner(new Path("/"), USER1, GROUP1);
        bak = System.err;

        final FsShell fshell = new FsShell(conf);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setErr(new PrintStream(out));

        // mkdir foo as user1
        user1.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                final int ret = ToolRunner.run(fshell, new String[] { "-mkdir", "/foo" });
                assertEquals("Return should be 0", 0, ret);
                out.reset();
                return null;
            }
        });

        user1.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // Give access to "other"
                final int ret = ToolRunner.run(fshell, new String[] { "-chmod", "707", "/foo" });
                assertEquals("Return should be 0", 0, ret);
                out.reset();
                return null;
            }
        });

        // No permission to write xattr for non-owning user (user2).
        user2.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                final int ret = ToolRunner.run(fshell,
                        new String[] { "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                final String str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });

        // But there should be permission to write xattr for
        // the owning user.
        user1.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                final int ret = ToolRunner.run(fshell,
                        new String[] { "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
                assertEquals("Returned should be 0", 0, ret);
                out.reset();
                return null;
            }
        });

        // There should be permission to read,but not to remove for
        // non-owning user (user2).
        user2.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // Read
                int ret = ToolRunner.run(fshell, new String[] { "-getfattr", "-n", "user.a1", "/foo" });
                assertEquals("Returned should be 0", 0, ret);
                out.reset();
                // Remove
                ret = ToolRunner.run(fshell, new String[] { "-setfattr", "-x", "user.a1", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                final String str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });

        // But there should be permission to read/remove for
        // the owning user.
        user1.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // Read
                int ret = ToolRunner.run(fshell, new String[] { "-getfattr", "-n", "user.a1", "/foo" });
                assertEquals("Returned should be 0", 0, ret);
                out.reset();
                // Remove
                ret = ToolRunner.run(fshell, new String[] { "-setfattr", "-x", "user.a1", "/foo" });
                assertEquals("Returned should be 0", 0, ret);
                out.reset();
                return null;
            }
        });
    } finally {
        if (bak != null) {
            System.setErr(bak);
        }
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:org.proteomecommons.tranche.cacheupdater.CacheUpdater.java

public void execute() {
    // first and foremost, make sure the proteomecommons tranche configuration is loaded
    ProteomeCommonsTrancheConfig.load();

    // set up directories
    if (!workingDirectory.exists()) {
        workingDirectory.mkdirs();/*from  ww  w  . j  a va2s  . co  m*/
    }

    if (!publishDirectory.exists()) {
        publishDirectory.mkdirs();
    }

    PrintStream detailsLog = null, errorLog = null, generalLog = null, stdOutLog = null, stdErrLog = null;
    try {
        // create the log files
        File detailsLogFile = new File(workingDirectory, "details.log");
        if (!detailsLogFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the detailed log file.");
        }
        detailsLog = new PrintStream(new FileOutputStream(detailsLogFile));

        File errorLogFile = new File(workingDirectory, "errors.log");
        if (!errorLogFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the error log file.");
        }
        errorLog = new PrintStream(new FileOutputStream(errorLogFile));

        File generalLogFile = new File(workingDirectory, "general.log");
        if (!generalLogFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the general log file.");
        }
        generalLog = new PrintStream(new FileOutputStream(generalLogFile));

        File changesLogFile = new File(workingDirectory, "changes.log");
        if (!changesLogFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the changes log file.");
        }
        changesLog = new PrintStream(new FileOutputStream(changesLogFile));

        File missingLogFile = new File(workingDirectory, "missing.log");
        if (!missingLogFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the missing log file.");
        }
        missingLog = new PrintStream(new FileOutputStream(missingLogFile));

        File invalidLogFile = new File(workingDirectory, "invalid.log");
        if (!invalidLogFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the invalid log file.");
        }
        invalidLog = new PrintStream(new FileOutputStream(invalidLogFile));

        File stdOutFile = new File(workingDirectory, "stdout.log");
        if (!stdOutFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the standard out log file.");
        }
        stdOutLog = new PrintStream(new FileOutputStream(stdOutFile));

        File stdErrFile = new File(workingDirectory, "stderr.log");
        if (!stdErrFile.createNewFile()) {
            throw new RuntimeException("There was a problem creating the standard error log file.");
        }
        stdErrLog = new PrintStream(new FileOutputStream(stdErrFile));

        // change standard out and err
        System.setOut(stdOutLog);
        System.setErr(stdErrLog);

        // set output to the detailed log
        log = detailsLog;
        err = errorLog;

        // run the cache updater
        start = System.currentTimeMillis();

        if (updateTagsDatabase || makeNewCache) {
            populateHashesSet();
        }
        if (updateTagsDatabase) {
            updateTagsDatabase();
        }
        if (makeNewCache) {
            createCacheFile();
            if (makeChanges) {
                publishCacheFile();
            }
        }
        if (indexTagsDatabase) {
            indexTagsDatabase();
        }
    } catch (Exception e) {
        log.println("ERROR: Fatal error. Program terminating.");
        err.println(e.getMessage());
        Thread t = new Thread() {

            public void run() {
                try {
                    EmailUtil.sendEmail("FATAL ERROR: Cache Updater",
                            new String[] { "augman85@gmail.com", "jfalkner@umich.edu",
                                    "bryanesmith@gmail.com" },
                            "A fatal error occurred on the cache updater. Check the logs on the proteomecommons.org server under \""
                                    + workingDirectory.getAbsolutePath() + "\" for more information.");
                } catch (Exception e) {
                }
            }
        };
        t.start();
    } finally {
        stop = System.currentTimeMillis();

        detailsLog.flush();
        detailsLog.close();

        printFileTypeLog();

        log = generalLog;
        printReportOfAction();
        generalLog.flush();
        generalLog.close();

        changesLog.flush();
        changesLog.close();
        missingLog.flush();
        missingLog.close();
        invalidLog.flush();
        invalidLog.close();
        errorLog.flush();
        errorLog.close();
        stdOutLog.flush();
        stdOutLog.close();
        stdErrLog.flush();
        stdErrLog.close();

        System.out
                .println("*** FINISHED BUILDING " + Text.getFormattedDate(System.currentTimeMillis()) + " ***");
    }
}