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:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Starts collecting kernel log/*  w w  w. j  av a 2s .  c o  m*/
 *
 * Requires root permission.
 *
 * @param file kernel log output filename
 */
private void startDmesg(String file) {
    Process sh = null;
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        // Appending
        String Command = "cat /proc/kmsg >> " + mApp.getTcpDumpTraceFolderName() + file + "\n";
        os.writeBytes(Command);
        os.flush();
    } catch (IOException e) {
        Log.e(TAG, "exception in startDmesg ", e);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            Log.e(TAG, "exception in startDmesg closing output stream ", e);
        }
    }
}

From source file:iracing.webapi.IracingWebApi.java

private SendPrivateMessageResult sendPrivateMessage(int customerDefinitionType, String customer, String subject,
        String message) throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;
    }/*  ww w. ja  v a  2  s  .c  om*/
    SendPrivateMessageResult output = SendPrivateMessageResult.UNKNOWN_ERROR;
    if (!cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;
    }
    try {
        // Make a connection
        URL url = new URL(FORUM_POST_PAGE_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        //multipart/form-data
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        //conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDRY);

        conn.addRequestProperty(COOKIE, cookie);

        StringBuilder data = new StringBuilder();

        // set the multipart form data parameters
        addMultipartFormData(data, "action", "sendSave");
        addMultipartFormData(data, "module", "pm");
        addMultipartFormData(data, "preview", "0");
        addMultipartFormData(data, "start", null);
        if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_ID) {
            addMultipartFormData(data, "toUsername", null);
            addMultipartFormData(data, "toUserId", customer);
        } else if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_NAME) {
            addMultipartFormData(data, "toUsername", customer);
            addMultipartFormData(data, "toUserId", null);
        }
        addMultipartFormData(data, "disa1ble_html", "on");
        addMultipartFormData(data, "attach_sig", "on");
        addMultipartFormData(data, "subject", subject);
        addMultipartFormData(data, "message", message);
        addMultipartFormData(data, "addbbcode24", "#444444");
        addMultipartFormData(data, "addbbcode26", "12");
        addMultipartFormData(data, "helpbox", "Italic Text: [i]Text[/i]  (alt+i)");

        data.append(twoHyphens).append(BOUNDRY).append(twoHyphens);
        DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
        try {
            dataOS.writeBytes(data.toString());
            dataOS.flush();
        } finally {
            dataOS.close();
        }

        conn.connect();

        if (isMaintenancePage(conn))
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;

        // Ensure we got the HTTP 200 response code
        int responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            throw new Exception(String.format("Received the response code %d from the URL %s : %s",
                    responseCode, url, conn.getResponseMessage()));
        }

        String response = getResponseText(conn);
        //            System.out.println(response);

        if (response.contains("Your message was successfully sent.")) {
            output = SendPrivateMessageResult.SUCCESS;
        } else if (response.contains(
                "Could not determine the user id. Please check if you typed the username correctly and try again.")) {
            output = SendPrivateMessageResult.USER_NOT_FOUND;
        } else if (response.contains(
                "Sorry, but this users inbox is currently full and cannot receive private messages at this time.")) {
            output = SendPrivateMessageResult.MAILBOX_FULL;
        }

        conn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return output;
}

From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceTest.java

@Test
@RunAsClient/*from ww  w . j a  va2s. c  o m*/
@Ignore
public void testCreatePackageFromDRLAsJson(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
    connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);
    connection.setDoOutput(true);

    //Send request
    BufferedReader br = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("simple_rules2.drl")));
    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
    while (br.ready())
        dos.writeBytes(br.readLine());
    dos.flush();
    dos.close();

    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON, connection.getContentType());
    //logger.log(LogLevel, IOUtils.toString(connection.getInputStream()));
}

From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceTest.java

@Test
@RunAsClient/*from  w w w  .  j  a  va 2  s. c om*/
@Ignore
public void testCreatePackageFromDRLAsJaxB(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
    connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
    connection.setDoOutput(true);

    //Send request
    BufferedReader br = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("simple_rules3.drl")));
    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
    while (br.ready())
        dos.writeBytes(br.readLine());
    dos.flush();
    dos.close();

    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_XML, connection.getContentType());
    //logger.log(LogLevel, IOUtils.toString(connection.getInputStream()));
}

From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceTest.java

