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.apache.hadoop.mapred.TestSpecialCharactersInOutputPath.java

public static boolean launchJob(String fileSys, String jobTracker, JobConf conf, int numMaps, int numReduces)
        throws IOException {

    final Path inDir = new Path("/testing/input");
    final Path outDir = new Path("/testing/output");
    FileSystem fs = FileSystem.getNamed(fileSys, conf);
    fs.delete(outDir, true);/* w  w w. j  a v  a2s  .c  om*/
    if (!fs.mkdirs(inDir)) {
        LOG.warn("Can't create " + inDir);
        return false;
    }
    // generate an input file
    DataOutputStream file = fs.create(new Path(inDir, "part-0"));
    file.writeBytes("foo foo2 foo3");
    file.close();

    // use WordCount example
    FileSystem.setDefaultUri(conf, fileSys);
    conf.set("mapred.job.tracker", jobTracker);
    conf.setJobName("foo");

    conf.setInputFormat(TextInputFormat.class);
    conf.setOutputFormat(SpecialTextOutputFormat.class);
    conf.setOutputKeyClass(LongWritable.class);
    conf.setOutputValueClass(Text.class);
    conf.setMapperClass(IdentityMapper.class);
    conf.setReducerClass(IdentityReducer.class);
    FileInputFormat.setInputPaths(conf, inDir);
    FileOutputFormat.setOutputPath(conf, outDir);
    conf.setNumMapTasks(numMaps);
    conf.setNumReduceTasks(numReduces);

    // run job and wait for completion
    RunningJob runningJob = JobClient.runJob(conf);

    try {
        assertTrue(runningJob.isComplete());
        assertTrue(runningJob.isSuccessful());
        assertTrue("Output folder not found!", fs.exists(new Path("/testing/output/" + OUTPUT_FILENAME)));
    } catch (NullPointerException npe) {
        // This NPE should no more happens
        fail("A NPE should not have happened.");
    }

    // return job result
    LOG.info("job is complete: " + runningJob.isSuccessful());
    return (runningJob.isSuccessful());
}

From source file:com.zf.util.Post_NetNew.java

/**
 * ?/* w w  w  .j av a2s .com*/
 * 
 * @param pams
 * @param ip
 * @param port
 * @return
 * @throws Exception
 */
public static String pn(Map<String, String> pams, String ip, int port) throws Exception {
    if (null == pams) {
        return "";
    }
    InetSocketAddress addr = new InetSocketAddress(ip, port);
    Proxy proxy = new Proxy(Type.HTTP, addr);
    String strtmp = "url";
    URL url = new URL(pams.get(strtmp));
    pams.remove(strtmp);
    strtmp = "body";
    String body = pams.get(strtmp);
    pams.remove(strtmp);
    strtmp = "POST";
    if (StringUtils.isEmpty(body))
        strtmp = "GET";
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy);
    httpConn.setConnectTimeout(30000);
    httpConn.setReadTimeout(30000);
    httpConn.setUseCaches(false);
    httpConn.setRequestMethod(strtmp);
    for (String pam : pams.keySet()) {
        httpConn.setRequestProperty(pam, pams.get(pam));
    }
    if ("POST".equals(strtmp)) {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(body);
        dos.flush();
    }
    int resultCode = httpConn.getResponseCode();
    StringBuilder sb = new StringBuilder();
    sb.append(resultCode).append("\n");
    String readLine;
    InputStream stream;
    try {
        stream = httpConn.getInputStream();
    } catch (Exception ignored) {
        stream = httpConn.getErrorStream();
    }
    try {
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
    } catch (Exception ignored) {
    }

    return sb.toString();
}

From source file:Main.java

public static String runAsRoot(String[] cmds) throws Exception {
    Process p = Runtime.getRuntime().exec("su");
    DataOutputStream os = new DataOutputStream(p.getOutputStream());
    InputStream is = p.getInputStream();
    String result = null;// www .  j  a  va 2s.c  o  m
    for (String tmpCmd : cmds) {
        os.writeBytes(tmpCmd + "\n");
        int readed = 0;
        byte[] buff = new byte[4096];
        while (is.available() <= 0) {
            try {
                Thread.sleep(5000);
            } catch (Exception ex) {
            }
        }

        while (is.available() > 0) {
            readed = is.read(buff);
            if (readed <= 0)
                break;
            String seg = new String(buff, 0, readed);
            result = seg; //result is a string to show in textview
        }
    }
    os.writeBytes("exit\n");
    os.flush();
    return result;
}

From source file:Main.java

