1 /* 2 * Copyright (C) 2016 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.apksig.util; 18 19 import com.android.apksig.internal.util.RandomAccessFileDataSink; 20 import java.io.File; 21 import java.io.IOException; 22 import java.io.RandomAccessFile; 23 import java.nio.ByteBuffer; 24 import org.junit.runner.RunWith; 25 import org.junit.runners.JUnit4; 26 27 /** 28 * Tests for the {@link DataSink} returned by 29 * {@link DataSinks#asDataSink(java.io.RandomAccessFile)}. 30 */ 31 @RunWith(JUnit4.class) 32 public class DataSinkFromRAFTest extends DataSinkTestBase<RandomAccessFileDataSink> { 33 34 @Override createDataSink()35 protected CloseableWithDataSink<RandomAccessFileDataSink> createDataSink() throws IOException { 36 File tmp = File.createTempFile(DataSourceFromRAFTest.class.getSimpleName(), ".bin"); 37 RandomAccessFile f = null; 38 try { 39 f = new RandomAccessFile(tmp, "rw"); 40 } finally { 41 if (f == null) { 42 tmp.delete(); 43 } 44 } 45 return CloseableWithDataSink.of( 46 (RandomAccessFileDataSink) DataSinks.asDataSink(f), 47 new DataSourceFromRAFTest.TmpFileCloseable(tmp, f)); 48 } 49 50 @Override getContents(RandomAccessFileDataSink dataSink)51 protected ByteBuffer getContents(RandomAccessFileDataSink dataSink) throws IOException { 52 RandomAccessFile f = dataSink.getFile(); 53 if (f.length() > Integer.MAX_VALUE) { 54 throw new IOException("File too large: " + f.length()); 55 } 56 byte[] contents = new byte[(int) f.length()]; 57 f.seek(0); 58 f.readFully(contents); 59 return ByteBuffer.wrap(contents); 60 } 61 } 62