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.telesign.util.TeleSignRequest.java

/**
 * Creates and sends the REST request.//ww  w .ja va2s  . 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 queryDMS(String DMS_endpoint, String postObject, String cookie) {
    HttpURLConnection connectionDMS = null;
    try {/* w w  w . j a  v  a  2 s.  c  o  m*/

        String postObjectString = postObject;
        byte[] postObjectByte = postObjectString.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postObjectByte.length;
        URL DMS_Url = new URL(dms_URL + "/" + DMS_endpoint);

        // prepare header
        connectionDMS = (HttpURLConnection) DMS_Url.openConnection();
        connectionDMS.setDoOutput(true);
        connectionDMS.setDoInput(true);
        connectionDMS.setConnectTimeout(5000);
        connectionDMS.setReadTimeout(5000);
        connectionDMS.setRequestProperty("Content-Type", "application/json");
        connectionDMS.setRequestProperty("Accept", "application/json");
        connectionDMS.setRequestProperty("charset", "utf-8");
        connectionDMS.setRequestProperty("vitalAccessToken", cookie);
        connectionDMS.setRequestMethod("POST");
        connectionDMS.setRequestProperty("Content-Length", Integer.toString(postDataLength));

        DataOutputStream wr = new DataOutputStream(connectionDMS.getOutputStream());
        wr.write(postObjectByte);
        wr.flush();
        int HttpResult = connectionDMS.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            Object obj = new InputStreamReader(connectionDMS.getInputStream(), "utf-8");

            return obj.toString();

        } else {
            return null;
        }
    } catch (Exception e) {
        //logger.error(e.toString());
        //throw new ConnectionErrorException("Error in connection with DMSManager");
    } finally {
        if (connectionDMS != null) {
            connectionDMS.disconnect();
        }
    }
    return "";
}

From source file:com.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * // www. j  a  va 2  s .  co m
 * @param extraHeaders   Extra headers to include in the request
 * @param method   The HTTP Method to user
 * @param relativeUrl   The URL after .com (/me)
 * @param body   The body of the message
 * @return Output in the preferred data format
 * @throws IOException
 */
protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl,
        String body) throws IOException {

    if (body == null) {
        body = "";
    }

    // append .xml extension when XML data format enabled.
    if (dataFormat == DataFormat.XML) {
        logger.debug("Using XML extension on route");

        String queryString = "";
        int queryStringIndex = relativeUrl.indexOf('?');
        if (queryStringIndex != -1) {
            queryString = relativeUrl.substring(queryStringIndex);
            relativeUrl = relativeUrl.substring(0, queryStringIndex);
        }

        String compareUrl = relativeUrl.toLowerCase();

        if (!compareUrl.endsWith(".xml")) {
            relativeUrl += ".xml";
        }

        if (queryStringIndex != -1) {
            relativeUrl += queryString;
        }
    }

    final String fullUrl = API_DOMAIN + relativeUrl;

    if (logger.isDebugEnabled()) {
        logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body);
    }

    URL url = new URL(fullUrl);
    Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body);

    if (oauthHeaders == null) {
        throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods");
    }

    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            if (!oauthHeaders.containsKey(key)) {
                oauthHeaders.put(key, extraHeaders.get(key));
            } else {
                throw new RuntimeException("Extra headers can not include OAuth headers");
            }
        }
    }

    HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
    try {
        request.setRequestMethod(method.toString());

        Set<String> oauthHeaderKeys = oauthHeaders.keySet();
        for (String oauthHeaderKey : oauthHeaderKeys) {
            request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey));
        }

        request.addRequestProperty("User-Agent", getServiceIdentifier());

        if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) {
            if (dataFormat == DataFormat.XML) {
                request.setRequestProperty("Content-Type", "application/xml");
            } else {
                request.setRequestProperty("Content-Type", "application/json");
            }

            request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length));
            request.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(request.getOutputStream());
            try {
                out.writeBytes(body);
                out.flush();
            } finally {
                out.close();
            }
        }

        Response response = new Response();
        response.setMethod(method.toString());
        response.setUrl(url.toString());
        response.setStatusCode(request.getResponseCode());
        response.setStatusMessage(request.getResponseMessage());
        response.setHeaders(request.getHeaderFields());

        InputStream inputStream = null;
        if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) {
            inputStream = request.getInputStream();
        } else {
            inputStream = request.getErrorStream();
        }

        boolean isBinary = false;
        if (inputStream != null) {
            StringBuilder responseBody = new StringBuilder();

            String contentType = request.getContentType();
            if (contentType != null) {
                if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml")
                        && !contentType.startsWith("application/json")) { // assume binary
                    isBinary = true;
                    inputStream = new Base64InputStream(inputStream, true); // base64 encode
                }
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    responseBody.append(line);
                }
            } finally {
                bufferedReader.close();
            }

            response.setContentType(contentType);

            if (isBinary) {
                String content = responseBody.toString();
                if (content.length() == 0) {
                    response.setBinaryContent(new byte[0]);
                } else {
                    response.setBinaryContent(Base64.decodeBase64(responseBody.toString()));
                }
            } else {
                response.setContent(responseBody.toString());
            }
        }

        if (logger.isDebugEnabled()) {
            if (isBinary) {
                logger.debug("RESPONSE - binary response omitted");
            } else {
                logger.debug("RESPONSE - " + response.toString());
            }
        }

        return response;
    } finally {
        request.disconnect();
    }

}

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

