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:gridool.util.net.SocketUtils.java

public static boolean write(final Socket socket, final byte[] b, final long delay, final int maxRetry)
        throws IOException {
    final OutputStream sockout = socket.getOutputStream();
    for (int i = 0; i < maxRetry; i++) {
        try {//w w w  .j a va  2  s. c  o m
            sockout.write(b);
            sockout.flush();
            return true;
        } catch (IOException e) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Failed to write to socket: " + socket.getRemoteSocketAddress() + " #" + i);
            }
        }
        if (delay > 0) {
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ie) {
                ;
            }
        }
    }
    if (LOG.isWarnEnabled()) {
        LOG.warn("Failed to write to socket: " + socket.getRemoteSocketAddress());
    }
    return false;
}

From source file:com.aqnote.shared.cryptology.cert.io.PKCSWriter.java

public static void storePKCS12File(PKCS12PfxPdu pfxPdu, OutputStream ostream) throws Exception {
    if (pfxPdu == null || ostream == null)
        return;// w  w  w. ja va 2  s . c om

    ostream.write(pfxPdu.getEncoded(ASN1Encoding.DER));
    ostream.close();
}

From source file:Base64.java

private static void writeBytes(File file, byte[] data) {
    try {//w  ww  .j a  v a2s  .co m
        OutputStream fos = new FileOutputStream(file);
        OutputStream os = new BufferedOutputStream(fos);
        os.write(data);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:FileCopyUtils.java

/**
 * Copy the contents of the given byte array to the given OutputStream.
 * Closes the stream when done./*from  ww  w.j  a v a 2 s.co  m*/
 * @param in the byte array to copy from
 * @param out the OutputStream to copy to
 * @throws IOException in case of I/O errors
 */
public static void copy(byte[] in, OutputStream out) throws IOException {

    try {
        out.write(in);
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            System.out.println("Could not close OutputStream:" + ex);
        }
    }
}

From source file:bluevia.SendSMS.java

public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) {
    try {//  w  w  w  . j a  v a2s .  co  m

        Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount");
        if (blueviaAccount != null) {
            String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key");
            String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret");
            String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key");
            String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret);
            consumer.setMessageSigner(new HmacSha1MessageSigner());
            consumer.setTokenWithSecret(access_key, access_secret);

            URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1");
            HttpURLConnection request = (HttpURLConnection) apiURI.openConnection();

            request.setRequestProperty("Content-Type", "application/json");
            request.setRequestMethod("POST");
            request.setDoOutput(true);

            consumer.sign(request);
            request.connect();

            String smsTemplate = "{\"smsText\": {\n  \"address\": {\"phoneNumber\": \"%s\"},\n  \"message\": \"%s\",\n  \"originAddress\": {\"alias\": \"%s\"},\n}}";
            String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key);

            OutputStream os = request.getOutputStream();
            os.write(smsMsg.getBytes());
            os.flush();

            int rc = request.getResponseCode();

            if (rc == HttpURLConnection.HTTP_CREATED)
                log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message));
            else
                log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage()));
        } else
            log.warning("BlueVia Account seems to be not configured!");

    } catch (Exception e) {
        log.severe(String.format("Exception sending SMS: %s", e.getMessage()));
    }
}

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

