org.apache.hc.core5.http.protocol.HttpContext Java Examples

The following examples show how to use org.apache.hc.core5.http.protocol.HttpContext. 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: HijackingHttpRequestExecutor.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public ClassicHttpResponse execute(
    ClassicHttpRequest request,
    HttpClientConnection conn,
    HttpResponseInformationCallback informationCallback,
    HttpContext context
) throws IOException, HttpException {
    Objects.requireNonNull(request, "HTTP request");
    Objects.requireNonNull(conn, "Client connection");
    Objects.requireNonNull(context, "HTTP context");

    InputStream hijackedInput = (InputStream) context.getAttribute(HIJACKED_INPUT_ATTRIBUTE);
    if (hijackedInput != null) {
        return executeHijacked(request, conn, context, hijackedInput);
    }

    return super.execute(request, conn, informationCallback, context);
}
 
Example #2
Source File: ListenpointHttp2.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(
        final Message<HttpRequest, byte[]> requestMessage,
        final ResponseTrigger responseTrigger,
        final HttpContext context
) throws HttpException, IOException {
    try {
        byte[] body = (byte[]) requestMessage.getBody();

        MsgHttp2 msg = new MsgHttp2(stack, requestMessage.getHead());

        TransactionId transactionId = new TransactionId(UUID.randomUUID().toString());
        Trans transaction = new Trans(stack, msg);
        msg.setTransaction(transaction);
        msg.setTransactionId(transactionId);
        msg.setResponseTrigger(responseTrigger);
        msg.setContext(context);
        msg.setListenpoint(listenpoint);

        if (body != null) {
            msg.setMessageContent(new String(body));
        }

        stack.receiveMessage(msg);

        GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL, "Listenpoint: receiveMessage() ", msg);
    } catch (Exception e) {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.PROTOCOL, e);
        throw new IOException(e);
    }
}
 
Example #3
Source File: HttpLoaderServer.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public void receiveRequest( HttpRequest request,
        HttpContext context, ClassicHttpResponse response
        )throws HttpException, IOException
{
    String method = request.getMethod().toUpperCase();
    String target = request.getPath();
    sendResponse(response,context,request);
}
 
Example #4
Source File: HttpLoaderServer.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public void sendResponse( ClassicHttpResponse response,HttpContext context, HttpRequest request)throws HttpException, IOException
{

    response.setCode(HttpStatus.SC_OK);
    File file = new File("D:/XMLloader/testPileHttp/test/fileTestHttp.txt");
    //FileEntity body = new FileEntity(file, "text/html");
    HttpEntity body = new StringEntity("");
    response.setEntity(body);
}
 
Example #5
Source File: ApacheDockerHttpClientImpl.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public Response execute(Request request) {
    HttpContext context = new BasicHttpContext();
    HttpUriRequestBase httpUriRequest = new HttpUriRequestBase(request.method(), URI.create(request.path()));
    httpUriRequest.setScheme(host.getSchemeName());
    httpUriRequest.setAuthority(new URIAuthority(host.getHostName(), host.getPort()));

    request.headers().forEach(httpUriRequest::addHeader);

    InputStream body = request.body();
    if (body != null) {
        httpUriRequest.setEntity(new InputStreamEntity(body, null));
    }

    if (request.hijackedInput() != null) {
        context.setAttribute(HijackingHttpRequestExecutor.HIJACKED_INPUT_ATTRIBUTE, request.hijackedInput());
        httpUriRequest.setHeader("Upgrade", "tcp");
        httpUriRequest.setHeader("Connection", "Upgrade");
    }

    try {
        CloseableHttpResponse response = httpClient.execute(host, httpUriRequest, context);

        return new ApacheResponse(httpUriRequest, response);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: TraceeHttpResponseInterceptor.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public final void process(HttpResponse response, HttpContext context) {
	final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);
	final Iterator<Header> headerIterator = response.headerIterator(TraceeConstants.TPIC_HEADER);
	if (headerIterator != null && headerIterator.hasNext() && filterConfiguration.shouldProcessContext(IncomingResponse)) {
		final List<String> stringTraceeHeaders = new ArrayList<>();
		while (headerIterator.hasNext()) {
			stringTraceeHeaders.add(headerIterator.next().getValue());
		}
		backend.putAll(filterConfiguration.filterDeniedParams(transportSerialization.parse(stringTraceeHeaders), IncomingResponse));
	}
}
 
Example #7
Source File: TraceeHttpRequestInterceptor.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public final void process(final HttpRequest httpRequest, final HttpContext httpContext) {
	final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);
	if (!backend.isEmpty() && filterConfiguration.shouldProcessContext(OutgoingRequest)) {
		final Map<String, String> filteredParams = filterConfiguration.filterDeniedParams(backend.copyToMap(), OutgoingRequest);
		httpRequest.setHeader(TraceeConstants.TPIC_HEADER, transportSerialization.render(filteredParams));
	}
}
 
