1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.emailcommon.mail; 18 19 import android.util.Base64; 20 import android.util.Base64OutputStream; 21 22 import org.apache.commons.io.IOUtils; 23 24 import java.io.IOException; 25 import java.io.InputStream; 26 import java.io.OutputStream; 27 28 public class Base64Body implements Body { 29 private final InputStream mSource; 30 // Because we consume the input stream, we can only write out once 31 private boolean mAlreadyWritten; 32 Base64Body(InputStream source)33 public Base64Body(InputStream source) { 34 mSource = source; 35 } 36 37 @Override getInputStream()38 public InputStream getInputStream() throws MessagingException { 39 return mSource; 40 } 41 42 /** 43 * This method consumes the input stream, so can only be called once 44 * @param out Stream to write to 45 * @throws IllegalStateException If called more than once 46 * @throws IOException 47 * @throws MessagingException 48 */ 49 @Override writeTo(OutputStream out)50 public void writeTo(OutputStream out) 51 throws IllegalStateException, IOException, MessagingException { 52 if (mAlreadyWritten) { 53 throw new IllegalStateException("Base64Body can only be written once"); 54 } 55 mAlreadyWritten = true; 56 try { 57 final Base64OutputStream b64out = new Base64OutputStream(out, Base64.DEFAULT); 58 IOUtils.copyLarge(mSource, b64out); 59 } finally { 60 mSource.close(); 61 } 62 } 63 } 64