@BeforeClass
public static void setup() {
    final BlockingHandler blockingHandler = new BlockingHandler();
    DefaultServer.setRootHandler(blockingHandler);
    blockingHandler.setRootHandler(new HttpHandler() {
        @Override/*  www  .  ja v a2  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()) {
                    exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                    final OutputStream outputStream = exchange.getOutputStream();
                    outputStream.write("Connection not persistent".getBytes());
                    outputStream.close();
                    return;
                }
                final OutputStream outputStream = exchange.getOutputStream();
                final InputStream inputStream = exchange.getInputStream();
                String m = HttpClientUtils.readResponse(inputStream);
                Assert.assertEquals(message.length(), m.length());
                Assert.assertEquals(message, m);
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:de.qaware.chronix.converter.common.Compression.java

/**
 * Compresses the given byte[]//w ww  . j  ava2 s. c o  m
 *
 * @param decompressed - the byte[] to compress
 * @return the byte[] compressed
 */
public static byte[] compress(byte[] decompressed) {
    if (decompressed == null) {
        return new byte[] {};
    }
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(decompressed.length);
    OutputStream gzipOutputStream = null;
    try {
        gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gzipOutputStream.write(decompressed);
        gzipOutputStream.flush();
        byteArrayOutputStream.flush();
    } catch (IOException e) {
        LOGGER.error("Exception occurred while compressing gzip stream.", e);
        return null;
    } finally {
        IOUtils.closeQuietly(gzipOutputStream);
        IOUtils.closeQuietly(byteArrayOutputStream);
    }

    return byteArrayOutputStream.toByteArray();
}

From source file:bluevia.SendSMS.java

public static void setFacebookWallPost(String userEmail, String post) {
    try {/*  w  ww . j a v a 2  s  .co m*/

        Properties facebookAccount = Util.getNetworkAccount(userEmail, Util.FaceBookOAuth.networkID);

        if (facebookAccount != null) {
            String access_key = facebookAccount.getProperty(Util.FaceBookOAuth.networkID + ".access_key");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            Entity blueviaUser = Util.getUser(userEmail);

            //FIXME
            URL fbAPI = new URL(
                    "https://graph.facebook.com/" + (String) blueviaUser.getProperty("alias") + "/feed");
            HttpURLConnection request = (HttpURLConnection) fbAPI.openConnection();

            String content = String.format("access_token=%s&message=%s", access_key,
                    URLEncoder.encode(post, "UTF-8"));

            request.setRequestMethod("POST");
            request.setRequestProperty("Content-Type", "javascript/text");
            request.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length));
            request.setDoOutput(true);
            request.setDoInput(true);

            OutputStream os = request.getOutputStream();
            os.write(content.getBytes());
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            int rc = request.getResponseCode();
            if (rc == HttpURLConnection.HTTP_OK) {
                StringBuffer body = new StringBuffer();
                String line;

                do {
                    line = br.readLine();
                    if (line != null)
                        body.append(line);
                } while (line != null);

                JSONObject id = new JSONObject(body.toString());
            } else
                log.severe(
                        String.format("Error %d posting FaceBook wall:%s\n", rc, request.getResponseMessage()));
        }
    } catch (Exception e) {
        log.severe(String.format("Exception posting FaceBook wall: %s", e.getMessage()));
    }
}

From source file:chen.android.toolkit.network.HttpConnection.java

/**
 * </br><b>title : </b>      ????POST??
 * </br><b>description :</b>????POST??
 * </br><b>time :</b>      2012-7-8 ?4:34:08
 * @param method         ??/*from w  ww.  j  a  va2  s  . c  o  m*/
 * @param url            POSTURL
 * @param datas            ????
 * @return               ???
 * @throws IOException
 */
private static InputStream connect(String method, URL url, byte[]... datas) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod(method);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    conn.setConnectTimeout(6 * 1000);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charset", "UTF-8");
    OutputStream outputStream = conn.getOutputStream();
    for (byte[] data : datas) {
        outputStream.write(data);
    }
    outputStream.close();
    return conn.getInputStream();
}

From source file:com.fizzed.blaze.system.LineAction.java

static public Deque<String> processLines(final Charset charset, final PipeMixin pipable,
        final LineOutputSupplier lineOuputSupplier) throws BlazeException {
    ObjectHelper.requireNonNull(pipable.getPipeInput(), "pipeInput is required");

    final Deque<String> lines = new ArrayDeque<>();

    final StreamableOutput lineOutput = lineOuputSupplier.create(lines);

    try {//w  w  w.  ja va2s.c o  m
        Streamables.copy(pipable.getPipeInput(), lineOutput);
    } catch (IOException e) {
        throw new WrappedBlazeException(e);
    }

    Streamables.close(pipable.getPipeInput());
    Streamables.close(lineOutput);

    if (pipable.getPipeOutput() != null) {
        try {
            OutputStream os = pipable.getPipeOutput().stream();
            for (String line : lines) {
                String s = line + "\r\n";
                os.write(s.getBytes(charset));
            }
        } catch (IOException e) {
            throw new WrappedBlazeException(e);
        } finally {
            Streamables.closeQuietly(pipable.getPipeOutput());
        }
    }

    return lines;
}