View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.client.util;
20  
21  import java.nio.ByteBuffer;
22  import java.util.Iterator;
23  import java.util.NoSuchElementException;
24  
25  import org.eclipse.jetty.client.api.ContentProvider;
26  
27  /**
28   * A {@link ContentProvider} for byte arrays.
29   */
30  public class BytesContentProvider implements ContentProvider
31  {
32      private final byte[][] bytes;
33      private final long length;
34  
35      public BytesContentProvider(byte[]... bytes)
36      {
37          this.bytes = bytes;
38          long length = 0;
39          for (byte[] buffer : bytes)
40              length += buffer.length;
41          this.length = length;
42      }
43  
44      @Override
45      public long getLength()
46      {
47          return length;
48      }
49  
50      @Override
51      public Iterator<ByteBuffer> iterator()
52      {
53          return new Iterator<ByteBuffer>()
54          {
55              private int index;
56  
57              @Override
58              public boolean hasNext()
59              {
60                  return index < bytes.length;
61              }
62  
63              @Override
64              public ByteBuffer next()
65              {
66                  try
67                  {
68                      return ByteBuffer.wrap(bytes[index++]);
69                  }
70                  catch (ArrayIndexOutOfBoundsException x)
71                  {
72                      throw new NoSuchElementException();
73                  }
74              }
75  
76              @Override
77              public void remove()
78              {
79                  throw new UnsupportedOperationException();
80              }
81          };
82      }
83  }