org.apache.http.RequestLine Java Examples

The following examples show how to use org.apache.http.RequestLine. 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: AopHttpClient.java    From ArgusAPM with Apache License 2.0 6 votes vote down vote up
private static HttpRequest handleRequest(HttpHost host, HttpRequest request, NetInfo data) {
    RequestLine requestLine = request.getRequestLine();
    if (requestLine != null) {
        String uri = requestLine.getUri();
        int i = (uri != null) && (uri.length() >= 10) && (uri.substring(0, 10).indexOf("://") >= 0) ? 1 : 0;
        if ((i == 0) && (uri != null) && (host != null)) {
            String uriFromHost = host.toURI().toString();
            data.setURL(uriFromHost + ((uriFromHost.endsWith("/")) || (uri.startsWith("/")) ? "" : "/") + uri);
        } else if (i != 0) {
            data.setURL(uri);
        }
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        if (entityRequest.getEntity() != null) {
            entityRequest.setEntity(new AopHttpRequestEntity(entityRequest.getEntity(), data));
        }
        return entityRequest;
    }
    return request;
}
 
Example #2
Source File: WrappedHttpRequest.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
public RequestLine getRequestLine()
{
    return new RequestLine()
    {
        @Override
        public String getMethod()
        {
            return implementation.getRequestLine().getMethod();
        }

        @Override
        public ProtocolVersion getProtocolVersion()
        {
            return implementation.getRequestLine().getProtocolVersion();
        }

        @Override
        public String getUri()
        {
            return newUri.toString();
        }
    };
}
 
Example #3
Source File: ApacheHttpClientTagAdapterTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
GetRequestUrlScenario(
    boolean requestIsNull, boolean requestIsWrapper, Object baseUri, boolean targetIsNull,
    String targetUri, String expectedResult
) {
    this.expectedResult = expectedResult;
    HttpRequest request = null;

    if (!requestIsNull) {
        request = (requestIsWrapper) ? mock(HttpRequestWrapper.class) : mock(HttpRequest.class);
        RequestLine requestLine = mock(RequestLine.class);
        doReturn(requestLine).when(request).getRequestLine();
        doReturn(baseUri).when(requestLine).getUri();

        if (!targetIsNull) {
            HttpHost target = HttpHost.create(targetUri);
            doReturn(target).when((HttpRequestWrapper) request).getTarget();
        }
    }

    this.requestMock = request;
}
 
Example #4
Source File: InstrHttpClientBuilderProvider.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public String getNameFor(String name, HttpRequest request) {
  try {
    String context = "";
    Header header = request.getFirstHeader("X-Forwarded-Context");
    if (header != null) {
      context = header.getValue();
    }
    RequestLine requestLine = request.getRequestLine();
    URIBuilder uriBuilder = new URIBuilder(requestLine.getUri());
    String resourcePath = InstrUtils.getResourcePath(uriBuilder.removeQuery().build().toString());
    return MetricRegistry.name("service", name, context + resourcePath, methodNameString(request));
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e);
  }
}
 
Example #5
Source File: ApacheHttpClientAspect.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@OnBefore
public static @Nullable TraceEntry onBefore(ThreadContext context,
        @BindParameter @Nullable HttpHost hostObj,
        @BindParameter @Nullable HttpRequest request) {
    if (request == null) {
        return null;
    }
    RequestLine requestLine = request.getRequestLine();
    if (requestLine == null) {
        return null;
    }
    String method = requestLine.getMethod();
    if (method == null) {
        method = "";
    } else {
        method += " ";
    }
    String host = hostObj == null ? "" : hostObj.toURI();
    String uri = requestLine.getUri();
    if (uri == null) {
        uri = "";
    }
    return context.startServiceCallEntry("HTTP", method + Uris.stripQueryString(uri),
            MessageSupplier.create("http client request: {}{}{}", method, host, uri),
            timerName);
}
 
Example #6
Source File: TestUtils.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a mock {@link IncomingRequest}.
 * 
 * @param uri
 *            the uri
 * @return the {@link IncomingRequest}
 */
