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:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java

private int getMsLayerCount(String url) {
    int cnt = -1;

    try {/* www.  j  a  v  a 2 s. c  o  m*/
        URL obj = new URL(url + "/query");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add request header
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Accept", "text/plain");

        String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly="
                + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        String jsonString = response.toString();

        JSONTokener tokener = new JSONTokener(jsonString);

        JSONObject root = new JSONObject(tokener);

        cnt = root.getInt("count");

    } catch (Exception e) {
        cnt = -2;
    } finally {
        return cnt;
    }

}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }/*from www .  ja  v a  2s .  c o  m*/
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:cms.service.util.ItemUtility.java

public String sendPost(String url, String urlParams) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    // Send post request
    con.setDoOutput(true);/*w  w  w . j  a va 2 s  . c  om*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParams);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    logger.info("\nSending 'POST' request to URL : " + url);
    logger.info("Post parameters : " + urlParams);
    logger.info("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    return (response.toString());

}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?url/*from w w w  . ja  v a  2  s. co  m*/
 *
 * @param inputStream ?
 * @param fileName    ??
 * @param fileType    
 * @param contentType 
 * @param identity    
 * @return 
 */
public static String uploadMediaFile(String requestUrl, FileInputStream inputStream, String fileName,
        String fileType, String contentType, String identity) {
    String lineEnd = System.getProperty("line.separator");
    String twoHyphens = "--";
    String boundary = "*****";
    String result = null;
    try {
        //?
        URL submit = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) submit.openConnection();
        //
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        //?
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", DEFAULT_CHARSET);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //??
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName
                + ";Content-Type=\"" + contentType + lineEnd);
        dos.writeBytes(lineEnd);

        byte[] buffer = new byte[8192]; // 8k
        int count = 0;
        while ((count = inputStream.read(buffer)) != -1) {
            dos.write(buffer, 0, count);
        }
        inputStream.close(); //?
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();

        InputStream is = conn.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, DEFAULT_CHARSET);
        BufferedReader br = new BufferedReader(isr);
        result = br.readLine();
        dos.close();
        is.close();
    } catch (IOException e) {
        logger.error("", e);
    }
    return result;
}

From source file:com.cisco.gerrit.plugins.slack.client.WebhookClient.java

/**
 * Initiates an HTTP POST to the provided Webhook URL.
 *
 * @param message The message payload.//from www  . j  a  v  a  2  s .  co  m
 * @param webhookUrl The URL to post to.
 * @return The response payload from Slack.
 */
