Example usage for java.io PrintWriter flush

List of usage examples for java.io PrintWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:mobisocial.musubi.ui.util.FeedHTML.java

public static void writeHeader(FileOutputStream fo, FeedManager feedManager, MFeed feed) {
    PrintWriter w = new PrintWriter(fo);
    w.print("<html>");
    w.print("<head>");
    w.print("<title>");
    w.print(StringEscapeUtils.escapeHtml4(UiUtil.getFeedNameFromMembersList(feedManager, feed)));
    w.print("</title>");
    w.print("</head>");
    w.print("<body>");
    w.print("<h1>");
    w.print(StringEscapeUtils.escapeHtml4(UiUtil.getFeedNameFromMembersList(feedManager, feed)));
    w.print("</h1>");
    w.flush();
}

From source file:Main.java

/**
 * Save the contents of a table to a TSV file
 * Note:  uses toString() on the header cells as well as the data cells.  If you've got funny columns,
 * expect funny behavior/*  w ww .j  a  va  2  s  .  c o m*/
 * @param table
 * @param outFile
 * @throws IOException
 */
public static void SaveTableAsTSV(JTable table, File outFile) throws IOException {
    PrintWriter outPW = new PrintWriter(outFile);

    TableModel tableModel = table.getModel();
    TableColumnModel columnModel = table.getColumnModel();

    StringBuffer headerLineBuf = new StringBuffer();
    for (int i = 0; i < columnModel.getColumnCount(); i++) {
        if (i > 0)
            headerLineBuf.append("\t");
        headerLineBuf.append(columnModel.getColumn(i).getHeaderValue().toString());
    }
    outPW.println(headerLineBuf.toString());
    outPW.flush();
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        StringBuffer lineBuf = new StringBuffer();
        for (int j = 0; j < tableModel.getColumnCount(); j++) {
            if (j > 0)
                lineBuf.append("\t");
            lineBuf.append(tableModel.getValueAt(i, j).toString());
        }
        outPW.println(lineBuf.toString());
        outPW.flush();
    }
    outPW.close();
}

From source file:com.zimbra.common.localconfig.LocalConfigUpgrade.java

static void usage(String error) {
    if (error != null)
        System.out.println("Error: " + error);
    Options opts = getAllOptions();//from  www. ja v  a2  s.c o  m
    PrintWriter pw = new PrintWriter(System.out, true);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp(pw, formatter.getWidth(), getCommandUsage(), null, opts, formatter.getLeftPadding(),
            formatter.getDescPadding(), null);
    pw.flush();
    if (error != null) {
        System.exit(1);
    } else {
        System.exit(0);
    }
}

From source file:Main.java

/**
 * Print a string representation of the current stack state of all the active threads.
 *//*from ww  w.  ja  v  a2  s  . co m*/
public static void printStackTraces(PrintWriter writer) {
    Map<Thread, StackTraceElement[]> map;
    try {
        map = Thread.getAllStackTraces();
    } catch (Throwable e) {
        writer.println("Failed to obtain stack traces: " + e);
        return;
    }
    if (map == null) {
        writer.println("No stack traces available");
        return;
    }
    for (Entry<Thread, StackTraceElement[]> entry : map.entrySet())
        printStackTrace(writer, entry.getKey(), entry.getValue());
    writer.flush();
}

From source file:eu.pawelsz.apache.beam.coders.TupleCoderGenerator.java

private static void createTupleClasses(File root) throws FileNotFoundException {
    File dir = getPackage(root, PACKAGE);

    PrintWriter writer = null;
    for (int i = FIRST; i <= LAST; i++) {
        //    for (int i = 4; i <= 4; i++) {
        File tupleFile = new File(dir, "Tuple" + i + "Coder.java");
        writer = new PrintWriter(tupleFile);
        writeTupleCoderClass(writer, i);
        writer.flush();
        writer.close();//from   w  w w .  j ava 2  s  .co m
    }

    File f = new File(dir, "RegisterTupleCoders.java");
    writer = new PrintWriter(f);
    writeRegistration(writer);
    writer.flush();
    writer.close();
}

From source file:eu.amidst.huginlink.examples.demos.ParallelTANDemo.java

/**
 * Writes "help" to the provided OutputStream.
 * @param options an Options object/*from   www . ja v a2  s .  co m*/
 * @param printedRowWidth an integer
 * @param header a String
 * @param footer a String
 * @param spacesBeforeOption an integer
 * @param spacesBeforeOptionDescription an integer
 * @param displayUsage a boolean
 * @param out an OutputStream object
 */
public static void printHelp(final Options options, final int printedRowWidth, final String header,
        final String footer, final int spacesBeforeOption, final int spacesBeforeOptionDescription,
        final boolean displayUsage, final OutputStream out) {
    final String commandLineSyntax = "run.sh eu.amidst.examples.ParallelTANDemo";
    final PrintWriter writer = new PrintWriter(out);
    final HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.printHelp(writer, printedRowWidth, commandLineSyntax, header, options, spacesBeforeOption,
            spacesBeforeOptionDescription, footer, displayUsage);
    writer.flush();
}

