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

The following examples show how to use org.eclipse.jetty.client.util.StringContentProvider. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: JettyXhrTransport.java    License: 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 Project: java-technology-stack   Source File: JettyXhrTransport.java    License: 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 3
Source Project: ja-micro   Source File: RpcClient.java    License: 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 4
Source Project: spring4-understanding   Source File: JettyXhrTransport.java    License: 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 5
@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 6
Source Project: micrometer   Source File: JettyClientMetricsTest.java    License: 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 7
Source Project: micrometer   Source File: JettyClientMetricsTest.java    License: 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 8
Source Project: micrometer   Source File: JettyClientMetricsTest.java    License: 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 9
Source Project: micrometer   Source File: JettyClientMetricsTest.java    License: 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 10
Source Project: micrometer   Source File: JettyClientMetricsTest.java    License: 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 11
Source Project: micrometer   Source File: JettyConnectionMetricsTest.java    License: 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 Project: ja-micro   Source File: HttpCommandProxy.java    License: 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 13
Source Project: ja-micro   Source File: RegistrationManager.java    License: 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 14
Source Project: athenz   Source File: HttpCertSigner.java    License: 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 15
Source Project: zeppelin   Source File: ZeppelinhubRestApiHandler.java    License: 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 16
Source Project: smarthome   Source File: CcuGateway.java    License: 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 17
Source Project: opencensus-java   Source File: HelloWorldClient.java    License: 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 Project: EDDI   Source File: HttpClientWrapper.java    License: 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 Project: cougar   Source File: JettyCougarRequestFactory.java    License: 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));
}