Java Code Examples for org.eclipse.jetty.client.api.Request#content()

The following examples show how to use org.eclipse.jetty.client.api.Request#content() . 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: JettyXhrTransport.java    From java-technology-stack with MIT License 6 votes vote down vote up
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method,
		HttpHeaders headers, @Nullable String body) {

	Request httpRequest = this.httpClient.newRequest(url).method(method);
	addHttpHeaders(httpRequest, headers);
	if (body != null) {
		httpRequest.content(new StringContentProvider(body));
	}
	ContentResponse response;
	try {
		response = httpRequest.send();
	}
	catch (Exception ex) {
		throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
	}
	HttpStatus status = HttpStatus.valueOf(response.getStatus());
	HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders());
	return (response.getContent() != null ?
			new ResponseEntity<>(response.getContentAsString(), responseHeaders, status) :
			new ResponseEntity<>(responseHeaders, status));
}
 
Example 2
Source File: BloomFilterPersistScalarFunction.java    From presto-bloomfilter with Apache License 2.0 6 votes vote down vote up
@SqlType(StandardTypes.BOOLEAN)
@Nullable
@SqlNullable
public static Boolean bloomFilterPersist(@SqlNullable @SqlType(BloomFilterType.TYPE) Slice bloomFilterSlice, @SqlType(StandardTypes.VARCHAR) Slice urlSlice) throws Exception
{
    // Nothing todo
    if (urlSlice == null) {
        return true;
    }
    BloomFilter bf = getOrLoadBloomFilter(bloomFilterSlice);

    // Persist
    // we do not try catch here to make sure that errors are communicated clearly to the client
    // and typical retry logic continues to work
    String url = new String(urlSlice.getBytes());
    if (!HTTP_CLIENT.isStarted()) {
        log.warn("Http client was not started, trying to start");
        HTTP_CLIENT.start();
    }
    Request post = HTTP_CLIENT.POST(url);
    post.content(new StringContentProvider(new String(bf.toBase64())));
    post.method("PUT");
    post.send();
    log.info("Persisted " + bf.toString() + " " + url);
    return true;
}
 
Example 3
Source File: JettyXhrTransport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, String body) {
	Request httpRequest = this.httpClient.newRequest(url).method(method);
	addHttpHeaders(httpRequest, headers);
	if (body != null) {
		httpRequest.content(new StringContentProvider(body));
	}
	ContentResponse response;
	try {
		response = httpRequest.send();
	}
	catch (Exception ex) {
		throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
	}
	HttpStatus status = HttpStatus.valueOf(response.getStatus());
	HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders());
	return (response.getContent() != null ?
		new ResponseEntity<String>(response.getContentAsString(), responseHeaders, status) :
		new ResponseEntity<String>(responseHeaders, status));
}
 
Example 4
Source File: JettyXhrTransport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method,
		HttpHeaders headers, @Nullable String body) {

	Request httpRequest = this.httpClient.newRequest(url).method(method);
	addHttpHeaders(httpRequest, headers);
	if (body != null) {
		httpRequest.content(new StringContentProvider(body));
	}
	ContentResponse response;
	try {
		response = httpRequest.send();
	}
	catch (Exception ex) {
		throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
	}
	HttpStatus status = HttpStatus.valueOf(response.getStatus());
	HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders());
	return (response.getContent() != null ?
			new ResponseEntity<>(response.getContentAsString(), responseHeaders, status) :
			new ResponseEntity<>(responseHeaders, status));
}
 
Example 5
Source File: JettyClientMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void requestSize() throws Exception {
    Request post = httpClient.POST("http://localhost:" + connector.getLocalPort() + "/ok");
    post.content(new StringContentProvider("123456"));
    post.send();
    httpClient.stop();

    assertTrue(singleRequestLatch.await(10, SECONDS));
    assertThat(registry.get("jetty.client.request.size")
            .tag("outcome", "SUCCESS")
            .tag("status", "200")
            .tag("uri", "/ok")
            .summary().totalAmount()).isEqualTo("123456".length());
}
 
