Example usage for java.io DataOutputStream writeBytes

List of usage examples for java.io DataOutputStream writeBytes

Introduction

In this page you can find the example usage for java.io DataOutputStream writeBytes.

Prototype

public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes out the string to the underlying output stream as a sequence of bytes.

Usage

From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java

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

    try {/*from w  w  w  .  ja  va  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 doPostHttp(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("") && !your_session_id.equals("none")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }/*from   ww w .  j  ava 2s  .  c o  m*/
    con.setRequestProperty("Content-Type", contentType);
    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("appmSamlSsoTokenId")) {
            return con.getHeaderField("Set-Cookie").split(";")[0].split("=")[1];
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie").split("=")[1].split(";")[0];
        } else {
            return response.toString();
        }
    }
    return null;
}

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   w w w. ja  v  a 2s  . com
    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);/*  ww w  .j  av a  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.esri.geoevent.test.tools.GetMapServiceCountRunnable.java

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

    try {//w w  w  .j av  a2  s . co  m
        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.snaplogic.snaps.lunex.RequestProcessor.java

public String execute(RequestBuilder rBuilder) throws MalformedURLException, IOException {
    try {/*from w ww.j a v  a2  s.c o  m*/
        URL api_url = new URL(rBuilder.getURL());
        HttpURLConnection httpUrlConnection = (HttpURLConnection) api_url.openConnection();
        httpUrlConnection.setRequestMethod(rBuilder.getMethod().toString());
        httpUrlConnection.setDoInput(true);
        httpUrlConnection.setDoOutput(true);
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            rBuilder.getHeaders().add(Pair.of(CONTENT_LENGTH, rBuilder.getRequestBodyLenght()));
        }
        for (Pair<String, String> header : rBuilder.getHeaders()) {
            if (!StringUtils.isEmpty(header.getKey()) && !StringUtils.isEmpty(header.getValue())) {
                httpUrlConnection.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        log.debug(String.format(LUNEX_HTTP_INFO, rBuilder.getSnapType(), rBuilder.getURL(),
                httpUrlConnection.getRequestProperties().toString()));
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            String paramsJson = null;
            if (!StringUtils.isEmpty(paramsJson = rBuilder.getRequestBody())) {
                DataOutputStream cgiInput = new DataOutputStream(httpUrlConnection.getOutputStream());
                log.debug(String.format(LUNEX_HTTP_REQ_INFO, paramsJson));
                cgiInput.writeBytes(paramsJson);
                cgiInput.flush();
                IOUtils.closeQuietly(cgiInput);
            }
        }

        List<String> input = null;
        StringBuilder response = new StringBuilder();
        try (InputStream iStream = httpUrlConnection.getInputStream()) {
            input = IOUtils.readLines(iStream);
        } catch (IOException ioe) {
            log.warn(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
            try (InputStream eStream = httpUrlConnection.getErrorStream()) {
                if (eStream != null) {
                    input = IOUtils.readLines(eStream);
                } else {
                    response.append(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
                }
            } catch (IOException ioe1) {
                log.warn(String.format(INPUT_STREAM_ERROR, ioe1.getMessage()));
            }
        }
        statusCode = httpUrlConnection.getResponseCode();
        log.debug(String.format(HTTP_STATUS, statusCode));
        if (input != null && !input.isEmpty()) {
            for (String line : input) {
                response.append(line);
            }
        }
        return formatResponse(response, rBuilder);
    } catch (MalformedURLException me) {
        log.error(me.getMessage(), me);
        throw me;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw ioe;
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw ex;
    }
}

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

private void sendMapping(String mapping)
/*     */ {//from w w  w.j a v a 2  s .  c om
    /* 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.shubhangrathore.xposed.xhover.MainActivity.java

/**
 * Restarts SystemUI. Requires SuperUser privilege.
 *
 * @return boolean true if successful, else false.
 *//* w w w .j a  v a2  s.  com*/
private boolean restartSystemUi() {
    boolean mSuccessful;
    try {
        Process mProcess = Runtime.getRuntime().exec("su");
        DataOutputStream mDataOutputStream = new DataOutputStream(mProcess.getOutputStream());
        mDataOutputStream.writeBytes("pkill com.android.systemui \n");
        mDataOutputStream.writeBytes("exit\n");
        mDataOutputStream.flush();
        // We wait for the command to be completed
        // before moving forward. This ensures that the method
        // returns only after all the commands' execution is complete.
        mProcess.waitFor();

        if (mProcess.exitValue() == 1) {
            // If control is here, that means the sub process has returned
            // an unsuccessful exit code.
            // Most probably, SuperUser permission was denied
            Log.e(TAG, "Utilities: SuperUser permission denied. Unable to restart SystemUI.");
            mSuccessful = false;
        } else {
            // SuperUser permission granted
            Log.i(TAG, "Utilities: SuperUser permission granted. SystemUI restarted.");
            mSuccessful = true;
        }
    } catch (IOException e) {
        Log.e(TAG, "restartSystemUI: I/O exception");
        mSuccessful = false;
    } catch (InterruptedException e) {
        Log.e(TAG, "restartSystemUI: InterruptedException exception");
        mSuccessful = false;
    }
    return mSuccessful;
}

From source file:org.coltram.nsd.bonjour.LocalExposedBonjourService.java

public void updateEvent(String eventName, String eventValue) {
    // get the event variable
    log.fine("zc ev update " + eventName + "=" + eventValue);
    EventVariable cbev = null;/*from   www  . j a  va 2s  . c  o  m*/
    for (EventVariable c : eventVariables) {
        if (eventName.equals(c.getEventName())) {
            cbev = c;
            break;
        }
    }
    if (cbev == null) {
        // wrong event name
        log.severe("wrong event name for this service: " + eventName);
        throw new RuntimeException("wrong event name for this service: " + eventName);
    }
    // check if the value changed really
    if (!eventValue.equals(cbev.getEventValue())) {
        for (EventSubscription cbes : subscriptions) {
            if (eventName.equals(cbes.getEventName())) {
                // this is called by the local bonjour service that is updating an event
                // we need to cmmunicate that to the subscribing atom (not a service)
                try {
                    // if is local
                    if (LocalHost.isLocal(cbes.getAddress())) {
                        log.fine("updateEvent Bonjour local " + eventName);
                        JSONObject object = new JSONObject();
                        object.put("purpose", "updateEvent");
                        object.put("eventName", eventName);
                        object.put("eventValue", eventValue);
                        object.put("callback", cbes.getCallback());
                        //object.put("originAtom", cbes.getOriginAtom());
                        topManager.getConnectionManager().getConnection(cbes.getOriginAtom())
                                .send(object.toString());
                    } else {
                        // send update to this listener
                        log.fine("updateEvent Bonjour remote " + eventName);
                        Socket socket = cbes.getSocket();
                        JSONObject object = new JSONObject();
                        object.put("purpose", "updateEvent");
                        object.put("eventName", eventName);
                        object.put("eventValue", eventValue);
                        object.put("callback", cbes.getCallback());
                        //object.put("originAtom", cbes.getOriginAtom());
                        DataOutputStream dos = cbes.getSocketDOS();
                        dos.writeBytes(object.toString() + "\n");
                        dos.flush();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // finally, update the event value in the event variable
        cbev.setEventValue(eventValue);
    }
}

From source file:com.nks.nksmod.otaupdater.DownloadsActivity.java

private void flashFiles(String[] files, boolean backup, boolean wipeCache, boolean wipeData) {
    try {//  w  ww .  ja  v a 2  s. c  om
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        os.writeBytes("echo 'NKS MOD Updater'\n");
        os.writeBytes("mkdir -p /cache/recovery/\n");
        os.writeBytes("rm -rf /cache/recovery/command\n");
        os.writeBytes("rm -rf /cache/recovery/extendedcommand\n");
        os.writeBytes("rm -rf /cache/recovery/update.zip\n");
        os.writeBytes("rm -rf /cache/recovery/nksmod.zip\n");
        os.writeBytes("echo 'boot-recovery' >> /cache/recovery/command\n");

        if (backup) {
            os.writeBytes("echo '--nandroid' >> /cache/recovery/command\n");
        }
        if (wipeData) {
            /* os.writeBytes("echo '--wipe_data' >> /cache/recovery/command\n"); */
        }
        if (wipeCache) {
            /* os.writeBytes("echo '--wipe_cache' >> /cache/recovery/command\n"); */
        }

        for (String file : files) {
            os.writeBytes("cp " + file + " /cache/recovery/nksmod.zip\n");
            os.writeBytes("echo '--update_package=/cache/recovery/nksmod.zip' >> /cache/recovery/command\n");
        }

        String rebootCmd = PropUtils.getRebootCmd();
        if (!rebootCmd.equals("$$NULL$$")) {
            os.writeBytes("sync\n");
            if (rebootCmd.endsWith(".sh")) {
                os.writeBytes("sh " + rebootCmd + "\n");
            } else {
                os.writeBytes(rebootCmd + "\n");
            }
        }

        os.writeBytes("sync\n");
        os.writeBytes("exit\n");
        os.flush();
        p.waitFor();
        ((PowerManager) getSystemService(POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        e.printStackTrace();
    }
}