public void FlashFile(final String filename) {
    final boolean[] mayBeContinued = { true };
    AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
    builder1.setTitle("Flashing Confirmation");
    builder1.setMessage(//from   w  w  w .jav  a2s .  c o  m
            "Are You sure you want to flash this file?\nIt will be added to the OpenRecoveryScript file and TWRP will automatically flash it without a warning!");
    builder1.setCancelable(true);
    builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            try {
                Process su = Runtime.getRuntime().exec("su");
                DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
                outputStream.writeBytes("cd /cache/recovery/\n");
                outputStream.flush();
                outputStream.writeBytes("rm openrecoveryscript\n");
                outputStream.flush();
                outputStream.writeBytes("echo install " + Environment.getExternalStorageDirectory()
                        + "/JgcaapUpdates/" + filename + ">openrecoveryscript\n");
                outputStream.flush();
                outputStream.writeBytes("exit\n");
                outputStream.flush();
                su.waitFor();
            } catch (IOException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
                mayBeContinued[0] = false;
            } catch (InterruptedException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
                mayBeContinued[0] = false;
            }
            if (mayBeContinued[0]) {
                RebootRecovery(true);
            }
        }
    });
    builder1.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });
    AlertDialog alert11 = builder1.create();
    alert11.show();
}

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  w  w w . j ava2  s  .  c  o  m

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

    return con.getInputStream();
}

From source file:com.otisbean.keyring.Ring.java

/**
 * Export data to the specified file.//from   w w w  .ja va  2  s .  co  m
 * 
 * @param outFile Path to the output file
 * @throws IOException
 * @throws GeneralSecurityException
 */
public void save(String outFile) throws IOException, GeneralSecurityException {
    log("save(" + outFile + ")");
    if (outFile.startsWith("http")) {
        URL url = new URL(outFile);
        URLConnection urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
        String message = "data=" + URLEncoder.encode(getExportData().toJSONString(), "UTF-8");
        dos.writeBytes(message);
        dos.flush();
        dos.close();

        // the server responds by saying 
        // "OK" or "ERROR: blah blah"

        BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        String s = br.readLine();
        if (!s.equals("OK")) {
            StringBuilder sb = new StringBuilder();
            sb.append("Failed to save to URL '");
            sb.append(url);
            sb.append("': ");
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            throw new IOException(sb.toString());
        }
        br.close();
    } else {
        Writer writer = getWriter(outFile);
        getExportData().writeJSONString(writer);
        closeWriter(writer, outFile);
    }
}

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   w  w w  . j  a  v  a  2  s  .c o 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.hadoopvietnam.cache.memcached.MemcachedCache.java

