1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.client.util;
20
21 import java.io.InputStream;
22 import java.nio.ByteBuffer;
23 import java.util.Iterator;
24 import java.util.NoSuchElementException;
25
26 import org.eclipse.jetty.client.api.ContentProvider;
27 import org.eclipse.jetty.util.BufferUtil;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 public class InputStreamContentProvider implements ContentProvider
46 {
47 private final InputStream stream;
48 private final int bufferSize;
49
50 public InputStreamContentProvider(InputStream stream)
51 {
52 this(stream, 4096);
53 }
54
55 public InputStreamContentProvider(InputStream stream, int bufferSize)
56 {
57 this.stream = stream;
58 this.bufferSize = bufferSize;
59 }
60
61 @Override
62 public long getLength()
63 {
64 return -1;
65 }
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81 protected ByteBuffer onRead(byte[] buffer, int offset, int length)
82 {
83 if (length <= 0)
84 return BufferUtil.EMPTY_BUFFER;
85 return ByteBuffer.wrap(buffer, offset, length);
86 }
87
88 @Override
89 public Iterator<ByteBuffer> iterator()
90 {
91 return new Iterator<ByteBuffer>()
92 {
93 private final byte[] bytes = new byte[bufferSize];
94 private Exception failure;
95 private ByteBuffer buffer;
96
97 @Override
98 public boolean hasNext()
99 {
100 try
101 {
102 int read = stream.read(bytes);
103 if (read > 0)
104 {
105 buffer = onRead(bytes, 0, read);
106 return true;
107 }
108 else if (read < 0)
109 {
110 return false;
111 }
112 else
113 {
114 buffer = BufferUtil.EMPTY_BUFFER;
115 return true;
116 }
117 }
118 catch (Exception x)
119 {
120 if (failure == null)
121 {
122 failure = x;
123 return true;
124 }
125 return false;
126 }
127 }
128
129 @Override
130 public ByteBuffer next()
131 {
132 ByteBuffer result = buffer;
133 buffer = null;
134 if (failure != null)
135 throw (NoSuchElementException)new NoSuchElementException().initCause(failure);
136 if (result == null)
137 throw new NoSuchElementException();
138 return result;
139 }
140
141 @Override
142 public void remove()
143 {
144 throw new UnsupportedOperationException();
145 }
146 };
147 }
148 }