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:at.illecker.hama.hybrid.examples.summation.SummationBSP.java

static BigDecimal writeSummationInputFile(FileSystem fs, Path dir, int fileCount) throws IOException {

    BigDecimal sum = new BigDecimal(0);
    Random rand = new Random();
    double rangeMin = 0;
    double rangeMax = 100;

    for (int i = 0; i < fileCount; i++) {
        DataOutputStream out = fs.create(new Path(dir, "part" + i));

        // loop between 50 and 149 times
        for (int j = 0; j < rand.nextInt(100) + 50; j++) {
            // generate key value pair inputs
            double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();

            String truncatedValue = new BigDecimal(randomValue)
                    .setScale(DOUBLE_PRECISION, BigDecimal.ROUND_DOWN).toString();

            String line = "key" + (j + 1) + "\t" + truncatedValue + "\n";
            out.writeBytes(line);

            sum = sum.add(new BigDecimal(truncatedValue));
            LOG.debug("input[" + j + "]: '" + line + "' sum: " + sum.toString());
        }/* w  ww.  j  a  va 2 s  . c  o m*/
        out.close();
    }
    return sum;
}

From source file:org.forgerock.openam.doc.jwt.bearer.Main.java

private static void post(String idToken, String sessionToken) throws Exception {
    URL token = new URL(tokenEndpoint);

    HttpURLConnection connection = (HttpURLConnection) token.openConnection();

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("Cookie", "iPlanetDirectoryPro=" + sessionToken);

    connection.setDoOutput(true);/*from w  ww. ja  v a2  s . com*/

    // This client is of type confidential, so authentication is required
    // according to http://tools.ietf.org/html/rfc6749#section-3.2.1
    String clientAssertionType = URLEncoder.encode("urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
            "UTF-8");
    String grantType = URLEncoder.encode("urn:ietf:params:oauth:grant-type:jwt-bearer", "UTF-8");
    String data = "client_assertion_type=" + clientAssertionType + "&client_assertion=" + idToken
            + "&grant_type=" + grantType + "&assertion=" + idToken;

    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    if (curlOut) {
        System.out.print("curl --request POST -H 'Content-Type=application/x-www-form-urlencoded' ");
        System.out.print("-H 'Cookie:iPlanetDirectoryPro=" + sessionToken + "' ");
        System.out.print("-d '" + data + "\' ");
        System.out.print("'" + tokenEndpoint + "'");
    }
    dataOutputStream.writeBytes(data);
    dataOutputStream.flush();
    dataOutputStream.close();

    int responseCode = connection.getResponseCode();

    BufferedReader input;
    if (responseCode == 200) {
        input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } else {
        input = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
    }

    StringBuilder response = new StringBuilder();
    if (input != null) {
        String line;
        while ((line = input.readLine()) != null) {
            response.append(line);
        }
        input.close();
    } else {
        response.append("No input stream from reader.");
    }

    System.out.println("Response code: " + responseCode);
    System.out.println(response.toString());
}

From source file:com.fota.Link.sdpApi.java

