Search in sources :

Example 21 with HttpRequest

use of org.apache.http.HttpRequest in project wso2-synapse by wso2.

the class ClientHandler method requestReady.

public void requestReady(final NHttpClientConnection conn) throws IOException, HttpException {
    // The connection is ready for submission of a new request
    HttpContext context = conn.getContext();
    ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context.getAttribute(TUNNEL_HANDLER);
    if (tunnelHandler != null && !tunnelHandler.isCompleted()) {
        Axis2HttpRequest axis2HttpRequest = (Axis2HttpRequest) (context.getAttribute(ATTACHMENT_KEY));
        Object targetHost = axis2HttpRequest.getMsgContext().getProperty(NhttpConstants.PROXY_PROFILE_TARGET_HOST);
        context.setAttribute(NhttpConstants.PROXY_PROFILE_TARGET_HOST, targetHost);
        if (!tunnelHandler.isRequested()) {
            HttpRequest request = tunnelHandler.generateRequest(context);
            if (proxyauthenticator != null) {
                proxyauthenticator.authenticatePreemptively(request, context);
            }
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Sending CONNECT request to " + tunnelHandler.getProxy());
            }
            conn.submitRequest(request);
            tunnelHandler.setRequested();
        }
        return;
    }
    Axis2HttpRequest axis2Req = (Axis2HttpRequest) context.removeAttribute(ATTACHMENT_KEY);
    if (axis2Req == null || axis2Req.isCompleted()) {
        return;
    }
    try {
        processConnection(conn, axis2Req);
    } catch (ConnectionClosedException e) {
        metrics.incrementFaultsSending();
        handleException("I/O Error submitting request : " + e.getMessage(), e, conn);
    }
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpContext(org.apache.http.protocol.HttpContext) ProxyTunnelHandler(org.apache.synapse.transport.http.conn.ProxyTunnelHandler) ConnectionClosedException(org.apache.http.ConnectionClosedException)

Example 22 with HttpRequest

use of org.apache.http.HttpRequest in project wso2-synapse by wso2.

the class TargetHandler method requestReady.

public void requestReady(NHttpClientConnection conn) {
    HttpContext context = conn.getContext();
    ProtocolState connState = null;
    try {
        connState = TargetContext.getState(conn);
        if (connState == ProtocolState.REQUEST_DONE || connState == ProtocolState.RESPONSE_BODY) {
            return;
        }
        if (connState != ProtocolState.REQUEST_READY) {
            handleInvalidState(conn, "Request not started");
            return;
        }
        ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context.getAttribute(PassThroughConstants.TUNNEL_HANDLER);
        if (tunnelHandler != null && !tunnelHandler.isCompleted()) {
            Object targetHost = TargetContext.get(conn).getRequestMsgCtx().getProperty(PassThroughConstants.PROXY_PROFILE_TARGET_HOST);
            context.setAttribute(PassThroughConstants.PROXY_PROFILE_TARGET_HOST, targetHost);
            if (!tunnelHandler.isRequested()) {
                HttpRequest request = tunnelHandler.generateRequest(context);
                if (targetConfiguration.getProxyAuthenticator() != null) {
                    targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, context);
                }
                if (log.isDebugEnabled()) {
                    log.debug(conn + ": Sending CONNECT request to " + tunnelHandler.getProxy());
                }
                conn.submitRequest(request);
                tunnelHandler.setRequested();
            }
            return;
        }
        TargetRequest request = TargetContext.getRequest(conn);
        if (request != null) {
            request.start(conn);
            targetConfiguration.getMetrics().incrementMessagesSent();
        }
        context.setAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME, System.currentTimeMillis());
        context.setAttribute(PassThroughConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis());
    } catch (IOException e) {
        logIOException(conn, e);
        TargetContext.updateState(conn, ProtocolState.CLOSED);
        targetConfiguration.getConnections().shutdownConnection(conn, true);
        MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();
        if (requestMsgCtx != null) {
            targetErrorHandler.handleError(requestMsgCtx, ErrorCodes.SND_IO_ERROR, "Error in Sender", null, connState);
        }
    } catch (HttpException e) {
        log.error(e.getMessage(), e);
        TargetContext.updateState(conn, ProtocolState.CLOSED);
        targetConfiguration.getConnections().shutdownConnection(conn, true);
        MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();
        if (requestMsgCtx != null) {
            targetErrorHandler.handleError(requestMsgCtx, ErrorCodes.SND_HTTP_ERROR, "Error in Sender", null, connState);
        }
    }
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpContext(org.apache.http.protocol.HttpContext) ProxyTunnelHandler(org.apache.synapse.transport.http.conn.ProxyTunnelHandler) HttpException(org.apache.http.HttpException) IOException(java.io.IOException) MessageContext(org.apache.axis2.context.MessageContext)