@Test
@RunAsClient//from   ww  w  .  j a va 2s .  c o  m
@Ignore
public void testCreatePackageFromDRLAsEntry(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.setDoOutput(true);

    //Send request
    BufferedReader br = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("simple_rules.drl")));
    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
    while (br.ready())
        dos.writeBytes(br.readLine());
    dos.flush();
    dos.close();

    /* Retry with a -1 from the connection */
    if (connection.getResponseCode() == -1) {
        url = new URL(baseURL, "rest/packages");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization",
                "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
        connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
        connection.setDoOutput(true);

        //Send request
        br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("simple_rules.drl")));
        dos = new DataOutputStream(connection.getOutputStream());
        while (br.ready())
            dos.writeBytes(br.readLine());
        dos.flush();
        dos.close();
    }

    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType());
    //logger.log(LogLevel, IOUtils.toString(connection.getInputStream()));
}

From source file:JavaTron.AudioTron.java

/**
 * Method to execute a POST Request to the Audiotron - JSC
 * //from  ww w  .jav  a 2 s . co  m
 * @param address - The requested page
 * @param args - The POST data
 * @param parser - A Parser Object fit for parsing the response
 *
 * @return null on success, a string on error.  The string describes
 *         the error.
 *
 * @throws IOException
 */
