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

public GetTaxResult GetTax(GetTaxRequest req) {

    //Create URL/*from  w  w w . ja v  a 2 s.c  om*/
    String taxget = svcURL + "/1.0/tax/get";
    URL url;

    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);   //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error.
        {
            GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

        else //Otherwise, print out the total tax calculated
        {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:org.jongo.mocks.JongoClient.java

private JongoResponse doRequest(final String url, final List<NameValuePair> parameters) {
    final String urlParameters = URLEncodedUtils.format(parameters, "UTF-8");
    JongoResponse response = null;//w w  w. ja v  a 2 s.  c o  m

    try {
        HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept", MediaType.APPLICATION_XML);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        con.setDoOutput(true);
        con.setDoInput(true);

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

        BufferedReader r = null;
        if (con.getResponseCode() != Response.Status.CREATED.getStatusCode()) {
            r = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            r = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }

        StringBuilder rawresponse = new StringBuilder();
        String strLine = null;
        while ((strLine = r.readLine()) != null) {
            rawresponse.append(strLine);
            rawresponse.append("\n");
        }

        try {
            response = XmlXstreamTest.successFromXML(rawresponse.toString());
        } catch (Exception e) {
            response = XmlXstreamTest.errorFromXML(rawresponse.toString());
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return response;

}

From source file:com.haulmont.yarg.formatters.impl.HtmlFormatter.java

protected void renderPdfDocument(String htmlContent, OutputStream outputStream) {
    ITextRenderer renderer = new ITextRenderer();
    File temporaryFile = null;//from  ww  w  .  jav  a  2  s .  c o  m
    try {
        temporaryFile = File.createTempFile("htmlReport", ".htm");
        DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(temporaryFile));
        dataOutputStream.write(htmlContent.getBytes(Charset.forName("UTF-8")));
        dataOutputStream.close();

        String url = temporaryFile.toURI().toURL().toString();
        renderer.setDocument(url);

        renderer.layout();
        renderer.createPDF(outputStream);
    } catch (Exception e) {
        throw wrapWithReportingException("", e);
    } finally {
        FileUtils.deleteQuietly(temporaryFile);
    }
}

From source file:org.darwinathome.client.HttpHub.java

public void setGenome(final Genome genome, final Exchange exchange) {
    submit(new ExchangeRunner(Hub.SET_GENOME_SERVICE, exchange) {
        @Override/*from   w ww .  j a  va2s  .c o  m*/
        HttpRequestBase getRequest(String serviceUrl) {
            HttpPost post = new HttpPost(serviceUrl);
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(baos);
                genome.write(dos);
                dos.close();
                ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
                entity.setContentType("application/octet-stream");
                post.setEntity(entity);
            } catch (IOException e) {
                log.warn("Problem marshalling", e);
                exchange.fail(Failure.MARSHALLING);
            }
            return post;
        }
    });
}

From source file:org.jongo.mocks.JongoClient.java

private JongoResponse doRequest(final String url, final String method, final String jsonParameters) {
    JongoResponse response = null;/*from  www  . j  ava  2 s  .c o  m*/

    try {
        HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection();
        con.setRequestMethod(method);
        con.setRequestProperty("Accept", MediaType.APPLICATION_XML);
        con.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
        con.setRequestProperty("Content-Length", "" + Integer.toString(jsonParameters.getBytes().length));
        con.setDoOutput(true);
        con.setDoInput(true);

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

        //            BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));

        BufferedReader r = null;
        if (con.getResponseCode() != Response.Status.OK.getStatusCode()
                && con.getResponseCode() != Response.Status.CREATED.getStatusCode()) {
            r = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            r = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }

        StringBuilder rawresponse = new StringBuilder();
        String strLine = null;
        while ((strLine = r.readLine()) != null) {
            rawresponse.append(strLine);
            rawresponse.append("\n");
        }

        try {
            response = XmlXstreamTest.successFromXML(rawresponse.toString());
        } catch (Exception e) {
            response = XmlXstreamTest.errorFromXML(rawresponse.toString());
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return response;
}

From source file:mendhak.teamcity.stash.api.StashClient.java

private String PostBuildStatusToStash(String targetURL, String body, String authHeader) {

    HttpURLConnection connection = null;
    try {//from   ww w.j  a  v  a2s.c  om

        Logger.LogInfo("Sending build status to " + targetURL);
        Logger.LogInfo("With body: " + body);
        Logger.LogInfo("Auth header: " + authHeader);

        connection = GetConnection(targetURL);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        connection.setRequestProperty("Content-Length", String.valueOf(body.getBytes().length));
        connection.setRequestProperty("Authorization", "Basic " + authHeader);

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

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(body);
        wr.flush();
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append("\r\n");
        }
        rd.close();
        return response.toString();

    } catch (Exception e) {

        Logger.LogError("Could not send data to Stash. ", e);
    } finally {

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

    return null;

}

From source file:com.nearinfinity.blur.mapreduce.BlurTask.java

public Job configureJob(Configuration configuration) throws IOException {
    if (getIndexingType() == INDEXING_TYPE.UPDATE) {
        checkTable();/*from   w ww .j  a v  a 2  s  .c o m*/
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutputStream output = new DataOutputStream(os);
    write(output);
    output.close();
    String blurTask = new String(Base64.encodeBase64(os.toByteArray()));
    configuration.set(BLUR_BLURTASK, blurTask);

    Job job = new Job(configuration, "Blur Indexer");
    job.setReducerClass(BlurReducer.class);
    job.setOutputKeyClass(BytesWritable.class);
    job.setOutputValueClass(BlurMutate.class);
    job.setNumReduceTasks(getNumReducers(configuration));
    return job;
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {//from ww  w .j  av a  2 s.  c  o  m
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

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

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;// www  .j  a va2  s .co m
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:com.cbagroup.sit.CreditTransfer.java

public String sendPOST() throws IOException, NoSuchAlgorithmException {
    String key = "api_key=cbatest123";
    //String url = "http://developer.cbagroup.com/api/CreditTransfer?api_key=cbatest123";
    String url = "http://developer.cbagroup.com/api/CreditTransfer?" + key;
    URL object = new URL(url);
    HttpURLConnection con = (HttpURLConnection) object.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");

    String urlParameters = "BankCode=Kenya&" + "BranchCode=COMBAPI&" + "Country=COMBAPI&"
            + "TranType=CreditTransfer&" + "Reference=Impalapay&" + "Currency=10.25&" + "Account=pay&"
            + "Amount=10.22&" + "Narration=payment&" + "Transaction Date=1.2.2017&";

    // Send post request
    con.setDoOutput(true);//from  ww w  .j a  v  a  2 s.co  m
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("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
    System.out.println(response.toString());

    //////////start  ////////////////////
    String result = response.toString();

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(result);

        JSONObject jsonObject = (JSONObject) obj;
        //System.out.println(jsonObject);

        long ResCode = (long) jsonObject.get("Response Code");
        System.out.println();
        System.out.println("Response Code : " + ResCode);
        System.out.println();

        if (ResCode == 1) {

            System.out.println("#########################################################");
            System.out.println("Fred hack Fail");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        } else {

            System.out.println("#########################################################");
            System.out.println("Fred hack Success");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        }

        //         long age = (Long) jsonObject.get("Description");
        //         System.out.println(age);

        // loop array
        //         JSONArray msg = (JSONArray) jsonObject.get("messages");
        //         Iterator<String> iterator = msg.iterator();
        //         while (iterator.hasNext()) {
        //             System.out.println(iterator.next());
        //}

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return response.toString();
}