Example #8
Source File: TraceeHttpResponseInterceptorTest.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testResponseInterceptorParsesHttpHeaderToBackend() throws Exception {
	final HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "not found"));
	httpResponse.setHeader(TraceeConstants.TPIC_HEADER, "foobi=bar");
	unit.process(httpResponse, mock(HttpContext.class));
	assertThat(backend.get("foobi"), equalTo("bar"));
}
 
Example #9
Source File: TraceeHttpRequestInterceptorTest.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testRequestInterceptorWritesTraceeContextToRequestHeader() throws Exception {
	final HttpRequest httpRequest = new BasicHttpRequest("GET", "http://localhost/pew");

	backend.put("foo", "bar");

	unit.process(httpRequest, mock(HttpContext.class));

	assertThat("HttpRequest contains TracEE Context Header", httpRequest.containsHeader(TraceeConstants.TPIC_HEADER), equalTo(true));
	assertThat(httpRequest.getFirstHeader(TraceeConstants.TPIC_HEADER).getValue(), equalTo("foo=bar"));
}
 
Example #10
Source File: MyH2ServerBootstrap.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public HttpAsyncServer create() {
    
    final HttpRequestMapper<Supplier<AsyncServerExchangeHandler>> registry = (final HttpRequest request, final HttpContext context) -> {
        return () -> new BasicServerExchangeHandler(asyncServerRequestHandler);
    };

    final HandlerFactory<AsyncServerExchangeHandler> handlerFactory;
    if (!filters.isEmpty()) {
        final NamedElementChain<AsyncFilterHandler> filterChainDefinition = new NamedElementChain<>();
        filterChainDefinition.addLast(
                new TerminalAsyncServerFilter(new DefaultAsyncResponseExchangeHandlerFactory(registry)),
                StandardFilters.MAIN_HANDLER.name());
        filterChainDefinition.addFirst(
                new AsyncServerExpectationFilter(),
                StandardFilters.EXPECT_CONTINUE.name());

        for (final FilterEntry<AsyncFilterHandler> entry : filters) {
            switch (entry.postion) {
                case AFTER:
                    filterChainDefinition.addAfter(entry.existing, entry.filterHandler, entry.name);
                    break;
                case BEFORE:
                    filterChainDefinition.addBefore(entry.existing, entry.filterHandler, entry.name);
                    break;
                case REPLACE:
                    filterChainDefinition.replace(entry.existing, entry.filterHandler);
                    break;
                case FIRST:
                    filterChainDefinition.addFirst(entry.filterHandler, entry.name);
                    break;
                case LAST:
                    filterChainDefinition.addLast(entry.filterHandler, entry.name);
                    break;
            }
        }

        NamedElementChain<AsyncFilterHandler>.Node current = filterChainDefinition.getLast();
        AsyncServerFilterChainElement execChain = null;
        while (current != null) {
            execChain = new AsyncServerFilterChainElement(current.getValue(), execChain);
            current = current.getPrevious();
        }

        handlerFactory = new AsyncServerFilterChainExchangeHandlerFactory(execChain);
    } else {
        handlerFactory = new DefaultAsyncResponseExchangeHandlerFactory(registry, new Decorator<AsyncServerExchangeHandler>() {

            @Override
            public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler handler) {
                return new BasicAsyncServerExpectationDecorator(handler);
            }

        });
    }

    final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory = new ServerH2StreamMultiplexerFactory(
            httpProcessor != null ? httpProcessor : H2Processors.server(),
            handlerFactory,
            h2Config != null ? h2Config : H2Config.DEFAULT,
            charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT,
            h2StreamListener,
            streamIdGenerator);
    final ServerHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ServerHttp1StreamDuplexerFactory(
            httpProcessor != null ? httpProcessor : HttpProcessors.server(),
            handlerFactory,
            http1Config != null ? http1Config : Http1Config.DEFAULT,
            charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT,
            DefaultConnectionReuseStrategy.INSTANCE,
            DefaultHttpRequestParserFactory.INSTANCE,
            DefaultHttpResponseWriterFactory.INSTANCE,
            DefaultContentLengthStrategy.INSTANCE,
            DefaultContentLengthStrategy.INSTANCE,
            http1StreamListener);
    final IOEventHandlerFactory ioEventHandlerFactory = new ServerHttpProtocolNegotiatorFactory(
            http1StreamHandlerFactory,
            http2StreamHandlerFactory,
            versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE,
            tlsStrategy != null ? tlsStrategy : new H2ServerTlsStrategy(443, 8443),
            handshakeTimeout);
    return new HttpAsyncServer(ioEventHandlerFactory, ioReactorConfig, ioSessionDecorator, exceptionCallback,
            sessionListener);
}
 
