    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one
    003 * or more contributor license agreements.  See the NOTICE file
    004 * distributed with this work for additional information
    005 * regarding copyright ownership.  The ASF licenses this file
    006 * to you under the Apache License, Version 2.0 (the
    007 * "License"); you may not use this file except in compliance
    008 * with the License.  You may obtain a copy of the License at
    009 *
    010 * http://www.apache.org/licenses/LICENSE-2.0
    011 *
    012 * Unless required by applicable law or agreed to in writing,
    013 * software distributed under the License is distributed on an
    014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    015 * KIND, either express or implied.  See the License for the
    016 * specific language governing permissions and limitations
    017 * under the License.
    018 */
    019package org.apache.commons.compress;
    020
    021import java.io.IOException;
    022
    023/**
    024 * If a stream checks for estimated memory allocation, and the estimate
    025 * goes above the memory limit, this is thrown.  This can also be thrown
    026 * if a stream tries to allocate a byte array that is larger than
    027 * the allowable limit.
    028 *
    029 * @since 1.14
    030 */
    031public class MemoryLimitException extends IOException {
    032
    033    private static final long serialVersionUID = 1L;
    034
    035    //long instead of int to account for overflow for corrupt files
    036    private final long memoryNeededInKb;
    037    private final int memoryLimitInKb;
    038
    039    public MemoryLimitException(final long memoryNeededInKb, final int memoryLimitInKb) {
    040        super(buildMessage(memoryNeededInKb, memoryLimitInKb));
    041        this.memoryNeededInKb = memoryNeededInKb;
    042        this.memoryLimitInKb = memoryLimitInKb;
    043    }
    044
    045    public MemoryLimitException(final long memoryNeededInKb, final int memoryLimitInKb, final Exception e) {
    046        super(buildMessage(memoryNeededInKb, memoryLimitInKb), e);
    047        this.memoryNeededInKb = memoryNeededInKb;
    048        this.memoryLimitInKb = memoryLimitInKb;
    049    }
    050
    051    public long getMemoryNeededInKb() {
    052        return memoryNeededInKb;
    053    }
    054
    055    public int getMemoryLimitInKb() {
    056        return memoryLimitInKb;
    057    }
    058
    059    private static String buildMessage(final long memoryNeededInKb, final int memoryLimitInKb) {
    060        return memoryNeededInKb + " kb of memory would be needed; limit was "
    061                + memoryLimitInKb + " kb. " +
    062                "If the file is not corrupt, consider increasing the memory limit.";
    063    }
    064}