Example 6
Source File: JettyClientMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void serverError() throws Exception {
    Request post = httpClient.POST("http://localhost:" + connector.getLocalPort() + "/error");
    post.content(new StringContentProvider("123456"));
    post.send();
    httpClient.stop();

    assertTrue(singleRequestLatch.await(10, SECONDS));
    assertThat(registry.get("jetty.client.requests")
            .tag("outcome", "SERVER_ERROR")
            .tag("status", "500")
            .tag("uri", "/error")
            .timer().count()).isEqualTo(1);
}
 
Example 7
Source File: JettyClientMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void handlerWrapperUncheckedException() throws Exception {
    Request post = httpClient.POST("http://localhost:" + connector.getLocalPort() + "/errorUnchecked");
    post.content(new StringContentProvider("123456"));
    post.send();
    httpClient.stop();

    assertTrue(singleRequestLatch.await(10, SECONDS));
    assertThat(registry.get("jetty.client.requests")
            .tag("outcome", "SERVER_ERROR")
            .tag("status", "500")
            .tag("uri", "/errorUnchecked")
            .timer().count()).isEqualTo(1);
}
 
Example 8
Source File: JettyClientMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void notFound() throws Exception {
    Request post = httpClient.POST("http://localhost:" + connector.getLocalPort() + "/doesNotExist");
    post.content(new StringContentProvider("123456"));
    post.send();
    httpClient.stop();

    assertTrue(singleRequestLatch.await(10, SECONDS));
    assertThat(registry.get("jetty.client.requests")
            .tag("outcome", "CLIENT_ERROR")
            .tag("status", "404")
            .tag("uri", "NOT_FOUND")
            .timer().count()).isEqualTo(1);
}
 
Example 9
Source File: JettyConnectionMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void contributesClientConnectorMetrics() throws Exception {
    HttpClient httpClient = new HttpClient();
    httpClient.setFollowRedirects(false);
    httpClient.addBean(new JettyConnectionMetrics(registry));

    CountDownLatch latch = new CountDownLatch(1);
    httpClient.addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {
        @Override
        public void lifeCycleStopped(LifeCycle event) {
            latch.countDown();
        }
    });

    httpClient.start();

    Request post = httpClient.POST("http://localhost:" + connector.getLocalPort());
    post.content(new StringContentProvider("123456"));
    post.send();
    httpClient.stop();

    assertTrue(latch.await(10, SECONDS));
    assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(1.0);
    assertThat(registry.get("jetty.connections.request").tag("type", "client").timer().count())
            .isEqualTo(1);
    assertThat(registry.get("jetty.connections.bytes.out").summary().totalAmount()).isGreaterThan(1);
}
 
Example 10
Source File: HttpCommandProxy.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
protected String sendRequest(String path, String data, HttpMethod method) throws Exception {
    String url = getServiceUrl(path);
    Request request = httpClient.newRequest(url).method(method).
            header(HttpHeader.CONTENT_TYPE, "application/json");
    if (data != null) {
        request.content(new StringContentProvider(data));
    }
    ContentResponse response = request.send();
    return response.getContentAsString();
}
 
Example 11
Source File: JettyClientMetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void successfulRequest() throws Exception {
    Request post = httpClient.POST("http://localhost:" + connector.getLocalPort() + "/ok");
    post.content(new StringContentProvider("123456"));
    post.send();
    httpClient.stop();

    assertTrue(singleRequestLatch.await(10, SECONDS));
    assertThat(registry.get("jetty.client.requests")
            .tag("outcome", "SUCCESS")
            .tag("status", "200")
            .tag("uri", "/ok")
            .timer().count()).isEqualTo(1);
}
 
Example 12
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 13
Source File: HttpCertSigner.java    From athenz with Apache License 2.0 5 votes vote down vote up
ContentResponse processX509CertRequest(final String csr, final List<Integer> extKeyUsage,
        int expiryTime, int retryCount) {
    
    ContentResponse response = null;
    try {
        Request request = httpClient.POST(x509CertUri);
        request.header(HttpHeader.ACCEPT, CONTENT_JSON);
        request.header(HttpHeader.CONTENT_TYPE, CONTENT_JSON);
        
        X509CertSignObject csrCert = new X509CertSignObject();
        csrCert.setPem(csr);
        csrCert.setX509ExtKeyUsage(extKeyUsage);
        if (expiryTime > 0 && expiryTime < maxCertExpiryTimeMins) {
            csrCert.setExpiryTime(expiryTime);
        }
        request.content(new StringContentProvider(JSON.string(csrCert)), CONTENT_JSON);
        
        // our max timeout is going to be 30 seconds. By default
        // we're picking a small value to quickly recognize when
        // our idle connections are disconnected by certsigner but
        // we won't allow any connections taking longer than 30 secs
        
        long timeout = retryCount * requestTimeout;
        if (timeout > 30) {
            timeout = 30;
        }
        request.timeout(timeout, TimeUnit.SECONDS);
        response = request.send();
    } catch (Exception ex) {
        LOGGER.error("Unable to process x509 certificate request", ex);
    }
    return response;
}
 
