Search in sources :

Example 1 with HttpMethod

use of org.eclipse.jetty.http.HttpMethod in project jetty.project by eclipse.

the class HttpClientLoadTest method test.

private void test(final CountDownLatch latch, final List<String> failures) {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    // Choose a random destination
    String host = random.nextBoolean() ? "localhost" : "127.0.0.1";
    // Choose a random method
    HttpMethod method = random.nextBoolean() ? HttpMethod.GET : HttpMethod.POST;
    boolean ssl = isTransportSecure();
    // Choose randomly whether to close the connection on the client or on the server
    boolean clientClose = false;
    if (!ssl && random.nextInt(100) < 5)
        clientClose = true;
    boolean serverClose = false;
    if (!ssl && random.nextInt(100) < 5)
        serverClose = true;
    int maxContentLength = 64 * 1024;
    int contentLength = random.nextInt(maxContentLength) + 1;
    test(getScheme(), host, method.asString(), clientClose, serverClose, contentLength, true, latch, failures);
}
Also used : ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) HttpMethod(org.eclipse.jetty.http.HttpMethod)

Example 2 with HttpMethod

use of org.eclipse.jetty.http.HttpMethod in project jersey by jersey.

the class JettyConnector method translateRequest.

private Request translateRequest(final ClientRequest clientRequest) {
    final HttpMethod method = HttpMethod.fromString(clientRequest.getMethod());
    if (method == null) {
        throw new ProcessingException(LocalizationMessages.METHOD_NOT_SUPPORTED(clientRequest.getMethod()));
    }
    final URI uri = clientRequest.getUri();
    final Request request = client.newRequest(uri);
    request.method(method);
    request.followRedirects(clientRequest.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true));
    final Object readTimeout = clientRequest.getConfiguration().getProperties().get(ClientProperties.READ_TIMEOUT);
    if (readTimeout != null && readTimeout instanceof Integer && (Integer) readTimeout > 0) {
        request.timeout((Integer) readTimeout, TimeUnit.MILLISECONDS);
    }
    return request;
}
Also used : Request(org.eclipse.jetty.client.api.Request) ClientRequest(org.glassfish.jersey.client.ClientRequest) URI(java.net.URI) HttpMethod(org.eclipse.jetty.http.HttpMethod) ProcessingException(javax.ws.rs.ProcessingException)

Example 3 with HttpMethod

use of org.eclipse.jetty.http.HttpMethod in project jetty.project by eclipse.

the class SmallThreadPoolLoadTest method test.

private boolean test(Session session, CountDownLatch latch) throws Exception {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    // Choose a random method
    boolean download = random.nextBoolean();
    HttpMethod method = download ? HttpMethod.GET : HttpMethod.POST;
    int maxContentLength = 128 * 1024;
    int contentLength = random.nextInt(maxContentLength) + 1;
    long requestId = requestIds.incrementAndGet();
    MetaData.Request request = newRequest(method.asString(), "/" + requestId, new HttpFields());
    if (download)
        request.getFields().put("X-Download", String.valueOf(contentLength));
    HeadersFrame requestFrame = new HeadersFrame(request, null, download);
    FuturePromise<Stream> promise = new FuturePromise<>();
    CountDownLatch requestLatch = new CountDownLatch(1);
    AtomicBoolean reset = new AtomicBoolean();
    session.newStream(requestFrame, promise, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                requestLatch.countDown();
        }

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            callback.succeeded();
            if (frame.isEndStream())
                requestLatch.countDown();
        }

        @Override
        public void onReset(Stream stream, ResetFrame frame) {
            reset.set(true);
            requestLatch.countDown();
        }
    });
    if (!download) {
        Stream stream = promise.get(5, TimeUnit.SECONDS);
        stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(contentLength), true), Callback.NOOP);
    }
    boolean success = requestLatch.await(5, TimeUnit.SECONDS);
    if (success)
        latch.countDown();
    else
        logger.warn("Request {} took too long{}Server:{}{}{}Client:{}{}", requestId, System.lineSeparator(), System.lineSeparator(), server.dump(), System.lineSeparator(), System.lineSeparator(), client.dump());
    return !reset.get();
}
Also used : FuturePromise(org.eclipse.jetty.util.FuturePromise) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callback(org.eclipse.jetty.util.Callback) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) IntStream(java.util.stream.IntStream) Stream(org.eclipse.jetty.http2.api.Stream) ResetFrame(org.eclipse.jetty.http2.frames.ResetFrame) HttpMethod(org.eclipse.jetty.http.HttpMethod)

Example 4 with HttpMethod

use of org.eclipse.jetty.http.HttpMethod in project smarthome by eclipse.

