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:org.runnerup.export.util.SyncHelper.java

public static void postMulti(HttpURLConnection conn, Part<?> parts[]) throws IOException {
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
    for (Part<?> part : parts) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + part.getName() + "\"");
        if (part.getFilename() != null)
            outputStream.writeBytes("; filename=\"" + part.getFilename() + "\"");
        outputStream.writeBytes(lineEnd);

        if (part.getContentType() != null)
            outputStream.writeBytes("Content-Type: " + part.getContentType() + lineEnd);
        if (part.getContentTransferEncoding() != null)
            outputStream/*from  w ww .j a v a  2s  .c  o  m*/
                    .writeBytes("Content-Transfer-Encoding: " + part.getContentTransferEncoding() + lineEnd);
        outputStream.writeBytes(lineEnd);
        part.getValue().write(outputStream);
        outputStream.writeBytes(lineEnd);
    }
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    outputStream.flush();
    outputStream.close();
}

From source file:Main.java

public static String getSuVersion() {
    Process process = null;/*from ww  w. j a  v a2s .com*/
    String inLine = null;

    try {
        process = Runtime.getRuntime().exec("sh");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        BufferedReader is = new BufferedReader(
                new InputStreamReader(new DataInputStream(process.getInputStream())), 64);
        os.writeBytes("su -v\n");

        // We have to hold up the thread to make sure that we're ready to read
        // the stream, using increments of 5ms makes it return as quick as
        // possible, and limiting to 1000ms makes sure that it doesn't hang for
        // too long if there's a problem.
        for (int i = 0; i < 400; i++) {
            if (is.ready()) {
                break;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                Log.w(TAG, "Sleep timer got interrupted...");
            }
        }
        if (is.ready()) {
            inLine = is.readLine();
            if (inLine != null) {
                return inLine;
            }
        } else {
            os.writeBytes("exit\n");
        }
    } catch (IOException e) {
        Log.e(TAG, "Problems reading current version.", e);
        return null;
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    return null;
}

From source file:Main.java

private static boolean installOrUninstallApk(String apkPath, String installOruninstall, String rOrP) {
    Process process = null;//from  www. j a  v  a 2  s. c om
    DataOutputStream os = null;
    String command = null;
    try {
        process = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(process.getOutputStream());
        command = "pm " + installOruninstall + " " + rOrP + " " + apkPath + " \n";
        os.writeBytes(command);
        os.flush();
        os.close();
        process.waitFor();
        process.destroy();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.amazon.pay.impl.Util.java

/**
 * This method uses HttpURLConnection instance to make requests.
 *
 * @param method The HTTP method (GET,POST,PUT,etc.).
 * @param url The URL//from w  w  w  .ja v a  2s.  c om
 * @param urlParameters URL Parameters
 * @param headers Header key-value pairs
 * @return ResponseData
 * @throws IOException
 */
public static ResponseData httpSendRequest(String method, String url, String urlParameters,
        Map<String, String> headers) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    if (headers != null && !headers.isEmpty()) {
        for (String key : headers.keySet()) {
            con.setRequestProperty(key, headers.get(key));
        }
    }
    con.setDoOutput(true);
    con.setRequestMethod(method);
    if (urlParameters != null) {
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }
    int responseCode = con.getResponseCode();

    BufferedReader in;
    if (responseCode != 200) {
        in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
    } else {
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine).append(LINE_SEPARATOR);
    }
    in.close();
    return new ResponseData(responseCode, response.toString());
}

From source file:och.util.NetUtil.java

public static String invokePost(HttpURLConnection conn, String postBody) throws IOException {

    try {// w  w w . j a va2s.co  m

        if (Util.isEmpty(postBody)) {

            conn.setDoOutput(false);

        } else {

            // Send post request
            conn.setDoOutput(true);

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

        int code = conn.getResponseCode();
        //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
        if (code == -1) {
            throw new IllegalStateException("NetUtil: conn.getResponseCode() return -1");
        }

        InputStream is = new BufferedInputStream(conn.getInputStream());
        String enc = conn.getHeaderField("Content-Encoding");
        if (enc != null && enc.equalsIgnoreCase("gzip")) {
            is = new GZIPInputStream(is);
        }
        String response = StreamUtil.streamToStr(is);
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:Main.java

public static int getSuVersionCode() {
    Process process = null;/*from w  ww .  j  ava  2s  .  co  m*/
    String inLine = null;

    try {
        process = Runtime.getRuntime().exec("sh");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        BufferedReader is = new BufferedReader(
                new InputStreamReader(new DataInputStream(process.getInputStream())), 64);
        os.writeBytes("su -v\n");

        // We have to hold up the thread to make sure that we're ready to read
        // the stream, using increments of 5ms makes it return as quick as
        // possible, and limiting to 1000ms makes sure that it doesn't hang for
        // too long if there's a problem.
        for (int i = 0; i < 400; i++) {
            if (is.ready()) {
                break;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                Log.w(TAG, "Sleep timer got interrupted...");
            }
        }
        if (is.ready()) {
            inLine = is.readLine();
            if (inLine != null && Integer.parseInt(inLine.substring(0, 1)) > 2) {
                inLine = null;
                os.writeBytes("su -V\n");
                inLine = is.readLine();
                if (inLine != null) {
                    return Integer.parseInt(inLine);
                }
            } else {
                return 0;
            }
        } else {
            os.writeBytes("exit\n");
        }
    } catch (IOException e) {
        Log.e(TAG, "Problems reading current version.", e);
        return 0;
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return 0;
}

From source file:Main.java

public static String execRootCmd(String cmd) {
    String result = "result : ";
    try {/*from  ww w  .java 2s  .c  o m*/
        Process p = Runtime.getRuntime().exec("su ");
        OutputStream outStream = p.getOutputStream();
        DataOutputStream dOutStream = new DataOutputStream(outStream);
        InputStream inStream = p.getInputStream();
        DataInputStream dInStream = new DataInputStream(inStream);
        String str1 = String.valueOf(cmd);
        String str2 = str1 + "\n";
        dOutStream.writeBytes(str2);
        dOutStream.flush();
        String str3 = null;
        String line = "";
        while ((line = dInStream.readLine()) != null) {
            Log.d("result", str3);
            str3 += line;
        }
        dOutStream.writeBytes("exit\n");
        dOutStream.flush();
        p.waitFor();
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        return result;
    }
}

From source file:com.ibm.mobilefirst.mobileedge.utils.RequestUtils.java

public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData,
        List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException {

    URL url = new URL("https://medge.mybluemix.net/alg/train");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(5000);// w  ww.  j a v  a 2s  . c o  m
    conn.setConnectTimeout(10000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

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

    JSONObject jsonToSend = createTrainBodyJSON(name, uuid, accelerometerData, gyroscopeData);

    OutputStream outputStream = conn.getOutputStream();
    DataOutputStream wr = new DataOutputStream(outputStream);
    wr.writeBytes(jsonToSend.toString());
    wr.flush();
    wr.close();

    outputStream.close();

    String response = "";

    int responseCode = conn.getResponseCode();

    //Log.e("BBB2","" + responseCode);

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
    } else {
        response = "{}";
    }

    handleResponse(response, requestResult);
}

From source file:org.apache.hadoop.mapred.pipes.TestPipes.java

/**
 * Run a map/reduce word count that does all of the map input and reduce
 * output directly rather than sending it back up to Java.
 * @param mr The mini mr cluster// ww  w  .j a  v a2s .c o  m
 * @param dfs the dfs cluster
 * @param program the program to run
 * @throws IOException
 */
static void runNonPipedProgram(MiniMRCluster mr, MiniDFSCluster dfs, Path program, JobConf conf)
        throws IOException {
    JobConf job;
    if (conf == null) {
        job = mr.createJobConf();
    } else {
        job = new JobConf(conf);
    }

    job.setInputFormat(WordCountInputFormat.class);
    FileSystem local = FileSystem.getLocal(job);
    Path testDir = new Path("file:" + System.getProperty("test.build.data"), "pipes");
    Path inDir = new Path(testDir, "input");
    nonPipedOutDir = new Path(testDir, "output");
    Path wordExec = new Path("testing/bin/application");
    Path jobXml = new Path(testDir, "job.xml");
    {
        FileSystem fs = dfs.getFileSystem();
        fs.delete(wordExec.getParent(), true);
        fs.copyFromLocalFile(program, wordExec);
    }
    DataOutputStream out = local.create(new Path(inDir, "part0"));
    out.writeBytes("i am a silly test\n");
    out.writeBytes("you are silly\n");
    out.writeBytes("i am a cat test\n");
    out.writeBytes("you is silly\n");
    out.writeBytes("i am a billy test\n");
    out.writeBytes("hello are silly\n");
    out.close();
    out = local.create(new Path(inDir, "part1"));
    out.writeBytes("mall world things drink java\n");
    out.writeBytes("hall silly cats drink java\n");
    out.writeBytes("all dogs bow wow\n");
    out.writeBytes("hello drink java\n");
    local.delete(nonPipedOutDir, true);
    local.mkdirs(nonPipedOutDir, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
    out.close();
    out = local.create(jobXml);
    job.writeXml(out);
    out.close();
    System.err.println("About to run: Submitter -conf " + jobXml + " -input " + inDir + " -output "
            + nonPipedOutDir + " -program " + dfs.getFileSystem().makeQualified(wordExec));
    try {
        int ret = ToolRunner.run(new Submitter(),
                new String[] { "-conf", jobXml.toString(), "-input", inDir.toString(), "-output",
                        nonPipedOutDir.toString(), "-program",
                        dfs.getFileSystem().makeQualified(wordExec).toString(), "-reduces", "2" });
        assertEquals(0, ret);
    } catch (Exception e) {
        assertTrue("got exception: " + StringUtils.stringifyException(e), false);
    }
}

From source file:com.clearcenter.mobile_demo.mdRest.java

static public String Login(String host, String username, String password, String token) throws JSONException {
    if (password == null)
        Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username);
    else/*www  .  j  av a2  s  . c  o m*/
        Log.i(TAG, "Login by password, host: " + host + ", username: " + username);

    try {
        URL url = new URL("https://" + host + URL_LOGIN);

        HttpsURLConnection http = CreateConnection(url);

        if (password != null) {
            // Setup HTTPS POST request
            String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password="
                    + URLEncoder.encode(password, "UTF-8") + "&submit=submit";

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length));

            // Write request
            DataOutputStream outputStream = new DataOutputStream(http.getOutputStream());
            outputStream.writeBytes(urlParams);
            outputStream.flush();
            outputStream.close();
        } else {
            http.setRequestMethod("GET");
            http.setRequestProperty("Cookie", token);
        }

        final StringBuffer response = ProcessRequest(http);

        // Process response
        JSONObject json_data = null;
        try {
            Log.i(TAG, "response: " + response.toString());
            json_data = new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return "";
        }
        if (json_data.has("result")) {
            final String cookie = http.getHeaderField("Set-Cookie");
            Integer result = RESULT_UNKNOWN;
            try {
                result = Integer.valueOf(json_data.getString("result"));
            } catch (NumberFormatException e) {
            }

            Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie);

            if (result == RESULT_SUCCESS) {
                if (cookie != null)
                    return cookie;
                else
                    return token;
            }

            // All other results are failures...
            return "";
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
    }

    Log.i(TAG, "Malformed result");
    return "";
}