Example 14
Source File: ZeppelinhubRestApiHandler.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private String sendToZeppelinHub(HttpMethod method,
                                 String url,
                                 String json,
                                 String token,
                                 boolean withResponse)
    throws IOException {
  Request request = client.newRequest(url).method(method).header(ZEPPELIN_TOKEN_HEADER, token);
  if ((method.equals(HttpMethod.PUT) || method.equals(HttpMethod.POST))
      && !StringUtils.isBlank(json)) {
    request.content(new StringContentProvider(json, "UTF-8"), "application/json;charset=UTF-8");
  }
  return withResponse ?
      sendToZeppelinHub(request) : sendToZeppelinHubWithoutResponseBody(request);
}
 
Example 15
Source File: CommandProxyServlet.java    From Scribengin with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void onResponseFailure(HttpServletRequest request, HttpServletResponse response, 
                                  Response proxyResponse, Throwable failure){
  //System.err.println("Response Failure!");
  this.setForwardingUrl();
  
  HttpClient c = null;
  try {
    c = this.createHttpClient();
  } catch (ServletException e1) {
    e1.printStackTrace();
  }
  
  final Request proxyRequest =  c.newRequest(this.forwardingUrl)
      .method(request.getMethod())
      .version(HttpVersion.fromString(request.getProtocol()));
  
  boolean hasContent = request.getContentLength() > 0 || request.getContentType() != null;
  for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();){
      String headerName = headerNames.nextElement();
      if (HttpHeader.TRANSFER_ENCODING.is(headerName))
          hasContent = true;
      for (Enumeration<String> headerValues = request.getHeaders(headerName); headerValues.hasMoreElements();){
          String headerValue = headerValues.nextElement();
          if (headerValue != null)
              proxyRequest.header(headerName, headerValue);
      }
  }

  // Add proxy headers
  addViaHeader(proxyRequest);
  addXForwardedHeaders(proxyRequest, request);

  final AsyncContext asyncContext = request.getAsyncContext();
  // We do not timeout the continuation, but the proxy request
  asyncContext.setTimeout(0);
  proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);

  if (hasContent)
    try {
      proxyRequest.content(proxyRequestContent(proxyRequest, request));
    } catch (IOException e) {
      e.printStackTrace();
    }

  customizeProxyRequest(proxyRequest, request);

  proxyRequest.send(new ProxyResponseListener(request, response));
}
 
Example 16
Source File: JettyCougarRequestFactory.java    From cougar with Apache License 2.0 4 votes vote down vote up
@Override
protected void addPostEntity(Request request, String postEntity, String contentType) {
    request.header(HttpHeader.CONTENT_TYPE, contentType +  "; charset=utf-8");
    request.content(new StringContentProvider(postEntity, UTF8));
}
 
