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.mitre.secretsharing.cli.cmd.RootCommand.java

@Override
public void showHelp(PrintStream out) {
    super.showHelp(out);

    out.println();//from   w  ww  . ja v  a  2 s. c om

    Options cmds = new Options();
    for (Command c : Commands.subCommands()) {
        cmds.addOption(null, c.getName(), false, c.getDescription());
    }

    HelpFormatter h = new HelpFormatter();
    h.setSyntaxPrefix("");
    h.setLongOptPrefix("");
    h.setOptionComparator(new Comparator<Option>() {
        @Override
        public int compare(Option o1, Option o2) {
            Integer p1 = Commands.names().indexOf(o1.getLongOpt());
            Integer p2 = Commands.names().indexOf(o2.getLongOpt());
            return p1.compareTo(p2);
        }
    });
    h.printHelp(new PrintWriter(out, true), 80, "Valid Commands:", "", cmds, 12, 12, getActualHelpFooter());
    out.flush();
}

From source file:abfab3d.io.output.STSWriter.java

private void writeManifest(AttributeGrid grid, MaterialMaker[] makers, String[] finish, OutputStream os) {

    PrintStream ps = new PrintStream(os);

    printf(ps, "<?xml version=\"1.0\"?>\n");
    printf(ps, "<model>\n");
    printf(ps, "<parts>\n");
    int len = makers.length;

    for (int i = 0; i < len; i++) {
        String fname = "part" + i + ".stl";
        // TODO: Do we want to dedup materialURN's?
        printf(ps, "   <part file=\"%s\" material=\"%s\" />\n", fname, makers[i].getMaterialURN());
    }/*from   w  w w.  jav a  2 s.  c  o m*/
    printf(ps, "</parts>\n");
    printf(ps, "<finishes>\n");
    for (String f : finish) {
        printf(ps, "   <finish urn=\"%s\" />\n", f);
    }
    printf(ps, "</finishes>\n");
    printf(ps, "</model>\n");

    ps.flush();
}

From source file:com.ibm.jaql.JaqlBaseTestCase.java

private void execute(String inputFileName, String outputFilename, int type)
        throws FileNotFoundException, IOException {
    // Initialize input, output streams
    // TODO: switch jaql output to PrintWriter instead of PrintStream
    FileWriter writer = new FileWriter(outputFilename);
    FastPrintWriter oStr = new FastPrintWriter(writer);
    Reader reader = new InputStreamReader(new FileInputStream(inputFileName), "UTF-8");
    reader = new EchoedReader(reader, writer);
    //      TeeInputStream teeInput = new TeeInputStream(input, oStr);

    // Initialize parser
    JaqlLexer lexer = new JaqlLexer(reader);
    JaqlParser parser = new JaqlParser(lexer);
    Context context = new Context();

    // Begin to loop all sentences
    boolean parsing = false;
    int qNum = 0;
    while (true) {
        try {//from w ww.  j av a2  s. com
            parser.env.reset();
            parsing = true;
            Expr expr = parser.parse();
            parsing = false;
            System.err.println("\n\nParsing query at " + inputFileName + ":" + lexer.getLine());
            writer.flush();
            if (parser.done) {
                break;
            }
            if (expr == null) {
                continue;
            }

            VarTagger.tag(expr);
            captures.clear();
            System.err.println("\nDecompiled query:");
            FastPrintBuffer exprText = new FastPrintBuffer();
            expr.decompile(exprText, captures);
            exprText.writeTo(System.err);
            System.err.println("\n;\nEnd decompiled query\n");

            if (type == PLAIN) {
                System.err.println("\nrunning formatResult");
                formatResult(qNum, expr, context, oStr);
            } else if (type == DECOMPLIE) {
                System.err.println("\nrunning formatDecompileResult");
                formatDecompileResult(expr, context, oStr);
            } else if (type == REWRITE) {
                System.err.println("\nrunning formatRewriteResult");
                formatRewriteResult(expr, context, oStr);
            }
            oStr.flush();

            context.reset();
            qNum++;
        } catch (Exception ex) {
            LOG.error(ex);
            ex.printStackTrace(System.err);
            formatFailure(qNum, oStr);
            oStr.flush();
            if (parsing) {
                BitSet bs = new BitSet();
                bs.add(JaqlParser.EOF);
                bs.add(JaqlParser.SEMI);
                try {
                    parser.consumeUntil(bs);
                } catch (TokenStreamException tse) {
                    queryFailure(tse);
                }
            }
        }
    }

    if (this.runRewriteResult & this.runCountResult && exprTypeCounter != null) {
        PrintStream cStr = new PrintStream(new FileOutputStream(this.m_countName));
        // Print out all concerned expression occurrences         
        java.util.Iterator<String> i = exprTypeCounter.keySet().iterator();
        while (i.hasNext()) {
            String tem = i.next();
            cStr.println(tem + "\t" + exprTypeCounter.get(tem));
        }
        cStr.flush();
        cStr.close();
        // clear type counter
        exprTypeCounter.clear();
    }

    // Close all streams
    context.reset();
    oStr.close();
    reader.close();

}

