1 /* 2 * Copyright (C) 2015 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 package com.android.voicemail.impl.mail; 17 18 import android.util.Base64; 19 import android.util.Base64OutputStream; 20 import java.io.IOException; 21 import java.io.InputStream; 22 import java.io.OutputStream; 23 import org.apache.commons.io.IOUtils; 24 25 public class Base64Body implements Body { 26 private final InputStream source; 27 // Because we consume the input stream, we can only write out once 28 private boolean alreadyWritten; 29 Base64Body(InputStream source)30 public Base64Body(InputStream source) { 31 this.source = source; 32 } 33 34 @Override getInputStream()35 public InputStream getInputStream() throws MessagingException { 36 return source; 37 } 38 39 /** 40 * This method consumes the input stream, so can only be called once 41 * 42 * @param out Stream to write to 43 * @throws IllegalStateException If called more than once 44 * @throws IOException 45 * @throws MessagingException 46 */ 47 @Override writeTo(OutputStream out)48 public void writeTo(OutputStream out) 49 throws IllegalStateException, IOException, MessagingException { 50 if (alreadyWritten) { 51 throw new IllegalStateException("Base64Body can only be written once"); 52 } 53 alreadyWritten = true; 54 try { 55 final Base64OutputStream b64out = new Base64OutputStream(out, Base64.DEFAULT); 56 IOUtils.copyLarge(source, b64out); 57 } finally { 58 source.close(); 59 } 60 } 61 } 62