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.IOException;
22 import java.io.InputStream;
23 import java.nio.ByteBuffer;
24 import java.util.Iterator;
25 import java.util.NoSuchElementException;
26
27 import org.eclipse.jetty.client.api.ContentProvider;
28 import org.eclipse.jetty.util.BufferUtil;
29 import org.eclipse.jetty.util.log.Log;
30 import org.eclipse.jetty.util.log.Logger;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 public class InputStreamContentProvider implements ContentProvider
53 {
54 private static final Logger LOG = Log.getLogger(InputStreamContentProvider.class);
55
56 private final InputStream stream;
57 private final int bufferSize;
58 private final boolean autoClose;
59
60 public InputStreamContentProvider(InputStream stream)
61 {
62 this(stream, 4096);
63 }
64
65 public InputStreamContentProvider(InputStream stream, int bufferSize)
66 {
67 this(stream, bufferSize, true);
68 }
69
70 public InputStreamContentProvider(InputStream stream, int bufferSize, boolean autoClose)
71 {
72 this.stream = stream;
73 this.bufferSize = bufferSize;
74 this.autoClose = autoClose;
75 }
76
77 @Override
78 public long getLength()
79 {
80 return -1;
81 }
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97 protected ByteBuffer onRead(byte[] buffer, int offset, int length)
98 {
99 if (length <= 0)
100 return BufferUtil.EMPTY_BUFFER;
101 return ByteBuffer.wrap(buffer, offset, length);
102 }
103
104 @Override
105 public Iterator<ByteBuffer> iterator()
106 {
107 return new Iterator<ByteBuffer>()
108 {
109 private final byte[] bytes = new byte[bufferSize];
110 private Exception failure;
111 private ByteBuffer buffer;
112
113 @Override
114 public boolean hasNext()
115 {
116 try
117 {
118 int read = stream.read(bytes);
119 if (read > 0)
120 {
121 buffer = onRead(bytes, 0, read);
122 return true;
123 }
124 else if (read < 0)
125 {
126 close();
127 return false;
128 }
129 else
130 {
131 buffer = BufferUtil.EMPTY_BUFFER;
132 return true;
133 }
134 }
135 catch (Exception x)
136 {
137 if (failure == null)
138 {
139 failure = x;
140
141
142 close();
143 return true;
144 }
145 return false;
146 }
147 }
148
149 @Override
150 public ByteBuffer next()
151 {
152 ByteBuffer result = buffer;
153 buffer = null;
154 if (failure != null)
155 throw (NoSuchElementException)new NoSuchElementException().initCause(failure);
156 if (result == null)
157 throw new NoSuchElementException();
158 return result;
159 }
160
161 @Override
162 public void remove()
163 {
164 throw new UnsupportedOperationException();
165 }
166
167 private void close()
168 {
169 if (autoClose)
170 {
171 try
172 {
173 stream.close();
174 }
175 catch (IOException x)
176 {
177 LOG.ignore(x);
178 }
179 }
180 }
181 };
182 }
183 }