Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {
    AQUtility.debug("multipart", url);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(NET_TIMEOUT * 4);
    conn.setDoInput(true);//from w  w w  .  j  av a  2  s . c  om
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);
    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }
    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, conn);
    }
    dos = new DataOutputStream(conn.getOutputStream());
    Object o = null;
    if (progress != null) {
        o = progress.get();
    }
    Progress p = null;
    if (o != null) {
        p = new Progress(o);
    }
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        writeObject(dos, entry.getKey(), entry.getValue(), p);
    }
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();
    conn.connect();
    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();
    byte[] data = null;
    String encoding = conn.getContentEncoding();
    String error = null;
    if ((code < 200) || (code >= 300)) {
        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");
        AQUtility.debug("error", error);
    } else {
        data = toData(encoding, conn.getInputStream());
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);
}

From source file:au.org.ala.spatial.util.RecordsSmall.java

private void makeSmallFile(String filename) throws Exception {
    FileWriter outputSpecies = new FileWriter(filename + "records.csv.small.species");
    DataOutputStream outputPoints = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.points")));
    DataOutputStream outputPointsToSpecies = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsToSpecies")));

    Map<String, Integer> lsidMap = new HashMap<String, Integer>(200000);
    byte start = 0;
    BufferedReader br = new BufferedReader(new FileReader(filename + "records.csv"));
    int[] header = new int[3];
    int row = start;
    int currentCount = 0;
    String[] line = new String[3];

    String rawline;/*from  w  w w.j  ava2 s .c o m*/
    while ((rawline = br.readLine()) != null) {
        currentCount++;
        int p1 = rawline.indexOf(44);
        int p2 = rawline.indexOf(44, p1 + 1);
        if (p1 >= 0 && p2 >= 0) {
            line[0] = rawline.substring(0, p1);
            line[1] = rawline.substring(p1 + 1, p2);
            line[2] = rawline.substring(p2 + 1, rawline.length());
            if (currentCount % 100000 == 0) {
                System.out.print("\rreading row: " + currentCount);
            }

            if (row == 0) {
                for (int e = 0; e < line.length; e++) {
                    if (line[e].equals("names_and_lsid")) {
                        header[0] = e;
                    }

                    if (line[e].equals("longitude")) {
                        header[1] = e;
                    }

                    if (line[e].equals("latitude")) {
                        header[2] = e;
                    }
                }

                logger.debug("header: " + header[0] + "," + header[1] + "," + header[2]);
            } else if (line.length >= 3) {
                try {
                    double lat = Double.parseDouble(line[header[2]]);
                    double lng = Double.parseDouble(line[header[1]]);

                    String species = line[header[0]];

                    Integer idx = lsidMap.get(species);
                    if (idx == null) {
                        idx = lsidMap.size();
                        lsidMap.put(species, idx);

                        outputSpecies.write(species);
                        outputSpecies.write("\n");
                    }

                    outputPoints.writeDouble(lat);
                    outputPoints.writeDouble(lng);

                    outputPointsToSpecies.writeInt(idx);
                } catch (Exception e) {
                    logger.error("failed to read records.csv row: " + row, e);
                }
            }

            row++;
        }
    }

    br.close();

    outputPointsToSpecies.flush();
    outputPointsToSpecies.close();
    outputPoints.flush();
    outputPoints.close();
    outputSpecies.flush();
    outputSpecies.close();

    FileUtils.writeStringToFile(new File(filename + "records.csv.small.speciesCount"),
            String.valueOf(lsidMap.size()));
}

From source file:com.adobe.aem.demomachine.communities.Loader.java

private static void postAnalytics(String analytics, String body) {

    if (analytics != null && body != null) {

        URLConnection urlConn = null;
        DataOutputStream printout = null;
        BufferedReader input = null;
        String tmp = null;/*from ww  w. ja  v  a 2s.  c  om*/
        try {

            logger.debug("New Analytics Event: " + body);

            URL sitecaturl = new URL("http://" + analytics);

            urlConn = sitecaturl.openConnection();
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            printout = new DataOutputStream(urlConn.getOutputStream());

            printout.writeBytes(body);
            printout.flush();
            printout.close();

            input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            while (null != ((tmp = input.readLine()))) {
                logger.debug(tmp);
            }
            printout.close();
            input.close();

        } catch (Exception ex) {

            logger.warn("Connectivity error: " + ex.getMessage());

        } finally {

            try {
                input.close();
                printout.close();
            } catch (Exception e) {
                // Omitted
            }

        }

    }

}

From source file:core.AbstractTest.java

