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:fr.Axeldu18.PterodactylAPI.Methods.POSTMethods.java

public String call(String methodURL, String data) {
    try {/*w ww .ja va2  s .  c o m*/
        URL url = new URL(methodURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        String hmac = main.getPublicKey() + "." + main.hmac(methodURL + data);
        System.out.println("DEBUG CALL: " + methodURL);
        System.out.println("DEBUG CALL2: " + methodURL + data);
        System.out.println("DEBUG CALL3: " + hmac);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Pterodactyl Java-API");
        connection.setRequestProperty("Authorization", "Bearer " + hmac.replaceAll("\n", ""));
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

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

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            return main.readResponse(connection.getInputStream()).toString();
        } else {
            return main.readResponse(connection.getErrorStream()).toString();
        }
    } catch (Exception e) {
        main.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
        return null;
    }
}

From source file:org.simple.net.httpstacks.HttpUrlConnStack.java

protected void setRequestParams(HttpURLConnection connection, Request<?> request)
        throws ProtocolException, IOException {
    HttpMethod method = request.getHttpMethod();
    connection.setRequestMethod(method.toString());
    // add params
    byte[] body = request.getBody();
    if (body != null) {
        // enable output
        connection.setDoOutput(true);/*w  w  w . j  ava2s .co  m*/
        // set content type
        connection.addRequestProperty(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
        // write params data to connection
        DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
        dataOutputStream.write(body);
        dataOutputStream.close();
    }
}

From source file:com.chinamobile.bcbsp.comm.DiskManager.java

/**
 * Save messages of every partition on disk for byte array version.
 * @param messages MessageBytePoolPerPartition
 * @param superStep int//from   ww  w .  j a va 2s.c  o  m
 * @param srcPartitionDstBucket int
 * @throws IOException e
 */
public void processMessagesSave(MessageBytePoolPerPartition messages, int superStep, int srcPartitionDstBucket)
        throws IOException {
    // LOG.info("####TAG1: "+srcPartitionDstBucket
    // +" ###TAG2: "+msgList.size());
    int count = messages.getMsgCount();
    int bucket = PartitionRule.getBucket(srcPartitionDstBucket);
    int srcPartition = PartitionRule.getPartition(srcPartitionDstBucket);
    String fileName = "srcPartition-" + srcPartition + "_" + "counter" + "-" + counter[srcPartitionDstBucket]++
            + "_" + "count" + "-" + count;
    String tmpPath = DiskManager.workerDir + "/" + "superstep-" + superStep + "/" + "bucket-" + bucket;
    File tmpFile = new File(tmpPath);
    if (!tmpFile.exists()) {
        tmpFile.mkdirs();
    }
    String url = new File(tmpFile, fileName).toString();
    // SpillingDiskOutputBuffer writeBuffer = new SpillingDiskOutputBuffer(url);
    FileOutputStream fot = new FileOutputStream(new File(url));
    BufferedOutputStream bos = new BufferedOutputStream(fot, MetaDataOfMessage.MESSAGE_IO_BYYES);
    DataOutputStream dos = new DataOutputStream(bos);
    messages.write(dos);
    dos.close();
}

From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java

public boolean performRequest() {

    jsonResponseArray = null;//from w  w w .j  ava  2 s  .  co  m
    jsonResponseObject = null;

    HttpURLConnection connection = null;

    try {

        // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP.
        mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject());
        byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8");

        URL url = new URL(mUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod(mRequestMethod);
        connection.setUseCaches(false);

        // For all methods except GET we need to include data in the body.
        if (mRequestMethod != "GET") {
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length));

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(postDataBytes);
            wr.flush();
            wr.close();
        }

        if (connection.getResponseCode() == 200) {
            InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line = buff.readLine().toString();
            buff.close();
            Object json = new JSONTokener(line).nextValue();
            if (json.getClass() == JSONObject.class) {
                jsonResponseObject = (JSONObject) json;
            } else if (json.getClass() == JSONArray.class) {
                jsonResponseArray = (JSONArray) json;
            } // else members will be left to null indicating no valid response.
            return true;
        }

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return false;
}

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