public static String getCtnInfo(String ncn) throws JDOMException {
    String resultStr = "";
    String logData = "";
    try {/*from w  w w . j a  va 2 s . com*/
        String cpId = PropUtil.getPropValue("sdp3g.id");
        String cpPw = PropUtil.getPropValue("sdp3g.pw");
        String authorization = cpId + ":" + cpPw;
        logData = "\r\n---------- Get Ctn Req Info start ----------\r\n";
        logData += " getCtnRequestInfo - authorization : " + authorization;
        byte[] encoded = Base64.encodeBase64(authorization.getBytes());
        authorization = new String(encoded);

        String contractType = "0";
        String contractNum = ncn.substring(0, 9);
        String customerId = ncn.substring(10, ncn.length() - 1);

        JSONObject reqJObj = new JSONObject();
        reqJObj.put("transactionid", "");
        reqJObj.put("sequenceno", "");
        reqJObj.put("userid", "");
        reqJObj.put("screenid", "");
        reqJObj.put("CONTRACT_NUM", contractNum);
        reqJObj.put("CUSTOMER_ID", customerId);
        reqJObj.put("CONTRACT_TYPE", contractType);

        authorization = "Basic " + authorization;

        String endPointUrl = PropUtil.getPropValue("sdp.oif555.url");

        logData += "\r\n getCtnRequestInfo - endPointUrl : " + endPointUrl;
        logData += "\r\n getCtnRequestInfo - authorization(encode) : " + authorization;
        logData += "\r\n getCtnRequestInfo - Content-type : application/json";
        logData += "\r\n getCtnRequestInfo - RequestMethod : POST";
        logData += "\r\n getCtnRequestInfo - json : " + reqJObj.toString();
        logData += "\r\n---------- Get Ctn Req Info end ----------";

        logger.info(logData);

        // connection
        URL url = new URL(endPointUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestProperty("Authorization", authorization);
        connection.setRequestProperty("Content-type", "application/json");

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        // output
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(reqJObj.toJSONString());
        wr.flush();
        wr.close();

        // input
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine = "";
        StringBuffer response = new StringBuffer();

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

        in.close();

        JSONParser jsonParser = new JSONParser();
        JSONObject respJsonObject = (JSONObject) jsonParser.parse(response.toString());

        //         String respTransactionId = (String) respJsonObject.get("transactionid");
        //         String respSequenceNo = (String) respJsonObject.get("sequenceno");
        //         String respReturnCode = (String) respJsonObject.get("returncode");
        //         String respReturnDescription = (String) respJsonObject.get("returndescription");
        //         String respErrorCode = (String) respJsonObject.get("errorcode");
        //         String respErrorDescription = (String) respJsonObject.get("errordescription");
        String respCtn = (String) respJsonObject.get("ctn");
        //         String respSubStatus = (String) respJsonObject.get("sub_status");
        //         String respSubStatusDate = (String) respJsonObject.get("sub_status_date");

        resultStr = respCtn;

        //resultStr = resValue;         
        //         resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr");
        connection.disconnect();

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

    return resultStr;
}

From source file:org.ctuning.openme.openme.java

public static JSONObject remote_access(JSONObject i) throws JSONException {
    /*//from   w  w w  .  j a  v a  2 s .  c  o m
    Input:  {
      remote_server_url      - remote server URL
      (module_uoa)           - module to run
      (action)               - action to perform
                                  if =='download', prepare entry/file download through Internet
            
      (save_to_file)         - if web_action==download,
                                  save output to this file
            
      (out)                  - if 'json', treat output as json
                                  if 'json_after_text', strip everything before json
                                  if 'txt', output to stdout
            
      ...                    - all other request parameters
            
      //FGG TBD - should add support for proxy
    }
            
    Output: {
      return   - return code = 0 if successful
                                > 0 if error
                                < 0 if warning (rarely used at this moment)
      (error)  - error text, if return > 0
      (stdout) - if out='txt', output there
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    URL u;
    HttpURLConnection c = null;

    // Prepare request
    String x = "";
    String post = "";

    String con = "";

    x = "";
    if (i.has("out"))
        x = (String) i.get("out");
    if (x != null && x != "")
        con = x;

    String url = "";
    if (i.has("remote_server_url")) {
        url = (String) i.get("remote_server_url");
        i.remove("remote_server_url");
    }
    if (url == null || url == "") {
        r.put("return", new Integer(1));
        r.put("error", "'remote_server_url is not defined");
        return r;
    }

    String save_to_file = "";
    if (i.has("save_to_file")) {
        save_to_file = (String) i.get("save_to_file");
        i.remove("save_to_file");
    }

    // Check if data download, not json and convert it to download request
    boolean download = false;

    x = "";
    if (i.has("action")) {
        x = (String) i.get("action");
    }
    if (x == "download" || x == "show") {
        download = true;
        if (post != "")
            post += "&";
        post += "module_uoa=web&action=" + x;

        if (i.has("module_uoa"))
            i.remove("module_uoa");
        if (i.has("out"))
            i.remove("out");
        i.remove("action");
    }

    // Prepare dict to transfer through Internet
    JSONObject ii = new JSONObject();
    ii.put("dict", i);
    JSONObject rx = convert_array_to_uri(ii);
    if ((Integer) rx.get("return") > 0)
        return rx;

    if (post != "")
        post += "&";
    post += "ck_json=" + ((String) rx.get("string"));

    // Prepare URL request
    String s = "";
    try {
        u = new URL(url);
        c = (HttpURLConnection) u.openConnection();

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length));
        c.setUseCaches(false);
        c.setDoInput(true);
        c.setDoOutput(true);

        //Send request
        DataOutputStream dos = new DataOutputStream(c.getOutputStream());
        dos.writeBytes(post);
        dos.flush();
        dos.close();
    } catch (IOException e) {
        if (c != null)
            c.disconnect();
        r.put("return", new Integer(1));
        r.put("error", "Failed sending request to remote server (" + e.getMessage() + ") ...");
        return r;
    }

    r.put("return", new Integer(0));

    // Check if download, not json!
    if (download) {
        String name = "default_download_name.dat";

        x = "";
        if (i.has("filename")) {
            x = ((String) i.get("filename"));
        }
        if (x != null && x != "") {
            File xf = new File(x);
            name = xf.getName();
        }

        if (save_to_file != null && save_to_file != "")
            name = save_to_file;

        //Reading response in binary and at the same time saving to file
        try {
            //Read response
            DataInputStream dis = new DataInputStream(c.getInputStream());
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(name));

            byte[] buf = new byte[16384];

            int len;

            while ((len = dis.read(buf)) != -1)
                dos.write(buf, 0, len);

            dos.close();
            dis.close();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Integer(1));
            r.put("error",
                    "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ...");
            return r;
        }
    } else {
        //Reading response in text
        try {
            //Read response
            InputStream is = c.getInputStream();
            BufferedReader f = new BufferedReader(new InputStreamReader(is));
            StringBuffer ss = new StringBuffer();

            while ((x = f.readLine()) != null) {
                ss.append(x);
                ss.append('\r');
            }

            f.close();
            s = ss.toString();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Integer(1));
            r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
            return r;
        }

        if (con == "json_after_text") {
            String json_sep = "*** ### --- CM JSON SEPARATOR --- ### ***";
            int li = s.lastIndexOf(json_sep);
            if (li >= 0) {
                s = s.substring(li + json_sep.length());
                s = s.trim();
            }
        }

        if (con == "json_after_text" || con == "json")
            r = new JSONObject(s);
        else
            r.put("stdout", s);
    }

    if (c != null)
        c.disconnect();

    return r;
}

From source file:org.openme_ck.openme_ck.java

public static JSONObject remote_access(JSONObject i) {
    /*/*from ww w.j  a  v  a2  s.c  o  m*/
    Input:  {
      remote_server_url      - remote server URL
      (module_uoa)           - module to run
      (action)               - action to perform
                                  if =='download', prepare entry/file download through Internet
            
      (save_to_file)         - if web_action==download,
                                  save output to this file
            
      (out)                  - if 'json', treat output as json
                                  if 'json_after_text', strip everything before json
                                  if 'txt', output to stdout
            
      ...                    - all other request parameters
            
      //FGG TBD - should add support for proxy
    }
            
    Output: {
      return   - return code = 0 if successful
                                > 0 if error
                                < 0 if warning (rarely used at this moment)
      (error)  - error text, if return > 0
      (stdout) - if out='txt', output there
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    URL u;
    HttpURLConnection c = null;

    // Prepare request
    String x = "";
    String post = "";

    String con = "";
    x = (String) i.get("out");
    if (x != null && x != "")
        con = x;

    String url = (String) i.get("remote_server_url");
    if (url == null || url == "") {
        r.put("return", new Long(1));
        r.put("error", "'remote_server_url is not defined");
        return r;
    }
    i.remove("remote_server_url");

    String save_to_file = (String) i.get("save_to_file");
    if (save_to_file != null)
        i.remove("save_to_file");

    // Check if data download, not json and convert it to download request
    boolean download = false;

    x = (String) i.get("action");
    if (x == "download" || x == "show") {
        download = true;
        if (post != "")
            post += "&";
        post += "module_uoa=web&action=" + x;
        i.remove("action");

        if (((String) i.get("module_uoa")) != null)
            i.remove("module_uoa");
        if (((String) i.get("out")) != null)
            i.remove("out");
    }

    // Prepare dict to transfer through Internet
    JSONObject ii = new JSONObject();
    ii.put("dict", i);
    JSONObject rx = convert_array_to_uri(ii);
    if ((Long) rx.get("return") > 0)
        return rx;

    if (post != "")
        post += "&";
    post += "ck_json=" + ((String) rx.get("string"));

    // Prepare URL request
    String s = "";
    try {
        //Connect
        u = new URL(url);
        c = (HttpURLConnection) u.openConnection();

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length));
        c.setUseCaches(false);
        c.setDoInput(true);
        c.setDoOutput(true);

        //Send request
        DataOutputStream dos = new DataOutputStream(c.getOutputStream());
        dos.writeBytes(post);
        dos.flush();
        dos.close();
    } catch (Exception e) {
        if (c != null)
            c.disconnect();

        r.put("return", new Long(1));
        r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
        return r;
    }

    r.put("return", new Long(0));

    // Check if download, not json!
    if (download) {
        String name = "default_download_name.dat";

        x = ((String) i.get("filename"));
        if (x != null && x != "") {
            File xf = new File(x);
            name = xf.getName();
        }

        if (save_to_file != null && save_to_file != "")
            name = save_to_file;

        //Reading response in binary and at the same time saving to file
        try {
            //Read response
            DataInputStream dis = new DataInputStream(c.getInputStream());
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(name));

            byte[] buf = new byte[16384];

            int len;

            while ((len = dis.read(buf)) != -1)
                dos.write(buf, 0, len);

            dos.close();
            dis.close();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Long(1));
            r.put("error",
                    "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ...");
            return r;
        }
    } else {
        //Reading response in text
        try {
            //Read response
            InputStream is = c.getInputStream();
            BufferedReader f = new BufferedReader(new InputStreamReader(is));
            StringBuffer ss = new StringBuffer();

            while ((x = f.readLine()) != null) {
                ss.append(x);
                ss.append('\r');
            }

            f.close();
            s = ss.toString();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Long(1));
            r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
            return r;
        }

        if (con == "json_after_text") {
            int li = s.lastIndexOf(json_sep);
            if (li >= 0) {
                s = s.substring(li + json_sep.length());

                li = s.lastIndexOf(json_sep2);
                if (li > 0) {
                    s = s.substring(0, li);
                }

                s = s.trim();
            }
        }

        if (con == "json_after_text" || con == "json") {
            //Parsing json
            try {
                JSONParser parser = new JSONParser();
                r = (JSONObject) parser.parse(s);
            } catch (ParseException ex) {
                r.put("return", new Long(1));
                r.put("error", "can't parse json output (" + ex + ") ...");
                return r;
            }
        } else
            r.put("stdout", s);
    }

    if (c != null)
        c.disconnect();

    return r;
}

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