From source file:org.wso2.msf4j.internal.router.HttpServerTest.java

@Test(timeout = 5000)
public void testConnectionClose() throws Exception {
    URL url = baseURI.resolve("/test/v1/connectionClose").toURL();

    // Fire http request using raw socket so that we can verify the connection get closed by the server
    // after the response.
    Socket socket = createRawSocket(url);
    try {//from w  w  w. j a  va  2 s.c  o m
        PrintStream printer = new PrintStream(socket.getOutputStream(), false, "UTF-8");
        printer.printf("GET %s HTTP/1.1\r\n", url.getPath());
        printer.printf("Host: %s:%d\r\n", url.getHost(), url.getPort());
        printer.print("\r\n");
        printer.flush();

        // Just read everything from the response. Since the server will close the connection, the read loop should
        // end with an EOF. Otherwise there will be timeout of this test case
        String response = CharStreams.toString(new InputStreamReader(socket.getInputStream(), Charsets.UTF_8));
        Assert.assertTrue(response.startsWith("HTTP/1.1 200 OK"));
    } finally {
        socket.close();
    }
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * // w  ww . jav a 2  s.c  o  m
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();
        hout.println(API_KEY);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}

From source file:org.intermine.webservice.server.WebService.java

private void logError(Throwable t, String msg, int code) {

    // Stack traces for all!
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(b);
    t.printStackTrace(ps);//from w  w w. ja  v a  2 s  .c  o  m
    ps.flush();

    if (code == Output.SC_INTERNAL_SERVER_ERROR) {
        LOG.error("Service failed by internal error. Request parameters: \n" + requestParametersToString()
                + b.toString());
    } else {
        LOG.debug("Service didn't succeed. It's not an internal error. " + "Reason: "
                + getErrorDescription(msg, code) + "\n" + b.toString());
    }
}

From source file:bi.meteorite.util.ITestBootstrap.java