From source file:com.iana.boesc.utility.BOESCUtil.java

public static String exceptionToString(Exception e) {
    StringWriter writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    e.printStackTrace(printWriter);/*from   w ww .  ja va2 s  .co  m*/
    printWriter.flush();
    String stackTrace = writer.toString();
    return stackTrace;
}

From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java

/**
 * Tries to upload the given file to the given HTTP server (via POST
 * method)./*from ww  w . ja  v  a2s  .co  m*/
 * 
 * @param file
 *            the file to upload
 * @param url
 *            the URL of the server, that is supposed to handle the file
 * @param monitor
 *            a monitor to report progress to
 * @throws IOException
 *             if an I/O error occurs
 * 
 */

public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException {

    final String CRLF = "\r\n";
    final String doubleDash = "--";
    final String boundary = generateBoundary();

    HttpURLConnection connection = null;
    OutputStream urlConnectionOut = null;
    FileInputStream fileIn = null;

    if (monitor == null)
        monitor = new NullProgressMonitor();

    int contentLength = (int) file.length();

    if (contentLength == 0) {
        log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist");
        return;
    }

    monitor.beginTask("Uploading file " + file.getName(), contentLength);

    try {
        URL connectionURL = new URL(url);

        if (!"http".equals(connectionURL.getProtocol()))
            throw new IOException("only HTTP protocol is supported");

        connection = (HttpURLConnection) connectionURL.openConnection();
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setReadTimeout(TIMEOUT);
        connection.setConnectTimeout(TIMEOUT);

        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName()
                + "\"; filename=\"" + file.getName() + "\"" + CRLF;

        String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF;

        String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF;

        contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length()
                + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length();

        connection.setFixedLengthStreamingMode(contentLength);

        connection.connect();

        urlConnectionOut = connection.getOutputStream();

        PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true);

        writer.append(doubleDash).append(boundary).append(CRLF);
        writer.append(contentDispositionLine);
        writer.append(contentTypeLine);
        writer.append(contentTransferEncoding);
        writer.append(CRLF);
        writer.flush();

        fileIn = new FileInputStream(file);
        byte[] buffer = new byte[8192];

        for (int read = 0; (read = fileIn.read(buffer)) > 0;) {
            if (monitor.isCanceled())
                return;

            urlConnectionOut.write(buffer, 0, read);
            monitor.worked(read);
        }

        urlConnectionOut.flush();

        writer.append(CRLF);
        writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost());
            return;
        }

        throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " ["
                + connection.getResponseMessage() + "]");
    } finally {
        IOUtils.closeQuietly(fileIn);
        IOUtils.closeQuietly(urlConnectionOut);

        if (connection != null)
            connection.disconnect();

        monitor.done();
    }
}

From source file:ai.grakn.migration.base.MigrationCLI.java

private static void printHelpMessage(MigrationOptions options) {
    HelpFormatter helpFormatter = new HelpFormatter();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(System.out, Charset.defaultCharset());
    PrintWriter printWriter = new PrintWriter(new BufferedWriter(outputStreamWriter));
    int width = helpFormatter.getWidth();
    int leftPadding = helpFormatter.getLeftPadding();
    int descPadding = helpFormatter.getDescPadding();
    helpFormatter.printHelp(printWriter, width, "migration.sh", null, options.getOptions(), leftPadding,
            descPadding, null);//  w  ww  .j  av  a  2  s.c o  m
    printWriter.flush();
}

From source file:com.example.admin.processingboilerplate.JsonIO.java

public static JSONObject pushJson(String requestURL, String jsonDataName, JSONObject json) {
    try {/*from   w ww . jav a 2s  .c  o  m*/
        String boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        //HttpURLConnection con = (HttpURLConnection) url.openConnection();
        URLConnection uc = (url).openConnection();
        HttpURLConnection con = requestURL.startsWith("https") ? (HttpsURLConnection) uc
                : (HttpURLConnection) uc;
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        con.setRequestProperty("User-Agent", USER_AGENT);
        OutputStream outputStream = con.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"" + "data" + "\"").append(CRLF);
        writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
        writer.append(CRLF);
        writer.append(json.toString()).append(CRLF);
        writer.flush();

        writer.append(CRLF).flush();
        writer.append("--" + boundary + "--").append(CRLF);
        writer.close();
        int status = con.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            StringBuilder sb = load(con);
            try {
                json = new JSONObject(sb.toString());
                return json;
            } catch (JSONException e) {
                Log.e("loadJson", e.getMessage(), e);
                e.printStackTrace();
                return new JSONObject();
            }
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new JSONObject();
}