public static IncomingRequest.Builder createIncomingRequest(String uri) {
    HttpHost httpHost = UriUtils.extractHost(uri);
    String scheme = httpHost.getSchemeName();
    String host = httpHost.getHostName();
    int port = httpHost.getPort();
    RequestLine requestLine = new BasicRequestLine("GET", uri, HttpVersion.HTTP_1_1);
    IncomingRequest.Builder builder = IncomingRequest.builder(requestLine);
    builder.setContext(new ContainerRequestContext() {
    });
    // Remove default ports
    if (port == -1 || (port == Http.DEFAULT_HTTP_PORT && "http".equals(scheme))
            || (port == Http.DEFAULT_HTTPS_PORT && "https".equals(scheme))) {
        builder.addHeader("Host", host);
    } else {
        builder.addHeader("Host", host + ":" + port);
    }
    builder.setSession(new MockSession());
    return builder;
}
 
Example #7
Source File: LowLevelRestController.java    From ProjectStudy with MIT License 6 votes vote down vote up
/**
 * 同步执行HTTP请求
 *
 * @param
 * @return org.springframework.http.ResponseEntity<java.lang.String>
 * @throws IOException
 * @author wliduo[[email protected]]
 * @date 2019/8/8 17:15
 */
@GetMapping("/es")
public ResponseBean getEsInfo() throws IOException {
    Request request = new Request("GET", "/");
    // performRequest是同步的,将阻塞调用线程并在请求成功时返回Response,如果失败则抛出异常
    Response response = restClient.performRequest(request);
    // 获取请求行
    RequestLine requestLine = response.getRequestLine();
    // 获取host
    HttpHost host = response.getHost();
    // 获取状态码
    int statusCode = response.getStatusLine().getStatusCode();
    // 获取响应头
    Header[] headers = response.getHeaders();
    // 获取响应体
    String responseBody = EntityUtils.toString(response.getEntity());
    return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
}
 
Example #8
Source File: LowLevelRestController.java    From ProjectStudy with MIT License 6 votes vote down vote up
/**
 * 同步执行HTTP请求
 *
 * @param
 * @return org.springframework.http.ResponseEntity<java.lang.String>
 * @throws IOException
 * @author wliduo[[email protected]]
 * @date 2019/8/8 17:15
 */
@GetMapping("/es")
public ResponseBean getEsInfo() throws IOException {
    Request request = new Request("GET", "/");
    // performRequest是同步的,将阻塞调用线程并在请求成功时返回Response,如果失败则抛出异常
    Response response = restClient.performRequest(request);
    // 获取请求行
    RequestLine requestLine = response.getRequestLine();
    // 获取host
    HttpHost host = response.getHost();
    // 获取状态码
    int statusCode = response.getStatusLine().getStatusCode();
    // 获取响应头
    Header[] headers = response.getHeaders();
    // 获取响应体
    String responseBody = EntityUtils.toString(response.getEntity());
    return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
}
 
Example #9
Source File: HttpClient4RequestWrapper.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public String getUrl() {
    final RequestLine requestLine = this.httpRequest.getRequestLine();
    if (requestLine != null) {
        return requestLine.getUri();
    }
    return null;
}
 
Example #10
Source File: DispatchRequestFactory.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public HttpRequest newHttpRequest(RequestLine requestLine)
        throws MethodNotSupportedException {
    String method = requestLine.getMethod();
    String uri = requestLine.getUri();
    return this.newHttpRequest(method, uri);
}
 
Example #11
Source File: HttpRequestParcel.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public HttpRequestParcel(HttpUriRequest request) {
    RequestLine line = request.getRequestLine();
    uri = line.getUri();
    method = line.getMethod();
    headers = new Bundle();
    for (Header header : request.getAllHeaders()) {
        headers.putString(header.getName(), header.getValue());
    }
    params = new Bundle();
    entity = null;
    files = new Bundle();
}
 
Example #12
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
boolean clientRequestsOurOptions(HttpRequest request) {
	RequestLine line = request.getRequestLine();

	if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod()))
		return false;

	if (!"*".equals(line.getUri()))
		return false;

	if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS)
			.getValue()))
		return false;

	return true;
}
 
