View Javadoc
1   package emissary.core.channels;
2   
3   import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
4   import org.apache.commons.lang3.Validate;
5   
6   import java.nio.channels.SeekableByteChannel;
7   
8   /**
9    * Provide an in-memory backed implementation for streaming data to a consumer
10   */
11  public final class InMemoryChannelFactory {
12      private InMemoryChannelFactory() {}
13  
14      /**
15       * Create a new instance of the factory using the provided byte array
16       * 
17       * @param bytes containing the data to provide to consumers in an immutable manner
18       * @return a new instance
19       */
20      public static SeekableByteChannelFactory create(final byte[] bytes) {
21          return ImmutableChannelFactory.create(new InMemoryChannelFactoryImpl(bytes));
22      }
23  
24      /**
25       * Private class to hide implementation details from callers
26       */
27      private static final class InMemoryChannelFactoryImpl implements SeekableByteChannelFactory {
28          /**
29           * The byte array this SeekableByteChannel is to represent.
30           */
31          private final byte[] bytes;
32  
33          private InMemoryChannelFactoryImpl(final byte[] bytes) {
34              Validate.notNull(bytes, "Required: bytes not null");
35  
36              this.bytes = bytes;
37          }
38  
39          /**
40           * Create an immutable byte channel to the existing byte array (no copy in/out regardless of how many channels are
41           * created)
42           * 
43           * @return the new channel instance
44           */
45          @Override
46          public SeekableByteChannel create() {
47              return new SeekableInMemoryByteChannel(bytes);
48          }
49      }
50  }