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:grakn.core.console.test.GraknConsoleIT.java

private Response runConsoleSession(String input, String... args) {
    args = addKeyspaceAndUriParams(args);

    OutputStream bufferOut = new ByteArrayOutputStream();
    OutputStream bufferErr = new ByteArrayOutputStream();

    PrintStream printOut = new PrintStream(new TeeOutputStream(bufferOut, System.out));
    PrintStream printErr = new PrintStream(new TeeOutputStream(bufferErr, System.err));

    try {//from  ww  w  .  j  av a2 s.  c  o  m
        System.setIn(new ByteArrayInputStream(input.getBytes()));
        GraknConsole console = new GraknConsole(args, printOut, printErr);
        console.run();
    } catch (Exception e) {
        printErr.println(e.getMessage());
        printErr.flush();
    } finally {
        resetIO();
    }

    printOut.flush();
    printErr.flush();

    return Response.of(bufferOut.toString(), bufferErr.toString());
}

From source file:jenkins.plugins.logstash.persistence.ElasticSearchDao.java

private String getErrorMessage(CloseableHttpResponse response) {
    ByteArrayOutputStream byteStream = null;
    PrintStream stream = null;
    try {//w w  w .j  av a  2  s  . c  o  m
        byteStream = new ByteArrayOutputStream();
        stream = new PrintStream(byteStream);

        try {
            stream.print("HTTP error code: ");
            stream.println(response.getStatusLine().getStatusCode());
            stream.print("URI: ");
            stream.println(uri.toString());
            stream.println("RESPONSE: " + response.toString());
            response.getEntity().writeTo(stream);
        } catch (IOException e) {
            stream.println(ExceptionUtils.getStackTrace(e));
        }
        stream.flush();
        return byteStream.toString();
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:org.itstechupnorth.walrus.text.WordCounter.java

public WordCounter printTo(PrintStream out) {
    out.println("# words: " + count.size());
    int i = 0;/*from  ww  w.j av a  2 s  . c  o m*/
    WordCount.Walk walk = count.descending();
    while (walk.hasNext()) {
        if (++i % 100 == 0)
            out.println("# @" + i);
        out.println(walk.next() + " " + walk.count());
    }
    out.println("#");
    out.println("# Just Words");
    out.println("#");
    i = 0;
    walk = count.descending();
    while (walk.hasNext()) {
        if (++i % 100 == 0)
            out.println("# @" + i);
        out.println(walk.next());
    }
    out.flush();
    return this;
}

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

/**
 * Export specific rows from an SSTable and write the resulting JSON to a
 * PrintStream./*w w  w . java 2 s .c  o m*/
 * 
 * @param desc
 *            the descriptor of the sstable table to read from
 * @param outs
 *            PrintStream to write the output to
 * @param toExport
 *            the keys corresponding to the rows to export
 * @param excludes
 *            keys to exclude from export
 * @throws IOException
 *             on failure to read/write input/output
 */
public static void export(Descriptor desc, PrintStream outs, Collection<String> toExport, String[] excludes)
        throws IOException {
    SSTableReader reader = SSTableReader.open(desc);
    SSTableScanner scanner = reader.getDirectScanner();

    IPartitioner<?> partitioner = reader.partitioner;

    if (excludes != null)
        toExport.removeAll(Arrays.asList(excludes));

    int i = 0;

    // last key to compare order
    DecoratedKey lastKey = null;

    for (String key : toExport) {
        DecoratedKey decoratedKey = partitioner.decorateKey(ByteBufferUtil.hexToBytes(key));

        if (lastKey != null && lastKey.compareTo(decoratedKey) > 0)
            throw new IOException("Key out of order! " + lastKey + " > " + decoratedKey);

        lastKey = decoratedKey;

        scanner.seekTo(decoratedKey);

        if (!scanner.hasNext())
            continue;

        SSTableIdentityIterator row = (SSTableIdentityIterator) scanner.next();
        if (!row.getKey().equals(decoratedKey))
            continue;

        serializeRow(row, decoratedKey, outs);

        if (i != 0)
            outs.println(",");

        i++;
    }

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

    scanner.close();
}

From source file:com.googlecode.clearnlp.component.AbstractStatisticalComponent.java

/** Called by {@link AbstractStatisticalComponent#saveModels(ZipOutputStream)}}. */
protected void saveFeatureTemplates(ZipOutputStream zout, String entryName) throws Exception {
    int i, size = f_xmls.length;
    PrintStream fout;
    LOG.info("Saving feature templates.\n");

    for (i = 0; i < size; i++) {
        zout.putNextEntry(new ZipEntry(entryName + i));
        fout = UTOutput.createPrintBufferedStream(zout);
        IOUtils.copy(UTInput.toInputStream(f_xmls[i].toString()), fout);
        fout.flush();
        zout.closeEntry();//  w  w w.j a va  2 s  .c  o m
    }
}

From source file:com.protheos.graphstream.JSONSender.java

/**
 * Send JSONObject message to Gephi server
 * //w  w  w . j  ava 2s . c o  m
 * @param obj
 *            , the JSON message content
 * @param operation
 *            , the operation sending to the server, like "updateGraph",
 *            "getGraph"
 */
private void doSend(JSONObject obj, String operation) {

    try {
        URL url = new URL("http", host, port, "/" + workspace + "?operation=" + operation + "&format=JSON");

        URLConnection connection = url.openConnection();

        connection.setDoOutput(true);
        connection.connect();

        OutputStream outputStream = null;
        PrintStream out = null;
        try {
            outputStream = connection.getOutputStream();
            out = new PrintStream(outputStream, true);

            out.print(obj.toString() + EOL);
            out.flush();
            out.close();

            // send event message to the server and read the result from the
            // server
            InputStream inputStream = connection.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bf.readLine()) != null) {
                // if (debug) debug(line);
            }
            inputStream.close();
        } catch (UnknownServiceException e) {
            // protocol doesn't support output
            e.printStackTrace();
            return;
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.tamingtext.tagrecommender.TestStackOverflowTagger.java

/** Dump the tag metrics */
public void dumpTags(final PrintStream out, final OpenObjectIntHashMap<String> tagCounts,
        final OpenObjectIntHashMap<String> tagCorrect) {

    out.println("-- tag\ttotal\tcorrect\tpct-correct --");

    tagCounts.forEachPair(new ObjectIntProcedure<String>() {
        @Override/* w w w  .  j a v  a 2 s .  c  o m*/
        public boolean apply(String tag, int total) {
            int correct = tagCorrect.get(tag);

            out.println(
                    tag + "\t" + total + "\t" + correct + "\t" + nf.format(((correct * 100) / (float) total)));
            return true;
        }
    });

    out.println();
    out.flush();
}

From source file:org.bml.gis.data.DataStoreManager.java

/**
 * <p>//from   www. j a  v a2s  .com
 * Prints each type name in the {@link DataStore} this {@link DataStoreManager}
 * is managing in the format of one type name per line. For a complete description
 * see {@link DataStore#getTypeNames()}
 * </p>
 *
 * @param thePrintStream A {@link PrintStream} to write the type names to.
 * @throws IOException Per calls {@link DataStore#getTypeNames()} or {@link PrintStream#println(java.lang.String)}
 * @throws NullPointerException if the parameter thePrintStream is passed as null.
 * @throws IllegalStateException if !this.isOpen
 * @pre thePrintStream != null
 * @pre this.isOpen()
 */
public void printTypeNames(final PrintStream thePrintStream)
        throws NullPointerException, IllegalStateException, IOException {
    Preconditions.checkNotNull(typeNameSet, "Can not print Type Names to a null PrintStream.");
    Preconditions.checkState(open, "Can not print type names for a DataStore that has been closed.");
    try {
        thePrintStream.println(StringUtils.join(this.dataStore.getTypeNames(), "\n"));
        thePrintStream.flush();
    } catch (IOException ioe) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("IOException caught while printing type names.", ioe);
        }
        throw ioe;
    } catch (NullPointerException npe) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("NullPointerException caught while printing type names.", npe);
        }
    }
}