protected String executeCommand(final String command, final Long timeout, final Boolean silent) {
    String response;/*ww w . ja va 2s  . c o m*/
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final PrintStream printStream = new PrintStream(byteArrayOutputStream);
    final CommandProcessor commandProcessor = getOsgiService(CommandProcessor.class);
    final CommandSession commandSession = commandProcessor.createSession(System.in, printStream, System.err);
    FutureTask<String> commandFuture = new FutureTask<String>(new Callable<String>() {
        public String call() {
            try {
                if (!silent) {
                    System.err.println(command);
                }
                commandSession.execute(command);
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
            printStream.flush();
            return byteArrayOutputStream.toString();
        }
    });

    try {
        executor.submit(commandFuture);
        response = commandFuture.get(timeout, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        response = "SHELL COMMAND TIMED OUT: ";
    }

    return response;
}

From source file:ai.grakn.test.graql.shell.GraqlShellIT.java

private String testShell(String input, ByteArrayOutputStream berr, String... args) throws Exception {
    args = specifyUniqueKeyspace(args);//w  w  w  .jav  a  2s  . c o  m

    InputStream in = new ByteArrayInputStream(input.getBytes());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    PrintStream out = new PrintStream(new TeeOutputStream(bout, trueOut));

    // Intercept stderr, but make sure it is still printed using the TeeOutputStream
    PrintStream err = new PrintStream(new TeeOutputStream(berr, trueErr));

    try {
        System.out.flush();
        System.err.flush();
        System.setIn(in);
        System.setOut(out);
        System.setErr(err);

        GraqlShell.runShell(args, expectedVersion, historyFile);
    } catch (Exception e) {
        System.setErr(trueErr);
        e.printStackTrace();
        err.flush();
        fail(berr.toString());
    } finally {
        resetIO();
    }

    out.flush();
    err.flush();

    return bout.toString();
}

From source file:com.buaa.cfs.utils.ReflectionUtils.java

/**
 * Print all of the thread's information and stack traces.
 *
 * @param stream the stream to/*from   w  w w  . ja  va  2s . c om*/
 * @param title  a string title for the stack trace
 */
public synchronized static void printThreadInfo(PrintStream stream, String title) {
    final int STACK_DEPTH = 20;
    boolean contention = threadBean.isThreadContentionMonitoringEnabled();
    long[] threadIds = threadBean.getAllThreadIds();
    stream.println("Process Thread Dump: " + title);
    stream.println(threadIds.length + " active threads");
    for (long tid : threadIds) {
        ThreadInfo info = threadBean.getThreadInfo(tid, STACK_DEPTH);
        if (info == null) {
            stream.println("  Inactive");
            continue;
        }
        stream.println("Thread " + getTaskName(info.getThreadId(), info.getThreadName()) + ":");
        Thread.State state = info.getThreadState();
        stream.println("  State: " + state);
        stream.println("  Blocked count: " + info.getBlockedCount());
        stream.println("  Waited count: " + info.getWaitedCount());
        if (contention) {
            stream.println("  Blocked time: " + info.getBlockedTime());
            stream.println("  Waited time: " + info.getWaitedTime());
        }
        if (state == Thread.State.WAITING) {
            stream.println("  Waiting on " + info.getLockName());
        } else if (state == Thread.State.BLOCKED) {
            stream.println("  Blocked on " + info.getLockName());
            stream.println("  Blocked by " + getTaskName(info.getLockOwnerId(), info.getLockOwnerName()));
        }
        stream.println("  Stack:");
        for (StackTraceElement frame : info.getStackTrace()) {
            stream.println("    " + frame.toString());
        }
    }
    stream.flush();
}

From source file:it.greenvulcano.jmx.impl.KarafJMXEntryPoint.java

/**
 * Initializes the modeler.//from  w w w .  j a  v a 2 s  .c  o m
 */
private void initModeler(Node conf) throws Exception {
    // The modeler requires an InputStream in order to configure itself,
    // so we need to serialize the configuration.

    DOMWriter writer = new DOMWriter();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream print = new PrintStream(out);

    // Read the DTD and put it in the out stream, in order to avoid the
    // exceptions
    // raised by the XML parser.
    //
    InputStream istream = getClass().getClassLoader().getResourceAsStream(MODELER_DTD);
    if (istream != null) {
        byte[] buf = new byte[2048];
        int l = 0;
        while ((l = istream.read(buf)) != -1) {
            print.write(buf, 0, l);
        }
        print.flush();
        istream.close();
    } else {
        LOG.warn(MODELER_DTD + " NOT FOUND. PLEASE, IGNORE FOLLOWING EXCEPTIONS.");
    }

    writer.write(conf, print);
    print.flush();
    print.close();

    // Prepares the input stream and initializes the modeler's Registry
    //
    ByteArrayInputStream stream = new ByteArrayInputStream(out.toByteArray());
    registry.loadDescriptors(stream);
}