private int httpRequest(String sUrl, String sMethod, JsonNode payload, Map<String, String> mParameters) {
    Logger.info("\n\nREQUEST:\n" + sMethod + " " + sUrl + "\nHEADERS: " + mHeaders + "\nParameters: "
            + mParameters + "\nPayload: " + payload + "\n");
    HttpURLConnection conn = null;
    BufferedReader br = null;/* w w w.j a v  a2 s . c o  m*/
    int nRet = 0;
    boolean fIsMultipart = false;

    try {
        setStatusCode(-1);
        setResponse(null);
        conn = getHttpConnection(sUrl, sMethod);
        if (mHeaders.size() > 0) {
            Set<String> keys = mHeaders.keySet();
            for (String sKey : keys) {
                conn.addRequestProperty(sKey, mHeaders.get(sKey));
                if (sKey.equals(HTTP.CONTENT_TYPE)) {
                    if (mHeaders.get(sKey).startsWith(MediaType.MULTIPART_FORM_DATA)) {
                        fIsMultipart = true;
                    }
                }
            }
        }

        if (payload != null || mParameters != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());

            try {
                if (payload != null) {
                    //conn.setRequestProperty("Content-Length", "" + node.toString().length());
                    out.writeBytes(payload.toString());
                }

                if (mParameters != null) {
                    Set<String> sKeys = mParameters.keySet();

                    if (fIsMultipart) {
                        out.writeBytes("--" + BOUNDARY + "\r\n");
                    }

                    for (String sKey : sKeys) {
                        if (fIsMultipart) {
                            out.writeBytes("Content-Disposition: form-data; name=\"" + sKey + "\"\r\n\r\n");
                            out.writeBytes(mParameters.get(sKey));
                            out.writeBytes("\r\n");
                            out.writeBytes("--" + BOUNDARY + "--\r\n");
                        } else {
                            out.writeBytes(URLEncoder.encode(sKey, "UTF-8"));
                            out.writeBytes("=");
                            out.writeBytes(URLEncoder.encode(mParameters.get(sKey), "UTF-8"));
                            out.writeBytes("&");
                        }
                    }

                    if (fIsMultipart) {
                        if (nvpFile != null) {
                            File f = Play.application().getFile(nvpFile.getName());
                            if (f == null) {
                                assertFail("Cannot find file <" + nvpFile.getName() + ">");
                            }
                            FileBody fb = new FileBody(f);
                            out.writeBytes("Content-Disposition: form-data; name=\"" + PARAM_FILE
                                    + "\";filename=\"" + fb.getFilename() + "\"\r\n");
                            out.writeBytes("Content-Type: " + nvpFile.getValue() + "\r\n\r\n");
                            out.write(getResource(nvpFile.getName()));
                        }
                        out.writeBytes("\r\n--" + BOUNDARY + "--\r\n");
                    }
                }
            } catch (Exception ex) {
                assertFail("Send request: " + ex.getMessage());
            } finally {
                try {
                    out.flush();
                } catch (Exception ex) {
                }
                try {
                    out.close();
                } catch (Exception ex) {
                }
            }
        }

        nRet = conn.getResponseCode();
        setStatusCode(nRet);
        if (nRet / 100 != 2) {
            if (conn.getErrorStream() != null) {
                br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }
        } else {
            if (conn.getInputStream() != null) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
        }

        if (br != null) {
            String temp = null;
            StringBuilder sb = new StringBuilder(1024);
            while ((temp = br.readLine()) != null) {
                sb.append(temp).append("\n");
            }
            setResponse(sb.toString().trim());
        }
        Logger.info("\nRESPONSE\nHTTP code: " + nRet + "\nContent: " + sResponse + "\n");
    } catch (Exception ex) {
        assertFail("httpRequest: " + ex.getMessage());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception ex) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return nRet;
}

From source file:MyZone.Settings.java

