View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.imaging.common.bytesource;
18  
19  import java.io.ByteArrayInputStream;
20  import java.io.IOException;
21  import java.io.InputStream;
22  
23  public class ByteSourceArray extends ByteSource {
24      private final byte[] bytes;
25  
26      public ByteSourceArray(final String fileName, final byte[] bytes) {
27          super(fileName);
28          this.bytes = bytes;
29      }
30  
31      public ByteSourceArray(final byte[] bytes) {
32          this(null, bytes);
33      }
34  
35      @Override
36      public InputStream getInputStream() {
37          return new ByteArrayInputStream(bytes);
38      }
39  
40      @Override
41      public byte[] getBlock(final long startLong, final int length) throws IOException {
42          final int start = (int) startLong;
43          // We include a separate check for int overflow.
44          if ((start < 0) || (length < 0) || (start + length < 0)
45                  || (start + length > bytes.length)) {
46              throw new IOException("Could not read block (block start: " + start
47                      + ", block length: " + length + ", data length: "
48                      + bytes.length + ").");
49          }
50  
51          final byte[] result = new byte[length];
52          System.arraycopy(bytes, start, result, 0, length);
53          return result;
54      }
55  
56      @Override
57      public long getLength() {
58          return bytes.length;
59      }
60  
61      @Override
62      public byte[] getAll() throws IOException {
63          return bytes;
64      }
65  
66      @Override
67      public String getDescription() {
68          return bytes.length + " byte array";
69      }
70  
71  }