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.openme.openme.java

public static JSONObject remote_access(JSONObject i) {
    /*//from   w  w w  .ja v  a  2 s .c  o  m
    Input:  {
      cm_remote_url             - remote URL
      (cm_user_uoa)             -
      (cm_user_password)        -
      (cm_user_password1)       -
      (remote_repo_uoa)
            
      (remote_pre_auth)         - if 'yes', need standard http login/password pre-authentication
      (cm_remote_user_name)     - remote username
      (cm_remote_user_password) - remote password
            
      (cm_web_module_uoa)       - module to run
      (cm_web_action)           - action to perform
                                  if =='download', prepare entry/file download through Internet
            
      (cm_save_to_file)         - if cm_web_action==download,
                                  save output to this file
            
      (cm_console)              - if 'json', treat output as json
                                  if 'json_after_text', strip everything before json
                                  if 'txt', output to cm_stdout
            
      ...                       - all other request parameters
            
      //FGG TBD - should add support for proxy
    }
            
    Output: {
      cm_return   - return code = 0 if successful
                                > 0 if error
                                < 0 if warning (rarely used at this moment)
      (cm_error)  - error text, if cm_return > 0
      (cm_stdout) - if cm_console='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("cm_console");
    if (x != null && x != "")
        con = x;

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

    x = (String) i.get("cm_user_uoa");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_uoa=" + x;
        i.remove("cm_user_uoa");
    }

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

    x = (String) i.get("cm_user_password");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_password=" + x;
        i.remove("cm_user_password");
    }

    x = (String) i.get("cm_user_password1");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_password1=" + x;
        i.remove("cm_user_password1");
    }

    x = (String) i.get("remote_repo_uoa");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_repo_uoa=" + x;
        i.remove("remote_repo_uoa");
    }

    // Check if needed remote pre-authentication
    String base64string = "";
    x = (String) i.get("remote_pre_auth");
    if (x == "yes") {
        i.remove("remote_pre_auth");

        String username = "";
        String password = "";

        x = (String) i.get("cm_remote_user_name");
        if (x != null && x != "") {
            username = x;
            i.remove("cm_remote_user_name");
        }

        x = (String) i.get("cm_remote_user_password");
        if (x != null && x != "") {
            password = x;
            i.remove("cm_remote_user_password");
        }

        x = username + ":" + password;
        base64string = new String(Base64.encodeBase64(x.replace("\n", "").getBytes()));
    }

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

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

        if (((String) i.get("cm_web_module_uoa")) != null)
            i.remove("cm_web_module_uoa");
        if (((String) i.get("cm_console")) != null)
            i.remove("cm_console");
    }

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

    if (post != "")
        post += "&";
    post += "cm_json=" + ((String) rx.get("cm_string1"));

    // 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));
        if (base64string != "")
            c.setRequestProperty("Authorization", "Basic " + base64string);
        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("cm_return", new Long(1));
        r.put("cm_error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
        return r;
    }

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

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

        x = ((String) i.get("cm_web_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("cm_return", new Long(1));
            r.put("cm_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("cm_return", new Long(1));
            r.put("cm_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") {
            //Parsing json
            try {
                JSONParser parser = new JSONParser();
                r = (JSONObject) parser.parse(s);
            } catch (ParseException ex) {
                r.put("cm_return", new Long(1));
                r.put("cm_error", "can't parse json output (" + ex + ") ...");
                return r;
            }
        } else
            r.put("cm_stdout", s);
    }

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

    return r;
}

From source file:it.crs4.pydoop.mapreduce.pipes.TaskLog.java

private static synchronized void writeToIndexFile(String logLocation, boolean isCleanup) throws IOException {
    // To ensure atomicity of updates to index file, write to temporary index
    // file first and then rename.
    File tmpIndexFile = getTmpIndexFile(currentTaskid, isCleanup);

    BufferedOutputStream bos = new BufferedOutputStream(SecureIOUtils.createForWrite(tmpIndexFile, 0644));
    DataOutputStream dos = new DataOutputStream(bos);
    //the format of the index file is
    //LOG_DIR: <the dir where the task logs are really stored>
    //STDOUT: <start-offset in the stdout file> <length>
    //STDERR: <start-offset in the stderr file> <length>
    //SYSLOG: <start-offset in the syslog file> <length>
    try {//from   w ww.  ja va2s. c om
        dos.writeBytes(LogFileDetail.LOCATION + logLocation + "\n" + LogName.STDOUT.toString() + ":");
        dos.writeBytes(Long.toString(prevOutLength) + " ");
        dos.writeBytes(Long.toString(new File(logLocation, LogName.STDOUT.toString()).length() - prevOutLength)
                + "\n" + LogName.STDERR + ":");
        dos.writeBytes(Long.toString(prevErrLength) + " ");
        dos.writeBytes(Long.toString(new File(logLocation, LogName.STDERR.toString()).length() - prevErrLength)
                + "\n" + LogName.SYSLOG.toString() + ":");
        dos.writeBytes(Long.toString(prevLogLength) + " ");
        dos.writeBytes(Long.toString(new File(logLocation, LogName.SYSLOG.toString()).length() - prevLogLength)
                + "\n");
        dos.close();
        dos = null;
    } finally {
        IOUtils.cleanup(LOG, dos);
    }

    File indexFile = getIndexFile(currentTaskid, isCleanup);
    Path indexFilePath = new Path(indexFile.getAbsolutePath());
    Path tmpIndexFilePath = new Path(tmpIndexFile.getAbsolutePath());

    if (localFS == null) {// set localFS once
        localFS = FileSystem.getLocal(new Configuration());
    }
    localFS.rename(tmpIndexFilePath, indexFilePath);
}

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

static synchronized void writeToIndexFile(String logLocation, TaskAttemptID currentTaskid, boolean isCleanup,
        Map<LogName, Long[]> lengths) throws IOException {
    // To ensure atomicity of updates to index file, write to temporary index
    // file first and then rename.
    File tmpIndexFile = getTmpIndexFile(currentTaskid, isCleanup);

    BufferedOutputStream bos = new BufferedOutputStream(SecureIOUtils.createForWrite(tmpIndexFile, 0644));
    DataOutputStream dos = new DataOutputStream(bos);
    //the format of the index file is
    //LOG_DIR: <the dir where the task logs are really stored>
    //STDOUT: <start-offset in the stdout file> <length>
    //STDERR: <start-offset in the stderr file> <length>
    //SYSLOG: <start-offset in the syslog file> <length>    
    dos.writeBytes(LogFileDetail.LOCATION + logLocation + "\n");
    for (LogName logName : LOGS_TRACKED_BY_INDEX_FILES) {
        Long[] lens = lengths.get(logName);
        dos.writeBytes(logName.toString() + ":" + lens[0].toString() + " "
                + Long.toString(lens[1].longValue() - lens[0].longValue()) + "\n");
    }/*from www.  j a v  a 2s. c  o  m*/
    dos.close();

    File indexFile = getIndexFile(currentTaskid, isCleanup);
    Path indexFilePath = new Path(indexFile.getAbsolutePath());
    Path tmpIndexFilePath = new Path(tmpIndexFile.getAbsolutePath());

    if (localFS == null) {// set localFS once
        localFS = FileSystem.getLocal(new Configuration());
    }
    localFS.rename(tmpIndexFilePath, indexFilePath);
}

