org.eclipse.jetty.client.util.StringContentProvider Java Examples

The following examples show how to use org.eclipse.jetty.client.util.StringContentProvider. 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: RpcClient.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
public String callSynchronous(JsonArray params, OrangeContext orangeContext)
        throws RpcCallException {
    HttpClientWrapper clientWrapper = loadBalancer.getHttpClientWrapper();
    HttpRequestWrapper balancedPost = clientWrapper.createHttpPost(this);

    //set custom headers
    if (orangeContext != null) {
        orangeContext.getProperties().forEach(balancedPost::setHeader);
    }

    balancedPost.setHeader("Content-type", TYPE_JSON);
    //TODO: fix: Temporary workaround below until go services are more http compliant
    balancedPost.setHeader("Connection", "close");
    JsonRpcRequest jsonRequest = new JsonRpcRequest(null, methodName, params);
    String json = jsonRequest.toString();
    balancedPost.setContentProvider(new StringContentProvider(json));

    logger.debug("Sending request of size {}", json.length());
    ContentResponse rpcResponse = clientWrapper.execute(balancedPost,
            new JsonRpcCallExceptionDecoder(), orangeContext);
    String rawResponse = rpcResponse.getContentAsString();
    logger.debug("Json response from the service: {}", rawResponse);

    return JsonRpcResponse.fromString(rawResponse).getResult().getAsString();
}
 
Example #5
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 #6
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 #7
Source File: CcuGateway.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Main method for sending a TclRega script and parsing the XML result.
 */
@SuppressWarnings("unchecked")
private synchronized <T> T sendScript(String script, Class<T> clazz) throws IOException {
    try {
        script = StringUtils.trim(script);
        if (StringUtils.isEmpty(script)) {
            throw new RuntimeException("Homematic TclRegaScript is empty!");
        }
        if (logger.isTraceEnabled()) {
            logger.trace("TclRegaScript: {}", script);
        }

        StringContentProvider content = new StringContentProvider(script, config.getEncoding());
        ContentResponse response = httpClient.POST(config.getTclRegaUrl()).content(content)
                .timeout(config.getTimeout(), TimeUnit.SECONDS)
                .header(HttpHeader.CONTENT_TYPE, "text/plain;charset=" + config.getEncoding()).send();

        String result = new String(response.getContent(), config.getEncoding());
        result = StringUtils.substringBeforeLast(result, "<xml><exec>");
        if (logger.isTraceEnabled()) {
            logger.trace("Result TclRegaScript: {}", result);
        }

        return (T) xStream.fromXML(result);
    } catch (Exception ex) {
        throw new IOException(ex.getMessage(), ex);
    }
}
 
Example #8
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 #9
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 #10
Source File: RegistrationManager.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
private boolean sendRegistration(JsonObject request) {
    try {
        ContentResponse httpResponse = httpClient.newRequest(getRegistrationUri()).
                content(new StringContentProvider(request.toString())).
                method(HttpMethod.PUT).header(HttpHeader.CONTENT_TYPE, "application/json").send();
        if (httpResponse.getStatus() == 200) {
            return true;
        }
    } catch (Exception ex) {
        logger.warn("Caught exception sending registration {}", request.toString(), ex);
    }
    return false;
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: HelloWorldClient.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
/**
 * HelloWorldClient sends http request periodically to {@link HelloWorldServer}. These requests
 * are instrumented using opencensus jetty client library to enable tracing and monitoring stats.
 */
public static void main(String[] args) throws Exception {
  BasicConfigurator.configure();

  initTracing();
  initStatsExporter();

  // Create http client that will trace requests. By default trace context is propagated using
  // w3c TraceContext propagator.
  // To use B3 propagation use following
  //    OcJettyHttpClient httpClient =
  //        new OcJettyHttpClient(
  //            new HttpClientTransportOverHTTP(),
  //            new SslContextFactory(),
  //            null,
  //            Tracing.getPropagationComponent().getB3Format());
  OcJettyHttpClient httpClient =
      new OcJettyHttpClient(
          new HttpClientTransportOverHTTP(), new SslContextFactory(), null, null);

  httpClient.start();

  do {
    HttpRequest request =
        (HttpRequest)
            httpClient
                .newRequest("http://localhost:8080/helloworld/request")
                .method(HttpMethod.GET);
    HttpRequest asyncRequest =
        (HttpRequest)
            httpClient
                .newRequest("http://localhost:8080/helloworld/request/async")
                .method(HttpMethod.GET);
    HttpRequest postRequest =
        (HttpRequest)
            httpClient
                .newRequest("http://localhost:8080/helloworld/request")
                .method(HttpMethod.POST);
    postRequest.content(new StringContentProvider("{\"hello\": \"world\"}"), "application/json");

    if (request == null) {
      logger.info("Request is null");
      break;
    }

    request.send();
    asyncRequest.send();
    postRequest.send();
    try {
      Thread.sleep(15000);
    } catch (Exception e) {
      logger.error("Error while sleeping");
    }
  } while (true);
}
 
Example #18
Source File: HttpClientWrapper.java    From EDDI with Apache License 2.0 4 votes vote down vote up
@Override
public IRequest setBodyEntity(String content, String encoding, String contentType) {
    this.requestBody = content;
    request.content(new StringContentProvider(this.requestBody, encoding), contentType);
    return this;
}
 
Example #19
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));
}