Example usage for android.util Base64OutputStream Base64OutputStream

List of usage examples for android.util Base64OutputStream Base64OutputStream

Introduction

In this page you can find the example usage for android.util Base64OutputStream Base64OutputStream.

Prototype

public Base64OutputStream(OutputStream out, int flags) 

Source Link

Document

Performs Base64 encoding on the data written to the stream, writing the encoded data to another OutputStream.

Usage

From source file:com.mail163.email.mail.transport.Rfc822Output.java

/**
 * Write a single attachment and its payload
 *///from  ww w  .j av  a2 s  . c om
private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment)
        throws IOException, MessagingException {
    //       String attachmentName = attachment.mFileName;
    String attachmentName = EncoderUtil.encodeAddressDisplayName(attachment.mFileName);

    writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachmentName + "\"");

    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    // Most attachments (real files) will send Content-Disposition.  The suppression option
    // is used when sending calendar invites.
    if ((attachment.mFlags & Attachment.FLAG_ICS_ALTERNATIVE_PART) == 0) {
        writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachmentName + "\";"
                + "\n size=" + Long.toString(attachment.mSize));
    }

    writeHeader(writer, "Content-ID", attachment.mContentId);
    writer.append("\r\n");

    // Set up input stream and write it out via base64
    InputStream inStream = null;
    try {
        // Use content, if provided; otherwise, use the contentUri
        if (attachment.mContentBytes != null) {
            inStream = new ByteArrayInputStream(attachment.mContentBytes);
        } else {
            // try to open the file
            Uri fileUri = Uri.parse(attachment.mContentUri);
            inStream = context.getContentResolver().openInputStream(fileUri);
        }
        // switch to output stream for base64 text output
        writer.flush();
        Base64OutputStream base64Out = new Base64OutputStream(out, Base64.CRLF | Base64.NO_CLOSE);
        // copy base64 data and close up
        IOUtils.copy(inStream, base64Out);
        base64Out.close();

        // The old Base64OutputStream wrote an extra CRLF after
        // the output.  It's not required by the base-64 spec; not
        // sure if it's required by RFC 822 or not.
        out.write('\r');
        out.write('\n');
        out.flush();
    } catch (FileNotFoundException fnfe) {
        // Ignore this - empty file is OK
    } catch (IOException ioe) {
        throw new MessagingException("Invalid attachment.", ioe);
    }
}

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 {//ww  w.j  a  va2s  .  co  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:com.hujiang.restvolley.webapi.request.JsonStreamerEntity.java

private void writeToFromFile(OutputStream os, FileWrapper wrapper) throws IOException {

    // Send the meta data.
    writeMetaData(os, wrapper.file.getName(), wrapper.contentType);

    int bytesRead;

    // Open the file for reading.
    FileInputStream in = new FileInputStream(wrapper.file);

    // Upload the file's contents in Base64.
    Base64OutputStream bos = new Base64OutputStream(os, Base64.NO_CLOSE | Base64.NO_WRAP);

    // Read from file until no more data's left to read.
    while ((bytesRead = in.read(buffer)) != -1) {
        bos.write(buffer, 0, bytesRead);
    }/*from w  ww.ja  v a 2s . c o m*/

    // Close the Base64 output stream.
    if (bos != null) {
        bos.close();
    }

    // End the meta data.
    endMetaData(os);

    // Safely close the input stream.
    if (in != null) {
        in.close();
    }
}

From source file:com.android.emailcommon.internet.Rfc822Output.java

/**
 * Write a single attachment and its payload
 *///from www.j a  v a 2s.  c  o  m
private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment)
        throws IOException, MessagingException {
    writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\"");
    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    // Most attachments (real files) will send Content-Disposition.  The suppression option
    // is used when sending calendar invites.
    if ((attachment.mFlags & Attachment.FLAG_ICS_ALTERNATIVE_PART) == 0) {
        writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName
                + "\";" + "\n size=" + Long.toString(attachment.mSize));
    }
    if (attachment.mContentId != null) {
        writeHeader(writer, "Content-ID", attachment.mContentId);
    }
    writer.append("\r\n");

    // Set up input stream and write it out via base64
    InputStream inStream = null;
    try {
        // Use content, if provided; otherwise, use the contentUri
        if (attachment.mContentBytes != null) {
            inStream = new ByteArrayInputStream(attachment.mContentBytes);
        } else {
            // try to open the file
            Uri fileUri = Uri.parse(attachment.mContentUri);
            inStream = context.getContentResolver().openInputStream(fileUri);
        }
        // switch to output stream for base64 text output
        writer.flush();
        Base64OutputStream base64Out = new Base64OutputStream(out, Base64.CRLF | Base64.NO_CLOSE);
        // copy base64 data and close up
        IOUtils.copy(inStream, base64Out);
        base64Out.close();

        // The old Base64OutputStream wrote an extra CRLF after
        // the output.  It's not required by the base-64 spec; not
        // sure if it's required by RFC 822 or not.
        out.write('\r');
        out.write('\n');
        out.flush();
    } catch (FileNotFoundException fnfe) {
        // Ignore this - empty file is OK
    } catch (IOException ioe) {
        throw new MessagingException("Invalid attachment.", ioe);
    }
}