From source file:com.openkm.rest.endpoint.RepositoryService.java

@POST
@Path("/executeScript")
@Consumes(MediaType.MULTIPART_FORM_DATA)
// The "script" parameter comes in the POST request body (encoded as XML or JSON).
public ScriptExecutionResult executeScript(List<Attachment> atts) throws GenericException {
    ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    ByteArrayOutputStream baErr = new ByteArrayOutputStream();
    ScriptExecutionResult result = new ScriptExecutionResult();
    InputStream is = null;/* w ww.j  av  a 2s  .  c o  m*/

    try {
        if (PrincipalUtils.hasRole(Config.DEFAULT_ADMIN_ROLE)) {
            for (Attachment att : atts) {
                if ("script".equals(att.getContentDisposition().getParameter("name"))) {
                    is = att.getDataHandler().getInputStream();
                }
            }

            if (is != null) {
                String script = IOUtils.toString(is);
                PrintStream psOut = new PrintStream(baOut);
                PrintStream psErr = new PrintStream(baErr);
                Interpreter bsh = new Interpreter(null, psOut, psErr, false);

                try {
                    Object ret = bsh.eval(script);
                    result.setResult(String.valueOf(ret));
                } finally {
                    psOut.flush();
                    psErr.flush();
                }

                result.setStderr(baErr.toString());
                result.setStdout(baOut.toString());
                return result;
            } else {
                throw new Exception("Missing script parameter");
            }
        } else {
            throw new AccessDeniedException("Only admin users allowed");
        }
    } catch (Exception e) {
        throw new GenericException(e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(baErr);
        IOUtils.closeQuietly(baOut);
    }
}

From source file:org.ow2.proactive.scheduler.ext.matlab.worker.MatlabConnectionRImpl.java

public void launch() throws Exception {

    PrintStream out = null;

    try {//w  w  w  .  j a v  a  2  s . co  m
        out = new PrintStream(new BufferedOutputStream(new FileOutputStream(mainFuncFile)));
    } catch (FileNotFoundException e) {
        sendAck(false);
        throw e;
    }

    out.println(fullcommand);
    out.flush();
    out.close();

    synchronized (running) {
        process = createMatlabProcess("cd('" + this.workingDirectory + "');PAMain();");
        running = true;
    }

    // Logging thread creation & start
    outputThreadDefinition = new IOTools.LoggingThread(new FileInputStream(taskOutputFile), "[MATLAB]", taskOut,
            debug ? null : startPattern, null, new String[] { lcFailedPattern, outofmemoryPattern });
    outputThread = new Thread(outputThreadDefinition, "OUT MATLAB");
    outputThread.setDaemon(true);
    outputThread.start();

    File ackFile = new File(workingDirectory, "matlab.ack");
    File nackFile = new File(workingDirectory, "matlab.nack");
    File endFile = new File(workingDirectory, "matlab.end");

    try {

        int cpt = 0;
        while (!ackFile.exists() && !nackFile.exists() && (cpt < TIMEOUT_START)
                && !outputThreadDefinition.patternFound(lcFailedPattern)
                && !outputThreadDefinition.patternFound(outofmemoryPattern) && running) {
            try {
                // WARNING : on windows platform, matlab is initialized by a startup program which exits immediately, we cannot take decisions based on exit status.
                int exitValue = process.exitValue();
                if (exitValue != 0) {
                    sendAck(false);
                    // outputThreadDefinition.goon = false; unnecessary as matlab process exited
                    throw new MatlabInitException("Matlab process exited with code : " + exitValue);
                } else {
                    // matlab uses a startup program, unfortunately, we won't be able to receive logs from the standard process
                    isMatlabUsingAStarter = true;

                }
                // maybe the matlab launcher exited
            } catch (IllegalThreadStateException e) {
                // ok process still exists
            }
            Thread.sleep(10);
            cpt++;
        }

        if (nackFile.exists()) {
            sendAck(false);
            throw new UnsufficientLicencesException();
        }
        if (outputThreadDefinition.patternFound(lcFailedPattern)) {
            process.destroy();
            process = null;
            sendAck(false);
            throw new UnsufficientLicencesException();
        }
        if (outputThreadDefinition.patternFound(outofmemoryPattern)) {
            process.destroy();
            process = null;
            sendAck(false);
            throw new RuntimeException("Out of memory error in Matlab process");
        }
        if (cpt >= TIMEOUT_START) {
            process.destroy();
            process = null;
            sendAck(false);
            String output = FileUtils.readFileToString(this.taskOutputFile, "UTF-8");
            throw new MatlabInitException("Timeout occured while starting Matlab, with following output ("
                    + this.taskOutputFile + "):" + nl + output);
        }
        if (!running) {
            sendAck(false);
            throw new MatlabInitException("Task killed while initialization");
        }
        sendAck(true);

        int exitValue = process.waitFor();
        if (exitValue != 0) {
            String output = FileUtils.readFileToString(this.taskOutputFile, "UTF-8");
            throw new MatlabInitException("Matlab process exited with code : " + exitValue
                    + " after task started. With following output (" + this.taskOutputFile + "):" + nl
                    + output);
        }
        // on windows the matlab initialization process can terminate while Matlab still exists in the background
        // we use then the end file to synchronize
        while (!endFile.exists()) {
            Thread.sleep(10);
        }

        // now we wait that matlab exists completely and remove its grasp on the file
        boolean isDeleted = false;
        while (!isDeleted) {
            try {
                isDeleted = endFile.delete();
            } catch (Exception e) {

            }
            if (!isDeleted) {
                Thread.sleep(10);
            }
        }
    } finally {
        if (ackFile.exists()) {
            ackFile.delete();
        }
        if (nackFile.exists()) {
            nackFile.delete();
        }
        if (endFile.exists()) {
            endFile.delete();
        }
    }

}