Example #13
Source File: ApacheHttpAsyncClientAspect.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@OnBefore
public static @Nullable AsyncTraceEntry onBefore(ThreadContext context,
        @BindParameter @Nullable HttpHost hostObj,
        @BindParameter @Nullable HttpRequest request,
        @BindParameter ParameterHolder<FutureCallback<HttpResponse>> callback) {
    if (request == null) {
        return null;
    }
    RequestLine requestLine = request.getRequestLine();
    if (requestLine == null) {
        return null;
    }
    String method = requestLine.getMethod();
    if (method == null) {
        method = "";
    } else {
        method += " ";
    }
    String host = hostObj == null ? "" : hostObj.toURI();
    String uri = requestLine.getUri();
    if (uri == null) {
        uri = "";
    }
    AsyncTraceEntry asyncTraceEntry = context.startAsyncServiceCallEntry("HTTP",
            method + Uris.stripQueryString(uri),
            MessageSupplier.create("http client request: {}{}{}", method, host, uri),
            timerName);
    callback.set(ExecuteAdvice.createWrapper(context, callback, asyncTraceEntry));
    return asyncTraceEntry;
}
 
Example #14
Source File: HttpAsyncRequestExecutorInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    HttpContext context = CONTEXT_LOCAL.get();
    CONTEXT_LOCAL.remove();
    if (context == null) {
        return;
    }
    final ContextCarrier contextCarrier = new ContextCarrier();
    HttpRequestWrapper requestWrapper = (HttpRequestWrapper) context.getAttribute(HttpClientContext.HTTP_REQUEST);
    HttpHost httpHost = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);

    RequestLine requestLine = requestWrapper.getRequestLine();
    String uri = requestLine.getUri();
    String operationName = uri.startsWith("http") ? new URL(uri).getPath() : uri;
    int port = httpHost.getPort();
    AbstractSpan span = ContextManager.createExitSpan(operationName, contextCarrier, httpHost.getHostName() + ":" + (port == -1 ? 80 : port));
    span.setComponent(ComponentsDefine.HTTP_ASYNC_CLIENT);
    Tags.URL.set(span, requestWrapper.getOriginal().getRequestLine().getUri());
    Tags.HTTP.METHOD.set(span, requestLine.getMethod());
    SpanLayer.asHttp(span);
    CarrierItem next = contextCarrier.items();
    while (next.hasNext()) {
        next = next.next();
        requestWrapper.setHeader(next.getHeadKey(), next.getHeadValue());
    }
}
 
Example #15
Source File: HttpClientExecuteInterceptorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void testUriNotProtocol() throws Throwable {
    when(request.getRequestLine()).thenReturn(new RequestLine() {
        @Override
        public String getMethod() {
            return "GET";
        }

        @Override
        public ProtocolVersion getProtocolVersion() {
            return new ProtocolVersion("http", 1, 1);
        }

        @Override
        public String getUri() {
            return "/test-web/test";
        }
    });
    httpClientExecuteInterceptor.beforeMethod(enhancedInstance, null, allArguments, argumentsType, null);
    httpClientExecuteInterceptor.afterMethod(enhancedInstance, null, allArguments, argumentsType, httpResponse);

    Assert.assertThat(segmentStorage.getTraceSegments().size(), is(1));
    TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);

    List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment);
    assertHttpSpan(spans.get(0));
    verify(request, times(3)).setHeader(anyString(), anyString());
}
 
Example #16
Source File: CXFHttpRequest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public RequestLine getRequestLine() {
    return new BasicRequestLine(
            method,
            uri != null ? uri.toASCIIString() : "/",
            HttpVersion.HTTP_1_1);
}
 
Example #17
Source File: HttpClientExecuteInterceptorTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    ServiceManager.INSTANCE.boot();
    httpClientExecuteInterceptor = new HttpClientExecuteInterceptor();

    PowerMockito.mock(HttpHost.class);
    when(statusLine.getStatusCode()).thenReturn(200);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(httpHost.getHostName()).thenReturn("127.0.0.1");
    when(httpHost.getSchemeName()).thenReturn("http");
    when(request.getRequestLine()).thenReturn(new RequestLine() {
        @Override
        public String getMethod() {
            return "GET";
        }

        @Override
        public ProtocolVersion getProtocolVersion() {
            return new ProtocolVersion("http", 1, 1);
        }

        @Override
        public String getUri() {
            return "http://127.0.0.1:8080/test-web/test";
        }
    });
    when(httpHost.getPort()).thenReturn(8080);

    allArguments = new Object[] {
        httpHost,
        request
    };
    argumentsType = new Class[] {
        httpHost.getClass(),
        request.getClass()
    };
}
 