From source file:com.tct.emailcommon.internet.Rfc822Output.java

/**
 * Write a single attachment and its payload
 */// ww w.  j a  v a2  s.  c  o m
private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment)
        throws IOException, MessagingException {
    writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" +
    // TS: junwei-xu 2014-12-05 EMAIL BUGFIX_861660 MOD_S
            MimeUtility.foldAndEncode2(attachment.mFileName, "ContentType".length() + 2) + "\"");
    // TS: junwei-xu 2014-12-05 EMAIL BUGFIX_861660 MOD_E
    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    // Most attachments (real files) will send Content-Disposition.  The suppression option
    // is used when sending calendar invites.
    if ((attachment.mFlags & Attachment.FLAG_ICS_ALTERNATIVE_PART) == 0) {
        writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" +
        // TS: junwei-xu 2014-12-05 EMAIL BUGFIX_861660 MOD_S
                MimeUtility.foldAndEncode2(attachment.mFileName, "ContentType".length() + 2)
                // TS: junwei-xu 2014-12-05 EMAIL BUGFIX_861660 MOD_E
                + "\";" + "\n size=" + Long.toString(attachment.mSize));
    }
    if (attachment.mContentId != null) {
        writeHeader(writer, "Content-ID", attachment.mContentId);
    }
    writer.append("\r\n");

    // Set up input stream and write it out via base64
    InputStream inStream = null;
    try {
        // Use content, if provided; otherwise, use the contentUri
        if (attachment.mContentBytes != null) {
            inStream = new ByteArrayInputStream(attachment.mContentBytes);
        } else {
            // First try the cached file
            final String cachedFile = attachment.getCachedFileUri();
            if (!TextUtils.isEmpty(cachedFile)) {
                final Uri cachedFileUri = Uri.parse(cachedFile);
                try {
                    inStream = context.getContentResolver().openInputStream(cachedFileUri);
                } catch (FileNotFoundException e) {
                    // Couldn't open the cached file, fall back to the original content uri
                    inStream = null;

                    LogUtils.i(TAG, "Rfc822Output#writeOneAttachment(), failed to load"
                            + "cached file, falling back to: %s", attachment.getContentUri());
                }
            }

            if (inStream == null) {
                // try to open the file
                final Uri fileUri = Uri.parse(attachment.getContentUri());
                inStream = context.getContentResolver().openInputStream(fileUri);
            }
        }
        // switch to output stream for base64 text output
        writer.flush();
        Base64OutputStream base64Out = new Base64OutputStream(out, Base64.CRLF | Base64.NO_CLOSE);
        // copy base64 data and close up
        IOUtils.copy(inStream, base64Out);
        base64Out.close();

        // The old Base64OutputStream wrote an extra CRLF after
        // the output.  It's not required by the base-64 spec; not
        // sure if it's required by RFC 822 or not.
        out.write('\r');
        out.write('\n');
        out.flush();
    } catch (FileNotFoundException fnfe) {
        // Ignore this - empty file is OK
        LogUtils.e(TAG, fnfe,
                "Rfc822Output#writeOneAttachment(), FileNotFoundException" + "when sending attachment");
    } catch (IOException ioe) {
        LogUtils.e(TAG, ioe, "Rfc822Output#writeOneAttachment(), IOException" + "when sending attachment");
        throw new MessagingException("Invalid attachment.", ioe);
    }
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

