Line data Source code
1 : // Copyright (C) 2016 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.ioutil; 16 : 17 : import static com.google.common.base.Preconditions.checkArgument; 18 : 19 : import java.io.ByteArrayOutputStream; 20 : import java.io.IOException; 21 : import java.io.OutputStream; 22 : 23 : /** A stream that throws an exception if it consumes data beyond a configured byte count. */ 24 : public class LimitedByteArrayOutputStream extends OutputStream { 25 : 26 : private final int maxSize; 27 : private final ByteArrayOutputStream buffer; 28 : 29 : /** 30 : * Constructs a LimitedByteArrayOutputStream, which stores output in memory up to a certain 31 : * specified size. When the output exceeds the specified size a LimitExceededException is thrown. 32 : * 33 : * @param max the maximum size in bytes which may be stored. 34 : * @param initial the initial size. It must be smaller than the max size. 35 : */ 36 0 : public LimitedByteArrayOutputStream(int max, int initial) { 37 0 : checkArgument(initial <= max); 38 0 : maxSize = max; 39 0 : buffer = new ByteArrayOutputStream(initial); 40 0 : } 41 : 42 : private void checkOversize(int additionalSize) throws IOException { 43 0 : if (buffer.size() + additionalSize > maxSize) { 44 0 : throw new LimitExceededException(); 45 : } 46 0 : } 47 : 48 : @Override 49 : public void write(int b) throws IOException { 50 0 : checkOversize(1); 51 0 : buffer.write(b); 52 0 : } 53 : 54 : @Override 55 : public void write(byte[] b, int off, int len) throws IOException { 56 0 : checkOversize(len); 57 0 : buffer.write(b, off, len); 58 0 : } 59 : 60 : /** Returns a newly allocated byte array with contents of the buffer. */ 61 : public byte[] toByteArray() { 62 0 : return buffer.toByteArray(); 63 : } 64 : 65 0 : public static class LimitExceededException extends IOException { 66 : private static final long serialVersionUID = 1L; 67 : } 68 : }