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    private static String buildMessage(final long memoryNeededInKb, final int memoryLimitInKb) {
036        return memoryNeededInKb + " kb of memory would be needed; limit was "
037                + memoryLimitInKb + " kb. " +
038                "If the file is not corrupt, consider increasing the memory limit.";
039    }
040    /** long instead of int to account for overflow for corrupt files. */
041    private final long memoryNeededInKb;
042
043    private final int memoryLimitInKb;
044
045    public MemoryLimitException(final long memoryNeededInKb, final int memoryLimitInKb) {
046        super(buildMessage(memoryNeededInKb, memoryLimitInKb));
047        this.memoryNeededInKb = memoryNeededInKb;
048        this.memoryLimitInKb = memoryLimitInKb;
049    }
050
051    public MemoryLimitException(final long memoryNeededInKb, final int memoryLimitInKb, final Exception e) {
052        super(buildMessage(memoryNeededInKb, memoryLimitInKb), e);
053        this.memoryNeededInKb = memoryNeededInKb;
054        this.memoryLimitInKb = memoryLimitInKb;
055    }
056
057    public int getMemoryLimitInKb() {
058        return memoryLimitInKb;
059    }
060
061    public long getMemoryNeededInKb() {
062        return memoryNeededInKb;
063    }
064}