public boolean retrieveCert() {
    while (true) {
        try {/* ww  w  . j av a 2 s .c om*/
            Socket toCAServer = new Socket(globalProperties.caAddress, globalProperties.caPort);
            toCAServer.setSoTimeout(IDLE_LIMIT);
            byte[] usernameBytes = username.getBytes("UTF-8");
            DataOutputStream outToCAServer = new DataOutputStream(toCAServer.getOutputStream());
            byte[] buffer = new byte[usernameBytes.length + 4];
            int len = 0;
            System.arraycopy(intToByteArray(usernameBytes.length), 0, buffer, len, 4);
            len += 4;
            System.arraycopy(usernameBytes, 0, buffer, len, usernameBytes.length);
            outToCAServer.write(buffer, 0, buffer.length);
            outToCAServer.flush();
            int i = 0;
            byte[] lenBytes = new byte[4];
            while (i < 4) {
                i += toCAServer.getInputStream().read(lenBytes, i, 4 - i);
                if (i < 0) {
                    if (DEBUG) {
                        System.out.println("DEBUG: line 2529 of Settings.java");
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    if (DEBUG) {
                        e.printStackTrace();
                    }
                }
            }
            len = byteArrayToInt(lenBytes);
            byte[] certBytes = new byte[len];
            i = 0;
            while (i < len) {
                i += toCAServer.getInputStream().read(certBytes, i, len - i);
                if (i < 0) {
                    if (DEBUG) {
                        System.out.println("DEBUG: line 2555 of Settings.java");
                    }
                    len = 4;
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    if (DEBUG) {
                        e.printStackTrace();
                    }
                }
            }
            if (len == 4) {
                Thread.sleep(30000);
                outToCAServer.close();
                toCAServer.close();
                continue;
            }
            outToCAServer.close();
            toCAServer.close();
            globalProperties.caCertPath = prefix + "/CAs/";
            CertVerifier y = new CertVerifier();
            userCertificate uc = y.verifyCertificate(certBytes, globalProperties.caCertPath,
                    globalProperties.keyPairAlgorithm, globalProperties.certSigAlgorithm);
            if (uc == null) {
                Thread.sleep(30000);
                continue;
            }
            File file = new File(prefix + username + "/cert/" + username + ".cert");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(certBytes);
            fos.flush();
            fos.close();
            outToCAServer.close();
            toCAServer.close();
            return true;
        } catch (Exception e) {
            if (DEBUG)
                e.printStackTrace();
        }
    }
}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {

    AQUtility.debug("multipart", url);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();

    conn.setInstanceFollowRedirects(false);

    conn.setConnectTimeout(NET_TIMEOUT * 4);

    conn.setDoInput(true);//ww  w. j  a v  a2s.  c om
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);

    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }

    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, conn);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    for (Map.Entry<String, Object> entry : params.entrySet()) {

        writeObject(dos, entry.getKey(), entry.getValue());

    }

    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();

    conn.connect();

    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();

    byte[] data = null;

    String encoding = conn.getContentEncoding();
    String error = null;

    if (code < 200 || code >= 300) {

        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");

        AQUtility.debug("error", error);
    } else {

        data = toData(encoding, conn.getInputStream());
    }

    AQUtility.debug("response", code);

    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);

}

From source file:fyp.project.uploadFile.UploadFile.java

public int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }/*w w  w .  j  av a  2s.c om*/
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                + fileName.substring(fileName.lastIndexOf("/")) + "\"" + lineEnd);

        m_log.log(Level.INFO, "Content-Disposition: form-data; name=\"file\";filename=\"{0}\"{1}",
                new Object[] { fileName.substring(fileName.lastIndexOf("/")), lineEnd });
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        m_log.log(Level.INFO, "Upload file to server" + "HTTP Response is : {0}: {1}",
                new Object[] { serverResponseMessage, serverResponseCode });

        // close streams
        m_log.log(Level.INFO, "Upload file to server{0} File is written", fileName);
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        m_log.log(Level.ALL, "Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //this block will give the response of upload link

    return serverResponseCode; // like 200 (Ok)

}

From source file:com.etalio.android.EtalioBase.java

protected String multipartRequest(String urlTo, InputStream fileInputStream, String filefield, String filename)
        throws ParseException, IOException, EtalioHttpException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    try {/*from  ww w .j a v  a  2s.  com*/
        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");

        connection.setRequestProperty("Authorization", " Bearer " + getEtalioToken().getAccessToken());
        connection.setRequestProperty("User-Agent", getEtalioUserAgent());
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\""
                + filename + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: " + MimeTypeUtil.getMimeType(filename) + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        inputStream = connection.getInputStream();

        if (connection.getResponseCode() > 300) {
            result = convertStreamToString(connection.getErrorStream());
        } else {
            result = this.convertStreamToString(inputStream);
        }

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();

        return result;
    } catch (Exception e) {
        throw new EtalioHttpException(connection.getResponseCode(), connection.getResponseMessage(),
                e.getMessage());
    }
}

From source file:com.gotraveling.external.androidquery.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {

    AQUtility.debug("multipart", url);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();

    conn.setInstanceFollowRedirects(false);

    conn.setConnectTimeout(NET_TIMEOUT * 4);

    conn.setDoInput(true);/* ww w  . java2s  . co m*/
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);

    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }

    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, conn);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    Object o = null;

    if (progress != null) {
        o = progress.get();
    }

    Progress p = null;

    if (o != null) {
        p = new Progress(o);
    }

    for (Map.Entry<String, Object> entry : params.entrySet()) {

        writeObject(dos, entry.getKey(), entry.getValue(), p);

    }

    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();

    conn.connect();

    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();

    byte[] data = null;

    String encoding = conn.getContentEncoding();
    String error = null;

    if (code < 200 || code >= 300) {

        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");

        AQUtility.debug("error", error);
    } else {

        data = toData(encoding, conn.getInputStream());
    }

    AQUtility.debug("response", code);

    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);

}