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