Example usage for java.io ByteArrayOutputStream close

List of usage examples for java.io ByteArrayOutputStream close

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayOutputStream has no effect.

Usage

From source file:com.breadwallet.tools.manager.SharedPreferencesManager.java

public static void putExchangeRates(Activity activity, Set<CurrencyEntity> rates) {
    SharedPreferences prefs = activity.getSharedPreferences(BRConstants.PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.remove(BRConstants.EXCHANGE_RATES);
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    ObjectOutputStream objectOutput;
    try {/*from w  w w .  j a v  a 2  s  .  c  o  m*/
        objectOutput = new ObjectOutputStream(arrayOutputStream);
        objectOutput.writeObject(rates);
        byte[] data = arrayOutputStream.toByteArray();
        objectOutput.close();
        arrayOutputStream.close();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Base64OutputStream b64 = new Base64OutputStream(out, Base64.NO_WRAP);
        b64.write(data);
        b64.close();
        out.close();
        editor.putString(BRConstants.EXCHANGE_RATES, new String(out.toByteArray()));

        editor.apply();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:nl.ctmm.trait.proteomics.qcviewer.utils.ReportPDFExporter.java

/**
 * Create image of the TIC Chart.//from   w  w  w.  java  2  s  . c o  m
 *
 * @param reportUnit Report unit for which to create TIC chart image.
 * @return TIC Chart image.
 */
private static Image createTICChartImage(final ReportUnit reportUnit) {
    /*Reference: http://vangjee.wordpress.com/2010/11/03/how-to-use-and-not-use-itext-and-jfreechart/
     * Apache License, Version 2.0
     */
    JFreeChart ticChart = null;
    try {
        ticChart = (JFreeChart) reportUnit.getChartUnit().getTicChart().clone();
    } catch (final CloneNotSupportedException e) {
        logger.log(Level.SEVERE, String.format(CLONE_EXCEPTION_MESSAGE, reportUnit.getMsrunName()), e);
    }
    final String titleString = String.format(TIC_GRAPH_TITLE, reportUnit.getMsrunName(),
            reportUnit.getChartUnit().getMaxTicIntensityString());
    final TextTitle newTitle = new TextTitle(titleString, Constants.PDF_CHART_TITLE_FONT);
    newTitle.setPaint(Color.red);
    if (ticChart != null) {
        ticChart.setTitle(newTitle);
    }
    Image chartImage = null;
    try {
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        if (ticChart != null) {
            ChartUtilities.writeChartAsPNG(byteArrayOutputStream, ticChart, CHART_IMAGE_WIDTH,
                    CHART_IMAGE_HEIGHT, new ChartRenderingInfo());
        }
        chartImage = Image.getInstance(byteArrayOutputStream.toByteArray());
        byteArrayOutputStream.close();
    } catch (final BadElementException | IOException e) {
        // TODO Explain when these exception can occur.
        /*
         * IOException occurs in case PDF file can not be created. 
         * e.g. PDF file with same name exist in the PDF directory and it is open. 
         * In this case, the PDF file can not be overwritten. 
         * BadElementException Signals an attempt to create an Element that hasn't got the right form. 
         */
        logger.log(Level.SEVERE, PDF_EXPORT_EXCEPTION_MESSAGE, e);
    }
    if (chartImage != null) {
        chartImage.setAlignment(Element.ALIGN_CENTER);
    }
    return chartImage;
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Stores BufferedImage as JPEG encoded bytestream
 *
 * @param bi/*from  ww  w.ja  v a  2 s  . com*/
 * @return
 * @throws IOException
 */
public static byte[] encodeBufferedImageAsJPEG(BufferedImage bi) throws IOException {

    byte[] byteStream = null;

    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    ImageIO.write(bi, "jpeg", baos);
    baos.flush();
    byteStream = baos.toByteArray();
    baos.close();

    return byteStream;
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Stores BufferedImage as JPEG2000 encoded bytestream
 *
 * @param bi//  w  ww .j a  v  a 2  s .  c  o m
 * @return
 * @throws IOException
 */
public static byte[] encodeBufferedImageAsJP2(BufferedImage bi) throws IOException {

    byte[] byteStream = null;

    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    ImageIO.write(bi, "jpeg2000", baos);
    baos.flush();
    byteStream = baos.toByteArray();
    baos.close();

    return byteStream;
}

From source file:com.clutch.ClutchAPIClient.java

private static void sendRequest(String url, boolean post, JSONObject payload, String version,
        final ClutchAPIResponseHandler responseHandler) {
    BasicHeader[] headers = { new BasicHeader("X-App-Version", version),
            new BasicHeader("X-UDID", ClutchUtils.getUDID()), new BasicHeader("X-API-Version", VERSION),
            new BasicHeader("X-App-Key", appKey), new BasicHeader("X-Bundle-Version", versionName),
            new BasicHeader("X-Platform", "Android"), };
    StringEntity entity = null;//www .  ja  v  a 2s. c  o  m
    try {
        entity = new StringEntity(payload.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Could not encode the JSON payload and attach it to the request: " + payload.toString());
        return;
    }
    HttpRequestBase request = null;
    if (post) {
        request = new HttpPost(url);
        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        request.setHeaders(headers);
    } else {
        request = new HttpGet(url);
    }

    class StatusCodeAndResponse {
        public int statusCode;
        public String response;

        public StatusCodeAndResponse(int statusCode, String response) {
            this.statusCode = statusCode;
            this.response = response;
        }
    }

    new AsyncTask<HttpRequestBase, Void, StatusCodeAndResponse>() {
        @Override
        protected StatusCodeAndResponse doInBackground(HttpRequestBase... requests) {
            try {
                HttpResponse resp = client.execute(requests[0]);

                HttpEntity entity = resp.getEntity();
                InputStream inputStream = entity.getContent();

                ByteArrayOutputStream content = new ByteArrayOutputStream();

                int readBytes = 0;
                byte[] sBuffer = new byte[512];
                while ((readBytes = inputStream.read(sBuffer)) != -1) {
                    content.write(sBuffer, 0, readBytes);
                }

                inputStream.close();

                String response = new String(content.toByteArray());

                content.close();

                return new StatusCodeAndResponse(resp.getStatusLine().getStatusCode(), response);
            } catch (IOException e) {
                if (responseHandler instanceof ClutchAPIDownloadResponseHandler) {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(e, "");
                } else {
                    responseHandler.onFailure(e, null);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(StatusCodeAndResponse resp) {
            if (responseHandler instanceof ClutchAPIDownloadResponseHandler) {
                if (resp.statusCode == 200) {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onSuccess(resp.response);
                } else {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(null, resp.response);
                }
            } else {
                if (resp.statusCode == 200) {
                    responseHandler.handleSuccessMessage(resp.response);
                } else {
                    responseHandler.handleFailureMessage(null, resp.response);
                }
            }
        }
    }.execute(request);
}

From source file:com.isa.utiles.Utiles.java

public static void downloadFile(String linkDescarga, String rutaDestino)
        throws MalformedURLException, IOException {

    URL urlFile = new URL(linkDescarga);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = new BufferedInputStream(urlFile.openStream());

    byte[] buf = new byte[1024];
    int n = 0;/*from  w  w w.j  a va 2s.  c o  m*/
    while (-1 != (n = in.read(buf))) {
        out.write(buf, 0, n);
    }
    out.close();
    in.close();

    /*
    byte[] response = out.toByteArray();
    FileOutputStream fos = new FileOutputStream(rutaDestino);
    fos.write(response);
    fos.close();
    */

    File file = new File(rutaDestino);
    file.setWritable(true);
    file.setReadable(true);

    BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
    bw.write(out.toString());
    bw.close();
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static byte[] gunzip(byte[] contentBytes) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    copy(new GZIPInputStream(new ByteArrayInputStream(contentBytes)), out);

    byte[] result = out.toByteArray();
    out.close();

    return result;
}

From source file:org.linkdroid.PostJob.java

/**
 * Posts the data to our webhook.//from   w  w w . j a v  a  2s . c  o m
 * 
 * The HMAC field calculation notes:
 * <ol>
 * <li>The Extras.HMAC field is calculated from all the non Extras.STREAM
 * fields; this includes all the original bundle extra fields, plus the
 * linkdroid fields (e.g Extras.STREAM_MIME_TYPE, and including
 * Extras.STREAM_HMAC); the NONCE is NOT prepended to the input since it will
 * be somewhere in the data bundle.</li>
 * <li>The Extras.STREAM_HMAC field is calculated by digesting the concat of
 * the NONCE (first) and the actual binary data obtained from the
 * EXTRAS_STREAM uri; this STREAM_HMAC field (along with the other
 * Extras.STREAM_* fields) are added to the data bundle, which will also be
 * hmac'd.</li>
 * <li>If no hmac secret is set, then the NONCEs will not be set in the upload
 * </li>
 * </ol>
 * 
 * @param contentResolver
 * @param webhook
 * @param data
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 */
public static void execute(ContentResolver contentResolver, Bundle webhook, Bundle data)
        throws UnsupportedEncodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {

    // Set constants that may be used in this method.
    final String secret = webhook.getString(WebhookColumns.SECRET);

    // This is the multipart form object that will contain all the data bundle
    // extras; it also will include the data of the extra stream and any other
    // extra linkdroid specific field required.
    MultipartEntity entity = new MultipartEntity();

    // Do the calculations to create our nonce string, if necessary.
    String nonce = obtainNonce(webhook);

    // Add the nonce to the data bundle if we have it.
    if (nonce != null) {
        data.putString(Extras.NONCE, nonce);
    }

    // We have a stream of data, so we need to add that to the multipart form
    // upload with a possible HMAC.
    if (data.containsKey(Intent.EXTRA_STREAM)) {
        Uri mediaUri = (Uri) data.get(Intent.EXTRA_STREAM);

        // Open our mediaUri, base 64 encode it and add it to our multipart upload
        // entity.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream b64os = new Base64OutputStream(baos);
        InputStream is = contentResolver.openInputStream(mediaUri);
        byte[] bytes = new byte[1024];
        int count;
        while ((count = is.read(bytes)) != -1) {
            b64os.write(bytes, 0, count);
        }
        is.close();
        baos.close();
        b64os.close();
        final String base64EncodedString = new String(baos.toByteArray(), UTF8);
        entity.addPart(Extras.STREAM, new StringBody(base64EncodedString, UTF8_CHARSET));

        // Add the mimetype of the stream to the data bundle.
        final String mimeType = contentResolver.getType(mediaUri);
        if (mimeType != null) {
            data.putString(Extras.STREAM_MIME_TYPE, mimeType);
        }

        // Do the hmac calculation of the stream and add it to the data bundle.
        // NOTE: This hmac string will be included as part of the input to the
        // other Extras hmac.
        if (shouldDoHmac(webhook)) {
            InputStream inputStream = contentResolver.openInputStream(mediaUri);
            final String streamHmac = hmacSha1(inputStream, secret, nonce);
            inputStream.close();
            data.putString(Extras.STREAM_HMAC, streamHmac);
            Log.d(TAG, "STREAM_HMAC: " + streamHmac);
        }
    }

    // Calculate the Hmac for all the items by iterating over the data bundle
    // keys in order.
    if (shouldDoHmac(webhook)) {
        final String dataHmac = calculateBundleExtrasHmac(data, secret);
        data.putString(Extras.HMAC, dataHmac);
        Log.d(TAG, "HMAC: " + dataHmac);
    }

    // Dump all the data bundle keys into the form.
    for (String k : data.keySet()) {
        Object value = data.get(k);
        // If the value is null, the key will still be in the form, but with
        // an empty string as its value.
        if (value != null) {
            entity.addPart(k, new StringBody(value.toString(), UTF8_CHARSET));
        } else {
            entity.addPart(k, new StringBody("", UTF8_CHARSET));
        }
    }

    // Create the client and request, then populate it with our multipart form
    // upload entity as part of the POST request; finally post the form.
    final String webhookUri = webhook.getString(WebhookColumns.URI);
    final HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(USER_AGENT_KEY, USER_AGENT);
    final HttpPost request = new HttpPost(webhookUri);
    request.setEntity(entity);
    HttpResponse response = client.execute(request);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
        break;
    default:
        throw new RuntimeException(response.getStatusLine().toString());
    }
}

From source file:Main.java

public static byte[] decodeQuotedPrintable(final byte[] bytes) {
    if (bytes == null) {
        return null;
    }//  ww w  . j a  va 2 s  .c  o m
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    for (int i = 0; i < bytes.length; i++) {
        final int b = bytes[i];
        if (b == '=') {
            try {
                final int u = Character.digit((char) bytes[++i], 16);
                final int l = Character.digit((char) bytes[++i], 16);
                buffer.write((char) ((u << 4) + l));
            } catch (Exception e) {
                //                    FileLog.e("tmessages", e);
                return null;
            }
        } else {
            buffer.write(b);
        }
    }
    byte[] array = buffer.toByteArray();
    try {
        buffer.close();
    } catch (Exception e) {
        //            FileLog.e("tmessages", e);
    }
    return array;
}

From source file:me.tfeng.toolbox.avro.AvroHelper.java

public static byte[] encodeRecord(IndexedRecord record) throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {//from   w  w w  .  j a  v  a  2  s.c  om
        EncoderFactory encoderFactory = EncoderFactory.get();
        BinaryEncoder binaryEncoder = encoderFactory.binaryEncoder(stream, null);
        SpecificDatumWriter<IndexedRecord> datumWriter = new SpecificDatumWriter<>(record.getSchema());
        datumWriter.write(record, binaryEncoder);
        binaryEncoder.flush();
    } finally {
        stream.close();
    }
    return stream.toByteArray();
}