private void encodeFileBase64(File file, DataOutputStream out) {
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    FileInputStream in = null;// ww  w.j  a va  2s . c  o m
    try {
        in = new FileInputStream(file);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return;
    }
    Base64OutputStream out64 = new Base64OutputStream(out, Base64.NO_CLOSE);
    try {
        while ((bytesRead = in.read(buffer)) > 0) { //this loop grabs more of the file and uploads it 4KB  at a time
            out64.write(buffer, 0, bytesRead);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
            out64.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }
}

From source file:ti.okhttp.TiOkhttpclient.java

private int addTitaniumFileAsPostData(String name, Object value) {
    try {/*  w  w  w. j a v  a2s  .  c  o m*/
        // TiResourceFile cannot use the FileBody approach directly, because it requires
        // a java File object, which you can't get from packaged resources. So
        // TiResourceFile uses the approach we use for blobs, which is write out the
        // contents to a temp file, then use that for the FileBody.
        if (value instanceof TiBaseFile && !(value instanceof TiResourceFile)) {
            TiBaseFile baseFile = (TiBaseFile) value;
            FileBody body = new FileBody(baseFile.getNativeFile(),
                    TiMimeTypeHelper.getMimeType(baseFile.nativePath()));
            parts.put(name, body);
            return (int) baseFile.getNativeFile().length();

        } else if (value instanceof TiBlob || value instanceof TiResourceFile) {
            TiBlob blob;
            if (value instanceof TiBlob) {
                blob = (TiBlob) value;
            } else {
                blob = ((TiResourceFile) value).read();
            }
            String mimeType = blob.getMimeType();
            File tmpFile = File.createTempFile("tixhr",
                    "." + TiMimeTypeHelper.getFileExtensionFromMimeType(mimeType, "txt"));
            FileOutputStream fos = new FileOutputStream(tmpFile);
            if (blob.getType() == TiBlob.TYPE_STREAM_BASE64) {
                TiBaseFile.copyStream(blob.getInputStream(),
                        new Base64OutputStream(fos, android.util.Base64.DEFAULT));
            } else {
                fos.write(blob.getBytes());
            }
            fos.close();

            tmpFiles.add(tmpFile);

            FileBody body = new FileBody(tmpFile, mimeType);
            parts.put(name, body);
            return (int) tmpFile.length();
        } else if (value instanceof HashMap) {
            // If value is a HashMap, it is actually a JSON
            JSONObject jsonObject = TiConvert.toJSON((HashMap<String, Object>) value);
            JsonBody jsonBody = new JsonBody(jsonObject, null);
            parts.put(name, jsonBody);
            return (int) jsonBody.getContentLength();
        } else {
            if (value != null) {
                Log.e(TAG, name + " is a " + value.getClass().getSimpleName());

            } else {
                Log.e(TAG, name + " is null");
            }
        }

    } catch (IOException e) {
        Log.e(TAG, "Error adding post data (" + name + "): " + e.getMessage());
    }
    return 0;
}

From source file:org.mozilla.gecko.BrowserApp.java

private void getFaviconFromCache(final EventCallback callback, final String url) {
    final OnFaviconLoadedListener listener = new OnFaviconLoadedListener() {
        @Override/*from w  w  w .  j av  a2s. c om*/
        public void onFaviconLoaded(final String url, final String faviconURL, final Bitmap favicon) {
            ThreadUtils.assertOnUiThread();
            // Convert Bitmap to Base64 data URI in background.
            ThreadUtils.postToBackgroundThread(new Runnable() {
                @Override
                public void run() {
                    ByteArrayOutputStream out = null;
                    Base64OutputStream b64 = null;

                    // Failed to load favicon from local.
                    if (favicon == null) {
                        callback.sendError("Failed to get favicon from cache");
                    } else {
                        try {
                            out = new ByteArrayOutputStream();
                            out.write("data:image/png;base64,".getBytes());
                            b64 = new Base64OutputStream(out, Base64.NO_WRAP);
                            favicon.compress(Bitmap.CompressFormat.PNG, 100, b64);
                            callback.sendSuccess(new String(out.toByteArray()));
                        } catch (IOException e) {
                            Log.w(LOGTAG, "Failed to convert to base64 data URI");
                            callback.sendError("Failed to convert favicon to a base64 data URI");
                        } finally {
                            try {
                                if (out != null) {
                                    out.close();
                                }
                                if (b64 != null) {
                                    b64.close();
                                }
                            } catch (IOException e) {
                                Log.w(LOGTAG, "Failed to close the streams");
                            }
                        }
                    }
                }
            });
        }
    };
    Favicons.getSizedFaviconForPageFromLocal(getContext(), url, listener);
}