Example 17
Source File: CountersLBSPolicy.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
     * Connect to an HTTP end point.
     * 
     * @param opts
     *            The connection options.
     * 
     * @return The connection.
     */
    static private JettyResponseListener doConnect(final HttpClient httpClient,
            final ConnectOptions opts) throws IOException {

        /*
         * Generate the fully formed and encoded URL.
         */
        // The requestURL (w/o URL query parameters).
        final String requestURL = opts.serviceURL;
        
        final StringBuilder urlString = new StringBuilder(requestURL);

        ConnectOptions.addQueryParams(urlString, opts.requestParams);

        if (log.isDebugEnabled()) {
            log.debug("*** Request ***");
            log.debug(requestURL);
            log.debug(opts.method);
            log.debug(urlString.toString());
        }

        Request request = null;
        try {

//            request = RemoteRepository.newRequest(httpClient, urlString.toString(),
//                    opts.method);
            request = httpClient.newRequest(urlString.toString()).method(
                  HttpMethod.GET);

            if (opts.requestHeaders != null) {

                for (Map.Entry<String, String> e : opts.requestHeaders
                        .entrySet()) {

                    request.header(e.getKey(), e.getValue());

                    if (log.isDebugEnabled())
                        log.debug(e.getKey() + ": " + e.getValue());

                }

            }
            
            if (opts.entity != null) {

            	final EntityContentProvider cp = new EntityContentProvider(opts.entity);
                request.content(cp, cp.getContentType());

            }

			final JettyResponseListener listener = new JettyResponseListener(
					request, TimeUnit.SECONDS.toMillis(300));

            request.send(listener);
            
            return listener;

        } catch (Throwable t) {
            /*
             * If something goes wrong, then close the http connection.
             * Otherwise, the connection will be closed by the caller.
             */
            try {
                
                if (request != null)
                    request.abort(t);
                
                
            } catch (Throwable t2) {
                log.warn(t2); // ignored.
            }
            throw new RuntimeException(requestURL + " : " + t, t);
        }

    }
 
Example 18
Source File: LoginHelper.java    From EMP-Connector with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static BayeuxParameters login(URL loginEndpoint, String username, String password,
        BayeuxParameters parameters) throws Exception {
    HttpClient client = new HttpClient(parameters.sslContextFactory());
    try {
        client.getProxyConfiguration().getProxies().addAll(parameters.proxies());
        client.start();
        URL endpoint = new URL(loginEndpoint, getSoapUri());
        Request post = client.POST(endpoint.toURI());
        post.content(new ByteBufferContentProvider("text/xml", ByteBuffer.wrap(soapXmlForLogin(username, password))));
        post.header("SOAPAction", "''");
        post.header("PrettyPrint", "Yes");
        ContentResponse response = post.send();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();

        LoginResponseParser parser = new LoginResponseParser();
        saxParser.parse(new ByteArrayInputStream(response.getContent()), parser);

        String sessionId = parser.sessionId;
        if (sessionId == null || parser.serverUrl == null) { throw new ConnectException(
                String.format("Unable to login: %s", parser.faultstring)); }

        URL soapEndpoint = new URL(parser.serverUrl);
        String cometdEndpoint = Float.parseFloat(parameters.version()) < 37 ? COMETD_REPLAY_OLD : COMETD_REPLAY;
        URL replayEndpoint = new URL(soapEndpoint.getProtocol(), soapEndpoint.getHost(), soapEndpoint.getPort(),
                new StringBuilder().append(cometdEndpoint).append(parameters.version()).toString());
        return new DelegatingBayeuxParameters(parameters) {
            @Override
            public String bearerToken() {
                return sessionId;
            }

            @Override
            public URL endpoint() {
                return replayEndpoint;
            }
        };
    } finally {
        client.stop();
        client.destroy();
    }
}
 
Example 19
Source File: ProxyServiceImpl.java    From moon-api-gateway with MIT License 4 votes vote down vote up
/**
 * Create a new request object based on the variables created in prepareProxyInterceptor.
 *
 * Determine the request Method.
 * Inject the header and query param into the new request object.
 * It also injects the body sent by the client into a byte array.
 *
 * @param request This is a client request.
 * @param responseInfo It is an object created by prepareProxyInterceptor. Contains the header, query, and body required for the proxy.
 * @return a new request object that is completely different from client request. This will request an api for the outbound service.
 */

private static Request setHeaderAndQueryInfo(Request request, ResponseInfo responseInfo) {
    Map<String, String> requestHeaders = responseInfo.getHeaders();

    requestHeaders.forEach(request::header);

    request.method(responseInfo.getRequestMethod());
    request.accept(responseInfo.getRequestAccept());

    if (Strings.isNotEmpty(responseInfo.getRequestContentType()) && Objects.nonNull(responseInfo.getRequestBody())) {
        request.content(new BytesContentProvider(responseInfo.getRequestBody()), responseInfo.getRequestContentType());
    }

    Map<String, String> requestQueryParams = responseInfo.getQueryStringMap();
    requestQueryParams.forEach(request::param);

    return request;
}
 
Example 20
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;

    }