use of java.io.ByteArrayOutputStream in project jetty.project by eclipse.
the class GZIPContentDecoderTest method testBigBlockOneByteAtATime.
@Test
public void testBigBlockOneByteAtATime() throws Exception {
String data = "0123456789ABCDEF";
for (int i = 0; i < 10; ++i) data += data;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream output = new GZIPOutputStream(baos);
output.write(data.getBytes(StandardCharsets.UTF_8));
output.close();
byte[] bytes = baos.toByteArray();
String result = "";
GZIPContentDecoder decoder = new GZIPContentDecoder(64);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) {
ByteBuffer decoded = decoder.decode(ByteBuffer.wrap(new byte[] { buffer.get() }));
if (decoded.hasRemaining())
result += StandardCharsets.UTF_8.decode(decoded).toString();
decoder.release(decoded);
}
assertEquals(data, result);
assertTrue(decoder.isFinished());
}
use of java.io.ByteArrayOutputStream in project jetty.project by eclipse.
the class AsyncMiddleManServletTest method testDiscardUpstreamAndDownstreamKnownContentLengthGzipped.
@Test
public void testDiscardUpstreamAndDownstreamKnownContentLengthGzipped() throws Exception {
final byte[] bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(StandardCharsets.UTF_8);
startServer(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// decode input stream thru gzip
ByteArrayOutputStream bos = new ByteArrayOutputStream();
IO.copy(new GZIPInputStream(request.getInputStream()), bos);
// ensure decompressed is 0 length
Assert.assertEquals(0, bos.toByteArray().length);
response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), "gzip");
response.getOutputStream().write(gzip(bytes));
}
});
startProxy(new AsyncMiddleManServlet() {
@Override
protected ContentTransformer newClientRequestContentTransformer(HttpServletRequest clientRequest, Request proxyRequest) {
return new GZIPContentTransformer(new DiscardContentTransformer());
}
@Override
protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
return new GZIPContentTransformer(new DiscardContentTransformer());
}
});
startClient();
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).header(HttpHeader.CONTENT_ENCODING, "gzip").content(new BytesContentProvider(gzip(bytes))).timeout(5, TimeUnit.SECONDS).send();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(0, response.getContent().length);
}
use of java.io.ByteArrayOutputStream in project jetty.project by eclipse.
the class ProxyServletTest method testCachingProxy.
@Test
public void testCachingProxy() throws Exception {
final byte[] content = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };
startServer(new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getHeader("Via") != null)
resp.addHeader(PROXIED_HEADER, "true");
resp.getOutputStream().write(content);
}
});
// Don't do this at home: this example is not concurrent, not complete,
// it is only used for this test and to verify that ProxyServlet can be
// subclassed enough to write your own caching servlet
final String cacheHeader = "X-Cached";
proxyServlet = new ProxyServlet() {
private Map<String, ContentResponse> cache = new HashMap<>();
private Map<String, ByteArrayOutputStream> temp = new HashMap<>();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ContentResponse cachedResponse = cache.get(request.getRequestURI());
if (cachedResponse != null) {
response.setStatus(cachedResponse.getStatus());
// Should copy headers too, but keep it simple
response.addHeader(cacheHeader, "true");
response.getOutputStream().write(cachedResponse.getContent());
} else {
super.service(request, response);
}
}
@Override
protected void onResponseContent(HttpServletRequest request, HttpServletResponse response, Response proxyResponse, byte[] buffer, int offset, int length, Callback callback) {
// Accumulate the response content
ByteArrayOutputStream baos = temp.get(request.getRequestURI());
if (baos == null) {
baos = new ByteArrayOutputStream();
temp.put(request.getRequestURI(), baos);
}
baos.write(buffer, offset, length);
super.onResponseContent(request, response, proxyResponse, buffer, offset, length, callback);
}
@Override
protected void onProxyResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) {
byte[] content = temp.remove(request.getRequestURI()).toByteArray();
ContentResponse cached = new HttpContentResponse(proxyResponse, content, null, null);
cache.put(request.getRequestURI(), cached);
super.onProxyResponseSuccess(request, response, proxyResponse);
}
};
startProxy();
startClient();
// First request
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
Assert.assertArrayEquals(content, response.getContent());
// Second request should be cached
response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(cacheHeader));
Assert.assertArrayEquals(content, response.getContent());
}
use of java.io.ByteArrayOutputStream in project jetty.project by eclipse.
the class RequestTest method testMultiPartFormDataReadInputThenParams.
@Test
@Ignore("See issue #1175")
public void testMultiPartFormDataReadInputThenParams() throws Exception {
final File tmpdir = MavenTestingUtils.getTargetTestingDir("multipart");
FS.ensureEmpty(tmpdir);
Handler handler = new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (baseRequest.getDispatcherType() != DispatcherType.REQUEST)
return;
// Fake a @MultiPartConfig'd servlet endpoint
MultipartConfigElement multipartConfig = new MultipartConfigElement(tmpdir.getAbsolutePath());
request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, multipartConfig);
// Normal processing
baseRequest.setHandled(true);
// Fake the commons-fileupload behavior
int length = request.getContentLength();
InputStream in = request.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
// KEY STEP (Don't Change!) commons-fileupload does not read to EOF
IO.copy(in, out, length);
// Record what happened as servlet response headers
response.setIntHeader("x-request-content-length", request.getContentLength());
response.setIntHeader("x-request-content-read", out.size());
// uri query parameter
String foo = request.getParameter("foo");
// form-data content parameter
String bar = request.getParameter("bar");
response.setHeader("x-foo", foo == null ? "null" : foo);
response.setHeader("x-bar", bar == null ? "null" : bar);
}
};
_server.stop();
_server.setHandler(handler);
_server.start();
String multipart = "--AaBbCc\r\n" + "content-disposition: form-data; name=\"bar\"\r\n" + "\r\n" + "BarContent\r\n" + "--AaBbCc\r\n" + "content-disposition: form-data; name=\"stuff\"\r\n" + "Content-Type: text/plain;charset=ISO-8859-1\r\n" + "\r\n" + "000000000000000000000000000000000000000000000000000\r\n" + "--AaBbCc--\r\n";
String request = "POST /?foo=FooUri HTTP/1.1\r\n" + "Host: whatever\r\n" + "Content-Type: multipart/form-data; boundary=\"AaBbCc\"\r\n" + "Content-Length: " + multipart.getBytes().length + "\r\n" + "Connection: close\r\n" + "\r\n" + multipart;
HttpTester.Response response = HttpTester.parseResponse(_connector.getResponse(request));
// It should always be possible to read query string
assertThat("response.x-foo", response.get("x-foo"), is("FooUri"));
// Not possible to read request content parameters?
// TODO: should this work?
assertThat("response.x-bar", response.get("x-bar"), is("null"));
}
use of java.io.ByteArrayOutputStream in project jetty.project by eclipse.
the class NetworkTrafficListenerTest method readResponse.
private byte[] readResponse(Socket socket) throws IOException {
socket.setSoTimeout(5000);
InputStream input = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read;
while ((read = input.read()) >= 0) {
baos.write(read);
// Handle non-chunked end of response
if (read == END_OF_CONTENT)
break;
// Handle chunked end of response
String response = baos.toString("UTF-8");
if (response.endsWith("\r\n0\r\n\r\n"))
break;
// Handle non-content responses
if (response.contains("Content-Length: 0") && response.endsWith("\r\n\r\n"))
break;
}
return baos.toByteArray();
}
Aggregations