Example #18
Source File: UpnpHttpRequestFactory.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public HttpRequest newHttpRequest(final RequestLine requestline)
        throws MethodNotSupportedException {
    if (requestline == null) {
        throw new IllegalArgumentException("Request line may not be null");
    }
    String method = requestline.getMethod();
    String uri = requestline.getUri();
    return newHttpRequest(method, uri);
}
 
Example #19
Source File: TestHttpHandler.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
	RequestLine requestLine = request.getRequestLine();
	this.method = requestLine.getMethod();
	this.uri = requestLine.getUri();

	HttpEntity entity = null;
	if (request instanceof HttpEntityEnclosingRequest) {
		entity = ((HttpEntityEnclosingRequest) request).getEntity();
		body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
	}
}
 
Example #20
Source File: UpnpHttpRequestFactory.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public HttpRequest newHttpRequest(final RequestLine requestline)
        throws MethodNotSupportedException {
    if (requestline == null) {
        throw new IllegalArgumentException("Request line may not be null");
    }
    String method = requestline.getMethod();
    String uri = requestline.getUri();
    return newHttpRequest(method, uri);
}
 
Example #21
Source File: HttpClientInterceptor.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public void process(HttpRequest request, HttpContext context)
{
    byte[] body = null;
    String mimeType = null;
    if (request instanceof HttpEntityEnclosingRequest)
    {
        HttpEntityEnclosingRequest requestWithBody = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = requestWithBody.getEntity();
        if (entity != null)
        {
            mimeType = Optional.ofNullable(ContentType.getLenient(entity))
                    .map(ContentType::getMimeType)
                    .orElseGet(() -> getMimeType(requestWithBody.getAllHeaders()));
            try (ByteArrayOutputStream baos = new ByteArrayOutputStream((int) entity.getContentLength()))
            {
                // https://github.com/apache/httpcomponents-client/commit/09cefc2b8970eea56d81b1a886d9bb769a48daf3
                entity.writeTo(baos);
                body = baos.toByteArray();
            }
            catch (IOException e)
            {
                LOGGER.error("Error is occurred at HTTP message parsing", e);
            }
        }
    }
    RequestLine requestLine = request.getRequestLine();
    String attachmentTitle = String.format("Request: %s %s", requestLine.getMethod(), requestLine.getUri());
    attachApiMessage(attachmentTitle, request.getAllHeaders(), body, mimeType, -1);
}
 
Example #22
Source File: HttpClientInterceptorTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private HttpEntityEnclosingRequest mockHttpEntityEnclosingRequest(Header[] allRequestHeaders, HttpEntity httpEntity)
{
    HttpEntityEnclosingRequest httpRequest = mock(HttpEntityEnclosingRequest.class);
    RequestLine requestLine = mock(RequestLine.class);
    when(httpRequest.getAllHeaders()).thenReturn(allRequestHeaders);
    when(httpRequest.getEntity()).thenReturn(httpEntity);
    when(httpRequest.getRequestLine()).thenReturn(requestLine);
    when(requestLine.getMethod()).thenReturn(METHOD);
    when(requestLine.getUri()).thenReturn(ENDPOINT);
    return httpRequest;
}
 
Example #23
Source File: HttpAsyncRequestProducerWrapper.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequest generateRequest() throws IOException, HttpException {
    // first read the volatile, span will become visible as a result
    HttpRequest request = delegate.generateRequest();

    if (request != null) {
        RequestLine requestLine = request.getRequestLine();
        if (requestLine != null) {
            String method = requestLine.getMethod();
            span.withName(method).appendToName(" ");
            span.getContext().getHttp().withMethod(method).withUrl(requestLine.getUri());
        }
        span.propagateTraceContext(request, headerSetter);
    }

    HttpHost host = getTarget();
    //noinspection ConstantConditions
    if (host != null) {
        String hostname = host.getHostName();
        if (hostname != null) {
            span.appendToName(hostname);
            HttpClientHelper.setDestinationServiceDetails(span, host.getSchemeName(), hostname, host.getPort());
        }
    }

    //noinspection ConstantConditions
    return request;
}
 