From source file:org.apache.hama.pipes.TestPipes.java

static BigDecimal writeSummationInputFile(FileSystem fs, Path dir) throws IOException {
    DataOutputStream out = fs.create(new Path(dir, "part0"));
    Random rand = new Random();
    double rangeMin = 0;
    double rangeMax = 100;
    BigDecimal sum = new BigDecimal(0);
    // loop between 50 and 149 times
    for (int i = 0; i < rand.nextInt(100) + 50; i++) {
        // generate key value pair inputs
        double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();
        String truncatedValue = new BigDecimal(randomValue).setScale(DOUBLE_PRECISION, BigDecimal.ROUND_DOWN)
                .toString();/*from  ww w  . j ava2s .  c om*/

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

        sum = sum.add(new BigDecimal(truncatedValue));
    }
    out.close();
    return sum;
}

From source file:org.apache.hadoop.streaming.TestUlimit.java

private void writeInputFile(FileSystem fs, Path dir) throws IOException {
    DataOutputStream out = fs.create(new Path(dir, "part0"));
    out.writeBytes(input);
    out.close();//from  ww w . j a v a  2 s.c o  m
}

From source file:cit360.sandbox.BackEndMenu.java

public static final void smtpExample() {
    // declaration section:
    // smtpClient: our client socket
    // os: output stream
    // is: input stream
    Socket smtpSocket = null;/*from www.  j a v a 2s.  c  om*/
    DataOutputStream os = null;
    DataInputStream is = null;
    // Initialization section:
    // Try to open a socket on port 25
    // Try to open input and output streams
    try {
        smtpSocket = new Socket("localhost", 25);
        os = new DataOutputStream(smtpSocket.getOutputStream());
        is = new DataInputStream(smtpSocket.getInputStream());
    } catch (UnknownHostException e) {
        System.err.println("Did not recognize server: localhost");
    } catch (IOException e) {
        System.err.println("Was not able to open I/O connection to: localhost");
    }
    // If everything has been initialized then we want to write some data
    // to the socket we have opened a connection to on port 25
    if (smtpSocket != null && os != null && is != null) {
        try {

            os.writeBytes("HELO\n");
            os.writeBytes("MAIL From: david.banks0889@gmail.com\n");
            os.writeBytes("RCPT To: david.banks0889@gmail.com\n");
            os.writeBytes("DATA\n");
            os.writeBytes("From: david.banks0889@gmail.com\n");
            os.writeBytes("Subject: TEST\n");
            os.writeBytes("Hi there\n"); // message body
            os.writeBytes("\n.\n");
            os.writeBytes("QUIT");
            // keep on reading from/to the socket till we receive the "Ok" from SMTP,
            // once we received that then we want to break.
            String responseLine;
            while ((responseLine = is.readLine()) != null) {
                System.out.println("Server: " + responseLine);
                if (responseLine.contains("Ok")) {
                    break;
                }
            }
            // clean up:
            // close the output stream
            // close the input stream
            // close the socket
            os.close();
            is.close();
            smtpSocket.close();
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}

From source file:org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity.java

private void writeEntry(DataOutputStream out) throws IOException {
    out.writeBytes("content-type: " + MimeTypeHelper.getMimeType(entry) + "\r\n\r\n");
    entry.writeTo(out);/*from   ww  w . j a v  a 2s  .  c om*/
    out.writeBytes("--" + boundary + "\r\n");
}

From source file:org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity.java

public void writeRequest(OutputStream arg0) throws IOException {
    DataOutputStream out = new DataOutputStream(arg0);
    out.writeBytes("--" + boundary + "\r\n");
    writeEntry(out);//from ww  w  .ja  va  2s.co  m
    writeInput(out);
}

From source file:net.portalblockz.portalbot.urlshorteners.GooGl.java

@Override
public String shorten(String url) {
    StringBuilder response = new StringBuilder();
    try {/*from ww  w  .j  a va 2  s .co  m*/
        URL req = new URL("https://www.googleapis.com/urlshortener/v1/url");

        HttpsURLConnection con = (HttpsURLConnection) req.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes("{\"longUrl\": \"" + url + "\"}");
        wr.flush();
        wr.close();

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

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

        JSONObject res = new JSONObject(response.toString());
        if (res.optString("id") != null)
            return res.getString("id");

    } catch (Exception ignored) {
        ignored.printStackTrace();
        System.out.print(response.toString());
    }
    return null;
}