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 {@link ByteBuffer}s.
29 * <p>
30 * The position and limit of the {@link ByteBuffer}s passed to the constructor are not modified,
31 * and each invocation of the {@link #iterator()} method returns a {@link ByteBuffer#slice() slice}
32 * of the original {@link ByteBuffer}.
33 */
34 public class ByteBufferContentProvider extends AbstractTypedContentProvider
35 {
36 private final ByteBuffer[] buffers;
37 private final int length;
38
39 public ByteBufferContentProvider(ByteBuffer... buffers)
40 {
41 this("application/octet-stream", buffers);
42 }
43
44 public ByteBufferContentProvider(String contentType, ByteBuffer... buffers)
45 {
46 super(contentType);
47 this.buffers = buffers;
48 int length = 0;
49 for (ByteBuffer buffer : buffers)
50 length += buffer.remaining();
51 this.length = length;
52 }
53
54 @Override
55 public long getLength()
56 {
57 return length;
58 }
59
60 @Override
61 public Iterator<ByteBuffer> iterator()
62 {
63 return new Iterator<ByteBuffer>()
64 {
65 private int index;
66
67 @Override
68 public boolean hasNext()
69 {
70 return index < buffers.length;
71 }
72
73 @Override
74 public ByteBuffer next()
75 {
76 try
77 {
78 ByteBuffer buffer = buffers[index];
79 buffers[index] = buffer.slice();
80 ++index;
81 return buffer;
82 }
83 catch (ArrayIndexOutOfBoundsException x)
84 {
85 throw new NoSuchElementException();
86 }
87 }
88
89 @Override
90 public void remove()
91 {
92 throw new UnsupportedOperationException();
93 }
94 };
95 }
96 }