Search in sources :

Example 1 with HttpContentResponse

use of org.eclipse.jetty.client.HttpContentResponse 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());
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Callback(org.eclipse.jetty.util.Callback) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) Test(org.junit.Test)

Example 2 with HttpContentResponse

use of org.eclipse.jetty.client.HttpContentResponse in project jetty.project by eclipse.

the class FutureResponseListener method onComplete.

@Override
public void onComplete(Result result) {
    response = new HttpContentResponse(result.getResponse(), getContent(), getMediaType(), getEncoding());
    failure = result.getFailure();
    latch.countDown();
}
Also used : HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse)

Example 3 with HttpContentResponse

use of org.eclipse.jetty.client.HttpContentResponse in project camel by apache.

the class AbstractClientBase method doHttpRequest.

protected void doHttpRequest(final Request request, final ClientResponseCallback callback) {
    // Highly memory inefficient,
    // but buffer the request content to allow it to be replayed for authentication retries
    final ContentProvider content = request.getContent();
    if (content instanceof InputStreamContentProvider) {
        final List<ByteBuffer> buffers = new ArrayList<>();
        for (ByteBuffer buffer : content) {
            buffers.add(buffer);
        }
        request.content(new ByteBufferContentProvider(buffers.toArray(new ByteBuffer[buffers.size()])));
        buffers.clear();
    }
    // execute the request
    request.send(new BufferingResponseListener(httpClient.getMaxContentLength()) {

        @Override
        public void onComplete(Result result) {
            Response response = result.getResponse();
            if (result.isFailed()) {
                // Failure!!!
                // including Salesforce errors reported as exception from SalesforceSecurityHandler
                Throwable failure = result.getFailure();
                if (failure instanceof SalesforceException) {
                    callback.onResponse(null, (SalesforceException) failure);
                } else {
                    final String msg = String.format("Unexpected error {%s:%s} executing {%s:%s}", response.getStatus(), response.getReason(), request.getMethod(), request.getURI());
                    callback.onResponse(null, new SalesforceException(msg, response.getStatus(), failure));
                }
            } else {
                // HTTP error status
                final int status = response.getStatus();
                SalesforceHttpRequest request = (SalesforceHttpRequest) ((SalesforceHttpRequest) result.getRequest()).getConversation().getAttribute(SalesforceSecurityHandler.AUTHENTICATION_REQUEST_ATTRIBUTE);
                if (status == HttpStatus.BAD_REQUEST_400 && request != null) {
                    // parse login error
                    ContentResponse contentResponse = new HttpContentResponse(response, getContent(), getMediaType(), getEncoding());
                    try {
                        session.parseLoginResponse(contentResponse, getContentAsString());
                        final String msg = String.format("Unexpected Error {%s:%s} executing {%s:%s}", status, response.getReason(), request.getMethod(), request.getURI());
                        callback.onResponse(null, new SalesforceException(msg, null));
                    } catch (SalesforceException e) {
                        final String msg = String.format("Error {%s:%s} executing {%s:%s}", status, response.getReason(), request.getMethod(), request.getURI());
                        callback.onResponse(null, new SalesforceException(msg, response.getStatus(), e));
                    }
                } else if (status < HttpStatus.OK_200 || status >= HttpStatus.MULTIPLE_CHOICES_300) {
                    // Salesforce HTTP failure!
                    request = (SalesforceHttpRequest) result.getRequest();
                    final String msg = String.format("Error {%s:%s} executing {%s:%s}", status, response.getReason(), request.getMethod(), request.getURI());
                    final SalesforceException cause = createRestException(response, getContentAsInputStream());
                    // for APIs that return body on status 400, such as Composite API we need content as well
                    callback.onResponse(getContentAsInputStream(), new SalesforceException(msg, response.getStatus(), cause));
                } else {
                    // Success!!!
                    callback.onResponse(getContentAsInputStream(), null);
                }
            }
        }

        @Override
        public InputStream getContentAsInputStream() {
            if (getContent().length == 0) {
                return null;
            }
            return super.getContentAsInputStream();
        }
    });
}
Also used : HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ByteBufferContentProvider(org.eclipse.jetty.client.util.ByteBufferContentProvider) InputStreamContentProvider(org.eclipse.jetty.client.util.InputStreamContentProvider) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) InputStreamContentProvider(org.eclipse.jetty.client.util.InputStreamContentProvider) ByteBuffer(java.nio.ByteBuffer) Result(org.eclipse.jetty.client.api.Result) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) ByteBufferContentProvider(org.eclipse.jetty.client.util.ByteBufferContentProvider) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener)

Aggregations

HttpContentResponse (org.eclipse.jetty.client.HttpContentResponse)3 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)2 Response (org.eclipse.jetty.client.api.Response)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InterruptedIOException (java.io.InterruptedIOException)1 ByteBuffer (java.nio.ByteBuffer)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 ServletException (javax.servlet.ServletException)1 ServletResponse (javax.servlet.ServletResponse)1 HttpServlet (javax.servlet.http.HttpServlet)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)1 ContentProvider (org.eclipse.jetty.client.api.ContentProvider)1 Result (org.eclipse.jetty.client.api.Result)1 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)1