/**
 * This creates a file in the dfs/*from  w w w .  j  ava  2  s.c om*/
 * @param dfs FileSystem Local File System where file needs to be picked
 * @param URIPATH Path dfs path where file needs to be copied
 * @param permission FsPermission File permission
 * @return returns the DataOutputStream
 */
public static DataOutputStream createTmpFileDFS(FileSystem dfs, Path URIPATH, FsPermission permission,
        String input) throws Exception {
    //Creating the path with the file
    DataOutputStream file = FileSystem.create(dfs, URIPATH, permission);
    file.writeBytes(input);
    file.close();
    return file;
}

From source file:de.ub0r.android.wifibarcode.WifiBarcodeActivity.java

/**
 * Run command as root.//from   w w  w .j a v  a 2 s  .  c  o  m
 *
 * @param command command
 * @return true, if command was successfully executed
 */
private static boolean runAsRoot(final String command) {
    Log.i(TAG, "running command as root: ", command);
    try {
        Runtime r = Runtime.getRuntime();
        Process p = r.exec("su");
        DataOutputStream d = new DataOutputStream(p.getOutputStream());
        d.writeBytes(command);
        d.writeBytes("\nexit\n");
        d.flush();
        int retval = p.waitFor();
        Log.i(TAG, "done");
        return (retval == 0);
    } catch (Exception e) {
        Log.e(TAG, "runAsRoot", e);
        return false;
    }
}

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

