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:ro.fortsoft.matilda.util.RecaptchaUtils.java

public static boolean verify(String recaptchaResponse, String secret) {
    if (StringUtils.isNullOrEmpty(recaptchaResponse)) {
        return false;
    }//  ww  w  . j ava  2s. c  om

    boolean result = false;
    try {
        URL url = new URL("https://www.google.com/recaptcha/api/siteverify");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // add request header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String postParams = "secret=" + secret + "&response=" + recaptchaResponse;
        //            log.debug("Post parameters '{}'", postParams);

        // send post request
        connection.setDoOutput(true);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(postParams);
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        log.debug("Response code '{}'", responseCode);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // print result
        log.debug("Response '{}'", response.toString());

        // parse JSON response and return 'success' value
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(response.toString());
        JsonNode nameNode = rootNode.path("success");

        result = nameNode.asBoolean();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return result;
}

From source file:Main.java

public static boolean isRoot() {
    Process process = null;/*w w  w.  j  av a2 s  .c  om*/
    DataOutputStream dos = null;
    try {
        process = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(process.getOutputStream());
        dos.writeBytes("exit\n");
        dos.flush();
        int exitValue = process.waitFor();
        if (exitValue == 0) {
            return true;
        }
    } catch (IOException e) {

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
            }
        }
    }
    return false;
}

From source file:Main.java

public static int execRootCmdSilent(String cmd) {

    int result = -1;
    DataOutputStream dos = null;

    try {/*from   ww w  .  j a va  2  s. com*/
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());

        dos.writeBytes(cmd + "\n");
        dos.flush();
        dos.writeBytes("exit\n");
        dos.flush();
        p.waitFor();
        result = p.exitValue();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:com.telefonica.iot.perseo.test.Help.java

public static Res sendMethod(String url, String body, String method) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod(method);//w  w w . ja v  a  2s . c om
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    String responseBody = getBodyResponse(con);
    return new Res(responseCode, responseBody);
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDatanodeJsp.java

static Path writeFile(FileSystem fs, Path f) throws IOException {
    DataOutputStream out = fs.create(f);
    try {//from www  .  ja  v a2 s.  co  m
        out.writeBytes("umamahesh: " + f);
    } finally {
        out.close();
    }
    assertTrue(fs.exists(f));
    return f;
}

From source file:javaphpmysql.JavaPHPMySQL.java

public static void sendPost() {
    //Creamos un objeto JSON
    JSONObject jsonObj = new JSONObject();
    //Aadimos el nombre, apellidos y email del usuario
    jsonObj.put("nombre", nombre);
    jsonObj.put("apellidos", apellidos);
    jsonObj.put("email", email);
    //Creamos una lista para almacenar el JSON
    List l = new LinkedList();
    l.addAll(Arrays.asList(jsonObj));
    //Generamos el String JSON
    String jsonString = JSONValue.toJSONString(l);
    System.out.println("JSON GENERADO:");
    System.out.println(jsonString);
    System.out.println("");

    try {/*  w w  w. j  a v a 2 s.co m*/
        //Codificar el json a URL
        jsonString = URLEncoder.encode(jsonString, "UTF-8");
        //Generar la URL
        String url = SERVER_PATH + "listenPost.php";
        //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON
        URL obj = new URL(url);
        //Creamos un objeto de conexin
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //Aadimos la cabecera
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //Creamos los parametros para enviar
        String urlParameters = "json=" + jsonString;
        // Enviamos los datos por POST
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        //Capturamos la respuesta del servidor
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("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);
        }
        //Mostramos la respuesta del servidor por consola
        System.out.println(response);
        //cerramos la conexin
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.pubkit.network.PubKitNetwork.java

public static JSONObject sendPost(String apiKey, JSONObject jsonObject) {
    URL url;//  w ww .  j a v a  2  s . com
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(PUBKIT_API_URL);
        String encodedData = jsonObject.toString();
        byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8");

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Length", "" + String.valueOf(postDataBytes.length));
        connection.setRequestProperty("api_key", apiKey);

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(encodedData);//set data
        wr.flush();

        //Get Response
        InputStream inputStream = connection.getErrorStream(); //first check for error.
        if (inputStream == null) {
            inputStream = connection.getInputStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        wr.close();
        rd.close();

        String responseString = response.toString();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return new JSONObject("{'error':'" + responseString + "'}");
        } else {
            try {
                return new JSONObject(responseString);
            } catch (JSONException e) {
                Log.e("PUBKIT", "Error parsing data", e);
            }
        }
    } catch (Exception e) {
        Log.e("PUBKIT", "Network exception:", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

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

public static String pn(Map<String, String> pams) throws Exception {
    if (null == pams) {
        return "";
    }//from  w  w w.java 2s.c om
    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();
    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:org.apache.hadoop.mapreduce.v2.TestMRAppWithCombiner.java

static void createInputOutPutFolder(Path inDir, Path outDir, int numMaps) throws Exception {
    FileSystem fs = FileSystem.get(conf);
    if (fs.exists(outDir)) {
        fs.delete(outDir, true);//from   www . j  a v  a2s .co  m
    }
    if (!fs.exists(inDir)) {
        fs.mkdirs(inDir);
    }
    String input = "The quick brown fox\n" + "has many silly\n" + "red fox sox\n";
    for (int i = 0; i < numMaps; ++i) {
        DataOutputStream file = fs.create(new Path(inDir, "part-" + i));
        file.writeBytes(input);
        file.close();
    }
}

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

public static TestResult launchWordCount(JobConf conf, Path inDir, Path outDir, String input, int numMaps,
        int numReduces, String sysDir) throws IOException {
    FileSystem inFs = inDir.getFileSystem(conf);
    FileSystem outFs = outDir.getFileSystem(conf);
    outFs.delete(outDir, true);//from  www  .  j  ava  2s.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);
    conf.set("mapred.system.dir", "/tmp/subru/mapred/system");
    JobClient jobClient = new JobClient(conf);
    RunningJob job = jobClient.runJob(conf);
    // Checking that the Job Client system dir is not used
    assertFalse(FileSystem.get(conf).exists(new Path(conf.get("mapred.system.dir"))));
    // Check if the Job Tracker system dir is propogated to client
    sysDir = jobClient.getSystemDir().toString();
    System.out.println("Job sys dir -->" + sysDir);
    assertFalse(sysDir.contains("/tmp/subru/mapred/system"));
    assertTrue(sysDir.contains("custom"));
    return new TestResult(job, TestMiniMRWithDFS.readOutput(outDir, conf));
}