/**
 * Get the byte[] from a ArrayList&lt;Long&gt;.
 *
 * @param inListOfLongs the list of longs to convert
 * @return the byte[] representation of the ArrayList
 * @throws IOException thrown if any errors encountered
 *///  ww  w  .  j  av a  2  s.c  o  m
protected byte[] getBytesFromList(final List<Long> inListOfLongs) throws IOException {
    if (inListOfLongs == null) {
        return null;
    }

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bytes);
    byte[] toReturn = null;
    try {
        for (Long oneLong : inListOfLongs) {
            out.writeLong(oneLong);
            out.flush();
        }

        toReturn = bytes.toByteArray();
    } finally {
        out.close();
    }

    return toReturn;
}

From source file:HttpPOSTMIDlet.java

private String requestUsingGET(String URLString) throws IOException {
    HttpConnection hpc = null;/*from w w  w . j  av a 2  s . com*/
    DataInputStream dis = null;
    DataOutputStream dos = null;

    boolean newline = false;
    String content = "";
    try {
        hpc = (HttpConnection) Connector.open(defaultURL);
        hpc.setRequestMethod(HttpConnection.POST);
        hpc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
        hpc.setRequestProperty("Content-Language", "zh-tw");
        hpc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        hpc.setRequestProperty("Content-Length", String.valueOf(URLString.length()));

        dos = new DataOutputStream(hpc.openOutputStream());
        dos.write(URLString.getBytes());
        dos.flush();

        InputStreamReader xdis = new InputStreamReader(hpc.openInputStream());

        int character;
        while ((character = xdis.read()) != -1) {
            if ((char) character == '\\') {
                newline = true;
                continue;
            } else {
                if ((char) character == 'n' && newline) {
                    content += "\n";
                    newline = false;
                } else if (newline) {
                    content += "\\" + (char) character;
                    newline = false;
                } else {
                    content += (char) character;
                    newline = false;
                }
            }

        }
        if (hpc != null)
            hpc.close();
        if (dis != null)
            dis.close();
    } catch (IOException e2) {
    }

    return content;
}

From source file:com.dao.ShopThread.java

private boolean doPTShop() throws Exception {
    long startTime = System.currentTimeMillis();
    // loadCookie();
    boolean result = true;
    LogUtil.webPrintf("??...");
    String postParams = addPTDynamicParams();
    LogUtil.webPrintf("???");
    LogUtil.webPrintf("?...");
    HttpURLConnection loginConn = getHttpPostConn(this.ptshopurl);
    loginConn.setRequestProperty("Host", "danbao.5173.com");
    loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
    LogUtil.debugPrintf("?HEADER===" + loginConn.getRequestProperties());
    DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream());
    wr.writeBytes(postParams);//from w w w . j  av a 2 s  .  c  o m
    wr.flush();
    wr.close();
    int responseCode = loginConn.getResponseCode();
    LogUtil.debugPrintf("\nSending 'POST' request to URL : " + this.ptshopurl);
    LogUtil.debugPrintf("Post parameters : " + postParams);
    LogUtil.debugPrintf("Response Code : " + responseCode);
    Map<String, List<String>> header = loginConn.getHeaderFields();
    LogUtil.debugPrintf("??HEADER===" + header);
    List<String> cookie = header.get("Set-Cookie");
    if (cookie == null || cookie.size() == 0) {
        result = false;
        LogUtil.webPrintf("?!");
    } else {
        LogUtil.webPrintf("??!");
        LogUtil.debugPrintf("cookie====" + cookie);
        LogUtil.debugPrintf("Location :" + loginConn.getURL().toString());
        setCookies(cookie);
        LogUtil.webPrintf("?...");
        String payurl = getPayKey(loginConn, "db");
        LogUtil.webPrintf("??");
        if (payurl != null && !payurl.equals("")) {
            LogUtil.debugPrintf("?url:" + payurl);
            LogUtil.webPrintf("...");
            pay(payurl);
            LogUtil.webPrintf("?");
        } else {
            LogUtil.webPrintf("?");
            LogUtil.debugPrintf("?url");
        }
    }
    return result;
}