org.eclipse.jetty.client.api.ContentProvider Java Examples

The following examples show how to use org.eclipse.jetty.client.api.ContentProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RpcClientIntegrationTest.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
@Override
public Request newRequest(String uri) {
    Request retval = mock(Request.class);
    try {
        if (requestsTimeout || (isFirstRequestTimeout && requests.isEmpty())) {
            when(retval.send()).thenThrow(new TimeoutException());
        } else {
            when(retval.send()).thenReturn(httpResponse);
        }
        if (requestsFail && featureFlag.equals("true")) {
            when(httpResponse.getStatus()).thenReturn(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else if (responseException != null) {
            when(httpResponse.getStatus()).thenReturn(responseException.getCategory().getHttpStatus());
        } else {
            when(httpResponse.getStatus()).thenReturn(HttpServletResponse.SC_OK);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    when(retval.method(anyString())).thenReturn(retval);
    when(retval.content(any(ContentProvider.class))).thenReturn(retval);
    when(retval.timeout(anyLong(), any(TimeUnit.class))).thenReturn(retval);
    requests.add(uri);
    return retval;
}
 
Example #2
Source File: HttpClientWrapperTest.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws InterruptedException, ExecutionException, TimeoutException {
    when(loadBalancer.getHealthyInstance()).thenReturn(createServiceEndpoint());
    when(loadBalancer.getHealthyInstanceExclude(anyListOf(ServiceEndpoint.class)))
        .thenReturn(createServiceEndpoint());

    when(rpcClient.getRetries()).thenReturn(NUMBER_OF_RETRIES);
    when(rpcClient.getTimeout()).thenReturn(0);
    httpClientWrapper.setLoadBalancer(loadBalancer);
    when(rpcClientMetrics.getMethodTimer(any(), any())).thenReturn(new GoTimer("timer"));
    when(tracer.buildSpan(any())).thenReturn(spanBuilder);
    when(spanBuilder.start()).thenReturn(span);
    when(httpClient.newRequest(any(URI.class))).thenReturn(request);
    when(httpClient.newRequest(any(String.class))).thenReturn(request);
    when(request.content(any(ContentProvider.class))).thenReturn(request);
    when(request.method(anyString())).thenReturn(request);
    when(request.timeout(anyLong(), any(TimeUnit.class))).thenReturn(request);
    when(request.send()).thenReturn(httpContentResponse);
    when(httpContentResponse.getStatus()).thenReturn(100);
    dependencyHealthCheck = mock(ServiceDependencyHealthCheck.class);
}
 
Example #3
Source File: ProxyServlet.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * retryEnabled の時だけだよ
 * @return
 */
private ContentProvider createRetryContentProvider() {
    final HttpServletRequest request = this.request;

    return new InputStreamContentProvider(
            new SequenceInputStream(new ByteArrayInputStream(this.contentBuffer.toByteArray()),
                    this.contentInputStream)) {
        @Override
        public long getLength() {
            return request.getContentLength();
        }

        @Override
        protected ByteBuffer onRead(byte[] buffer, int offset, int length) {
            if (ProxyServlet.this._isDebugEnabled) {
                ProxyServlet.this._log
                        .debug("{} proxying content to upstream: {} bytes", getRequestId(request), length);
            }
            return super.onRead(buffer, offset, length);
        }
    };
}
 
Example #4
Source File: HttpRequestBuilderTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPostWithContentType() throws Exception {
    ArgumentCaptor<ContentProvider> argumentCaptor = ArgumentCaptor.forClass(ContentProvider.class);

    mockResponse(HttpStatus.OK_200);

    String result = HttpRequestBuilder.postTo(URL).withContent("{json: true}", "application/json")
            .getContentAsString();

    assertEquals("Some content", result);

    // verify just the content-type to be added to the request
    verify(requestMock).method(HttpMethod.POST);
    verify(requestMock).content(argumentCaptor.capture(), ArgumentMatchers.eq("application/json"));
}
 
Example #5
Source File: HttpRequestBuilderTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private String getContentFromProvider(ContentProvider value) {
    ByteBuffer element = value.iterator().next();
    byte[] data = new byte[element.limit()];
    // Explicit cast for compatibility with covariant return type on JDK 9's ByteBuffer
    ((ByteBuffer) ((Buffer) element.duplicate()).clear()).get(data);
    return new String(data, StandardCharsets.UTF_8);
}
 
Example #6
Source File: HttpRequestBuilderTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPostWithContentType() throws Exception {
    ArgumentCaptor<ContentProvider> argumentCaptor = ArgumentCaptor.forClass(ContentProvider.class);

    mockResponse(HttpStatus.OK_200);

    String result = HttpRequestBuilder.postTo(URL).withContent("{json: true}", "application/json")
            .getContentAsString();

    assertEquals("Some content", result);

    // verify just the content-type to be added to the request
    verify(requestMock).method(HttpMethod.POST);
    verify(requestMock).content(argumentCaptor.capture(), ArgumentMatchers.eq("application/json"));
}
 
Example #7
Source File: ProxyServlet.java    From logbook-kai with MIT License 5 votes vote down vote up
private Request createProxyRequest(HttpServletRequest request, HttpServletResponse response, URI targetUri,
        ContentProvider contentProvider) {
    final Request proxyRequest = this._client.newRequest(targetUri)
            .method(HttpMethod.fromString(request.getMethod()))
            .version(HttpVersion.fromString(request.getProtocol()));

    // Copy headers
    for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
        String headerName = headerNames.nextElement();
        String lowerHeaderName = headerName.toLowerCase(Locale.ENGLISH);

        // Remove hop-by-hop headers
        if (HOP_HEADERS.contains(lowerHeaderName))
            continue;

        if ((this._hostHeader != null) && lowerHeaderName.equals("host"))
            continue;

        for (Enumeration<String> headerValues = request.getHeaders(headerName); headerValues.hasMoreElements();) {
            String headerValue = headerValues.nextElement();
            if (headerValue != null)
                proxyRequest.header(headerName, headerValue);
        }
    }

    // Force the Host header if configured
    if (this._hostHeader != null)
        proxyRequest.header(HttpHeader.HOST, this._hostHeader);

    proxyRequest.content(contentProvider);
    this.customizeProxyRequest(proxyRequest, request);
    proxyRequest.timeout(this.getTimeout(), TimeUnit.MILLISECONDS);
    return proxyRequest;
}
 
Example #8
Source File: TestMultipartContent.java    From database with GNU General Public License v2.0 5 votes vote down vote up
void display(ContentProvider cp) {
	Iterator<ByteBuffer> iter = cp.iterator();
	
	while (iter.hasNext()) {
		System.out.println(new String(iter.next().array()));
	}
}
 
Example #9
Source File: MultipartContentProvider.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void addPart(final String name, final ContentProvider part, final String mimetype) {
	throw new UnsupportedOperationException();
}
 
Example #10
Source File: CapturingRequest.java    From cougar with Apache License 2.0 4 votes vote down vote up
@Override
public ContentProvider getContent() {
    return null;  //To change body of implemented methods use File | Settings | File Templates.
}
 
Example #11
Source File: HttpRequestBuilderTest.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private String getContentFromProvider(ContentProvider value) {
    ByteBuffer element = value.iterator().next();
    byte[] data = new byte[element.limit()];
    ((ByteBuffer) element.duplicate().clear()).get(data);
    return new String(data, StandardCharsets.UTF_8);
}
 
Example #12
Source File: JerseyUnixSocketConnector.java    From tessera with Apache License 2.0 4 votes vote down vote up
private ClientResponse doApply(ClientRequest request) throws Exception {

        HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());
        final URI originalUri = request.getUri();
        final URI uri;
        Path basePath = Paths.get(unixfile);

        if (originalUri.getScheme().startsWith("unix")) {
            
            String path = originalUri.getRawPath()
                    .replaceFirst(basePath.toString(), "");

            LOGGER.trace("Extracted path {} from {}",path, originalUri.getRawPath());

            uri = UriBuilder.fromUri(originalUri)
                    .replacePath(path)
                    .scheme("http")
                    .port(99)
                    .host("localhost")
                    .build();
                        
            LOGGER.trace("Created psuedo uri {} for originalUri {}", uri, originalUri);
        } else {
            uri = originalUri;
        }

        Request clientRequest = httpClient.newRequest(uri)
                .method(httpMethod);

        MultivaluedMap<String, Object> headers = request.getHeaders();

        headers.keySet().stream().forEach(name -> {
            headers.get(name).forEach(value -> {
                clientRequest.header(name, Objects.toString(value));
            });

        });

        if (request.hasEntity()) {
            final long length = request.getLengthLong();

            try (ByteArrayOutputStream bout = new ByteArrayOutputStream()){

                request.setStreamProvider((int contentLength) -> bout);
                request.writeEntity();

                ContentProvider content = new BytesContentProvider(bout.toByteArray());
                clientRequest.content(content);
            }

        }
        final ContentResponse contentResponse = clientRequest.send();

        int statusCode = contentResponse.getStatus();
        String reason = contentResponse.getReason();

        LOGGER.trace("uri {}, method: {},statusCode:{},reason: {} ", uri, httpMethod, statusCode, reason);

        final Response.StatusType status = Statuses.from(statusCode, reason);

        ClientResponse response = new ClientResponse(status, request);
        contentResponse.getHeaders().stream()
                .forEach(header -> {
                    response.headers(header.getName(), (Object[]) header.getValues());
                });

        response.setEntityStream(new ByteArrayInputStream(contentResponse.getContent()));
        return response;

    }
 
Example #13
Source File: AdminProxyHandler.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
protected ContentProvider proxyRequestContent(HttpServletRequest request,
                                              HttpServletResponse response, Request proxyRequest) throws IOException {
    return new ReplayableProxyContentProvider(request, response, proxyRequest, request.getInputStream());
}
 
Example #14
Source File: HttpRequestWrapper.java    From ja-micro with Apache License 2.0 4 votes vote down vote up
public ContentProvider getContentProvider() {
    return contentProvider;
}
 
Example #15
Source File: HttpRequestWrapper.java    From ja-micro with Apache License 2.0 4 votes vote down vote up
public void setContentProvider(ContentProvider contentProvider) {
    this.contentProvider = contentProvider;
}
 
Example #16
Source File: TestMultipartContent.java    From database with GNU General Public License v2.0 3 votes vote down vote up
public void testSimpleFormContent() throws UnsupportedEncodingException {
	
   	final List<NameValuePair> formparams = new ArrayList<NameValuePair>();
   	
   	formparams.add(new BasicNameValuePair("First Name", "Martyn"));
   	formparams.add(new BasicNameValuePair("Last Name", "Cutcher"));
    	
   	final HttpEntity entity =  new UrlEncodedFormEntity(formparams, "UTF-8");
   	
   	final ContentProvider content = new EntityContentProvider(entity);
   	
   	System.out.println(new String(entity.getContentType().toString()));
}
 
Example #17
Source File: HttpRequestBuilderTest.java    From openhab-core with Eclipse Public License 2.0 3 votes vote down vote up
@Test
public void testPostWithContent() throws Exception {
    ArgumentCaptor<ContentProvider> argumentCaptor = ArgumentCaptor.forClass(ContentProvider.class);

    mockResponse(HttpStatus.OK_200);

    String result = HttpRequestBuilder.postTo(URL).withContent("{json: true}").getContentAsString();

    assertEquals("Some content", result);

    // verify the content to be added to the request
    verify(requestMock).content(argumentCaptor.capture(), ArgumentMatchers.eq(null));

    assertEquals("{json: true}", getContentFromProvider(argumentCaptor.getValue()));
}
 
Example #18
Source File: HttpRequestBuilderTest.java    From smarthome with Eclipse Public License 2.0 3 votes vote down vote up
@Test
public void testPostWithContent() throws Exception {
    ArgumentCaptor<ContentProvider> argumentCaptor = ArgumentCaptor.forClass(ContentProvider.class);

    mockResponse(HttpStatus.OK_200);

    String result = HttpRequestBuilder.postTo(URL).withContent("{json: true}").getContentAsString();

    assertEquals("Some content", result);

    // verify the content to be added to the request
    verify(requestMock).content(argumentCaptor.capture(), ArgumentMatchers.eq(null));

    assertEquals("{json: true}", getContentFromProvider(argumentCaptor.getValue()));
}