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.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void appendToFile(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    if (!isNull(ArgList) && !isUndefined(ArgList)) {
        try {//from  w  w  w  . j a  v  a 2 s  .com
            FileOutputStream file = new FileOutputStream(Context.toString(ArgList[0]), true);
            DataOutputStream out = new DataOutputStream(file);
            out.writeBytes(Context.toString(ArgList[1]));
            out.flush();
            out.close();
        } catch (Exception er) {
            throw Context.reportRuntimeError(er.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call appendToFile requires arguments.");
    }
}

From source file:fyp.project.uploadFile.UploadFile.java

public int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }//from w w  w.  ja  v a  2 s  . co  m
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        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("file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                + fileName.substring(fileName.lastIndexOf("/")) + "\"" + lineEnd);

        m_log.log(Level.INFO, "Content-Disposition: form-data; name=\"file\";filename=\"{0}\"{1}",
                new Object[] { fileName.substring(fileName.lastIndexOf("/")), lineEnd });
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        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);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        m_log.log(Level.INFO, "Upload file to server" + "HTTP Response is : {0}: {1}",
                new Object[] { serverResponseMessage, serverResponseCode });

        // close streams
        m_log.log(Level.INFO, "Upload file to server{0} File is written", fileName);
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        m_log.log(Level.ALL, "Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //this block will give the response of upload link

    return serverResponseCode; // like 200 (Ok)

}

From source file:com.citrus.mobile.RESTclient.java

public JSONObject makeWithdrawRequest(String accessToken, double amount, String currency, String owner,
        String accountNumber, String ifscCode) {
    HttpsURLConnection conn;/* ww  w .  j a v  a  2 s.  c  o  m*/
    DataOutputStream wr = null;
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = urls.getString(base_url) + urls.getString(type);

        conn = (HttpsURLConnection) new URL(url).openConnection();

        //add reuqest header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        StringBuffer buff = new StringBuffer("amount=");
        buff.append(amount);

        buff.append("&currency=");
        buff.append(currency);

        buff.append("&owner=");
        buff.append(owner);

        buff.append("&account=");
        buff.append(accountNumber);

        buff.append("&ifsc=");
        buff.append(ifscCode);

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

        wr.writeBytes(buff.toString());
        wr.flush();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + buff.toString());
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

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

        txnDetails = new JSONObject(response.toString());

    } catch (JSONException exception) {
        exception.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (wr != null) {
                wr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return txnDetails;
}

From source file:org.apache.hadoop.io.TestArrayOutputStream.java

private void runComparison(ArrayOutputStream aos, DataOutputStream dos, ByteArrayOutputStream bos)
        throws IOException {
    Random r = new Random();
    // byte//from w w  w  . ja va2 s . c o m
    int b = r.nextInt(128);
    aos.write(b);
    dos.write(b);

    // byte[]
    byte[] bytes = new byte[10];
    r.nextBytes(bytes);
    aos.write(bytes, 0, 10);
    dos.write(bytes, 0, 10);

    // Byte
    aos.writeByte(b);
    dos.writeByte(b);

    // boolean
    boolean bool = r.nextBoolean();
    aos.writeBoolean(bool);
    dos.writeBoolean(bool);

    // short
    short s = (short) r.nextInt();
    aos.writeShort(s);
    dos.writeShort(s);

    // char
    int c = r.nextInt();
    aos.writeChar(c);
    dos.writeChar(c);

    // int
    int i = r.nextInt();
    aos.writeInt(i);
    dos.writeInt(i);

    // long
    long l = r.nextLong();
    aos.writeLong(l);
    dos.writeLong(l);

    // float
    float f = r.nextFloat();
    aos.writeFloat(f);
    dos.writeFloat(f);

    // double
    double d = r.nextDouble();
    aos.writeDouble(d);
    dos.writeDouble(d);

    // strings
    String str = RandomStringUtils.random(20);
    aos.writeBytes(str);
    aos.writeChars(str);
    aos.writeUTF(str);
    dos.writeBytes(str);
    dos.writeChars(str);
    dos.writeUTF(str);

    byte[] expected = bos.toByteArray();
    assertEquals(expected.length, aos.size());

    byte[] actual = new byte[aos.size()];
    System.arraycopy(aos.getBytes(), 0, actual, 0, actual.length);
    // serialized bytes should be the same
    assertTrue(Arrays.equals(expected, actual));
}

From source file:iracing.webapi.IracingWebApi.java

private String doPostRequestUrlEncoded(boolean needForumCookie, String url, String parameters)
        throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return null;
    }/*  ww w  . ja va  2  s . c om*/
    if (needForumCookie && !cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return null;
    }
    String output = null;
    try {
        // URL of CGI-Bin script.
        URL oUrl = new URL(url);
        // URL connection channel.
        HttpURLConnection urlConn = (HttpURLConnection) oUrl.openConnection();
        // Let the run-time system (RTS) know that we want input.
        urlConn.setDoInput(true);
        // Let the RTS know that we want to do output.
        urlConn.setDoOutput(true);
        // No caching, we want the real thing.
        urlConn.setUseCaches(false);
        urlConn.addRequestProperty(COOKIE, cookie);

        // request to have the response gzipped (bringing a 3.5Mb response down to 175kb)
        urlConn.addRequestProperty("Accept-Encoding", "gzip");

        urlConn.setRequestMethod("POST");
        // Specify the content type.
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream());
        try {
            printout.writeBytes(parameters);
            printout.flush();
        } finally {
            printout.close();
        }

        output = getResponseText(urlConn);
        //            System.out.println(output);

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

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