Example #11
Source File: ListenpointHttp2.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
@Override
public AsyncRequestConsumer<Message<HttpRequest, byte[]>> prepare(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
    return new BasicRequestConsumer<>(() -> new BasicAsyncEntityConsumer());
}
 
Example #12
Source File: MsgHttp2.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public HttpContext getContext() {
    return context;
}
 
Example #13
Source File: MsgHttp2.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public void setContext(HttpContext context) {
    this.context = context;
}
 
Example #14
Source File: HttpLoaderServer.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public void handle(final HttpRequest request,
        final ClassicHttpResponse response,
        final HttpContext context)throws HttpException, IOException
{
    receiveRequest(request,context,response);
}
 
Example #15
Source File: HttpLoaderServer.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void handle(ClassicHttpRequest request, ClassicHttpResponse response, HttpContext context)
		throws HttpException, IOException {
	receiveRequest(request,context,response);
	
}
 
Example #16
Source File: HijackingHttpRequestExecutor.java    From docker-java with Apache License 2.0 4 votes vote down vote up
private ClassicHttpResponse executeHijacked(
    ClassicHttpRequest request,
    HttpClientConnection conn,
    HttpContext context,
    InputStream hijackedInput
) throws HttpException, IOException {
    try {
        context.setAttribute(HttpCoreContext.SSL_SESSION, conn.getSSLSession());
        context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, conn.getEndpointDetails());
        final ProtocolVersion transportVersion = request.getVersion();
        if (transportVersion != null) {
            context.setProtocolVersion(transportVersion);
        }

        conn.sendRequestHeader(request);
        conn.sendRequestEntity(request);
        conn.flush();

        ClassicHttpResponse response = conn.receiveResponseHeader();
        if (response.getCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
            conn.terminateRequest(request);
            throw new ProtocolException("Expected 101 Switching Protocols, got: " + new StatusLine(response));
        }

        Thread thread = new Thread(() -> {
            try {
                BasicClassicHttpRequest fakeRequest = new BasicClassicHttpRequest("POST", "/");
                fakeRequest.setHeader(HttpHeaders.CONTENT_LENGTH, Long.MAX_VALUE);
                fakeRequest.setEntity(new HijackedEntity(hijackedInput));
                conn.sendRequestEntity(fakeRequest);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        thread.setName("docker-java-httpclient5-hijacking-stream-" + System.identityHashCode(request));
        thread.setDaemon(true);
        thread.start();

        // 101 -> 200
        response.setCode(200);
        conn.receiveResponseEntity(response);
        return response;

    } catch (final HttpException | IOException | RuntimeException ex) {
        Closer.closeQuietly(conn);
        throw ex;
    }
}