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.mpich.MpichContainerWrapper.java

public void run() {
    try {/* w  w w .j  a  v a2 s  .  c o  m*/
        clientSock = new Socket(ioServer, ioServerPort);
        System.setOut(new PrintStream(clientSock.getOutputStream(), true));
        System.setErr(new PrintStream(clientSock.getOutputStream(), true));

        String hostName = InetAddress.getLocalHost().getHostName();
        System.out.println("Starting process " + executable + " on " + hostName);

        List<String> commands = new ArrayList<String>();
        commands.add(executable);
        if (appArgs != null && appArgs.length > 0) {
            commands.addAll(Arrays.asList(appArgs));
        }

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

        Map<String, String> evns = processBuilder.environment();
        evns.put("PMI_RANK", rank);
        evns.put("PMI_SIZE", np);
        evns.put("PMI_ID", pmiid);
        evns.put("PMI_PORT", pmiServer + ":" + pmiServerPort);

        if (this.isSpawn) {
            evns.put("PMI_SPAWNED", "1");
        }

        LOG.info("Starting process:");
        for (String cmd : commands) {
            LOG.info(cmd + "\n");
        }

        Process process = processBuilder.start();
        System.out.println("Process exit with value " + process.waitFor());
        System.out.println("EXIT");//Stopping IOThread
        clientSock.close();
    } catch (UnknownHostException exp) {
        System.err.println("Unknown Host Exception, Host not found");
        exp.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.tools.TestHadoopArchives.java

private static List<String> lsr(final FsShell shell, String dir) throws Exception {
    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   ww  w  . j  a v  a 2  s . com
    System.setErr(out);
    final String results;
    try {
        assertEquals(0, shell.run(new String[] { "-lsr", dir }));
        results = bytes.toString();
    } finally {
        IOUtils.closeStream(out);
        System.setOut(oldOut);
        System.setErr(oldErr);
    }

    final String dirname = dir.substring(dir.lastIndexOf(Path.SEPARATOR));
    final List<String> paths = new ArrayList<String>();
    for (StringTokenizer t = new StringTokenizer(results, "\n"); t.hasMoreTokens();) {
        final String s = t.nextToken();
        final int i = s.indexOf(dirname);
        if (i >= 0) {
            paths.add(s.substring(i + dirname.length()));
        }
    }
    Collections.sort(paths);
    return paths;
}

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

@Before
public void setUp() throws IOException {
    setupWorkDir();//from www. j  av a2 s  .c o m

    // Setup necessary mock
    final JarLocation location = mock(JarLocation.class);
    when(location.getVersion()).thenReturn(Optional.of("1.0.0"));
    when(location.toString()).thenReturn("alexandria-app.jar");

    // Add commands you want to test
    ServerApplication serverApplication = new ServerApplication();
    final Bootstrap<ServerConfiguration> bootstrap = new Bootstrap<>(serverApplication);
    final AppInfo appInfo = new AppInfo().setVersion("$version$").setBuildDate("$buildDate$");
    serverApplication.addCommands(bootstrap, appInfo);

    // Redirect stdout and stderr to our byte streams
    System.setOut(new PrintStream(stdOut));
    System.setErr(new PrintStream(stdErr));

    // Build what'll run the command and interpret arguments
    cli = new Cli(location, bootstrap, stdOut, stdErr);
}

From source file:ai.serotonin.backup.Base.java

void execute() {
    final File processLock = new File(".lock" + suffix);
    if (processLock.exists()) {
        sendEmail("Backup/restore failure!", "Another process is already running. Aborting new run.");
        return;/*w  ww .  j  a v  a 2  s . c o m*/
    }

    String emailSubject = null;
    try (MulticastOutputStream mos = new MulticastOutputStream();
            final FileOutputStream logOut = new FileOutputStream("log" + suffix + ".txt", true);
            final PrintStream out = new PrintStream(mos)) {
        lock(processLock);

        // Redirect output to file and memory log.
        memoryLog = new ByteArrayOutputStream();

        //            mos.setExceptionHandler(new IOExceptionHandler() {
        //                @Override
        //                public void ioException(OutputStream stream, IOException e) {
        //                    e.printStackTrace(s);
        //                }
        //            });
        mos.addStream(logOut);
        mos.addStream(memoryLog);

        System.setOut(out);
        System.setErr(out);

        executeImpl();
        emailSubject = "Backup/restore completion";
    } catch (final Exception e) {
        LOG.error("An error occurred", e);

        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        // TODO sw isn't used?
        emailSubject = "Backup/restore failure!";
    } finally {
        // Send the result email
        final String content = new String(memoryLog.toByteArray());
        sendEmail(emailSubject, content);

        unlock(processLock);
    }
}

From source file:org.kepler.gui.KeplerInitializer.java

public static void initializeSystem() throws Exception {
    System.out.println("Kepler Initializing...");
    // Only run initialization once.
    if (hasBeenInitialized) {
        return;//w  w  w  .j a  v a 2s .c o m
    }

    hasBeenInitialized = true;

    ConfigurationProperty commonProperty = ConfigurationManager.getInstance()
            .getProperty(ConfigurationManager.getModule("common"));

    autoUpdate = Boolean.parseBoolean(commonProperty.getProperty("autoDataSourcesUpdate.value").getValue());
    autoUpdateDelay = Integer.parseInt(commonProperty.getProperty("autoDataSourcesUpdate.delay").getValue());

    // Add the dbconnection type.
    Constants.add("dbconnection", new DBConnectionToken());

    DotKeplerManager dkm = DotKeplerManager.getInstance();

    // String log_file_setting = c.getValue("//log_file");
    String log_file_setting = commonProperty.getProperty("log_file").getValue();

    if (log_file_setting != null) {
        if (log_file_setting.equalsIgnoreCase("true")) {
            log_file = true;
        } else {
            log_file = false;
        }
    }
    if (log_file) {
        try {
            FileOutputStream err = new FileOutputStream("kepler_stderr.log");
            PrintStream errPrintStream = new PrintStream(err);
            System.setErr(errPrintStream);
            System.setOut(errPrintStream);
        } catch (FileNotFoundException fnfe) {
            System.out.println("Warning: Failure to redirect log to a file.");
        }
    }

    // First get the entries named mkdir. We will make
    // directories for each of these entries under the UserDir.

    List mkdirList = commonProperty.getProperties("startup");
    List mkdirs = ConfigurationProperty.getValueList(mkdirList, "mkdir", true);

    for (Iterator i = mkdirs.iterator(); i.hasNext();) {
        String dir = (String) i.next();
        if (dir == null || dir.length() == 0) {
            continue;
        }

        dir = dkm.getCacheDir(dir);

        File f = new File(dir);
        if (!f.exists()) {
            boolean created = f.mkdirs();
            if (created) {
                log.debug("Making directory " + dir);
            }
        }
    }

    Connection conn = DatabaseFactory.getDBConnection();

    //
    // Get the tabletestsql entry. This is the sql used to test if a
    // table already exists in the database.
    //
    String tabletestsql = commonProperty.getProperty("startup.tabletestsql").getValue();
    PreparedStatement tabletest = null;
    if (tabletestsql != null) {
        tabletest = conn.prepareStatement(tabletestsql);
    }

    // We use pattern matching to extract the tablename from the
    // ddl statement. This is a Java 1.4 regex regular expression
    // which extracts the word after the string "table". The
    // match is case insensitive so "table" will also match
    // "TABLE". The "(" ")" characters denote a grouping. This
    // will be returned as group 1.

    Pattern extractTable = Pattern.compile("table\\s+(\\w*)", Pattern.CASE_INSENSITIVE);

    // Get the list of ddl statements defining the tables to create.
    List createTableList = commonProperty.getProperties("startup");
    List createtables = ConfigurationProperty.getValueList(createTableList, "createtable", true);

    final String schemaName = CacheManager.getDatabaseSchemaName();

    for (Iterator i = createtables.iterator(); i.hasNext();) {
        String ddl = (String) i.next();
        // Create our Matcher object for the ddl string.
        Matcher m = extractTable.matcher(ddl);
        // Matcher.find() looks for any match of the pattern in the string.
        m.find();

        String tablename = m.group(1);
        if (tabletest == null) {
            log.error("unable to test for table: " + tablename);
            continue;
        }

        tabletest.setString(1, tablename);
        tabletest.setString(2, schemaName);
        ResultSet rs = tabletest.executeQuery();
        if (rs.next()) {
            log.debug("Table " + tablename + " already exists");
            continue;
        }
        Statement statement = conn.createStatement();
        statement.execute(ddl);
        statement.close();
        log.debug("Table " + tablename + " created");
    }
    tabletest.close();

    // Get the Authorized Namespace after the tables are set up.
    AuthNamespace an = AuthNamespace.getInstance();
    an.initialize();

    // Hook to execute arbitrary sql statements on the internal database.
    // List sqls = c.getList("//startup/sql");
    List sqlList = commonProperty.getProperties("startup");
    List sqls = ConfigurationProperty.getValueList(sqlList, "sql", true);
    Statement statement = null;
    for (Iterator i = sqls.iterator(); i.hasNext();) {
        String statementStr = (String) i.next();
        log.info("Executing sql command " + statementStr);
        statement = conn.createStatement();
        statement.execute(statementStr);
    }
    if (statement != null)
        statement.close();
    conn.close();

    // Set the icon loader to load Kepler files
    MoMLParser.setIconLoader(new KeplerIconLoader());

    // set the initial directory for file dialogs
    setDefaultFileDialogDir();

    // refresh the datasources from the registry
    updateDataSources();
}

From source file:org.apache.spark.simr.Simr.java

public void redirectOutput(String filePrefix) throws IOException {
    FSDataOutputStream stdout = fs.create(new Path(conf.get("simr_out_dir") + "/" + filePrefix + ".stdout"));
    FSDataOutputStream stderr = fs.create(new Path(conf.get("simr_out_dir") + "/" + filePrefix + ".stderr"));
    System.setOut(new PrintStream(stdout));
    System.setErr(new PrintStream(stderr));
}

From source file:be.makercafe.apps.makerbench.Main.java

@Override
public void start(Stage primaryStage) {
    setupWorkspace();//from  w  ww.j  av a 2s .  c  o  m
    rootContextMenu = createViewerContextMenu();
    viewer = createViewer();

    this.stage = primaryStage;
    BorderPane p = new BorderPane();

    p.setTop(createMenuBar());

    // p.setLeft(viewer);
    tabFolder = new TabPane();
    BorderPane bodyPane = new BorderPane();
    TextArea taConsole = new TextArea();
    taConsole.setPrefSize(Double.MAX_VALUE, 200.0);
    taConsole.setEditable(false);

    Console console = new Console(taConsole);
    PrintStream ps = new PrintStream(console, true);
    System.setOut(ps);
    System.setErr(ps);

    bodyPane.setBottom(taConsole);
    bodyPane.setCenter(tabFolder);
    SplitPane splitpane = new SplitPane();
    splitpane.getItems().addAll(viewer, bodyPane);
    splitpane.setDividerPositions(0.0f, 1.0f);
    p.setCenter(splitpane);

    Scene scene = new Scene(p, 1024, 800);
    //scene.getStylesheets().add(this.getClass().getResource("/styles/java-keywords.css").toExternalForm());

    primaryStage.setResizable(true);
    primaryStage.setTitle("Makerbench");
    primaryStage.setScene(scene);
    //primaryStage.getIcons().add(new Image("/path/to/stackoverflow.jpg"));
    primaryStage.show();
}

From source file:ConsoleWindowTest.java

public static void init() {
    JFrame frame = new JFrame();
    frame.setTitle("ConsoleWindow");
    final JTextArea output = new JTextArea();
    output.setEditable(false);/*w  w w  . ja  v a 2s  .c  o m*/
    frame.add(new JScrollPane(output));
    frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    frame.setLocation(DEFAULT_LEFT, DEFAULT_TOP);
    frame.setFocusableWindowState(false);
    frame.setVisible(true);

    // define a PrintStream that sends its bytes to the output text area
    PrintStream consoleStream = new PrintStream(new OutputStream() {
        public void write(int b) {
        } // never called

        public void write(byte[] b, int off, int len) {
            output.append(new String(b, off, len));
        }
    });

    // set both System.out and System.err to that stream
    System.setOut(consoleStream);
    System.setErr(consoleStream);
}

From source file:org.apache.jk.apr.AprImpl.java

/** Sets the System.err stream */

public static void setErr(String filename) {
    try {//from   w w w  . ja  v  a  2  s.com
        if (filename != null) {
            System.setErr(new PrintStream(new FileOutputStream(filename)));
        }
    } catch (Throwable th) {
    }
}

From source file:org.apache.hadoop.hive.metastore.tools.TestSchemaToolForMetastore.java

@After
public void tearDown() throws IOException, SQLException {
    File metaStoreDir = new File(testMetastoreDB);
    if (metaStoreDir.exists()) {
        FileUtils.forceDeleteOnExit(metaStoreDir);
    }/*from  w w  w. j ava  2 s .  co m*/
    System.setOut(outStream);
    System.setErr(errStream);
    if (conn != null) {
        conn.close();
    }
}