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:edu.pdx.cecs.orcycle.NoteUploader.java

boolean uploadOneNote(long noteId) {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {//from  ww w.j  a  va  2s  . c o m
        JSONArray jsonNoteResponses = getNoteResponsesJSON(noteId);

        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        JSONObject jsonNote;
        if (null != (jsonNote = getNoteJSON(noteId))) {
            try {
                String deviceId = userId;

                dos.writeBytes(notesep + ContentField("note") + jsonNote.toString() + "\r\n");
                dos.writeBytes(
                        notesep + ContentField("version") + String.valueOf(kSaveNoteProtocolVersion) + "\r\n");
                dos.writeBytes(notesep + ContentField("device") + deviceId + "\r\n");
                dos.writeBytes(notesep + ContentField("noteResponses") + jsonNoteResponses.toString() + "\r\n");

                if (null != imageData) {
                    dos.writeBytes(notesep + "Content-Disposition: form-data; name=\"file\"; filename=\""
                            + deviceId + ".jpg\"\r\n" + "Content-Type: image/jpeg\r\n\r\n");
                    dos.write(imageData);
                    dos.writeBytes("\r\n");
                }

                dos.writeBytes(notesep);
                dos.flush();
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
                return false;
            } finally {
                dos.close();
            }
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // JSONObject responseData = new JSONObject(serverResponseMessage);
            Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 201 || serverResponseCode == 202) {
                mDb.open();
                mDb.updateNoteStatus(noteId, NoteData.STATUS_SENT);
                mDb.close();
                result = true;
            }
        } else {
            result = false;
        }
    } catch (IllegalStateException ex) {
        Log.e(MODULE_TAG, ex.getMessage());
        return false;
    } catch (IOException ex) {
        Log.e(MODULE_TAG, ex.getMessage());
        return false;
    } catch (JSONException ex) {
        Log.e(MODULE_TAG, ex.getMessage());
        return false;
    } finally {
        NoteUploader.setPending(noteId, false);
    }
    return result;
}

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

/**
 * Test the truncation of DEBUGOUT file by {@link TaskLogsTruncater}
 * @throws IOException //ww w .j a va 2  s.  c om
 */
@Test
@Ignore // Trunction is now done in the Child JVM, because the TaskTracker
        // no longer has write access to the user log dir. MiniMRCluster
        // needs to be modified to put the config params set here in a config
        // on the Child's classpath
public void testDebugLogsTruncationWithMiniMR() throws IOException {

    MiniMRCluster mr = null;
    try {
        final long LSIZE = 10000L;
        JobConf clusterConf = new JobConf();
        clusterConf.setLong(TaskLogsTruncater.MAP_USERLOG_RETAIN_SIZE, LSIZE);
        clusterConf.setLong(TaskLogsTruncater.REDUCE_USERLOG_RETAIN_SIZE, LSIZE);
        mr = new MiniMRCluster(1, "file:///", 3, null, null, clusterConf);

        JobConf conf = mr.createJobConf();

        Path inDir = new Path(TEST_ROOT_DIR + "/input");
        Path outDir = new Path(TEST_ROOT_DIR + "/output");
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outDir)) {
            fs.delete(outDir, true);
        }
        if (!fs.exists(inDir)) {
            fs.mkdirs(inDir);
        }
        String input = "The quick brown fox jumped over the lazy dog";
        DataOutputStream file = fs.create(new Path(inDir, "part-0"));
        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(1);
        conf.setMaxMapAttempts(1);
        conf.setNumReduceTasks(0);
        conf.setMapperClass(TestMiniMRMapRedDebugScript.MapClass.class);

        // copy debug script to cache from local file system.
        Path scriptPath = new Path(TEST_ROOT_DIR, "debug-script.txt");
        String debugScriptContent = "for ((i=0;i<1000;i++)); " + "do " + "echo \"Lots of logs! Lots of logs! "
                + "Waiting to be truncated! Lots of logs!\";" + "done";
        DataOutputStream scriptFile = fs.create(scriptPath);
        scriptFile.writeBytes(debugScriptContent);
        scriptFile.close();
        new File(scriptPath.toUri().getPath()).setExecutable(true);

        URI uri = scriptPath.toUri();
        DistributedCache.createSymlink(conf);
        DistributedCache.addCacheFile(uri, conf);
        conf.setMapDebugScript(scriptPath.toUri().getPath());

        RunningJob job = null;
        try {
            JobClient jc = new JobClient(conf);
            job = jc.submitJob(conf);
            try {
                jc.monitorAndPrintJob(conf, job);
            } catch (InterruptedException e) {
                //
            }
        } catch (IOException ioe) {
        } finally {
            for (TaskCompletionEvent tce : job.getTaskCompletionEvents(0)) {
                File debugOutFile = TaskLog.getTaskLogFile(tce.getTaskAttemptId(), false,
                        TaskLog.LogName.DEBUGOUT);
                if (debugOutFile.exists()) {
                    long length = debugOutFile.length();
                    assertEquals("DEBUGOUT log file length for " + tce.getTaskAttemptId() + " is " + length
                            + " and not " + LSIZE, length, LSIZE + truncatedMsgSize);
                }
            }
        }
    } finally {
        if (mr != null) {
            mr.shutdown();
        }
    }
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private static void writeField(DataOutputStream dos, String name, String value) throws IOException {
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
    dos.writeBytes(lineEnd);/*from w ww . jav  a 2 s .  co m*/
    dos.writeBytes(lineEnd);
    byte[] data = value.getBytes("UTF-8");
    dos.write(data);
    dos.writeBytes(lineEnd);
}