/**
 * Logs the output "dumpsys alarm" to the provided filename.
 *
 * Output contains list of scheduled alarms & historical alarm statistics since
 * device bootup.//from  w w  w .  j  av  a  2s  .  co  m
 *
 * Note: On Froyo & older Android OS versions dumpsys output consists of absolute
 * times (in ms), but on later versions is relative in the format 1h1m20s32ms.
 *
 * Requires root permission.
 *
 * @param file Alarm log output filename
 */
private void getAlarmInfo(String file) {
    Process sh = null;
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        String Command = "dumpsys alarm > " + mApp.getTcpDumpTraceFolderName() + file + "\n";
        os.writeBytes(Command);
        os.flush();
    } catch (IOException e) {
        Log.e(TAG, "exception in getAlarmInfo ", e);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            Log.e(TAG, "exception in getAlarmInfo closing output stream ", e);
        }
    }
}

From source file:com.netease.qa.emmagee.service.EmmageeService.java

public void getlog() {

    new Thread(new Runnable() {
        @Override/* ww w .j a  va 2 s. co m*/
        public void run() {
            try {
                Process process = null;
                DataOutputStream os = null;
                String logcatCommand;
                if (packageName.contains("elong")) {
                    logcatCommand = "logcat -v time |grep --line-buffered -E \"GreenDaoHelper_insert_e|Displayed\" | grep -v -E \"show|logs|back|info\"";
                } else {
                    logcatCommand = "logcat -v time |grep --line-buffered -E \"Displayed\"";
                }

                Runtime.getRuntime().exec("logcat -c");
                process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
                os = new DataOutputStream(process.getOutputStream());
                os.write(logcatCommand.getBytes());
                os.writeBytes(COMMAND_LINE_END);
                os.flush();
                bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                bufferedWriter = new BufferedWriter(new FileWriter(new File("/sdcard/logcat.log")));
                String line = null;
                while (!isServiceStop) {
                    while ((line = bufferedReader.readLine()) != null) {
                        bufferedWriter.write(line + Constants.LINE_END);
                    }
                    try {
                        Thread.currentThread().sleep(Settings.SLEEP_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                os.close();
                bufferedWriter.flush();
                bufferedReader.close();
                process.destroy();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }
        }
    }).start();

}

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

@Test
@RunAsClient/*from  ww  w  .  java  2  s .c  o  m*/
public void testCreatePackageFromJAXB(@ArquillianResource URL baseURL) throws Exception {
    Package p = createTestPackage("TestCreatePackageFromJAXB");
    JAXBContext context = JAXBContext.newInstance(p.getClass());
    Marshaller marshaller = context.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.marshal(p, sw);
    String xml = sw.toString();
    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_XML);
    connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    //Send request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(xml);
    wr.flush();
    wr.close();

    assertEquals(200, connection.getResponseCode());
}

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

@Test
@RunAsClient/*from   w  w w.ja  v  a  2s . co  m*/
@Ignore
public void testUpdatePackageFromJAXB(@ArquillianResource URL baseURL) throws Exception {
    Package p = createTestPackage("TestCreatePackageFromJAXB");
    p.setDescription("Updated description.");
    JAXBContext context = JAXBContext.newInstance(p.getClass());
    Marshaller marshaller = context.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.marshal(p, sw);
    String xml = sw.toString();
    URL url = new URL(baseURL, "rest/packages/TestCreatePackageFromJAXB");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML);
    connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    //Send request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(xml);
    wr.flush();
    wr.close();

    assertEquals(204, connection.getResponseCode());
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataExt(JSONObject obj) {
    String requestUrl;/*from  w  w  w .j  av  a  2 s . c  om*/
    String id;
    String method;
    String body;
    String headers;
    try {
        //Request url
        requestUrl = obj.getString("url");

        //ID that correlates the request to the event
        id = obj.getString("id");

        //Request method
        method = obj.getString("method");

        //Request body
        body = obj.getString("body");

        //Request header
        headers = obj.getString("headers");

        String js = null;
        if (method == null || method.length() == 0)
            method = "GET";

        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
        boolean forceUTF8 = false;

        try {
            if (headers.length() > 0) {
                String[] headerArray = headers.split("&");

                //Set request header
                for (String header : headerArray) {
                    String[] headerPair = header.split("=");
                    if (headerPair.length == 2) {
                        String field = headerPair[0];
                        String value = headerPair[1];
                        if (field != null && value != null) {
                            if (!"content-length".equals(field.toLowerCase())) {//skip Content-Length - causes error because it is managed by the request
                                connection.setRequestProperty(field, value);
                            }

                            field = field.toLowerCase();
                            value = value.toLowerCase();
                            if (field.equals("content-type") && value.indexOf("charset") > -1
                                    && value.indexOf("utf-8") > -1) {
                                forceUTF8 = true;
                            }
                        }
                    }
                }

            }

            if ("POST".equalsIgnoreCase(method)) {
                connection.setRequestMethod(method);
                connection.setDoOutput(true);
                connection.setFixedLengthStreamingMode(body.length());
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(body);
                dStream.flush();
                dStream.close();
            }

            //inject response
            int statusCode = connection.getResponseCode();

            final StringBuilder response = new StringBuilder();
            try {
                InputStream responseStream = connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                br.close();
            } catch (Exception e) {
            }

            String responseBody = null;
            // how to handle UTF8 without EntityUtils?
            //                if (forceUTF8) {
            //                    responseBody = EntityUtils.toString(entity, "UTF-8");
            //                } else {
            //                    responseBody = EntityUtils.toString(entity);
            //                }
            responseBody = response.toString();
            String responseMessage = connection.getResponseMessage();

            char[] bom = { 0xef, 0xbb, 0xbf };
            //check for BOM characters, then strip if present
            if (responseBody.length() >= 3 && responseBody.charAt(0) == bom[0]
                    && responseBody.charAt(1) == bom[1] && responseBody.charAt(2) == bom[2]) {
                responseBody = responseBody.substring(3);
            }

            //escape existing backslashes
            responseBody = responseBody.replaceAll("\\\\", "\\\\\\\\");

            //escape internal double-quotes
            responseBody = responseBody.replaceAll("\"", "\\\\\"");
            responseBody = responseBody.replaceAll("'", "\\\\'");

            //replace linebreaks with \n
            responseBody = responseBody.replaceAll("\\r\\n|\\r|\\n", "\\\\n");

            StringBuilder extras = new StringBuilder("{");
            extras.append(String.format("status:'%d',", statusCode));

            String status = null;
            switch (statusCode) {
            case 200:
                status = "OK";
                break;
            case 201:
                status = "CREATED";
                break;
            case 202:
                status = "Accepted";
                break;
            case 203:
                status = "Partial Information";
                break;
            case 204:
                status = "No Response";
                break;
            case 301:
                status = "Moved";
                break;
            case 302:
                status = "Found";
                break;
            case 303:
                status = "Method";
                break;
            case 304:
                status = "Not Modified";
                break;
            case 400:
                status = "Bad request";
                break;
            case 401:
                status = "Unauthorized";
                break;
            case 402:
                status = "PaymentRequired";
                break;
            case 403:
                status = "Forbidden";
                break;
            case 404:
                status = "Not found";
                break;
            case 500:
                status = "Internal Error";
                break;
            case 501:
                status = "Not implemented";
                break;
            case 502:
                status = "Service temporarily overloaded";
                break;
            case 503:
                status = "Gateway timeout";
                break;
            }
            extras.append(String.format("statusText:'%s',", status));
            extras.append("headers: {");

            List<String> cookieData = new ArrayList<String>();
            Map<String, List<String>> allHeaders = connection.getHeaderFields();
            for (String key : allHeaders.keySet()) {
                if (key == null) {
                    continue;
                }
                String value = connection.getHeaderField(key);
                value = value.replaceAll("'", "\\\\'");
                if (key.toLowerCase().equals("set-cookie"))
                    cookieData.add(value);
                else
                    extras.append(String.format("'%s':'%s',", key, value));
            }

            String concatCookies = cookieData.toString();
            concatCookies = concatCookies.substring(0, concatCookies.length());
            extras.append(String.format("'Set-Cookie':'%s',",
                    concatCookies.substring(1, concatCookies.length() - 1)));

            String cookieArray = "[";
            for (int i = 0; i < cookieData.size(); i++)
                cookieArray += String.format("'%s',", cookieData.get(i));
            cookieArray += "]";

            extras.append("'All-Cookies': " + cookieArray);
            extras.append("} }");

            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=true;e.id='%s';e.response='%s';e.extras=%s;document.dispatchEvent(e);",
                    id, responseBody, extras.toString());

        } catch (Exception ex) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, ex.getMessage());
        } catch (OutOfMemoryError err) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, err.getMessage());
        } finally {
            connection.disconnect();
        }

        injectJS(js);

    } catch (Exception e) {
        Log.d("getRemoteDataExt", e.getMessage());
    }
}