public String getAuthToken(String apiEndPoint, String encodedCliAndSecret) {

    //receives : apiEndPoint (https://api.test.sabre.com)
    //encodedCliAndSecret : base64Encode(  base64Encode(V1:[user]:[group]:[domain]) + ":" + base64Encode([secret]) )
    String strRet = null;/*from  ww  w .  ja  va2s .co m*/

    try {

        URL urlConn = new URL(apiEndPoint + "/v1/auth/token");
        URLConnection conn = urlConn.openConnection();

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

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Authorization", "Basic " + encodedCliAndSecret);
        conn.setRequestProperty("Accept", "application/json");

        //send request
        DataOutputStream dataOut = new DataOutputStream(conn.getOutputStream());
        dataOut.writeBytes("grant_type=client_credentials");
        dataOut.flush();
        dataOut.close();

        //get response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String strChunk = "";
        StringBuilder sb = new StringBuilder();
        while (null != ((strChunk = rd.readLine())))
            sb.append(strChunk);

        //parse the token
        JSONObject respParser = new JSONObject(sb.toString());
        strRet = respParser.getString("access_token");

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return strRet;

}

From source file:com.csipsimple.backup.SipSharedPreferencesHelper.java

@Override
public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) {
    boolean forceBackup = (oldState == null);

    long fileModified = 1;
    if (prefsFiles != null) {
        fileModified = prefsFiles.lastModified();
    }/*from w w  w .j a va 2  s  .  com*/
    try {
        if (!forceBackup) {
            FileInputStream instream = new FileInputStream(oldState.getFileDescriptor());
            DataInputStream in = new DataInputStream(instream);
            long lastModified = in.readLong();
            in.close();

            if (lastModified < fileModified) {
                forceBackup = true;
            }
        }
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage previous local backup state", e);
        forceBackup = true;
    }

    Log.d(THIS_FILE, "Will backup profiles ? " + forceBackup);
    if (forceBackup) {
        JSONObject settings = SipProfileJson.serializeSipSettings(mContext);
        try {
            writeData(data, settings.toString());
        } catch (IOException e) {
            Log.e(THIS_FILE, "Cannot manage remote backup", e);
        }
    }

    try {
        FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
        DataOutputStream out = new DataOutputStream(outstream);
        out.writeLong(fileModified);
        out.close();
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage final local backup state", e);
    }

}

From source file:edu.uci.ics.pregelix.example.util.TestCluster.java

private void startHDFS() throws IOException {
    conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/core-site.xml"));
    conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/mapred-site.xml"));
    conf.addResource(new Path(PATH_TO_HADOOP_CONF + "/hdfs-site.xml"));
    FileSystem lfs = FileSystem.getLocal(new Configuration());
    lfs.delete(new Path("build"), true);
    System.setProperty("hadoop.log.dir", "logs");
    dfsCluster = new MiniDFSCluster(conf, numberOfNC, true, null);
    FileSystem dfs = FileSystem.get(conf);
    Path src = new Path(DATA_PATH);
    Path dest = new Path(HDFS_PATH);
    dfs.mkdirs(dest);//from   w  w  w .  j  a v  a  2  s  .  c o m
    dfs.copyFromLocalFile(src, dest);

    src = new Path(DATA_PATH2);
    dest = new Path(HDFS_PATH2);
    dfs.mkdirs(dest);
    dfs.copyFromLocalFile(src, dest);

    src = new Path(DATA_PATH3);
    dest = new Path(HDFS_PATH3);
    dfs.mkdirs(dest);
    dfs.copyFromLocalFile(src, dest);

    src = new Path(DATA_PATH4);
    dest = new Path(HDFS_PATH4);
    dfs.mkdirs(dest);
    dfs.copyFromLocalFile(src, dest);

    src = new Path(DATA_PATH5);
    dest = new Path(HDFS_PATH5);
    dfs.mkdirs(dest);
    dfs.copyFromLocalFile(src, dest);

    DataOutputStream confOutput = new DataOutputStream(new FileOutputStream(new File(HADOOP_CONF_PATH)));
    conf.writeXml(confOutput);
    confOutput.flush();
    confOutput.close();
}

From source file:TaxSvc.TaxSvc.java

public CancelTaxResult CancelTax(CancelTaxRequest req) {

    //Create URL//from w  ww . ja  va2 s .  c  om
    String taxget = svcURL + "/1.0/tax/cancel";
    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) //Note: tax/cancel will return a 200 response even if the document could not be cancelled. Special attention needs to be paid to the ResultCode.
        { //If we got a more serious error, print out the error message.
            CancelTaxResult res = mapper.readValue(conn.getErrorStream(), CancelTaxResult.class); //Deserialize response
            return res;
        } else {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            CancelTaxResponse res = mapper.readValue(conn.getInputStream(), CancelTaxResponse.class); //Deserialize response
            return res.CancelTaxResult;
        }

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

    }
}

From source file:com.skubit.bitid.loaders.SignInAsyncTaskLoader.java

private void writeRequest(String message) throws IOException {
    DataOutputStream dos = new DataOutputStream(mConnection.getOutputStream());
    dos.write(message.getBytes());//from w ww. jav a2s  .co  m
    dos.close();
}

From source file:com.QuarkLabs.BTCeClientJavaFX.networking.AuthRequest.java

public JSONObject makeRequest(String method, Map<String, String> arguments)
        throws UnsupportedEncodingException {
    if (method == null) {
        return null;
    }/*from  ww  w . j a  va 2s .c om*/
    if (arguments == null) {
        arguments = new HashMap<>();
    }
    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = (Map.Entry<String, String>) it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    try {
        mac.init(_key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }
    StringBuilder out = new StringBuilder();
    try {
        HttpURLConnection urlConnection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        urlConnection.setRequestProperty("Key", key);
        String sign = byteArrayToHexString(mac.doFinal(postData.getBytes("UTF-8")));
        urlConnection.setRequestProperty("Sign", sign);
        urlConnection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();
        if (urlConnection.getResponseCode() == 200) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                out.append(line);
            }
            rd.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new JSONObject(out.toString());
}