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