From source file:com.almunt.jgcaap.systemupdater.MainActivity.java

public void FlashFile(final String filename) {
    final boolean[] mayBeContinued = { true };
    AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
    builder1.setTitle("Flashing Confirmation");
    builder1.setMessage(/* w  w  w .  jav  a 2  s. com*/
            "Are You sure you want to flash this file?\nIt will be added to the OpenRecoveryScript file and TWRP will automatically flash it without a warning!");
    builder1.setCancelable(true);
    builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            try {
                Process su = Runtime.getRuntime().exec("su");
                DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
                outputStream.writeBytes("cd /cache/recovery/\n");
                outputStream.flush();
                outputStream.writeBytes("rm openrecoveryscript\n");
                outputStream.flush();
                outputStream.writeBytes("echo install " + Environment.getExternalStorageDirectory()
                        + "/JgcaapUpdates/" + filename + ">openrecoveryscript\n");
                outputStream.flush();
                outputStream.writeBytes("exit\n");
                outputStream.flush();
                su.waitFor();
            } catch (IOException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
                mayBeContinued[0] = false;
            } catch (InterruptedException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
                mayBeContinued[0] = false;
            }
            if (mayBeContinued[0]) {
                RebootRecovery(true);
            }
        }
    });
    builder1.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });
    AlertDialog alert11 = builder1.create();
    alert11.show();
}

From source file:org.jitsi.videobridge.influxdb.LoggingHandler.java

/**
 * Sends the string <tt>s</tt> as the contents of an HTTP POST request to
 * {@link #url}.//  w  w w . j  ava2  s .c  om
 * @param s the content of the POST request.
 */
private void sendPost(final String s) {
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json");

        connection.setDoOutput(true);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(s);
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        if (responseCode != 200)
            throw new IOException("HTTP response code: " + responseCode);
    } catch (IOException ioe) {
        logger.info("Failed to post to influxdb: " + ioe);
    }
}

From source file:com.telesign.util.TeleSignRequest.java

/**
 * Creates and sends the REST request.//from  www.j  a  va  2s . co m
 *
 * @return A string containing the TeleSign web server's Response.
 * @throws IOException
 *          A {@link java.security.SignatureException} signals that an
 *          error occurred while attempting to sign the Request.
 */
