Example usage for java.io OutputStream write

List of usage examples for java.io OutputStream write

Introduction

In this page you can find the example usage for java.io OutputStream write.

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this output stream.

Usage

From source file:bit.changepurse.wdk.util.CheckedExceptionMethods.java

public static void write(OutputStream os, byte[] bytes) {
    try {/*www.j a va2  s  . com*/
        os.write(bytes);
    } catch (IOException e) {
        throw new UncheckedException(e);
    }
}

From source file:Main.java

static byte[] httpRequest(String url, byte[] requestBytes, int connectionTimeOutMs, int readTimeOutMs) {
    byte[] bArr = null;
    if (!(url == null || requestBytes == null)) {
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        try {//  ww  w  .j  a  v  a  2 s  . com
            urlConnection = (HttpURLConnection) new URL(url).openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(connectionTimeOutMs);
            urlConnection.setReadTimeout(readTimeOutMs);
            urlConnection.setFixedLengthStreamingMode(requestBytes.length);
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(requestBytes);
            outputStream.close();
            if (urlConnection.getResponseCode() != 200) {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            } else {
                inputStream = urlConnection.getInputStream();
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[16384];
                while (true) {
                    int chunkSize = inputStream.read(buffer);
                    if (chunkSize < 0) {
                        break;
                    } else if (chunkSize > 0) {
                        result.write(buffer, 0, chunkSize);
                    }
                }
                bArr = result.toByteArray();
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e2) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
        } catch (IOException e3) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e4) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e5) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
    return bArr;
}

From source file:Main.java

/**
 *
 * Send an ADB command using existing socket connection
 *
 * the streams provided must be from a socket connected to adbd already
 *
 * @param is input stream of the socket connection
 * @param os output stream of the socket
 * @param cmd the adb command to send/*from   w ww. ja  v  a 2  s .c  om*/
 * @return if adb gave a success response
 * @throws IOException
 */
public static boolean sendAdbCmd(InputStream is, OutputStream os, String cmd) throws IOException {
    byte[] buf = new byte[ADB_RESPONSE_SIZE];

    cmd = String.format("%04X", cmd.length()) + cmd;
    os.write(cmd.getBytes());
    int read = is.read(buf);
    if (read != ADB_RESPONSE_SIZE || !ADB_OK.equals(new String(buf))) {
        Log.w(LOGTAG, "adb cmd faild.");
        return false;
    }
    return true;
}

From source file:Main.java

/**
 * Performs execution of the shell command on remote host.
 * @param host ip address or name of the host.
 * @param port telnet port//from  w w  w .j  a va 2s.c o m
 * @param command shell command to be executed.
 * @return true if success, false on error.
 */
public static final boolean executeRemotely(String host, int port, String command) {
    Socket socket = null;
    OutputStream os = null;

    try {
        socket = new Socket(host, port);

        os = socket.getOutputStream();

        os.write(command.getBytes());
        os.flush();

        return true;
    } catch (UnknownHostException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {

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

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

From source file:Main.java

public static boolean writeByte(@NonNull File file, @NonNull String content) {
    if (file.isDirectory()) {
        return false;
    }/*from  ww w  .j  av  a2  s.  co  m*/
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
        }
    }
    OutputStream out = null;
    try {
        out = new FileOutputStream(file);
        byte[] b = content.getBytes();
        out.write(b);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        CloseableClose(out);
    }
}

From source file:io.undertow.server.handlers.PreChunkedResponseTransferCodingTestCase.java

@BeforeClass
public static void setup() {
    final BlockingHandler blockingHandler = new BlockingHandler();
    DefaultServer.setRootHandler(blockingHandler);
    blockingHandler.setRootHandler(new HttpHandler() {
        @Override//from ww  w.ja  va2 s  . c o  m
        public void handleRequest(final HttpServerExchange exchange) {
            try {
                if (connection == null) {
                    connection = exchange.getConnection();
                } else if (!DefaultServer.isAjp() && !DefaultServer.isProxy()
                        && connection != exchange.getConnection()) {
                    final OutputStream outputStream = exchange.getOutputStream();
                    outputStream.write("Connection not persistent".getBytes());
                    outputStream.close();
                    return;
                }
                exchange.getResponseHeaders().put(Headers.TRANSFER_ENCODING, Headers.CHUNKED.toString());
                exchange.putAttachment(HttpAttachments.PRE_CHUNKED_RESPONSE, true);
                new StringWriteChannelListener(chunkedMessage).setup(exchange.getResponseChannel());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:com.usefullc.platform.common.utils.IOUtils.java

/**
 * /*  www  .j a v  a2 s . co m*/
 * 
 * @param content
 * @param fileName
 * @param response
 */
public static void download(byte[] content, String fileName, HttpServletResponse response) {
    try {
        // response
        response.reset();

        // ??linux ?  linux utf-8,windows  GBK)
        String defaultEncoding = System.getProperty("file.encoding");
        if (defaultEncoding != null && defaultEncoding.equals("UTF-8")) {

            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
        } else {
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        }

        // responseHeader
        response.addHeader("Content-Length", "" + content.length);
        response.setContentType("application/octet-stream");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(content);
        toClient.flush();
        toClient.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

/**
 * Issue a POST request to the server./*from w  w w  . j a  va  2 s . c  o  m*/
 *
 * @param endpoint POST address.
 * @param params request parameters.
 * @return response
 * @throws IOException propagated from POST.
 */
private static String executePost(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    StringBuffer response = new StringBuffer();
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    //Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();

        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);

        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response.toString();
}

From source file:flow.visibility.tapping.OpenDaylightHelper.java

/** The function for inserting the flow */

public static boolean installFlow(JSONObject postData, String user, String password, String baseURL) {

    StringBuffer result = new StringBuffer();

    /** Check the connection to ODP REST API page */

    try {/*w w w  . ja v a 2 s  . c  om*/

        if (!baseURL.contains("http")) {
            baseURL = "http://" + baseURL;
        }
        baseURL = baseURL + "/controller/nb/v2/flowprogrammer/default/node/OF/"
                + postData.getJSONObject("node").get("id") + "/staticFlow/" + postData.get("name");

        /** Create URL = base URL + container */
        URL url = new URL(baseURL);

        /** Create authentication string and encode it to Base64*/
        String authStr = user + ":" + password;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        /** Create Http connection */
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        /** Set connection properties */
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        /** Set JSON Post Data */
        OutputStream os = connection.getOutputStream();
        os.write(postData.toString().getBytes());
        os.close();

        /** Get the response from connection's inputStream */
        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    /** checking the result of REST API connection */

    if ("success".equalsIgnoreCase(result.toString())) {
        return true;
    } else {
        return false;
    }
}

From source file:org.envirocar.app.network.HTTPClient.java

public static HttpEntity createEntity(byte[] data) throws IOException {
    AbstractHttpEntity entity;/* w w w.j ava 2  s  . c om*/
    if (data.length < MIN_GZIP_SIZE) {
        entity = new ByteArrayEntity(data);
    } else {
        ByteArrayOutputStream arr = new ByteArrayOutputStream();
        OutputStream zipper = new GZIPOutputStream(arr);
        zipper.write(data);
        zipper.close();
        entity = new ByteArrayEntity(arr.toByteArray());
        entity.setContentEncoding("gzip");
    }
    return entity;
}