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.QuarkLabs.BTCeClient.exchangeApi.AuthRequest.java

/**
 * Makes any request, which require authentication
 *
 * @param method    Method of Trade API/*from ww  w  .ja v  a 2 s .co m*/
 * @param arguments Additional arguments, which can exist for this method
 * @return Response of type JSONObject
 * @throws JSONException
 */
@Nullable
public JSONObject makeRequest(@NotNull String method, Map<String, String> arguments) throws JSONException {

    if (key.length() == 0 || secret.length() == 0) {
        return new JSONObject("{success:0,error:'No key/secret provided'}");
    }

    if (arguments == null) {
        arguments = new HashMap<>();
    }

    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator<Map.Entry<String, String>> it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = 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;
    }

    HttpURLConnection connection = null;
    BufferedReader bufferedReader = null;
    DataOutputStream wr = null;
    try {
        connection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Key", key);
        byte[] array = mac.doFinal(postData.getBytes("UTF-8"));
        connection.setRequestProperty("Sign", byteArrayToHexString(array));
        wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        InputStream response = connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String line;
            bufferedReader = new BufferedReader(new InputStreamReader(response));
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            return new JSONObject(sb.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:com.intacct.ws.APISession.java

/**
  * You won't normally use this function, but if you just want to pass a fully constructed XML document
  * to Intacct, then use this function.//from w ww . ja v a2s .  c o m
  *
  * @param String body     a Valid XML string
  * @param String endPoint URL to post the XML to
  *
  * @throws exception
  * @return String the raw XML returned by Intacct
  */
public static String execute(String body, String endpoint) throws IOException {
    StringBuffer response = null;
    HttpURLConnection connection = null;

    // Create connection
    URL url = new URL(endpoint);
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");

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

    //Send request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    /*
     wr.writeBytes ("fName=" + URLEncoder.encode("???", "UTF-8") + body +
                "&lName=" + URLEncoder.encode("???", "UTF-8"));
    */

    wr.writeBytes("xmlrequest=" + URLEncoder.encode(body, "UTF-8"));
    wr.flush();
    wr.close();

    //Get Response   
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    String line;
    response = new StringBuffer();
    while ((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    rd.close();

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

    return response.toString();
}

From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java

/**
 * Finishes the addition of entries to this archive, without closing it.
 * /*from   ww w  . j  ava  2s . c om*/
 * @throws IOException if archive is already closed.
 */
public void finish() throws IOException {
    if (finished) {
        throw new IOException("This archive has already been finished");
    }
    finished = true;

    final long headerPosition = file.getFilePointer();

    final ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
    final DataOutputStream header = new DataOutputStream(headerBaos);

    writeHeader(header);
    header.flush();
    final byte[] headerBytes = headerBaos.toByteArray();
    file.write(headerBytes);

    final CRC32 crc32 = new CRC32();

    // signature header
    file.seek(0);
    file.write(SevenZFile.sevenZSignature);
    // version
    file.write(0);
    file.write(2);

    // start header
    final ByteArrayOutputStream startHeaderBaos = new ByteArrayOutputStream();
    final DataOutputStream startHeaderStream = new DataOutputStream(startHeaderBaos);
    startHeaderStream.writeLong(Long.reverseBytes(headerPosition - SevenZFile.SIGNATURE_HEADER_SIZE));
    startHeaderStream.writeLong(Long.reverseBytes(0xffffFFFFL & headerBytes.length));
    crc32.reset();
    crc32.update(headerBytes);
    startHeaderStream.writeInt(Integer.reverseBytes((int) crc32.getValue()));
    startHeaderStream.flush();
    final byte[] startHeaderBytes = startHeaderBaos.toByteArray();
    crc32.reset();
    crc32.update(startHeaderBytes);
    file.writeInt(Integer.reverseBytes((int) crc32.getValue()));
    file.write(startHeaderBytes);
}

From source file:com.almunt.jgcaap.systemupdater.MainActivity.java

public String getOS() {
    String outputString = "";
    try {/*  w  w w. jav  a2s  .c  o m*/
        Process su = Runtime.getRuntime().exec("sh");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
        InputStream inputStream = su.getInputStream();
        outputStream.writeBytes("getprop ro.cm.version" + "\nprint alemun@romania\n");
        outputStream.flush();
        outputString = "";
        while (outputString.endsWith("alemun@romania\n") == false) {
            if (inputStream.available() > 0) {
                byte[] dstInput = new byte[inputStream.available()];
                inputStream.read(dstInput);
                String additionalString = new String(dstInput);
                outputString += additionalString;
            }
        }
        outputString = "Current ROM: " + outputString.substring(0, outputString.length() - 15);
        su.destroy();
    } catch (IOException e) {
        currentRomcardView.setVisibility(CardView.GONE);
    }
    if (outputString.replaceAll("jgcaap", "").length() < outputString.length())
        while (outputString.endsWith("bacon") == false)
            outputString = outputString.substring(0, outputString.length() - 1);
    else
        currentRomcardView.setVisibility(CardView.GONE);
    return outputString;
}

From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java

private void writeFileAntiItems(final DataOutput header) throws IOException {
    boolean hasAntiItems = false;
    final BitSet antiItems = new BitSet(0);
    int antiItemCounter = 0;
    for (final SevenZArchiveEntry file1 : files) {
        if (!file1.hasStream()) {
            final boolean isAnti = file1.isAntiItem();
            antiItems.set(antiItemCounter++, isAnti);
            hasAntiItems |= isAnti;/*from   w w  w  .j  a  va  2 s .c  om*/
        }
    }
    if (hasAntiItems) {
        header.write(NID.kAnti);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final DataOutputStream out = new DataOutputStream(baos);
        writeBits(out, antiItems, antiItemCounter);
        out.flush();
        final byte[] contents = baos.toByteArray();
        writeUint64(header, contents.length);
        header.write(contents);
    }
}

From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java

private void writeFileEmptyStreams(final DataOutput header) throws IOException {
    boolean hasEmptyStreams = false;
    for (final SevenZArchiveEntry entry : files) {
        if (!entry.hasStream()) {
            hasEmptyStreams = true;/*www .j  av a  2  s.co m*/
            break;
        }
    }
    if (hasEmptyStreams) {
        header.write(NID.kEmptyStream);
        final BitSet emptyStreams = new BitSet(files.size());
        for (int i = 0; i < files.size(); i++) {
            emptyStreams.set(i, !files.get(i).hasStream());
        }
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final DataOutputStream out = new DataOutputStream(baos);
        writeBits(out, emptyStreams, files.size());
        out.flush();
        final byte[] contents = baos.toByteArray();
        writeUint64(header, contents.length);
        header.write(contents);
    }
}

From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java

private void writeFileEmptyFiles(final DataOutput header) throws IOException {
    boolean hasEmptyFiles = false;
    int emptyStreamCounter = 0;
    final BitSet emptyFiles = new BitSet(0);
    for (final SevenZArchiveEntry file1 : files) {
        if (!file1.hasStream()) {
            final boolean isDir = file1.isDirectory();
            emptyFiles.set(emptyStreamCounter++, !isDir);
            hasEmptyFiles |= !isDir;/*from  w w w  .ja  va2 s .  c om*/
        }
    }
    if (hasEmptyFiles) {
        header.write(NID.kEmptyFile);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final DataOutputStream out = new DataOutputStream(baos);
        writeBits(out, emptyFiles, emptyStreamCounter);
        out.flush();
        final byte[] contents = baos.toByteArray();
        writeUint64(header, contents.length);
        header.write(contents);
    }
}

From source file:edu.pdx.cecs.orcycle.UserFeedbackUploader.java

boolean uploadUserInfoV4() {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {//from w  ww.j a v a 2 s .  c om
        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        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("Cycleatl-Protocol-Version", "4");

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        JSONObject jsonUser;
        if (null != (jsonUser = getUserJSON())) {
            try {
                String deviceId = userId;

                dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n");
                dos.writeBytes(
                        fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n");
                dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n");
                dos.writeBytes(fieldSep);
                dos.flush();
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
                return false;
            } finally {
                dos.close();
            }
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // JSONObject responseData = new JSONObject(serverResponseMessage);
            Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 201 || serverResponseCode == 202) {
                // TODO: Record somehow that data was uploaded successfully
                result = true;
            }
        } else {
            result = false;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:com.pinterest.deployservice.events.EventSenderImpl.java

public void sendDeployEvent(String what, String tags, String data) throws Exception {
    JsonObject object = new JsonObject();
    object.addProperty("what", what);
    object.addProperty("tags", tags);
    object.addProperty("data", data);
    final String paramsToSend = object.toString();
    DataOutputStream output = null;
    HttpURLConnection connection = null;
    int retry = 0;
    while (retry < TOTAL_RETRY) {
        try {/*from w  ww . j  a va  2s  .  c o m*/
            URL requestUrl = new URL(this.URL);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setDoOutput(true);

            connection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setRequestMethod("POST");
            output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(paramsToSend);
            output.flush();
            output.close();
            String result = IOUtils.toString(connection.getInputStream(), "UTF-8").toLowerCase();
            LOG.info("Successfully send events to the statsboard: " + result);
            return;
        } catch (Exception e) {
            LOG.error("Failed to send event", e);
        } finally {
            IOUtils.closeQuietly(output);
            if (connection != null) {
                connection.disconnect();
            }
            retry++;
        }
    }
    throw new DeployInternalException("Failed to send event");
}

From source file:eu.eexcess.partnerwizard.webservice.WizardRESTService.java

public String cmdExecute(ArrayList<String> commands) {
    Process shell = null;/*w ww. ja  v  a 2s  .  co  m*/
    DataOutputStream out = null;
    BufferedReader in = null;
    StringBuilder processOutput = new StringBuilder();
    processOutput.append(new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()))
            .append("\n");
    try {
        shell = Runtime.getRuntime().exec("cmd");//su if needed
        out = new DataOutputStream(shell.getOutputStream());

        in = new BufferedReader(new InputStreamReader(shell.getInputStream()));

        // Executing commands
        for (String command : commands) {
            LOGGER.info("executing:\n" + command);
            out.writeBytes(command + "\n");
            out.flush();
        }

        out.writeBytes("exit\n");
        out.flush();
        String line;
        while ((line = in.readLine()) != null) {
            processOutput.append(line).append("\n");
        }

        //LOGGER.info("result:\n" + processOutput);
        processOutput.append(new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()))
                .append("\n");
        String output = processOutput.toString();
        shell.waitFor();
        LOGGER.info(processOutput.toString());
        LOGGER.info("finished!");
        return output;
    } catch (Exception e) {
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            // shell.destroy();
        } catch (Exception e) {
            // hopeless
        }
    }
    return "";
}