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:edu.unc.lib.dl.ui.util.FileIOUtil.java

public static void stream(OutputStream outStream, HttpMethodBase method) throws IOException {
    try (InputStream in = method.getResponseBodyAsStream();
            BufferedInputStream reader = new BufferedInputStream(in)) {
        byte[] buffer = new byte[4096];
        int count = 0;
        int length = 0;
        while ((length = reader.read(buffer)) >= 0) {
            try {
                outStream.write(buffer, 0, length);
                if (count++ % 5 == 0) {
                    outStream.flush();
                }// w  ww. j a  v  a2 s  . c  om
            } catch (IOException e) {
                // Differentiate between socket being closed when writing vs
                // reading
                throw new ClientAbortException(e);
            }
        }
        try {
            outStream.flush();
        } catch (IOException e) {
            throw new ClientAbortException(e);
        }
    }
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

private static Response invoke(UrlBuilder url, String method, String contentType,
        Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset,
        BigInteger length, Map<String, String> params) {
    try {/*ww  w.ja va 2s.  c  o  m*/
        // Log.d("URL", url.toString());

        // connect
        HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null || forceOutput);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT);

        // set content type
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        // set other headers
        if (httpHeaders != null) {
            for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                if (header.getValue() != null) {
                    for (String value : header.getValue()) {
                        conn.addRequestProperty(header.getKey(), value);
                    }
                }
            }
        }

        // range
        BigInteger tmpOffset = offset;
        if ((tmpOffset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((tmpOffset == null) || (tmpOffset.signum() == -1)) {
                tmpOffset = BigInteger.ZERO;
            }

            sb.append(tmpOffset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        // add url form parameters
        if (params != null) {
            DataOutputStream ostream = null;
            OutputStream os = null;
            try {
                os = conn.getOutputStream();
                ostream = new DataOutputStream(os);

                Set<String> parameters = params.keySet();
                StringBuffer buf = new StringBuffer();

                int paramCount = 0;
                for (String it : parameters) {
                    String parameterName = it;
                    String parameterValue = (String) params.get(parameterName);

                    if (parameterValue != null) {
                        parameterValue = URLEncoder.encode(parameterValue, "UTF-8");
                        if (paramCount > 0) {
                            buf.append("&");
                        }
                        buf.append(parameterName);
                        buf.append("=");
                        buf.append(parameterValue);
                        ++paramCount;
                    }
                }
                ostream.writeBytes(buf.toString());
            } finally {
                if (ostream != null) {
                    ostream.flush();
                    ostream.close();
                }
                IOUtils.closeStream(os);
            }
        }

        // send data

        if (writer != null) {
            // conn.setChunkedStreamingMode((64 * 1024) - 1);
            OutputStream connOut = null;
            connOut = conn.getOutputStream();
            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:org.kuali.mobility.push.service.send.AndroidSendService.java

/**
 * Writes the data over the connection/*from  w  w  w  .j  a v  a 2s.c  o  m*/
 * @param conn
 * @param data
 * @return
 * @throws java.net.MalformedURLException
 * @throws java.io.IOException
 */
private static String sendToGCM(HttpsURLConnection conn, String data) throws IOException {
    byte[] dataBytes = data.getBytes();
    conn.setFixedLengthStreamingMode(dataBytes.length);
    OutputStream out = null;
    String response = null;
    try {
        out = conn.getOutputStream();
        out.write(dataBytes);
        out.flush();
        response = readResponse(conn);

    } catch (IOException e) {
        LOG.warn("Exception while trying to write data to GCM", e);
    } finally {
        IOUtils.closeQuietly(out);
        conn.disconnect();
    }
    return response;
}

From source file:Main.java

public static void writeCString(OutputStream out, String s, String characterSet, int fixedLen)
        throws IOException {
    byte[] bytes = s.getBytes(characterSet);
    out.write(bytes.length);//from  w  ww  . j av  a  2s .c o m
    fixedLen -= 1;

    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:Main.java

/**
 * Save PNG image with background color//w  ww.  java 2 s . co  m
 * @param strFileName Save file path
 * @param bitmap Input bitmap
 * @param nBackgroundColor background color
 * @return whether success or not
 */
public static boolean saveBitmapPNGWithBackgroundColor(String strFileName, Bitmap bitmap,
        int nBackgroundColor) {
    boolean bSuccess1 = false;
    boolean bSuccess2 = false;
    boolean bSuccess3;
    File saveFile = new File(strFileName);

    if (saveFile.exists()) {
        if (!saveFile.delete())
            return false;
    }

    int nA = (nBackgroundColor >> 24) & 0xff;

    // If Background color alpha is 0, Background color substitutes as white
    if (nA == 0)
        nBackgroundColor = 0xFFFFFFFF;

    Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(newBitmap);
    canvas.drawColor(nBackgroundColor);
    canvas.drawBitmap(bitmap, rect, rect, new Paint());

    OutputStream out = null;

    try {
        bSuccess1 = saveFile.createNewFile();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        out = new FileOutputStream(saveFile);
        bSuccess2 = newBitmap.compress(CompressFormat.PNG, 100, out);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (out != null) {
            out.flush();
            out.close();
            bSuccess3 = true;
        } else
            bSuccess3 = false;

    } catch (IOException e) {
        e.printStackTrace();
        bSuccess3 = false;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    return (bSuccess1 && bSuccess2 && bSuccess3);
}

From source file:Main.java

public static void writeWString(OutputStream out, String s, int fixedLen) throws IOException {
    byte[] bytes = s.getBytes();
    writeShort(out, bytes.length);// w w  w . ja  v a 2  s  .  co 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:io.lavagna.web.support.ResourceController.java

private static void output(String file, ServletContext context, OutputStream os, BeforeAfter ba)
        throws IOException {
    ba.before(file, context, os);//from w ww  .j a va2 s  .c o  m
    try (InputStream is = context.getResourceAsStream(file)) {
        StreamUtils.copy(is, os);
    }
    ba.after(file, context, os);
    os.flush();
}

From source file:org.crazydog.util.spring.StreamUtils.java

/**
 * Copy the contents of the given InputStream to the given OutputStream.
 * Leaves both streams open when done./*from   www  .  j  a v a  2s .  c  om*/
 * @param in the InputStream to copy from
 * @param out the OutputStream to copy to
 * @return the number of bytes copied
 * @throws IOException in case of I/O errors
 */
public static int copy(InputStream in, OutputStream out) throws IOException {
    org.springframework.util.Assert.notNull(in, "No InputStream specified");
    org.springframework.util.Assert.notNull(out, "No OutputStream specified");
    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;
}

From source file:com.gmobi.poponews.util.HttpHelper.java

public static Response upload(String url, InputStream is) {
    Response response = new Response();
    String boundary = Long.toHexString(System.currentTimeMillis());
    HttpURLConnection connection = null;
    try {//from   www  .  j  av a 2 s. co  m
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        byte[] st = ("--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"data\"\r\n"
                + "Content-Type: application/octet-stream; charset=UTF-8\r\n"
                + "Content-Transfer-Encoding: binary\r\n\r\n").getBytes();
        byte[] en = ("\r\n--" + boundary + "--\r\n").getBytes();
        connection.setRequestProperty("Content-Length", String.valueOf(st.length + en.length + is.available()));
        OutputStream os = connection.getOutputStream();
        os.write(st);
        FileHelper.copy(is, os);
        os.write(en);
        os.flush();
        os.close();
        response.setStatusCode(connection.getResponseCode());
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
    }

    return response;
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?/*from   w  w w  .  j  ava 2s.  c om*/
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}