Example 23 with HttpRequest

use of org.apache.http.HttpRequest in project crnk-framework by crnk-project.

the class CharsetTest method testUTF8isDefault.

public void testUTF8isDefault(boolean okHttp) throws InstantiationException, IllegalAccessException {
    requestContentType = null;
    responseContentType = null;
    if (okHttp) {
        OkHttpAdapter adapter = OkHttpAdapter.newInstance();
        adapter.addListener(new OkHttpAdapterListener() {

            @Override
            public void onBuild(OkHttpClient.Builder builder) {
                builder.addInterceptor(new Interceptor() {

                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        requestContentType = chain.request().header(HttpHeaders.HTTP_CONTENT_TYPE);
                        Response response = chain.proceed(chain.request());
                        responseContentType = response.header(HttpHeaders.HTTP_CONTENT_TYPE);
                        return response;
                    }
                });
            }
        });
        client.setHttpAdapter(adapter);
    } else {
        HttpClientAdapter adapter = HttpClientAdapter.newInstance();
        adapter.addListener(new HttpClientAdapterListener() {

            @Override
            public void onBuild(HttpClientBuilder builder) {
                builder.addInterceptorFirst(new HttpRequestInterceptor() {

                    @Override
                    public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
                        Header header = httpRequest.getFirstHeader(HttpHeaders.HTTP_CONTENT_TYPE);
                        requestContentType = header != null ? header.getValue() : null;
                    }
                });
                builder.addInterceptorFirst(new HttpResponseInterceptor() {

                    @Override
                    public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
                        Header header = httpResponse.getFirstHeader(HttpHeaders.HTTP_CONTENT_TYPE);
                        responseContentType = header != null ? header.getValue() : null;
                    }
                });
            }
        });
        client.setHttpAdapter(adapter);
    }
    ResourceRepositoryV2<Task, Long> testRepo = client.getRepositoryForType(Task.class);
    Task entity = new Task();
    entity.setId(1L);
    entity.setName("äöüé@¢€");
    testRepo.create(entity);
    Assert.assertEquals(HttpHeaders.JSONAPI_CONTENT_TYPE_AND_CHARSET, requestContentType);
    Assert.assertEquals(HttpHeaders.JSONAPI_CONTENT_TYPE_AND_CHARSET, responseContentType);
    Task savedEntity = testRepo.findOne(1L, new QuerySpec(Task.class));
    Assert.assertEquals(entity.getName(), savedEntity.getName());
    Assert.assertNull(requestContentType);
    Assert.assertEquals(HttpHeaders.JSONAPI_CONTENT_TYPE_AND_CHARSET, responseContentType);
}
Also used : HttpRequest(org.apache.http.HttpRequest) Task(io.crnk.test.mock.models.Task) OkHttpClient(okhttp3.OkHttpClient) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpClientAdapterListener(io.crnk.client.http.apache.HttpClientAdapterListener) Response(okhttp3.Response) HttpResponse(org.apache.http.HttpResponse) HttpClientAdapter(io.crnk.client.http.apache.HttpClientAdapter) Header(org.apache.http.Header) OkHttpAdapterListener(io.crnk.client.http.okhttp.OkHttpAdapterListener) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) OkHttpAdapter(io.crnk.client.http.okhttp.OkHttpAdapter) HttpResponseInterceptor(org.apache.http.HttpResponseInterceptor) QuerySpec(io.crnk.core.queryspec.QuerySpec) Interceptor(okhttp3.Interceptor) HttpResponseInterceptor(org.apache.http.HttpResponseInterceptor) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor)