/**
 * Create a file in the given dir and set permissions r_xr_xr_x sothat no one
 * can delete it directly(without doing chmod).
 * Creates dir/subDir and dir/subDir/file
 *///from   w ww . j av  a  2 s .co m
static void createFileAndSetPermissions(JobConf jobConf, Path dir) throws IOException {
    Path subDir = new Path(dir, "subDir");
    FileSystem fs = FileSystem.getLocal(jobConf);
    fs.mkdirs(subDir);
    Path p = new Path(subDir, "file");
    java.io.DataOutputStream out = fs.create(p);
    out.writeBytes("dummy input");
    out.close();
    // no write permission for subDir and subDir/file
    int ret = 0;
    if ((ret = FileUtil.chmod(subDir.toUri().getPath(), "a=rx", true)) != 0) {
        LOG.warn("chmod failed for " + subDir + ";retVal=" + ret);
    }
}

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

public static RunningJob runJob(JobConf conf, Path inDir, Path outDir, int numMaps, int numReds)
        throws IOException {

    FileSystem fs = FileSystem.get(conf);
    if (fs.exists(outDir)) {
        fs.delete(outDir, true);/*from  ww  w.  jav  a 2 s .com*/
    }
    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();
    }

    conf.setInputFormat(TextInputFormat.class);
    conf.setOutputKeyClass(LongWritable.class);
    conf.setOutputValueClass(Text.class);

    FileInputFormat.setInputPaths(conf, inDir);
    FileOutputFormat.setOutputPath(conf, outDir);
    conf.setNumMapTasks(numMaps);
    conf.setNumReduceTasks(numReds);

    JobClient jobClient = new JobClient(conf);
    RunningJob job = jobClient.submitJob(conf);

    return job;
}