public String executeRequest() throws IOException {

    String signingString = getSigningString(customer_id);
    String signature;
    String url_output = "";

    // Create the absolute form of the resource URI, and place it in a string buffer.
    StringBuffer full_url = new StringBuffer(base).append(resource);

    if (params.size() > 0) {

        full_url.append("?");
        int i = 0;

        for (String key : params.keySet()) {

            if (++i != 0) {

                full_url.append("&");
            }

            full_url.append(URLEncoder.encode(key, "UTF-8")).append("=")
                    .append(URLEncoder.encode(params.get(key), "UTF-8"));
        }
    }

    url = new URL(full_url.toString());

    // Create the Signature using the formula: Signature = Base64(HMAC-SHA( YourTeleSignAPIKey, UTF-8-Encoding-Of( StringToSign )).
    try {

        signature = encode(signingString, secret_key);
    } catch (SignatureException e) {

        System.err.println("Error signing request " + e.getMessage());

        return null;
    }

    String auth_header = "TSA " + customer_id + ":" + signature;

    connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(connectTimeout);
    connection.setReadTimeout(readTimeout);
    connection.setRequestProperty("Authorization", auth_header);
    setTLSProtocol();

    if (post) {

        connection.setRequestProperty("Content-Length", Integer.toString(body.length()));
    }

    for (String key : ts_headers.keySet()) {

        connection.setRequestProperty(key, ts_headers.get(key));
    }

    for (String key : headers.keySet()) {

        connection.setRequestProperty(key, headers.get(key));
    }

    if (post) {

        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        wr.writeBytes(body);
        wr.flush();
        wr.close();
    }

    int response = connection.getResponseCode();

    BufferedReader in;

    try {

        InputStream isr = (response == 200) ? connection.getInputStream() : connection.getErrorStream();
        in = new BufferedReader(new InputStreamReader(isr));
        String urlReturn;

        while ((urlReturn = in.readLine()) != null) {

            url_output += urlReturn;
        }

        in.close();
    } catch (IOException e) {
        System.err.println("IOException while reading from input stream " + e.getMessage());
        throw new RuntimeException(e);
    }

    return url_output;
}

From source file:com.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * /*from w  w w .j a  v a2s.c o m*/
 * @param extraHeaders   Extra headers to include in the request
 * @param method   The HTTP Method to user
 * @param relativeUrl   The URL after .com (/me)
 * @param body   The body of the message
 * @return Output in the preferred data format
 * @throws IOException
 */
protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl,
        String body) throws IOException {

    if (body == null) {
        body = "";
    }

    // append .xml extension when XML data format enabled.
    if (dataFormat == DataFormat.XML) {
        logger.debug("Using XML extension on route");

        String queryString = "";
        int queryStringIndex = relativeUrl.indexOf('?');
        if (queryStringIndex != -1) {
            queryString = relativeUrl.substring(queryStringIndex);
            relativeUrl = relativeUrl.substring(0, queryStringIndex);
        }

        String compareUrl = relativeUrl.toLowerCase();

        if (!compareUrl.endsWith(".xml")) {
            relativeUrl += ".xml";
        }

        if (queryStringIndex != -1) {
            relativeUrl += queryString;
        }
    }

    final String fullUrl = API_DOMAIN + relativeUrl;

    if (logger.isDebugEnabled()) {
        logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body);
    }

    URL url = new URL(fullUrl);
    Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body);

    if (oauthHeaders == null) {
        throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods");
    }

    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            if (!oauthHeaders.containsKey(key)) {
                oauthHeaders.put(key, extraHeaders.get(key));
            } else {
                throw new RuntimeException("Extra headers can not include OAuth headers");
            }
        }
    }

    HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
    try {
        request.setRequestMethod(method.toString());

        Set<String> oauthHeaderKeys = oauthHeaders.keySet();
        for (String oauthHeaderKey : oauthHeaderKeys) {
            request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey));
        }

        request.addRequestProperty("User-Agent", getServiceIdentifier());

        if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) {
            if (dataFormat == DataFormat.XML) {
                request.setRequestProperty("Content-Type", "application/xml");
            } else {
                request.setRequestProperty("Content-Type", "application/json");
            }

            request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length));
            request.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(request.getOutputStream());
            try {
                out.writeBytes(body);
                out.flush();
            } finally {
                out.close();
            }
        }

        Response response = new Response();
        response.setMethod(method.toString());
        response.setUrl(url.toString());
        response.setStatusCode(request.getResponseCode());
        response.setStatusMessage(request.getResponseMessage());
        response.setHeaders(request.getHeaderFields());

        InputStream inputStream = null;
        if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) {
            inputStream = request.getInputStream();
        } else {
            inputStream = request.getErrorStream();
        }

        boolean isBinary = false;
        if (inputStream != null) {
            StringBuilder responseBody = new StringBuilder();

            String contentType = request.getContentType();
            if (contentType != null) {
                if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml")
                        && !contentType.startsWith("application/json")) { // assume binary
                    isBinary = true;
                    inputStream = new Base64InputStream(inputStream, true); // base64 encode
                }
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    responseBody.append(line);
                }
            } finally {
                bufferedReader.close();
            }

            response.setContentType(contentType);

            if (isBinary) {
                String content = responseBody.toString();
                if (content.length() == 0) {
                    response.setBinaryContent(new byte[0]);
                } else {
                    response.setBinaryContent(Base64.decodeBase64(responseBody.toString()));
                }
            } else {
                response.setContent(responseBody.toString());
            }
        }

        if (logger.isDebugEnabled()) {
            if (isBinary) {
                logger.debug("RESPONSE - binary response omitted");
            } else {
                logger.debug("RESPONSE - " + response.toString());
            }
        }

        return response;
    } finally {
        request.disconnect();
    }

}

