1/* 2 * Copyright (C) 2010 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 17package com.android.voicemail.impl.mail.store.imap; 18 19import com.android.voicemail.impl.VvmLog; 20import com.android.voicemail.impl.mail.FixedLengthInputStream; 21import java.io.ByteArrayInputStream; 22import java.io.IOException; 23import java.io.InputStream; 24import java.io.UnsupportedEncodingException; 25 26/** Subclass of {@link ImapString} used for literals backed by an in-memory byte array. */ 27public class ImapMemoryLiteral extends ImapString { 28 private final String TAG = "ImapMemoryLiteral"; 29 private byte[] mData; 30 31 /* package */ ImapMemoryLiteral(FixedLengthInputStream in) throws IOException { 32 // We could use ByteArrayOutputStream and IOUtils.copy, but it'd perform an unnecessary 33 // copy.... 34 mData = new byte[in.getLength()]; 35 int pos = 0; 36 while (pos < mData.length) { 37 int read = in.read(mData, pos, mData.length - pos); 38 if (read < 0) { 39 break; 40 } 41 pos += read; 42 } 43 if (pos != mData.length) { 44 VvmLog.w(TAG, "length mismatch"); 45 } 46 } 47 48 @Override 49 public void destroy() { 50 mData = null; 51 super.destroy(); 52 } 53 54 @Override 55 public String getString() { 56 try { 57 return new String(mData, "US-ASCII"); 58 } catch (UnsupportedEncodingException e) { 59 VvmLog.e(TAG, "Unsupported encoding: ", e); 60 } 61 return null; 62 } 63 64 @Override 65 public InputStream getAsStream() { 66 return new ByteArrayInputStream(mData); 67 } 68 69 @Override 70 public String toString() { 71 return String.format("{%d byte literal(memory)}", mData.length); 72 } 73} 74