Example usage for java.io PrintStream flush

List of usage examples for java.io PrintStream flush

Introduction

In this page you can find the example usage for java.io PrintStream flush.

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:org.openspaces.test.client.executor.Executor.java

/**
 * Redirect process output stream to desired abstract {@link OutputStream} (FileOutputStream,
 * System.out)./*from w  ww.ja  va 2  s .c o m*/
 *
 * @param process   a forked process
 * @param outStream an abstract output stream.
 * @param command   an execution command.
 */
static void redirectOutputStream(final Process process, OutputStream outStream, Command command) {
    //outStream may be null if no redirection is required
    if (outStream == null)
        return; //no redirection required

    /* override system.out stream to avoid close() */
    if (outStream == System.out)
        outStream = new StandardOutputStream();

    final PrintStream procOutStream = new PrintStream(outStream);
    final InputStream processInputStream = process.getInputStream();

    procOutStream.println(command + "\n");

    /* start in background ProccessOutputCollector */
    _forkableExecutor.execute(new Runnable() {
        public void run() {
            String line = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(processInputStream));

            try {
                while ((line = in.readLine()) != null) {
                    procOutStream.println(line);
                    procOutStream.flush();
                }
            } catch (IOException ex) {
                if (_logger.isDebugEnabled())
                    _logger.debug("Caught exception by ProcessOutputStream.", ex);
            } catch (NullPointerException ex) {
                // ignore since JDK 1.4 has a bug
            } finally {
                if (procOutStream != null)
                    procOutStream.close();
            }

            if (_logger.isDebugEnabled())
                _logger.debug("ForkProcess Thread: " + Thread.currentThread().getName() + " was terminated.");
        }// run()
    }// Runnable
    );

    /* give an opportunity to start processor-collector thread before the process was destroyed */
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
    }
    ;
}

From source file:com.moss.greenshell.wizard.catastrophe.PostMortemScreen.java

public static void submitErrorReport(final Throwable cause, final ErrorReportDecorator... decorators)
        throws Exception {

    List<ErrorReportChunk> chunks = new LinkedList<ErrorReportChunk>();

    try {/*from  w  w  w  .j a va 2s  .  c o m*/
        if (cause instanceof InternalErrorException) {
            InternalErrorException ie = (InternalErrorException) cause;
            ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                    ie.id().getBytes("UTF8"));
            chunks.add(chunk);
        } else if (cause instanceof SOAPFaultException) {
            SOAPFaultException soapFault = (SOAPFaultException) cause;
            String content = soapFault.getFault().getFirstChild().getTextContent();
            String prefix = "Internal Service Error Occurred: ";
            if (content.startsWith(prefix)) {
                String id = content.substring(prefix.length());
                ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                        id.getBytes("UTF8"));
                chunks.add(chunk);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }

    // STACK TRACE
    ByteArrayOutputStream stackBytes = new ByteArrayOutputStream();
    PrintStream stackPrintStream = new PrintStream(stackBytes);
    cause.printStackTrace(stackPrintStream);
    stackPrintStream.close();
    stackBytes.close();

    ErrorReportChunk chunk = new ErrorReportChunk("stack trace", "text/plain", stackBytes.toByteArray());
    chunks.add(chunk);

    // THREAD DUMP

    ByteArrayOutputStream dumpBytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(dumpBytes);
    Map<Thread, StackTraceElement[]> traceMap = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> next : traceMap.entrySet()) {
        out.println();
        out.println(next.getKey().getName());
        for (StackTraceElement line : next.getValue()) {
            String className = emptyIfNull(line.getClassName());
            String methodName = emptyIfNull(line.getMethodName());
            String fileName = emptyIfNull(line.getFileName());

            out.println("    " + className + "." + methodName + " (" + fileName + " line "
                    + line.getLineNumber() + ")");
        }
    }
    out.flush();
    out.close();
    ErrorReportChunk stackDump = new ErrorReportChunk("thread dump", "text/plain", dumpBytes.toByteArray());
    chunks.add(stackDump);

    // SYSTEM PROPERTIES
    ByteArrayOutputStream propsBytes = new ByteArrayOutputStream();
    PrintStream propsOut = new PrintStream(propsBytes);
    for (Map.Entry<Object, Object> next : System.getProperties().entrySet()) {
        propsOut.println(" " + next.getKey() + "=" + next.getValue());
    }
    propsOut.flush();
    propsOut.close();
    chunks.add(new ErrorReportChunk("system properties", "text/plain", propsBytes.toByteArray()));

    // LOCAL CLOCK
    chunks.add(new ErrorReportChunk("local clock", "text/plain", new DateTime().toString().getBytes()));

    // NETWORKING
    StringBuffer networking = new StringBuffer();
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        networking.append("INTERFACE: " + iface.getName() + " (" + iface.getDisplayName() + ")\n");
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            networking.append("  Address:" + address.getHostAddress() + "\n");
            networking.append("      Cannonical Host Name: " + address.getCanonicalHostName() + "\n");
            networking.append("                 Host Name: " + address.getHostName() + "\n");
        }
    }
    chunks.add(new ErrorReportChunk("network configuration", "text/plain", networking.toString().getBytes()));

    // DECORATORS
    if (decorators != null) {
        for (ErrorReportDecorator decorator : decorators) {
            chunks.addAll(decorator.makeChunks(cause));
        }
    }
    ErrorReport report = new ErrorReport(chunks);
    Reporter reporter = new Reporter();
    ReportId id = reporter.submitReport(report);
}