Example #24
Source File: AbstractHttpRequestInterceptor.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
public void appendHttpClientRequestSpanTags(HttpRequest httpRequest,
                                            SofaTracerSpan httpClientSpan) {
    if (httpClientSpan == null) {
        return;
    }
    if (this.appName == null) {
        this.appName = SofaTracerConfiguration.getProperty(
            SofaTracerConfiguration.TRACER_APPNAME_KEY, StringUtils.EMPTY_STRING);
    }
    //lazy init
    RequestLine requestLine = httpRequest.getRequestLine();
    String methodName = requestLine.getMethod();
    //appName
    httpClientSpan.setTag(CommonSpanTags.LOCAL_APP,
        this.appName == null ? StringUtils.EMPTY_STRING : this.appName);
    //targetAppName
    httpClientSpan.setTag(CommonSpanTags.REMOTE_APP,
        this.targetAppName == null ? StringUtils.EMPTY_STRING : this.targetAppName);
    if (httpRequest instanceof HttpRequestWrapper) {
        HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) httpRequest;
        httpClientSpan.setTag(CommonSpanTags.REQUEST_URL, httpRequestWrapper.getOriginal()
            .getRequestLine().getUri());
    } else {
        httpClientSpan.setTag(CommonSpanTags.REQUEST_URL, requestLine.getUri());
    }
    //method
    httpClientSpan.setTag(CommonSpanTags.METHOD, methodName);
    //length
    if (httpRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest;
        HttpEntity httpEntity = httpEntityEnclosingRequest.getEntity();
        httpClientSpan.setTag(CommonSpanTags.REQ_SIZE,
            httpEntity == null ? -1 : httpEntity.getContentLength());
    }
    //carrier
    this.processHttpClientRequestCarrier(httpRequest, httpClientSpan);
}
 
Example #25
Source File: UserAgentRequestHeaderTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * UserAgentRequestHeader adds correct header with current version.
 * @throws Exception If something goes wrong.
 */
@Test
public void correctUserAgentHeader() throws Exception {
    final RequestLine mockRequestLine = Mockito.mock(RequestLine.class);
    Mockito.when(mockRequestLine.getMethod()).thenReturn("GET");
    final HttpRequest mockRequest = Mockito.mock(HttpRequest.class);
    Mockito.when(mockRequest.getRequestLine()).thenReturn(mockRequestLine);
    Mockito.when(mockRequest.getParams()).thenReturn(new BasicHttpParams());

    final UserAgentRequestHeader header = new UserAgentRequestHeader();
    header.process(mockRequest, null);

    final ArgumentCaptor<Header> headerCaptor =
        ArgumentCaptor.forClass(Header.class);
    Mockito.verify(mockRequest).addHeader(headerCaptor.capture());
    MatcherAssert.assertThat(
        "Header name must be User-Agent",
        headerCaptor.getValue().getName(),
        new IsEqual<>("User-Agent")
    );
    final Pattern pattern =
        Pattern.compile("(?<=docker-java-api.\\/.)(.*)(?=.See)");
    final Matcher matcher =
        pattern.matcher(headerCaptor.getValue().getValue());
    MatcherAssert.assertThat(
        "Header value must have version in it",
        matcher.find(),
        new IsEqual<>(true)
    );
}
 
Example #26
Source File: ApacheHttpClientTagAdapterTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    implSpy = spy(new ApacheHttpClientTagAdapter());
    requestMock = mock(HttpRequest.class);
    responseMock = mock(HttpResponse.class);

    requestLineMock = mock(RequestLine.class);

    doReturn(requestLineMock).when(requestMock).getRequestLine();
}
 
Example #27
Source File: WingtipsApacheHttpClientUtilTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    requestMock = mock(HttpRequest.class);
    requestLineMock = mock(RequestLine.class);

    doReturn(requestLineMock).when(requestMock).getRequestLine();
}
 