public static int execRootCmdSilent(String cmd) {
    try {/*  ww  w  .java 2  s.c o  m*/
        Process p = Runtime.getRuntime().exec("su ");
        Object obj = p.getOutputStream();
        DataOutputStream dOutStream = new DataOutputStream((OutputStream) obj);
        String str = String.valueOf(cmd);
        obj = str + "\n";
        dOutStream.writeBytes((String) obj);
        dOutStream.flush();
        dOutStream.writeBytes("exit\n");
        dOutStream.flush();
        p.waitFor();
        int result = p.exitValue();
        return (Integer) result;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:Main.java

public static void killProcess(int pid) {
    Process sh = null;//from   ww w .  jav  a 2s  .co m
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        final String Command = "kill -9 " + pid + "\n";
        os.writeBytes(Command);
        os.flush();
        sh.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void forceStopAPK(String pkgName) {
    Process sh = null;/*from w ww.j  a va 2 s. c o m*/
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        final String Command = "am force-stop" + pkgName;
        os.writeBytes(Command);
        os.flush();
        sh.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void execCommand(String paramString) {
    try {/*from w  ww  .ja v a 2s  . co m*/
        String[] arrayOfString = new String[1];
        arrayOfString[0] = paramString;
        DataOutputStream localDataOutputStream = new DataOutputStream(
                Runtime.getRuntime().exec("su").getOutputStream());
        for (int i = 0;; i++) {
            if (i >= 1) {
                localDataOutputStream.writeBytes("exit\n");
                localDataOutputStream.flush();
                localDataOutputStream.wait();
                return;
            }
            localDataOutputStream.writeBytes(arrayOfString[i] + "\n");
            localDataOutputStream.flush();
        }
    } catch (Exception localException) {
    }
}

From source file:com.android.dialer.omni.PlaceUtil.java

/**
 * Executes a post request and return a JSON object
 * @param url The API URL//from  w  w w .ja va 2 s . c o m
 * @param data The data to post in POST field
 * @return the JSON object
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject postJsonRequest(String url, String postData) throws IOException, JSONException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");

    if (DEBUG)
        Log.d(TAG, "Posting: " + postData + " to " + url);

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(postData);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JSONObject json = new JSONObject(response.toString());
    return json;
}

From source file:Main.java

public static String executeHttpsPost(String url, String data, InputStream key) {
    HttpsURLConnection localHttpsURLConnection = null;
    try {//from  w  w w.  j  av  a2s.co m
        URL localURL = new URL(url);
        localHttpsURLConnection = (HttpsURLConnection) localURL.openConnection();
        localHttpsURLConnection.setRequestMethod("POST");
        localHttpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

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

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

        localHttpsURLConnection.connect();
        Certificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates();

        byte[] arrayOfByte1 = new byte[294];
        DataInputStream localDataInputStream = new DataInputStream(key);
        localDataInputStream.readFully(arrayOfByte1);
        localDataInputStream.close();

        Certificate localCertificate = arrayOfCertificate[0];
        PublicKey localPublicKey = localCertificate.getPublicKey();
        byte[] arrayOfByte2 = localPublicKey.getEncoded();

        for (int i = 0; i < arrayOfByte2.length; i++) {
            if (arrayOfByte2[i] != arrayOfByte1[i])
                throw new RuntimeException("Public key mismatch");
        }

        DataOutputStream localDataOutputStream = new DataOutputStream(
                localHttpsURLConnection.getOutputStream());
        localDataOutputStream.writeBytes(data);
        localDataOutputStream.flush();
        localDataOutputStream.close();

        InputStream localInputStream = localHttpsURLConnection.getInputStream();
        BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));

        StringBuffer localStringBuffer = new StringBuffer();
        String str1;
        while ((str1 = localBufferedReader.readLine()) != null) {
            localStringBuffer.append(str1);
            localStringBuffer.append('\r');
        }
        localBufferedReader.close();

        return localStringBuffer.toString();
    } catch (Exception localException) {
        byte[] arrayOfByte1;
        localException.printStackTrace();
        return null;
    } finally {
        if (localHttpsURLConnection != null)
            localHttpsURLConnection.disconnect();
    }
}

From source file:Main.java

public static void killProcesses(Context context, int pid, String processName) {

    String cmd = "kill -9 " + pid;
    String Command = "am force-stop " + processName + "\n";
    Process sh = null;/*from w  w  w  .j ava2 s .  c o m*/
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        os.writeBytes(Command + "\n");
        os.writeBytes(cmd + "\n");
        os.writeBytes("exit\n");
        os.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        sh.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // AbLogUtil.d(AbAppUtil.class, "#kill -9 "+pid);
    Log.i("AppUtil", processName);
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    String packageName = null;
    try {
        if (processName.indexOf(":") == -1) {
            packageName = processName;
        } else {
            packageName = processName.split(":")[0];
        }

        activityManager.killBackgroundProcesses(packageName);

        //
        Method forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage",
                String.class);
        forceStopPackage.setAccessible(true);
        forceStopPackage.invoke(activityManager, packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }

}