From source file:net.imagini.cassandra.DumpSSTables.SSTableExport.java

/**
 * Enumerate row keys from an SSTableReader and write the result to a
 * PrintStream./*from w  ww  . j  a  va2 s.co m*/
 * 
 * @param desc
 *            the descriptor of the file to export the rows from
 * @param outs
 *            PrintStream to write the output to
 * @throws IOException
 *             on failure to read/write input/output
 */
public static void enumeratekeys(Descriptor desc, PrintStream outs) throws IOException {
    KeyIterator iter = new KeyIterator(desc);
    DecoratedKey lastKey = null;
    while (iter.hasNext()) {
        DecoratedKey key = iter.next();

        // validate order of the keys in the sstable
        if (lastKey != null && lastKey.compareTo(key) > 0)
            throw new IOException("Key out of order! " + lastKey + " > " + key);
        lastKey = key;

        outs.println(ByteBufferUtil.string(key.key));
    }
    iter.close();
    outs.flush();
}

From source file:com.anrisoftware.mongoose.buildins.echobuildin.EchoBuildin.java

@Override
protected void doCall() {
    PrintStream stream = new PrintStream(getOutput());
    output.output(stream, text);/*from   www . j  a va2 s . c  om*/
    stream.flush();
}

From source file:pxb.android.tinysign.TinySign.java

private static Manifest generateSF(Manifest manifest)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print = new PrintStream(new DigestOutputStream(new OutputStream() {

        @Override//from   w  ww.j a  va2  s  . c o m
        public void write(byte[] arg0) throws IOException {
        }

        @Override
        public void write(byte[] arg0, int arg1, int arg2) throws IOException {
        }

        @Override
        public void write(int arg0) throws IOException {
        }
    }, md), true, "UTF-8");
    Manifest sf = new Manifest();
    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue("SHA1-Digest", eBase64(md.digest()));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }
    return sf;
}

From source file:imagingbook.lib.math.Matrix.java

public static void printToStream(double[][] A, PrintStream strm) {
    strm.format("{");
    for (int i = 0; i < A.length; i++) {
        if (i == 0)
            strm.format("{");
        else/*from   w  w  w.j  ava  2  s  . c  om*/
            strm.format(", \n{");
        for (int j = 0; j < A[i].length; j++) {
            if (j == 0)
                strm.format(fStr, A[i][j]);
            else
                strm.format(", " + fStr, A[i][j]);
        }
        strm.format("}");
    }
    strm.format("}");
    strm.flush();
}

