1 //
2 // ========================================================================
3 // Copyright (c) 1995-2014 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 /**
26 * A {@link ContentProvider} for byte arrays.
27 */
28 public class BytesContentProvider extends AbstractTypedContentProvider
29 {
30 private final byte[][] bytes;
31 private final long length;
32
33 public BytesContentProvider(byte[]... bytes)
34 {
35 this("application/octet-stream", bytes);
36 }
37
38 public BytesContentProvider(String contentType, byte[]... bytes)
39 {
40 super(contentType);
41 this.bytes = bytes;
42 long length = 0;
43 for (byte[] buffer : bytes)
44 length += buffer.length;
45 this.length = length;
46 }
47
48 @Override
49 public long getLength()
50 {
51 return length;
52 }
53
54 @Override
55 public Iterator<ByteBuffer> iterator()
56 {
57 return new Iterator<ByteBuffer>()
58 {
59 private int index;
60
61 @Override
62 public boolean hasNext()
63 {
64 return index < bytes.length;
65 }
66
67 @Override
68 public ByteBuffer next()
69 {
70 try
71 {
72 return ByteBuffer.wrap(bytes[index++]);
73 }
74 catch (ArrayIndexOutOfBoundsException x)
75 {
76 throw new NoSuchElementException();
77 }
78 }
79
80 @Override
81 public void remove()
82 {
83 throw new UnsupportedOperationException();
84 }
85 };
86 }
87 }