the class HttpUtil method executeUrlAndGetReponse.

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 *
 * @param httpMethod the HTTP method to use
 * @param url the url to execute
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or <code>null</code> if no content should be
 *            send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout in milliseconds to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response as a ContentResponse object or <code>NULL</code> when the request went wrong
 * @throws IOException when the request execution failed, timed out or it was interrupted
 */
private static ContentResponse executeUrlAndGetReponse(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) throws IOException {
    startHttpClient(CLIENT);
    HttpProxy proxy = null;
    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        AuthenticationStore authStore = CLIENT.getAuthenticationStore();
        ProxyConfiguration proxyConfig = CLIENT.getProxyConfiguration();
        List<Proxy> proxies = proxyConfig.getProxies();
        proxy = new HttpProxy(proxyHost, proxyPort);
        proxies.add(proxy);
        authStore.addAuthentication(new BasicAuthentication(proxy.getURI(), Authentication.ANY_REALM, proxyUser, proxyPassword));
    }
    HttpMethod method = HttpUtil.createHttpMethod(httpMethod);
    Request request = CLIENT.newRequest(url).method(method).timeout(timeout, TimeUnit.MILLISECONDS);
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            request.header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey));
        }
    }
    // add basic auth header, if url contains user info
    try {
        URI uri = new URI(url);
        if (uri.getUserInfo() != null) {
            String[] userInfo = uri.getUserInfo().split(":");
            String user = userInfo[0];
            String password = userInfo[1];
            String basicAuthentication = "Basic " + B64Code.encode(user + ":" + password, StringUtil.__ISO_8859_1);
            request.header(HttpHeader.AUTHORIZATION, basicAuthentication);
        }
    } catch (URISyntaxException e) {
        logger.debug("String {} can not be parsed as URI reference", url);
    }
    // add content if a valid method is given ...
    if (content != null && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT))) {
        request.content(new InputStreamContentProvider(content), contentType);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("About to execute {}", request.getURI());
    }
    try {
        ContentResponse response = request.send();
        int statusCode = response.getStatus();
        if (statusCode >= HttpStatus.BAD_REQUEST_400) {
            String statusLine = statusCode + " " + response.getReason();
            logger.debug("Method failed: {}", statusLine);
        }
        return response;
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        if (proxy != null) {
            // Remove the proxy, that has been added for this request
            CLIENT.getProxyConfiguration().getProxies().remove(proxy);
        }
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Request(org.eclipse.jetty.client.api.Request) URISyntaxException(java.net.URISyntaxException) InputStreamContentProvider(org.eclipse.jetty.client.util.InputStreamContentProvider) IOException(java.io.IOException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpProxy(org.eclipse.jetty.client.HttpProxy) HttpProxy(org.eclipse.jetty.client.HttpProxy) Proxy(org.eclipse.jetty.client.ProxyConfiguration.Proxy) ProxyConfiguration(org.eclipse.jetty.client.ProxyConfiguration) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) HttpMethod(org.eclipse.jetty.http.HttpMethod) AuthenticationStore(org.eclipse.jetty.client.api.AuthenticationStore)

Example 5 with HttpMethod

use of org.eclipse.jetty.http.HttpMethod in project spring-boot by spring-projects.

the class JettyHandlerWrappers method createGzipHandlerWrapper.

static HandlerWrapper createGzipHandlerWrapper(Compression compression) {
    GzipHandler handler = new GzipHandler();
    handler.setMinGzipSize((int) compression.getMinResponseSize().toBytes());
    handler.setIncludedMimeTypes(compression.getMimeTypes());
    for (HttpMethod httpMethod : HttpMethod.values()) {
        handler.addIncludedMethods(httpMethod.name());
    }
    return handler;
}
Also used : GzipHandler(org.eclipse.jetty.server.handler.gzip.GzipHandler) HttpMethod(org.eclipse.jetty.http.HttpMethod)

Aggregations

HttpMethod (org.eclipse.jetty.http.HttpMethod)5 URI (java.net.URI)2 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)2 Request (org.eclipse.jetty.client.api.Request)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 URISyntaxException (java.net.URISyntaxException)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 IntStream (java.util.stream.IntStream)1 ProcessingException (javax.ws.rs.ProcessingException)1 HttpProxy (org.eclipse.jetty.client.HttpProxy)1 ProxyConfiguration (org.eclipse.jetty.client.ProxyConfiguration)1 Proxy (org.eclipse.jetty.client.ProxyConfiguration.Proxy)1 AuthenticationStore (org.eclipse.jetty.client.api.AuthenticationStore)1 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)1 BasicAuthentication (org.eclipse.jetty.client.util.BasicAuthentication)1 InputStreamContentProvider (org.eclipse.jetty.client.util.InputStreamContentProvider)1 HttpFields (org.eclipse.jetty.http.HttpFields)1