Example usage for java.io OutputStream flush

List of usage examples for java.io OutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:org.alfresco.webservice.util.ContentUtils.java

/**
 * Helper method to copy from one stream to another
 * //w w w.j  a v a 2s . c o m
 * @param in
 * @param out
 * @return
 * @throws IOException
 */
public static int copy(InputStream in, OutputStream out) throws IOException {
    try {
        int byteCount = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        return byteCount;
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
            // Could not close input stream
        }
        try {
            out.close();
        } catch (IOException ex) {
            // Could not close output stream
        }
    }
}

From source file:Main.java

public static void writeWString(OutputStream out, String s, String characterSet, int fixedLen)
        throws IOException {
    byte[] bytes = s.getBytes(characterSet);
    writeShort(out, bytes.length);/* ww  w.  jav a  2  s  .  c  o m*/
    fixedLen -= 2;

    if (fixedLen <= 0)
        return;

    if (fixedLen <= bytes.length) {
        out.write(bytes, 0, fixedLen);
    } else {
        out.write(bytes);
        byte[] fillBytes = new byte[fixedLen - bytes.length];
        Arrays.fill(fillBytes, (byte) 0);
        out.write(fillBytes);
    }

    out.flush();
}

From source file:com.yiji.openapi.sdk.util.Servlets.java

public static void writeResponse(HttpServletResponse response, String data) {
    OutputStream output = null;
    InputStream input = null;//from w w w  . j  a  v a 2  s.c  o m
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        output = response.getOutputStream();
        input = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8")));
        IOUtils.copy(input, output);
        output.flush();
    } catch (Exception e) {
        throw new RuntimeException("?(flushResponse):" + e.getMessage());
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
    }
}

From source file:SimpleProxyServer.java

/**
 * runs a single-threaded proxy server on
 * the specified local port. It never returns.
 */// ww  w. ja v  a 2 s . c  o m
