Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:ai.eve.volley.Request.java

/**
 * Returns the raw POST or PUT body to be sent.
 * //  w  w  w . ja  v a 2 s  . c om
 * @throws AuthFailureError
 *             in the event of auth failure
 */
public void getBody(HttpURLConnection connection) throws AuthFailureError {
    Map<String, String> params = getParams();
    if (params != null && params.size() > 0) {
        byte[] bs = encodeParameters(params, getParamsEncoding());
        try {
            if (bs != null) {
                connection.setDoOutput(true);
                connection.addRequestProperty(HTTP.CONTENT_TYPE, getBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(bs);
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

JSONObject doRequest(HttpURLConnection connection, String data) throws IOException, JSONException {
    int responseCode = -1;
    InputStream response = null;/*from   w  w w .  java 2s . c o  m*/
    DataOutputStream outputStream = null;

    try {
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(pinnedSSLSocketFactory);
        }

        connection.setRequestProperty("Content-Type", "application/json");
        if (data != null) {
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(data.getBytes());
            outputStream.flush();
            outputStream.close();
        } else {
            connection.setRequestMethod("GET");
        }

        responseCode = connection.getResponseCode();
        response = connection.getInputStream();

        if (responseCode != 204) {
            String responseString = IOUtils.toString(response);
            JSONObject jsonObject = new JSONObject(responseString);
            return jsonObject;
        } else {
            return null;
        }
    } catch (IOException e) {
        if (responseCode < 200 || responseCode >= 300) {
            response = connection.getErrorStream();
            if (response != null) {
                String responseString = IOUtils.toString(response);
                throw new RuntimeException(responseString);
            }
        }
        throw e;
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(response);
    }
}

From source file:com.datatorrent.contrib.hdht.HDHTWalManager.java

/**
 * Copy old WAL files to current location from startPosition to End Position in old WAL.
 * @param startPosition/*from  w  w w  .  j  a v a 2s.  c  o m*/
 * @param endPosition
 * @param oldWalKey
 */
public void copyWALFiles(WalPosition startPosition, WalPosition endPosition, long oldWalKey) {
    try {
        for (long i = startPosition.fileId; i < endPosition.fileId; i++) {
            if (bfs.exists(oldWalKey, WAL_FILE_PREFIX + i)) {
                DataInputStream in = bfs.getInputStream(oldWalKey, WAL_FILE_PREFIX + i);
                DataOutputStream out = bfs.getOutputStream(walKey, WAL_FILE_PREFIX + walFileId);

                IOUtils.copyLarge(in, out);
                in.close();
                out.close();
                walFileId++;
            }
        }
        // Copy last file upto end position offset
        copyWalPart(startPosition, endPosition, oldWalKey);
        if (maxWalFileSize > 0 && walSize > maxWalFileSize) {
            writer.close();
            writer = null;
            walFileId++;
            walSize = 0;
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.telesign.util.TeleSignRequest.java

/**
 * Creates and sends the REST request./*w w  w . j ava  2 s .  c o  m*/
 *
 * @return A string containing the TeleSign web server's Response.
 * @throws IOException
 *          A {@link java.security.SignatureException} signals that an
 *          error occurred while attempting to sign the Request.
 */
public String executeRequest() throws IOException {

    String signingString = getSigningString(customer_id);
    String signature;
    String url_output = "";

    // Create the absolute form of the resource URI, and place it in a string buffer.
    StringBuffer full_url = new StringBuffer(base).append(resource);

    if (params.size() > 0) {

        full_url.append("?");
        int i = 0;

        for (String key : params.keySet()) {

            if (++i != 0) {

                full_url.append("&");
            }

            full_url.append(URLEncoder.encode(key, "UTF-8")).append("=")
                    .append(URLEncoder.encode(params.get(key), "UTF-8"));
        }
    }

    url = new URL(full_url.toString());

    // Create the Signature using the formula: Signature = Base64(HMAC-SHA( YourTeleSignAPIKey, UTF-8-Encoding-Of( StringToSign )).
    try {

        signature = encode(signingString, secret_key);
    } catch (SignatureException e) {

        System.err.println("Error signing request " + e.getMessage());

        return null;
    }

    String auth_header = "TSA " + customer_id + ":" + signature;

    connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(connectTimeout);
    connection.setReadTimeout(readTimeout);
    connection.setRequestProperty("Authorization", auth_header);
    setTLSProtocol();

    if (post) {

        connection.setRequestProperty("Content-Length", Integer.toString(body.length()));
    }

    for (String key : ts_headers.keySet()) {

        connection.setRequestProperty(key, ts_headers.get(key));
    }

    for (String key : headers.keySet()) {

        connection.setRequestProperty(key, headers.get(key));
    }

    if (post) {

        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        wr.writeBytes(body);
        wr.flush();
        wr.close();
    }

    int response = connection.getResponseCode();

    BufferedReader in;

    try {

        InputStream isr = (response == 200) ? connection.getInputStream() : connection.getErrorStream();
        in = new BufferedReader(new InputStreamReader(isr));
        String urlReturn;

        while ((urlReturn = in.readLine()) != null) {

            url_output += urlReturn;
        }

        in.close();
    } catch (IOException e) {
        System.err.println("IOException while reading from input stream " + e.getMessage());
        throw new RuntimeException(e);
    }

    return url_output;
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryDMSTest(String dms_endpoint, String body) throws UnsupportedEncodingException, IOException,
        KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

    HttpURLConnection connection = null;
    // Of course everything will go over HTTPS (here we trust anything, we do not check the certificate)
    SSLContext sc = null;//from  ww w  .  j  a v a  2 s. com
    try {
        sc = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e1) {

    }

    InputStream is;
    BufferedReader rd;
    char cbuf[] = new char[1000000];
    int len;

    String urlParameters = body; // test cookie is the user performing the evalaution
    // The array of resources to evaluate policies on must be included

    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;
    URL url = new URL(dms_URL + "/" + dms_endpoint);
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setRequestProperty("Cookie", cookie); // Include cookies (permissions evaluated for normal user, advanced user has the rights to evaluate)

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(postData);
        wr.close();

        // Get Response
        int err = connection.getResponseCode();
        if (err >= 200 && err < 300) {

            is = connection.getInputStream();
            //             
            rd = new BufferedReader(new InputStreamReader(is));
            //                //StringBuilder rd2 = new StringBuilder();

            len = rd.read(cbuf);
            String resp2 = String.valueOf(cbuf).substring(0, len - 1);
            rd.close();
            return resp2;

            //            char[] buffer = new char[1024*1024];
            //            StringBuilder output = new StringBuilder();
            //            int readLength = 0;
            //            while (readLength != -1) {
            //                readLength = rd.read(buffer, 0, buffer.length);
            //                if (readLength != -1) {
            //                    output.append(buffer, 0, readLength);
            //                }
            //            }

            //                return output.toString();
        }

    } catch (Exception e) {
        throw new java.net.ConnectException();
        //log 
    } finally {
        if (connection != null) {
            connection.disconnect();

        }
    }
    return null;
}

From source file:de.burlov.ultracipher.core.Database.java

public String computeChecksum() {
    DigestOutputStream digest = new DigestOutputStream(new RIPEMD160Digest());
    DataOutputStream out = new DataOutputStream(digest);

    try {//from   w  w w. j  a va  2  s. c  o m
        for (Entry<String, Long> entry : deletedEntries.entrySet()) {
            out.writeUTF(entry.getKey());
            out.writeLong(entry.getValue());
        }
        for (DataEntry entry : entries.values()) {
            out.writeUTF(entry.getId());
            out.writeUTF(entry.getName());
            out.writeUTF(entry.getTags());
            out.writeUTF(entry.getText());
        }
        out.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return new String(Hex.encode(digest.getDigest()));
}

From source file:it.unimi.dsi.sux4j.io.ChunkedHashStore.java

/** Resets this store using a new seed. All accumulated data are cleared, and a new seed is reinstated.
 * //from ww w  . j  a  v a2 s .c o  m
 * @param seed the new seed.
 * @throws IllegalStateException if this store was locked by a call to {@link #seed()}, and never {@linkplain #clear() cleared} thereafter.
 */

public void reset(final long seed) {
    if (locked)
        throw new IllegalStateException();
    if (DEBUG)
        System.err.println("RESET(" + seed + ")");
    filteredSize = 0;
    this.seed = seed;
    checkedForDuplicates = false;
    Arrays.fill(count, 0);
    try {
        for (DataOutputStream d : dos)
            d.close();
        for (int i = 0; i < DISK_CHUNKS; i++)
            dos[i] = new DataOutputStream(
                    new FastBufferedOutputStream(new FileOutputStream(file[i]), OUTPUT_BUFFER_SIZE));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.constellio.app.services.appManagement.AppManagementService.java

InputStream getInputForPost(String url, String infoSent) throws IOException {
    URL obj = new URL(url);

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);//from www .  java2  s  .  c o m

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(infoSent);
    wr.flush();
    wr.close();

    return con.getInputStream();
}

From source file:com.dao.ShopThread.java

private String getPayKey(HttpURLConnection conn, String type) throws Exception {
    LogUtil.debugPrintf("");
    String keyurl = conn.getURL().toString();
    String postParams = getKeyDynamicParams(keyurl, type);
    HttpURLConnection loginConn = getHttpPostConn(keyurl);
    loginConn.setRequestProperty("Accept-Encoding", "deflate");// ??
    loginConn.setRequestProperty("Referer", keyurl);
    loginConn.setRequestProperty("Host", "danbao.5173.com");
    loginConn.setRequestProperty("Pragma", "no-cache");
    loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
    LogUtil.debugPrintf("?keyHEADER===" + loginConn.getRequestProperties());
    LogUtil.debugPrintf("?keypostParams===" + postParams);
    DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream());
    wr.writeBytes(postParams);/*from www. jav a 2  s.  co  m*/
    wr.flush();
    wr.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer(2000);
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    String payurl = response.toString();
    LogUtil.debugPrintf("keyHtml:" + payurl);
    payurl = payurl.substring(payurl.indexOf("action") + "action".length(), payurl.indexOf("></form>"));
    payurl = payurl.substring(payurl.indexOf("\"") + 1, payurl.lastIndexOf("\""));
    Map<String, List<String>> header = loginConn.getHeaderFields();
    LogUtil.debugPrintf("?key?HEADER===" + header);
    List<String> cookie = header.get("Set-Cookie");
    if (cookie == null || cookie.size() == 0) {
        LogUtil.debugPrintf("?keycookie----------->");
    } else {
        LogUtil.debugPrintf("?keycookie----------->");
        LogUtil.debugPrintf("cookie====" + cookie);
        setCookies(cookie);
    }
    LogUtil.debugPrintf("?key?----------->");
    return payurl;
}

From source file:com.lostad.app.base.util.RequestUtil.java

/** 
 * HTTP??????,??? /*from  ww  w .j av a  2 s . com*/
 * @param actionUrl  
 * @param params ? key???,value? 
 * @param files 
 * @throws Exception 
 */
public static String postFile(String actionUrl, Map<String, String> params, FormFile[] files, String token)
        throws Exception {
    try {
        String BOUNDARY = "---------7d4a6d158c9"; //?  
        String MULTIPART_FORM_DATA = "multipart/form-data";

        URL url = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);//?  
        conn.setDoOutput(true);//?  
        conn.setUseCaches(false);//?Cache  
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
        conn.setRequestProperty("token", token);
        //????
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {//?  
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                sb.append(entry.getValue());
                sb.append("\r\n");
            }
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());//????  

        //??  
        for (FormFile file : files) {
            StringBuilder split = new StringBuilder();
            split.append("--");
            split.append(BOUNDARY);
            split.append("\r\n");
            split.append("Content-Disposition: form-data;name=\"" + file.getFormname() + "\";filename=\""
                    + file.getFilname() + "\"\r\n");
            split.append("Content-Type: " + file.getContentType() + "\r\n\r\n");
            outStream.write(split.toString().getBytes());
            outStream.write(file.getData(), 0, file.getData().length);
            outStream.write("\r\n".getBytes());
        }
        byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//??           
        outStream.write(end_data);
        outStream.flush();
        int cah = conn.getResponseCode();
        if (cah != 200)
            throw new RuntimeException("url");
        InputStream is = conn.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        outStream.close();
        conn.disconnect();
        return b.toString();
    } catch (Exception e) {

        throw e;
    }
}