From source file:nl.basjes.hadoop.io.compress.TestSplittableCodecSeams.java

/**
 * Write the specified number of records to file in test dir using codec.
 * Records are simply lines random ASCII
 *//*from   w w w  . java  2  s. c  om*/
private static Path writeSplitTestFile(final Configuration conf,
        final Class<? extends SplittableCompressionCodec> codecClass, final long records,
        final int recordLength, final int trailingSizeJitter, final int randomizeEveryNChars)
        throws IOException {

    RAND.setSeed(1); // Make the tests better reproducable

    final FileSystem fs = FileSystem.getLocal(conf);
    final SplittableCompressionCodec codec = ReflectionUtils.newInstance(codecClass, conf);

    final Path wd = new Path(new Path(System.getProperty("test.build.data", "/tmp")).makeQualified(fs.getUri(),
            fs.getWorkingDirectory()), codec.getClass().getSimpleName());

    final Path file = new Path(wd,
            "test-" + records + "-" + recordLength + "-" + trailingSizeJitter + codec.getDefaultExtension());
    DataOutputStream out = null;
    final Compressor cmp = CodecPool.getCompressor(codec);
    try {
        out = new DataOutputStream(codec.createOutputStream(fs.create(file, true), cmp));

        for (long seq = 1; seq <= records; ++seq) {
            final String line = randomGibberish(
                    recordLength + (trailingSizeJitter > 0 ? RAND.nextInt(trailingSizeJitter) : 0),
                    randomizeEveryNChars) + "\n";
            // There must be a simpler way to output ACSII instead of 2 byte UNICODE
            out.writeBytes(new String(line.getBytes("UTF-8"), "US-ASCII"));
        }
    } finally {
        IOUtils.cleanup(LOG, out);
        CodecPool.returnCompressor(cmp);
    }
    return file;
}