From source file:imagingbook.lib.math.Matrix.java

public static void printToStream(float[][] A, PrintStream strm) {
    strm.format("{");
    for (int i = 0; i < A.length; i++) {
        if (i == 0)
            strm.format("{");
        else//  w  w  w.  j  a va2s.  c  o  m
            strm.format(", \n{");
        for (int j = 0; j < A[i].length; j++) {
            if (j == 0)
                strm.format(fStr, A[i][j]);
            else
                strm.format(", " + fStr, A[i][j]);
        }
        strm.format("}");
    }
    strm.format("}");
    strm.flush();
}

From source file:com.hazelcast.simulator.probes.probes.impl.HdrLatencyDistributionResult.java

@Override
public String toHumanString() {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintStream stream = new PrintStream(outputStream);
    histogram.outputPercentileDistribution(stream, 1.0);
    stream.flush();
    return new String(outputStream.toByteArray());
}

From source file:org.apache.cassandra.tools.SSTableExport.java

static void export(SSTableReader reader, PrintStream outs, String[] excludes) throws IOException {
    Set<String> excludeSet = new HashSet<String>();

    if (excludes != null)
        excludeSet = new HashSet<String>(Arrays.asList(excludes));

    SSTableIdentityIterator row;/*from   w  w  w . jav  a  2 s .  c o  m*/
    SSTableScanner scanner = reader.getDirectScanner(BufferedRandomAccessFile.DEFAULT_BUFFER_SIZE);

    outs.println("{");

    int i = 0;

    // collecting keys to export
    while (scanner.hasNext()) {
        row = (SSTableIdentityIterator) scanner.next();

        String currentKey = bytesToHex(row.getKey().key);

        if (excludeSet.contains(currentKey))
            continue;
        else if (i != 0)
            outs.println(",");

        serializeRow(row, row.getKey(), outs);

        i++;
    }

    outs.println("\n}");
    outs.flush();

    scanner.close();
}

From source file:com.yahoo.storm.yarn.LaunchCommand.java

@Override
public void process(CommandLine cl) throws Exception {

    String config_file = null;//from  w  w  w  .  j  av a  2s.  c o  m
    List remaining_args = cl.getArgList();
    if (remaining_args != null && !remaining_args.isEmpty()) {
        config_file = (String) remaining_args.get(0);
    }
    Map stormConf = Config.readStormConfig(config_file);

    String appName = cl.getOptionValue("appname", "Storm-on-Yarn");
    String queue = cl.getOptionValue("queue", "default");

    String storm_zip_location = cl.getOptionValue("stormZip");
    Integer amSize = (Integer) stormConf.get(Config.MASTER_SIZE_MB);

    StormOnYarn storm = null;
    try {
        storm = StormOnYarn.launchApplication(appName, queue, amSize, stormConf, storm_zip_location);
        LOG.debug("Submitted application's ID:" + storm.getAppId());

        //download storm.yaml file
        String storm_yaml_output = cl.getOptionValue("stormConfOutput");
        if (storm_yaml_output != null && storm_yaml_output.length() > 0) {
            //try to download storm.yaml
            StormMaster.Client client = storm.getClient();
            if (client != null)
                StormMasterCommand.downloadStormYaml(client, storm_yaml_output);
            else
                LOG.warn("No storm.yaml is downloaded");
        }

        //store appID to output
        String output = cl.getOptionValue("output");
        if (output == null)
            System.out.println(storm.getAppId());
        else {
            PrintStream os = new PrintStream(output);
            os.println(storm.getAppId());
            os.flush();
            os.close();
        }
    } finally {
        if (storm != null) {
            storm.stop();
        }
    }
}