public static void runServer(String host, int remoteport, int localport) throws IOException {
    // Create a ServerSocket to listen for connections with
    ServerSocket ss = new ServerSocket(localport);

    final byte[] request = new byte[1024];
    byte[] reply = new byte[4096];

    while (true) {
        Socket client = null, server = null;
        try {
            // Wait for a connection on the local port
            client = ss.accept();

            final InputStream streamFromClient = client.getInputStream();
            final OutputStream streamToClient = client.getOutputStream();

            // Make a connection to the real server.
            // If we cannot connect to the server, send an error to the
            // client, disconnect, and continue waiting for connections.
            try {
                server = new Socket(host, remoteport);
            } catch (IOException e) {
                PrintWriter out = new PrintWriter(streamToClient);
                out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n");
                out.flush();
                client.close();
                continue;
            }

            // Get server streams.
            final InputStream streamFromServer = server.getInputStream();
            final OutputStream streamToServer = server.getOutputStream();

            // a thread to read the client's requests and pass them
            // to the server. A separate thread for asynchronous.
            Thread t = new Thread() {
                public void run() {
                    int bytesRead;
                    try {
                        while ((bytesRead = streamFromClient.read(request)) != -1) {
                            streamToServer.write(request, 0, bytesRead);
                            streamToServer.flush();
                        }
                    } catch (IOException e) {
                    }

                    // the client closed the connection to us, so close our
                    // connection to the server.
                    try {
                        streamToServer.close();
                    } catch (IOException e) {
                    }
                }
            };

            // Start the client-to-server request thread running
            t.start();

            // Read the server's responses
            // and pass them back to the client.
            int bytesRead;
            try {
                while ((bytesRead = streamFromServer.read(reply)) != -1) {
                    streamToClient.write(reply, 0, bytesRead);
                    streamToClient.flush();
                }
            } catch (IOException e) {
            }

            // The server closed its connection to us, so we close our
            // connection to our client.
            streamToClient.close();
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            try {
                if (server != null)
                    server.close();
                if (client != null)
                    client.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:es.deustotech.piramide.utils.tts.TextToSpeechWeb.java

private static void downloadFile(HttpResponse response, OutputStream os) throws IOException {
    final InputStream is = response.getEntity().getContent();
    long size = response.getEntity().getContentLength();
    final BufferedInputStream bis = new BufferedInputStream(is);
    final byte[] buffer = new byte[1024 * 1024]; // 1 MB
    long position = 0;
    while (position < size) {
        final int read = bis.read(buffer, 0, buffer.length);
        if (read <= 0) {
            break;
        }//from   w w  w  . j  av a  2s . c o  m
        os.write(buffer, 0, read);
        os.flush();

        position += read;
    }
    is.close();
}

From source file:de.unirostock.sems.cbarchive.web.Tools.java

/**
 * writes a input stream entirely into a newly created temp file.
 * Closes all streams afterwards/*from   w w  w .java2 s.  c o  m*/
 *
 * @param tempFileName the temp file name
 * @param input the input
 * @return Path to temp file
 * @throws IOException the IO exception
 */
public static Path writeStreamToTempFile(String tempFileName, InputStream input) throws IOException {

    // copy the stream to a temp file
    Path temp = Files.createTempFile(Fields.TEMP_FILE_PREFIX, tempFileName);
    // write file to disk
    OutputStream output = new FileOutputStream(temp.toFile());
    IOUtils.copy(input, output);

    output.flush();
    output.close();
    input.close();

    return temp;
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call to get a new client credentials token, required for creating new account
 * //  w  w  w. j  a v a  2s .  com
 * @param url
 * @param clientCredentialsToken
 * @param httpMethod
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 * @throws JSONException
 */
public static String getClientCredentialsResponse(Context context, String url, String clientCredentialsToken,
        String httpMethod, Bundle httpBody)
        throws MalformedURLException, IOException, ProtocolException, JSONException {
    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
        // If we have refreshed max number of times, we will not do so again
        if (refreshed == 1) {
            refreshLimitReached = true;
        }

        HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url)));
        trustAllHosts();
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        connection.setRequestMethod(httpMethod);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        String authValue = "Bearer " + clientCredentialsToken;
        connection.setRequestProperty("Authorization", authValue);
        connection.connect();

        if (!httpBody.isEmpty()) {
            OutputStream os = new BufferedOutputStream(connection.getOutputStream());
            os.write(encodePostBody(httpBody).getBytes());
            os.flush();
        }

        try {
            LoggingUtils.d(LOG_TAG, connection.toString());
            response = readFromStream(connection.getInputStream());
        } catch (FileNotFoundException e) {
            response = readFromStream(connection.getErrorStream());
        } finally {
            connection.disconnect();
        }

        // Allow for calls to return nothing
        if (response.length() == 0) {
            return "";
        }

        // Check for JSON parsing errors (will throw JSONException is can't be parsed)
        JSONObject object = new JSONObject(response);

        // If no error, return response
        if (!object.has("error")) {
            return response;
        }
        // If there is a refresh token error, refresh the token
        else if (object.getString("error").equals("invalid_token")) {
            if (refreshLimitReached) {
                // Give up
                return response;
            } else {
                // Refresh the token
                WebServiceAuthProvider.refreshAccessToken(context);
                refreshed++;
            }
        }
    } // while(!refreshLimitReached)

    return response;
}

From source file:weka.core.ChartUtils.java

/**
 * Write a BufferedImage to a destination output stream as a png
 * /*from  w w  w.ja  v a  2s.  c o m*/
 * @param image the image to write
 * @param dest the destination output stream
 * @throws IOException if a problem occurs
 */
public static void writeImage(BufferedImage image, OutputStream dest) throws IOException {
    ImageIO.write(image, "png", dest);

    dest.flush();
    dest.close();
}

From source file:io.druid.java.util.common.CompressionUtils.java

/**
 * gunzip from the source stream to the destination stream.
 *
 * @param in  The input stream which is to be decompressed. This stream is closed.
 * @param out The output stream to write to. This stream is closed
 *
 * @return The number of bytes written to the output stream.
 *
 * @throws IOException//w w w.  j av  a  2 s. c o  m
 */
public static long gunzip(InputStream in, OutputStream out) throws IOException {
    try (GZIPInputStream gzipInputStream = gzipInputStream(in)) {
        final long result = ByteStreams.copy(gzipInputStream, out);
        out.flush();
        return result;
    } finally {
        out.close();
    }
}

From source file:Main.java

/**
 * Write the entire contents of the supplied string to the given stream. This method always flushes and closes the stream when
 * finished.//  ww  w  .java  2s . c om
 * 
 * @param content the content to write to the stream; may be null
 * @param stream the stream to which the content is to be written
 * @throws IOException
 * @throws IllegalArgumentException if the stream is null
 */
public static void write(String content, OutputStream stream) throws IOException {
    boolean error = false;
    try {
        if (content != null) {
            byte[] bytes = content.getBytes();
            stream.write(bytes, 0, bytes.length);
        }
    } catch (IOException e) {
        error = true; // this error should be thrown, even if there is an error flushing/closing stream
        throw e;
    } catch (RuntimeException e) {
        error = true; // this error should be thrown, even if there is an error flushing/closing stream
        throw e;
    } finally {
        try {
            stream.flush();
        } catch (IOException e) {
            if (!error)
                throw e;
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                if (!error)
                    throw e;
            }
        }
    }
}