Example 24 with HttpRequest

use of org.apache.http.HttpRequest in project joynr by bmwcarit.

the class IsCreateChannelHttpRequest method matches.

@Override
public boolean matches(Object argument) {
    HttpRequest request = (HttpRequest) argument;
    // check if tracking ID is sent in header
    Header trackingIdHeader = request.getFirstHeader("X-Atmosphere-tracking-id");
    if (trackingIdHeader == null) {
        // no tracking ID header set at all
        return false;
    } else {
        if (!trackingIdHeader.getValue().equals(trackingId)) {
            // wrong tracking ID header set
            return false;
        }
    }
    // check if channel ID is sent as query parameter ccid
    List<NameValuePair> queryParameters = URLEncodedUtils.parse(URI.create(request.getRequestLine().getUri()), "UTF-8");
    for (NameValuePair queryParameter : queryParameters) {
        if (queryParameter.getName().equals("ccid") && queryParameter.getValue().equals(ccid)) {
            // right channel ID sent
            return true;
        } else {
            // wrong channel ID sent
            return false;
        }
    }
    // no query parameter with ccid sent at all
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) NameValuePair(org.apache.http.NameValuePair) Header(org.apache.http.Header)

Example 25 with HttpRequest

use of org.apache.http.HttpRequest in project incubator-skywalking by apache.

the class HttpClientExecuteInterceptor method beforeMethod.

@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
    if (allArguments[0] == null || allArguments[1] == null) {
        // illegal args, can't trace. ignore.
        return;
    }
    final HttpHost httpHost = (HttpHost) allArguments[0];
    HttpRequest httpRequest = (HttpRequest) allArguments[1];
    final ContextCarrier contextCarrier = new ContextCarrier();
    AbstractSpan span = null;
    String remotePeer = httpHost.getHostName() + ":" + (httpHost.getPort() > 0 ? httpHost.getPort() : "https".equals(httpHost.getSchemeName().toLowerCase()) ? 443 : 80);
    try {
        URL url = new URL(httpRequest.getRequestLine().getUri());
        span = ContextManager.createExitSpan(url.getPath(), contextCarrier, remotePeer);
    } catch (MalformedURLException e) {
        throw e;
    }
    span.setComponent(ComponentsDefine.HTTPCLIENT);
    Tags.URL.set(span, httpRequest.getRequestLine().getUri());
    Tags.HTTP.METHOD.set(span, httpRequest.getRequestLine().getMethod());
    SpanLayer.asHttp(span);
    CarrierItem next = contextCarrier.items();
    while (next.hasNext()) {
        next = next.next();
        httpRequest.setHeader(next.getHeadKey(), next.getHeadValue());
    }
}
Also used : HttpRequest(org.apache.http.HttpRequest) ContextCarrier(org.apache.skywalking.apm.agent.core.context.ContextCarrier) MalformedURLException(java.net.MalformedURLException) CarrierItem(org.apache.skywalking.apm.agent.core.context.CarrierItem) HttpHost(org.apache.http.HttpHost) URL(java.net.URL) AbstractSpan(org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan)

Aggregations

HttpRequest (org.apache.http.HttpRequest)155 HttpResponse (org.apache.http.HttpResponse)57 HttpContext (org.apache.http.protocol.HttpContext)56 HttpHost (org.apache.http.HttpHost)52 Test (org.junit.Test)40 IOException (java.io.IOException)36 Header (org.apache.http.Header)33 HttpException (org.apache.http.HttpException)33 HttpEntity (org.apache.http.HttpEntity)27 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)25 BasicHttpRequest (org.apache.http.message.BasicHttpRequest)22 HttpGet (org.apache.http.client.methods.HttpGet)21 HttpPost (org.apache.http.client.methods.HttpPost)21 URI (java.net.URI)19 ProtocolException (org.apache.http.ProtocolException)18 AbortableHttpRequest (org.apache.http.client.methods.AbortableHttpRequest)16 StringEntity (org.apache.http.entity.StringEntity)16 ArrayList (java.util.ArrayList)14 NameValuePair (org.apache.http.NameValuePair)14 CredentialsProvider (org.apache.http.client.CredentialsProvider)14