1 /* 2 * Copyright (C) 2011 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.tradefed.result; 17 18 import com.android.tradefed.log.LogUtil.CLog; 19 import com.android.tradefed.util.FileUtil; 20 21 import java.io.File; 22 import java.io.FileInputStream; 23 import java.io.IOException; 24 import java.io.InputStream; 25 26 /** 27 * A File-backed InputStreamSource. Creates a snapshot of original {@link InputStream} contents to 28 * ensure that {@link #createInputStream()} will return identically-behaving {@link InputStream}s as 29 * required. 30 */ 31 public class SnapshotInputStreamSource implements InputStreamSource { 32 private File mBackingFile; 33 private boolean mIsCancelled = false; 34 35 /** Constructor for a file-backed {@link InputStreamSource} */ 36 public SnapshotInputStreamSource(String name, InputStream stream) { 37 if (stream == null) { 38 throw new NullPointerException(); 39 } 40 41 try { 42 mBackingFile = createBackingFile(name, stream); 43 } catch (IOException e) { 44 // Log an error and invalidate ourself 45 CLog.e("Received IOException while trying to wrap a stream"); 46 CLog.e(e); 47 close(); 48 } 49 } 50 51 /** 52 * Create the backing file and fill it with the contents of {@code stream}. 53 * 54 * <p>Exposed for unit testing 55 */ 56 File createBackingFile(String name, InputStream stream) throws IOException { 57 File backingFile = 58 FileUtil.createTempFile(name + "_" + this.getClass().getSimpleName() + "_", ".txt"); 59 FileUtil.writeToFile(stream, backingFile); 60 return backingFile; 61 } 62 63 /** 64 * {@inheritDoc} 65 */ 66 @Override 67 public synchronized InputStream createInputStream() { 68 if (mIsCancelled) { 69 return null; 70 } 71 72 try { 73 return new FileInputStream(mBackingFile); 74 } catch (IOException e) { 75 return null; 76 } 77 } 78 79 /** {@inheritDoc} */ 80 @Override 81 public synchronized void close() { 82 mIsCancelled = true; 83 FileUtil.deleteFile(mBackingFile); 84 mBackingFile = null; 85 } 86 87 /** 88 * {@inheritDoc} 89 */ 90 @Override 91 public long size() { 92 return mBackingFile.length(); 93 } 94 } 95 96