protected String post(String address, Vector args, Parser parser) throws IOException {
    String ret = null;
    URL url;
    HttpURLConnection conn;
    String formData = new String();

    // Build the POST data
    for (int i = 0; i < args.size(); i += 2) {
        if (showPost) {
            System.out.print("POST: " + args.get(i).toString() + " = ");
            System.out.println(args.get(i + 1).toString());
        }
        formData += URLEncoder.encode(args.get(i).toString(), "UTF-8") + "="
                + URLEncoder.encode(args.get(i + 1).toString(), "UTF-8");
        if (i + 2 != args.size())
            formData += "&";
    }

    // Build the connection Headers and POST the data
    try {
        url = new URL("http://" + getServer() + address);
        if (showAddress || showPost) {
            System.out.println("POST: " + address);
            System.out.println("POST: " + formData);
        }
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // Authorization header
        String auth = getUsername() + ":" + getPassword();
        conn.setRequestProperty("Authorization", "Basic " + B64Encode(auth.getBytes()));
        // Debug
        if (showAuth) {
            System.out.println("POST: AUTH: " + auth);
        }
        conn.setRequestProperty("Content Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(formData.getBytes().length));
        conn.setRequestProperty("Content-Language", "en-US");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Send the request to the audiotron
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(formData);
        wr.flush();
        wr.close();

        // Process the Response
        if (conn.getResponseCode() != 200 && conn.getResponseCode() != 302) {
            try {
                ret = conn.getResponseMessage();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            if (ret == null) {
                ret = "Unknown Error";
            }
            if (parser != null) {
                parser.begin(ret);
            }
            return ret;
        }

        isr = new InputStreamReader(conn.getInputStream());

        BufferedReader reader = new BufferedReader(isr);
        String s;

        getBuffer = new StringBuffer();

        if (parser != null) {
            parser.begin(null);
        }

        while ((s = reader.readLine()) != null) {
            if (showGet) {
                System.out.println(s);
            }
            getBuffer.append(s);
            getBuffer.append("\n");
            if (parser == null) {
                //  getBuffer.append(s);
            } else {
                if (!parser.parse(s)) {
                    return "Parse Error";
                }
            }
        }

        if (parser == null && showUnparsedOutput) {
            System.out.println(getBuffer);
        }
        if (parser != null) {
            parser.end(false);
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        // if this happens, call the parse method if there is a parser
        // with a null value to indicate an error
        if (parser != null) {
            parser.end(true);
        }
        throw (ioe);
    } finally {
        try {
            isr.close();
        } catch (Exception e) {
            // this is ok
        }
    }

    return ret;
}

From source file:com.curso.listadapter.net.RESTClient.java

public void writeFile(DataOutputStream dos, String NameParamImage, File file) {
    //BEGIN THE UPLOAD
    Log.d("Test", "(********) BEGINS THE WRITTING");
    if (file.exists()) {
        Log.d("Test", "(*****) FILE EXISTES");
    } else {//from   w ww .ja va 2 s  .c  om
        Log.d("Test", "(*****) FILE DOES NOT EXIST");
    }
    try {
        FileInputStream fileInputStream;
        fileInputStream = new FileInputStream(file);
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        Log.e("Test", "(*****) fileInputStream.available():" + fileInputStream.available());
        post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\"" + file.getName()
                + "\"" + lineEnd;
        String mimetype = getMimeType(file.getName());
        post += "Content-Type: " + mimetype + lineEnd;
        post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

        dos.writeBytes(post);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        fileInputStream.close();
        post += lineEnd;
        post += twoHyphens + boundary + twoHyphens;
        Log.i("Test", "(********) WRITING FILE ENDED");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Log.d("Test", "(********) EXITING FROM FILE WRITTING");
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

private void getBatteryInfo() {
    Process sh = null;/*from  w w  w. j a v a  2 s. c  o  m*/
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        dumpsysTimestamp = System.currentTimeMillis();
        String Command = "dumpsys batteryinfo > " + mApp.getTcpDumpTraceFolderName() + outBatteryInfoFileName
                + "\n";
        os.writeBytes(Command);
        os.flush();
        Log.d(TAG, "getBatteryInfo timestamp " + dumpsysTimestamp);
        Runtime.getRuntime().exec("cat " + dumpsysTimestamp + " >> " + mApp.getTcpDumpTraceFolderName()
                + outBatteryInfoFileName + "\n");
    } catch (IOException e) {
        Log.e(TAG, "exception in getBatteryInfo ", e);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            Log.e(TAG, "exception in getBatteryInfo closing output stream ", e);
        }
    }
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Starts the video capture of the device desktop by reading frame buffer
 * using ffmpeg command//from   w w  w . j  a  v a2  s. c  o m
 */
private void startScreenVideoCapture() {
    Process sh = null;
    DataOutputStream os = null;
    try {
        if (DEBUG) {
            Log.e(TAG, "Starting Video Capture");
        }
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        String Command = "cd " + ARODataCollector.INTERNAL_DATA_PATH + " \n";
        os.writeBytes(Command);
        Command = "chmod 777 ffmpeg \n";
        os.writeBytes(Command);
        Command = "./ffmpeg -f fbdev -vsync 2 -r 3 -i /dev/graphics/fb0 /sdcard/ARO/" + TRACE_FOLDERNAME
                + "/video.mp4 2> /data/ffmpegout.txt \n";
        os.writeBytes(Command);
        Command = "exit\n";
        os.writeBytes(Command);
        os.flush();
        sh.waitFor();
    } catch (IOException e) {
        Log.e(TAG, "exception in startScreenVideoCapture", e);
    } catch (InterruptedException e) {
        Log.e(TAG, "exception in startScreenVideoCapture", e);
    } finally {
        try {
            if (DEBUG) {
                Log.e(TAG, "Stopped Video Capture in startScreenVideoCapture");
            }
            os.close();
            // Reading start time of Video from ffmpegout file
            mApp.readffmpegStartTimefromFile();
        } catch (IOException e) {
            Log.e(TAG, "IOException in reading video start time", e);
        } catch (NumberFormatException e) {
            Log.e(TAG, "NumberFormatException in reading video start time", e);
        }
        try {
            // Recording start time of video
            mApp.writeVideoTraceTime(Double.toString(mApp.getAROVideoCaptureStartTime()));
            mApp.closeVideoTraceTimeFile();
        } catch (IOException e) {
            Log.e(TAG, "IOException in writing video start time", e);
        }
        if (mApp.getTcpDumpStartFlag() && !mApp.getARODataCollectorStopFlag()) {
            mApp.setVideoCaptureFailed(true);
        }
        try {
            mApp.setAROVideoCaptureRunningFlag(false);
            sh.destroy();
        } catch (Exception e) {
            Log.e(TAG, "Failed to destroy shell during Video Capture termination");
        }
    }
}

From source file:UploadTest.java

@Test
public void java_lib_put() {
    try {//from   ww  w  .  j av a  2  s  .  co m
        URL myurl;
        HttpURLConnection conn;
        String port = "9000";
        String user = "edoweb-admin";
        String password = "admin";
        String encoding = Base64.encodeBase64String((user + ":" + password).getBytes());
        String boundary = "" + System.currentTimeMillis() + "";
        String crlf = "\r\n";
        String twoHyphens = "--";
        String attachmentName = "data";
        File uploadFile = new File("/home/raul/test/frl%3A6376984/123.txt");
        String attachmentFileName = uploadFile.getName();

        DataOutputStream request;

        myurl = new URL("http://localhost:9000/resource/frl:6376984/data");
        System.out.println(myurl.toString());
        conn = (HttpURLConnection) myurl.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Authorization", " Basic " + encoding);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Content-Length", String.valueOf(uploadFile.length()));
        conn.setRequestProperty("Accept", "*/*");
        conn.connect();

        FileInputStream fis = new FileInputStream(uploadFile);
        // BufferedInputStream buf = new BufferedInputStream(fis);
        request = new DataOutputStream(conn.getOutputStream());
        request.writeBytes(twoHyphens + boundary + crlf);
        request.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\""
                + attachmentFileName + "\"" + crlf);
        request.writeBytes("Content-Type: application/pdf");

        request.writeBytes(crlf);

        byte[] streamFileBytes = new byte[4096];
        int bytesRead = -1;

        while ((bytesRead = fis.read(streamFileBytes)) != -1) {
            request.write(streamFileBytes, 0, bytesRead);
        }

        request.writeBytes(crlf);
        request.writeBytes(twoHyphens + boundary + crlf);
        request.close();
        conn.disconnect();
        System.out.println(conn.getResponseCode());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}