Example #28
Source File: WingtipsApacheHttpClientInterceptorTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    resetTracing();

    initialSpanNameFromStrategy = new AtomicReference<>("span-name-from-strategy-" + UUID.randomUUID().toString());
    strategyInitialSpanNameMethodCalled = new AtomicBoolean(false);
    strategyRequestTaggingMethodCalled = new AtomicBoolean(false);
    strategyResponseTaggingAndFinalSpanNameMethodCalled = new AtomicBoolean(false);
    strategyInitialSpanNameArgs = new AtomicReference<>(null);
    strategyRequestTaggingArgs = new AtomicReference<>(null);
    strategyResponseTaggingArgs = new AtomicReference<>(null);
    tagAndNamingStrategy = new ArgCapturingHttpTagAndSpanNamingStrategy(
        initialSpanNameFromStrategy, strategyInitialSpanNameMethodCalled, strategyRequestTaggingMethodCalled,
        strategyResponseTaggingAndFinalSpanNameMethodCalled, strategyInitialSpanNameArgs,
        strategyRequestTaggingArgs, strategyResponseTaggingArgs
    );
    tagAndNamingAdapterMock = mock(HttpTagAndSpanNamingAdapter.class);

    interceptor = new WingtipsApacheHttpClientInterceptor(true, tagAndNamingStrategy, tagAndNamingAdapterMock);

    requestMock = mock(HttpRequest.class);
    responseMock = mock(HttpResponse.class);
    httpContext = new BasicHttpContext();
    requestLineMock = mock(RequestLine.class);
    statusLineMock = mock(StatusLine.class);

    method = "GET";
    uri = "http://localhost:4242/foo/bar";

    responseCode = 200;

    doReturn(requestLineMock).when(requestMock).getRequestLine();
    doReturn(method).when(requestLineMock).getMethod();
    doReturn(uri).when(requestLineMock).getUri();

    doReturn(statusLineMock).when(responseMock).getStatusLine();
    doReturn(responseCode).when(statusLineMock).getStatusCode();
}
 
Example #29
Source File: HttpAsyncClientInterceptorTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    ServiceManager.INSTANCE.boot();
    httpAsyncClientInterceptor = new HttpAsyncClientInterceptor();
    requestExecutorInterceptor = new HttpAsyncRequestExecutorInterceptor();
    sessionRequestConstructorInterceptor = new SessionRequestConstructorInterceptor();
    completeInterceptor = new SessionRequestCompleteInterceptor();

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.HTTP_REQUEST, requestWrapper);
    httpContext.setAttribute(HttpClientContext.HTTP_TARGET_HOST, httpHost);
    CONTEXT_LOCAL.set(httpContext);
    when(httpHost.getHostName()).thenReturn("127.0.0.1");
    when(httpHost.getSchemeName()).thenReturn("http");

    final RequestLine requestLine = new RequestLine() {
        @Override
        public String getMethod() {
            return "GET";
        }

        @Override
        public ProtocolVersion getProtocolVersion() {
            return new ProtocolVersion("http", 1, 1);
        }

        @Override
        public String getUri() {
            return "http://127.0.0.1:8080/test-web/test";
        }
    };

    when(response.getStatusLine()).thenReturn(new StatusLine() {
        @Override
        public ProtocolVersion getProtocolVersion() {
            return new ProtocolVersion("http", 1, 1);
        }

        @Override
        public int getStatusCode() {
            return 200;
        }

        @Override
        public String getReasonPhrase() {
            return null;
        }
    });

    when(requestWrapper.getRequestLine()).thenReturn(requestLine);
    when(requestWrapper.getOriginal()).thenReturn(new HttpGet("http://localhost:8081/original/test"));
    when(httpHost.getPort()).thenReturn(8080);

    enhancedInstance = new EnhancedInstance() {

        private Object object;

        @Override
        public Object getSkyWalkingDynamicField() {
            return object;
        }

        @Override
        public void setSkyWalkingDynamicField(Object value) {
            this.object = value;
        }
    };
}
 
Example #30
Source File: RandomTestMocks.java    From BUbiNG with Apache License 2.0 4 votes vote down vote up
@Override
public RequestLine getRequestLine() {
	return requestLine;
}