001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.imaging.common.bytesource;
018
019import java.io.IOException;
020import java.io.InputStream;
021
022import org.apache.commons.imaging.common.BinaryFunctions;
023
024public abstract class ByteSource {
025    private final String fileName;
026
027    public ByteSource(final String fileName) {
028        this.fileName = fileName;
029    }
030
031    public final InputStream getInputStream(final long start) throws IOException {
032        InputStream is = null;
033        boolean succeeded = false;
034        try {
035            is = getInputStream();
036            BinaryFunctions.skipBytes(is, start);
037            succeeded = true;
038        } finally {
039            if (!succeeded && is != null) {
040                is.close();
041            }
042        }
043        return is;
044    }
045
046    public abstract InputStream getInputStream() throws IOException;
047
048    public byte[] getBlock(final int start, final int length) throws IOException {
049        return getBlock(0xFFFFffffL & start, length);
050    }
051
052    public abstract byte[] getBlock(long start, int length) throws IOException;
053
054    public abstract byte[] getAll() throws IOException;
055
056    /**
057     * This operation can be VERY expensive; for inputstream byte sources, the
058     * entire stream must be drained to determine its length.
059     *
060     * @return the byte source length
061     * @throws IOException if it fails to read the byte source data
062     */
063    public abstract long getLength() throws IOException;
064
065    public abstract String getDescription();
066
067    public final String getFileName() {
068        return fileName;
069    }
070
071}