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.internal.util; 18 19 import com.android.apksig.util.DataSink; 20 import java.io.IOException; 21 import java.io.OutputStream; 22 import java.nio.ByteBuffer; 23 24 /** 25 * {@link DataSink} which outputs received data into the associated {@link OutputStream}. 26 */ 27 public class OutputStreamDataSink implements DataSink { 28 29 private static final int MAX_READ_CHUNK_SIZE = 65536; 30 31 private final OutputStream mOut; 32 33 /** 34 * Constructs a new {@code OutputStreamDataSink} which outputs received data into the provided 35 * {@link OutputStream}. 36 */ OutputStreamDataSink(OutputStream out)37 public OutputStreamDataSink(OutputStream out) { 38 if (out == null) { 39 throw new NullPointerException("out == null"); 40 } 41 mOut = out; 42 } 43 44 /** 45 * Returns {@link OutputStream} into which this data sink outputs received data. 46 */ getOutputStream()47 public OutputStream getOutputStream() { 48 return mOut; 49 } 50 51 @Override consume(byte[] buf, int offset, int length)52 public void consume(byte[] buf, int offset, int length) throws IOException { 53 mOut.write(buf, offset, length); 54 } 55 56 @Override consume(ByteBuffer buf)57 public void consume(ByteBuffer buf) throws IOException { 58 if (!buf.hasRemaining()) { 59 return; 60 } 61 62 if (buf.hasArray()) { 63 mOut.write( 64 buf.array(), 65 buf.arrayOffset() + buf.position(), 66 buf.remaining()); 67 buf.position(buf.limit()); 68 } else { 69 byte[] tmp = new byte[Math.min(buf.remaining(), MAX_READ_CHUNK_SIZE)]; 70 while (buf.hasRemaining()) { 71 int chunkSize = Math.min(buf.remaining(), tmp.length); 72 buf.get(tmp, 0, chunkSize); 73 mOut.write(tmp, 0, chunkSize); 74 } 75 } 76 } 77 } 78