private String postRequest(String message, String webhookUrl) {
    String response;

    HttpURLConnection connection;
    connection = null;
    try {
        connection = openConnection(webhookUrl);
        try {
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");

            connection.setDoInput(true);
            connection.setDoOutput(true);

            DataOutputStream request;
            request = new DataOutputStream(connection.getOutputStream());

            request.write(message.getBytes(StandardCharsets.UTF_8));
            request.flush();
            request.close();
        } catch (IOException e) {
            throw new RuntimeException("Error posting message to Slack: [" + e.getMessage() + "].", e);
        }

        response = getResponse(connection);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return response;
}

From source file:com.esri.geoevent.test.tools.GetMapServiceCountRunnable.java

private int getMsLayerCount(String url) {
    int cnt = -1;

    try {//www . jav a2  s  .com
        URL obj = new URL(url + "/query");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Accept", "text/plain");

        String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly="
                + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        String jsonString = response.toString();

        JSONTokener tokener = new JSONTokener(jsonString);

        JSONObject root = new JSONObject(tokener);

        cnt = root.getInt("count");

    } catch (Exception e) {
        cnt = -2;
    } finally {
        return cnt;
    }

}

From source file:com.newrelic.agent.Obfuscation.Proguard.java

private void sendMapping(String mapping)
/*     */ {//from   w  w w .j ava  2 s .c o m
    /* 138 */ StringBuilder requestBody = new StringBuilder();
    /*     */
    /* 140 */ requestBody.append("proguard=" + URLEncoder.encode(mapping));
    /* 141 */ requestBody.append("&buildId=" + NewRelicClassVisitor.getBuildId());
    /*     */ try
    /*     */ {
        /* 144 */ String host = "mobile-symbol-upload.newrelic.com";
        /* 145 */ if (this.mappingApiHost != null) {
            /* 146 */ host = this.mappingApiHost;
            /*     */ }
        /*     */
        /* 149 */ URL url = new URL("https://" + host + "/symbol");
        /* 150 */ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        /*     */
        /* 152 */ connection.setUseCaches(false);
        /* 153 */ connection.setDoOutput(true);
        /* 154 */ connection.setRequestMethod("POST");
        /* 155 */ connection.setRequestProperty("X-APP-LICENSE-KEY", this.licenseKey);
        /* 156 */ connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        /* 157 */ connection.setRequestProperty("Content-Length", Integer.toString(requestBody.length()));
        /*     */
        /* 159 */ DataOutputStream request = new DataOutputStream(connection.getOutputStream());
        /* 160 */ request.writeBytes(requestBody.toString());
        /* 161 */ request.close();
        /*     */
        /* 163 */ int responseCode = connection.getResponseCode();
        /* 164 */ if (responseCode == 400) {
            /* 165 */ InputStream inputStream = connection.getErrorStream();
            /* 166 */ String response = convertStreamToString(inputStream);
            /* 167 */ this.log
                    .error("Unable to send your ProGuard mapping.txt to New Relic as the params are incorrect: "
                            + response);
            /* 168 */ this.log
                    .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually.");
            /* 169 */ } else if (responseCode > 400) {
            /* 170 */ InputStream inputStream = connection.getErrorStream();
            /* 171 */ String response = convertStreamToString(inputStream);
            /* 172 */ this.log.error("Unable to send your ProGuard mapping.txt to New Relic - received status "
                    + responseCode + ": " + response);
            /* 173 */ this.log
                    .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually.");
            /*     */ }
        /*     */
        /* 176 */ this.log.info("Successfully sent mapping.txt to New Relic.");
        /*     */
        /* 178 */ connection.disconnect();
        /*     */ } catch (IOException e) {
        /* 180 */ this.log.error("Encountered an error while uploading your ProGuard mapping to New Relic", e);
        /* 181 */ this.log
                .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually.");
        /*     */ }
    /*     */ }

From source file:com.cloudbase.CBHelperRequest.java

public void run() {
    HttpConnection hc = null;/*from   w w  w  .  j a  va  2  s  .  c om*/
    InputStream is = null;

    try {
        hc = (HttpConnection) Connector.open(url + ";deviceside=true");
        hc.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + CBHelperRequest.FIELD_BOUNDARY);

        hc.setRequestMethod(HttpConnection.POST);

        ByteArrayOutputStream request = new ByteArrayOutputStream();//hc.openOutputStream();

        // Add your data
        Enumeration params = this.postData.keys();
        while (params.hasMoreElements()) {
            String curKey = (String) params.nextElement();
            request.write(this.getParameterPostData(curKey, (String) this.postData.get(curKey)));
            //entity.addPart(new CBStringPart(curKey, this.postData.get(curKey)));
        }
        // if we have file attachments then add each file to the multipart request
        if (this.files != null && this.files.size() > 0) {

            for (int i = 0; i < this.files.size(); i++) {
                CBHelperAttachment curFile = (CBHelperAttachment) this.files.elementAt(i);
                String name = curFile.getFileName();

                request.write(this.getFilePostData(i, name, curFile.getFileData()));
            }
        }
        request.flush();
        hc.setRequestProperty("Content-Length", "" + request.toByteArray().length);
        OutputStream requestStream = hc.openOutputStream();
        requestStream.write(request.toByteArray());
        requestStream.close();

        is = hc.openInputStream();

        // if we have a responder then parse the response data into the global CBHelperResponse object
        if (this.responder != null) {
            try {
                resp = new CBHelperResponse();
                resp.setFunction(this.function);

                int ch;
                ByteArrayOutputStream response = new ByteArrayOutputStream();

                while ((ch = is.read()) != -1) {
                    response.write(ch);
                }

                // if it's a download then we need to save the file content into a temporary file in
                // application cache folder. Then return that file to the responder
                if (this.function.equals("download")) {
                    String filePath = "file:///store/home/user/" + this.fileId;
                    FileConnection fconn = (FileConnection) Connector.open(filePath);
                    if (fconn.exists()) {
                        fconn.delete();
                    }
                    fconn.create();

                    DataOutputStream fs = fconn.openDataOutputStream();
                    fs.write(response.toByteArray());
                    fs.close();
                    fconn.close();
                    resp.setDownloadedFile(filePath);
                } else {

                    // if it's not a download parse the JSON response and set all 
                    // the variables in the CBHelperResponse object
                    String responseString = new String(response.toByteArray());//EntityUtils.toString(response.getEntity());

                    //System.out.println("Received response string: " + responseString);
                    resp.setResponseDataString(responseString);

                    JSONTokener tokener = new JSONTokener(responseString);
                    JSONObject jsonOutput = new JSONObject(tokener);

                    // Use the cloudbase.io deserializer to get the data in a Map<String, Object>
                    // format.
                    JSONObject outputData = jsonOutput.getJSONObject(this.function);

                    resp.setData(outputData.get("message"));
                    resp.setErrorMessage((String) outputData.get("error"));
                    resp.setSuccess(((String) outputData.get("status")).equals("OK"));
                }
                //Application.getApplication().enterEventDispatcher();
                responder.handleResponse(resp);
            } catch (Exception e) {
                System.out.println("Error while parsing response: " + e.getMessage());
                e.printStackTrace();
            }
        }

    } catch (Exception e) {
        System.out.println("Error while opening connection and sending data: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.kylinolap.rest.service.UserService.java

private byte[] serialize(Collection<? extends GrantedAuthority> auths) {
    if (null == auths) {
        return null;
    }//from  ww  w  . j  a v a 2s .c  o m

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(buf);

    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(dout, auths);
        dout.close();
        buf.close();
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
    }

    return buf.toByteArray();
}

From source file:edu.umn.cs.spatialHadoop.indexing.RTreeLocalIndexer.java

@Override
public void buildLocalIndex(File nonIndexedFile, Path outputIndexedFile, Shape shape)
        throws IOException, InterruptedException {
    // Read all data of the written file in memory
    byte[] cellData = new byte[(int) nonIndexedFile.length()];
    InputStream cellIn = new BufferedInputStream(new FileInputStream(nonIndexedFile));
    cellIn.read(cellData);//w  ww.  j a  v a 2  s .  c  o m
    cellIn.close();

    // Build an RTree over the elements read from file
    // Create the output file
    FileSystem outFS = outputIndexedFile.getFileSystem(conf);
    DataOutputStream cellStream = outFS.create(outputIndexedFile);
    cellStream.writeLong(SpatialSite.RTreeFileMarker);
    int degree = 4096 / RTree.NodeSize;
    boolean fastAlgorithm = conf.get(SpatialSite.RTREE_BUILD_MODE, "fast").equals("fast");
    RTree.bulkLoadWrite(cellData, 0, cellData.length, degree, cellStream, shape.clone(), fastAlgorithm);
    cellStream.close();
}