From source file:com.almunt.jgcaap.systemupdater.MainActivity.java

public void RebootRecovery(boolean update) {
    AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
    builder1.setTitle("Recovery Reboot");
    if (update)//  w  w  w. j a v  a  2 s  .  c  o m
        builder1.setMessage(
                "Would you like to reboot into recovery now to complete update?\nClear ORS will delete the OpenRecoveryScript to stop TWRP from automatically installing any files.");
    else
        builder1.setMessage("Would you like to reboot into recovery now.\n"
                + "Clear ORS will delete the current OpenRecoveryScript and stop any automatic update installations in TWRP");
    builder1.setCancelable(true);
    builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            try {
                Process su = Runtime.getRuntime().exec("su");
                DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
                outputStream.writeBytes("reboot recovery\n");
                outputStream.flush();
                outputStream.writeBytes("exit\n");
                outputStream.flush();
                su.waitFor();
            } catch (IOException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
            } catch (InterruptedException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
            }
        }
    });
    builder1.setNeutralButton("Clear ORS", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            try {
                Process su = Runtime.getRuntime().exec("su");
                DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
                outputStream.writeBytes("cd /cache/recovery/\n");
                outputStream.flush();
                outputStream.writeBytes("rm openrecoveryscript\n");
                outputStream.flush();
                outputStream.writeBytes("exit\n");
                outputStream.flush();
                su.waitFor();
                Toast.makeText(MainActivity.this, "OpenRecoveryScript file was cleared", Toast.LENGTH_LONG)
                        .show();
            } catch (IOException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
            } catch (InterruptedException e) {
                Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show();
            }
        }
    });
    builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });
    if (update)
        builder1.setNegativeButton("Reboot Later", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            }
        });

    AlertDialog alert11 = builder1.create();
    alert11.show();
}

From source file:com.vimc.ahttp.HurlWorker.java

/**
 * write string parameters//from   w w w.j  a va 2s.c  o  m
 */
private void writeStringFields(Map<String, String> params, DataOutputStream output, String boundary)
        throws IOException {
    StringBuilder sb = new StringBuilder();
    for (String key : params.keySet()) {
        sb.append(TWO_HYPHENS + boundary + LINE_END);
        sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + LINE_END);
        sb.append(LINE_END);
        sb.append(params.get(key) + LINE_END);
    }
    output.writeBytes(sb.toString());// ????
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private static void writeData(DataOutputStream dos, String name, String filename, InputStream is)
        throws IOException {
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\";" + " filename=\"" + filename + "\""
            + lineEnd);//from  ww  w. java2 s . co m
    //added to specify type
    dos.writeBytes("Content-Type: application/octet-stream");
    dos.writeBytes(lineEnd);
    dos.writeBytes("Content-Transfer-Encoding: binary");
    dos.writeBytes(lineEnd);
    dos.writeBytes(lineEnd);
    AQUtility.copy(is, dos);
    dos.writeBytes(lineEnd);
}