View Javadoc

1   /*
2    * Copyright 2007 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package net.sf.morph.util;
17  
18  import java.io.InputStream;
19  import java.io.BufferedInputStream;
20  import java.io.IOException;
21  
22  import org.springframework.core.io.Resource;
23  
24  /**
25   * Special <code>InputStream</code> that will concatenate the contents of a Spring Resource[].
26   * Adapted from Apache Ant ConcatResourceInputStream.
27   */
28  public class ResourceArrayInputStream extends InputStream {
29  
30      private static final int EOF = -1;
31      private boolean eof = false;
32      private InputStream currentStream;
33      private Resource[] resources;
34      private int index = -1;
35  
36      /**
37       * Construct a new ResourceArrayInputStream.
38       * @param resources
39       */
40      public ResourceArrayInputStream(Resource[] resources) {
41      	this.resources = resources;
42      }
43  
44      /**
45       * Close the stream.
46       * @throws IOException if there is an error.
47       */
48       public void close() throws IOException {
49          closeCurrent();
50          eof = true;
51      }
52  
53      /**
54       * Read a byte.
55       * @return the byte (0 - 255) or -1 if this is the end of the stream.
56       * @throws IOException if there is an error.
57       */
58      public int read() throws IOException {
59          if (eof) {
60              return EOF;
61          }
62          int result = readCurrent();
63          if (result == EOF) {
64              nextResource();
65              result = readCurrent();
66          }
67          return result;
68      }
69  
70      private int readCurrent() throws IOException {
71          return eof || currentStream == null ? EOF : currentStream.read();
72      }
73  
74      private void nextResource() throws IOException {
75          closeCurrent();
76          if (resources == null || ++index == resources.length) {
77          	eof = true;
78          } else {
79          	currentStream = new BufferedInputStream(resources[index].getInputStream());
80          }
81      }
82  
83      private void closeCurrent() {
84  		if (currentStream != null) {
85  			try {
86  				currentStream.close();
87  			} catch (IOException e) {
88  				//ignore
89  			}
90  	        currentStream = null;
91  		}
92      }
93  }