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.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse putWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;/*from  ww w .  j  av a 2  s.  c  o m*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String userName, String password)
        throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;/*from  www  .  j  a v a  2  s  .  c om*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            return new HttpsResponse(sb.toString(), conn.getResponseCode());
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
    }
    return null;
}

From source file:org.apache.hadoop.mapred.TestMiniMRWithDFS.java

public static TestResult launchWordCount(JobConf conf, Path inDir, Path outDir, String input, int numMaps,
        int numReduces) throws IOException {
    FileSystem inFs = inDir.getFileSystem(conf);
    FileSystem outFs = outDir.getFileSystem(conf);
    outFs.delete(outDir, true);/* w w w  . j ava2  s  . c  o  m*/
    if (!inFs.mkdirs(inDir)) {
        throw new IOException("Mkdirs failed to create " + inDir.toString());
    }
    {
        DataOutputStream file = inFs.create(new Path(inDir, "part-0"));
        file.writeBytes(input);
        file.close();
    }
    conf.setJobName("wordcount");
    conf.setInputFormat(TextInputFormat.class);

    // the keys are words (strings)
    conf.setOutputKeyClass(Text.class);
    // the values are counts (ints)
    conf.setOutputValueClass(IntWritable.class);

    conf.setMapperClass(WordCount.MapClass.class);
    conf.setCombinerClass(WordCount.Reduce.class);
    conf.setReducerClass(WordCount.Reduce.class);
    FileInputFormat.setInputPaths(conf, inDir);
    FileOutputFormat.setOutputPath(conf, outDir);
    conf.setNumMapTasks(numMaps);
    conf.setNumReduceTasks(numReduces);
    RunningJob job = JobClient.runJob(conf);
    return new TestResult(job, readOutput(outDir, conf));
}

From source file:org.apache.hadoop.mapred.TestChildsKillingOfSuspendTask.java

private static void createInput(Path inDir, Configuration conf) throws IOException {
    String input = "Hadoop is framework for data intensive distributed "
            + "applications.\n Hadoop enables applications " + "to work with thousands of nodes.";
    FileSystem fs = inDir.getFileSystem(conf);
    if (!fs.mkdirs(inDir)) {
        throw new IOException("Failed to create the input directory:" + inDir.toString());
    }/*from  ww  w  . j a  v  a 2s  . c o m*/
    fs.setPermission(inDir, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
    DataOutputStream file = fs.create(new Path(inDir, "data.txt"));
    int i = 0;
    while (i < 10) {
        file.writeBytes(input);
        i++;
    }
    file.close();
}

From source file:Main.java

public static int execRootCmdForExitCode(String[] cmds) {
    int result = -1;
    DataOutputStream dos = null;
    DataInputStream dis = null;/*from w  ww  .  j av a  2 s  .c om*/

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        for (String cmd : cmds) {
            Log.i("CmdUtils", cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
        }
        dos.writeBytes("exit\n");
        dos.flush();
        String line;
        while ((line = dis.readLine()) != null) {
            Log.d("result", line);
        }
        p.waitFor();
        result = p.exitValue();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:Main.java

public static String execRootCmd(String[] cmds) {
    String result = "";
    DataOutputStream dos = null;
    DataInputStream dis = null;//from  w  w  w  .  j  av  a2s. c o m

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        for (String cmd : cmds) {
            Log.i("CmdUtils", cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
        }
        dos.writeBytes("exit\n");
        dos.flush();
        String line;
        while ((line = dis.readLine()) != null) {
            Log.d("result", line);
            result += line;
        }
        p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:org.apache.hadoop.mapred.TestStreamingJobProcessTree.java

private static void createInput(Path inDir, Configuration conf) throws IOException {
    FileSystem fs = inDir.getFileSystem(conf);
    if (!fs.mkdirs(inDir)) {
        throw new IOException("Failed to create the input directory:" + inDir.toString());
    }//from  w ww .  j  av  a 2 s . c  o  m
    fs.setPermission(inDir, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
    DataOutputStream file = fs.create(new Path(inDir, "data.txt"));
    String input = "Process tree cleanup of Streaming job tasks.";
    file.writeBytes(input + "\n");
    file.close();
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

protected static void assembleMultipartFiles(DataOutputStream out, Map<String, String> vars,
        Map<String, File> files) throws IOException {
    for (String key : vars.keySet()) {
        out.writeBytes("--" + BOUNDARY + CRLF);
        out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + CRLF);
        out.writeBytes(CRLF);//from  w  w  w .ja v a  2  s  .c  o m
        out.writeBytes(vars.get(key) + CRLF);
    }

    for (String key : files.keySet()) {
        File f = files.get(key);
        out.writeBytes("--" + BOUNDARY + CRLF);
        out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + f.getName() + "\""
                + CRLF);
        out.writeBytes("Content-Type: application/octet-stream" + CRLF);
        out.writeBytes(CRLF);

        // write file
        int maxBufferSize = 1024;
        FileInputStream fin = new FileInputStream(f);
        int bytesAvailable = fin.available();
        int bufferSize = Math.min(maxBufferSize, bytesAvailable);
        byte[] buffer = new byte[bufferSize];

        int bytesRead = fin.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            out.write(buffer, 0, bufferSize);
            bytesAvailable = fin.available();
            bufferSize = Math.min(maxBufferSize, bytesAvailable);
            bytesRead = fin.read(buffer, 0, bufferSize);
        }
    }
    out.writeBytes(CRLF);
    out.writeBytes("--" + BOUNDARY + "--" + CRLF);
    out.writeBytes(CRLF);
}

From source file:Main.java

public static BufferedReader shellExecute(String[] commands, boolean requireRoot) {
    Process shell = null;//  w  w  w  .ja  v a2  s. c  o  m
    DataOutputStream out = null;
    BufferedReader reader = null;
    String startCommand = requireRoot ? "su" : "sh";
    try {
        shell = Runtime.getRuntime().exec(startCommand);
        out = new DataOutputStream(shell.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
        for (String command : commands) {
            out.writeBytes(command + "\n");
            out.flush();
        }
        out.writeBytes("exit\n");
        out.flush();
        shell.waitFor();
    } catch (Exception e) {
        Log.e(TAG, "ShellRoot#shExecute() finished with error", e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {

        }
    }
    return reader;
}

From source file:export.FormCrawler.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 (int i = 0; i < parts.length; i++) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + parts[i].name + "\"");
        if (parts[i].filename != null)
            outputStream.writeBytes("; filename=\"" + parts[i].filename + "\"");
        outputStream.writeBytes(lineEnd);

        if (parts[i].contentType != null)
            outputStream.writeBytes("Content-Type: " + parts[i].contentType + lineEnd);
        if (parts[i].contentTransferEncoding != null)
            outputStream.writeBytes("Content-Transfer-Encoding: " + parts[i].contentTransferEncoding + lineEnd);
        outputStream.writeBytes(lineEnd);
        parts[i].value.write(outputStream);
        outputStream.writeBytes(lineEnd);
    }//from w w  w.  j  a v  a 2s. c  o m
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    outputStream.flush();
    outputStream.close();
}