Search in sources :

Example 6 with Request

use of com.palantir.dialogue.Request in project conjure-java-runtime by palantir.

the class JaxRsClientDialogueEndpointTest method testPostWithBody.

@Test
public void testPostWithBody() {
    Channel channel = stubNoContentResponseChannel();
    StubService service = JaxRsClient.create(StubService.class, channel, runtime);
    service.post("Hello, World!");
    ArgumentCaptor<Endpoint> endpointCaptor = ArgumentCaptor.forClass(Endpoint.class);
    ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class);
    verify(channel).execute(endpointCaptor.capture(), requestCaptor.capture());
    Endpoint endpoint = endpointCaptor.getValue();
    assertThat(endpoint.serviceName()).isEqualTo("StubService");
    assertThat(endpoint.endpointName()).isEqualTo("post");
    assertThat(endpoint.httpMethod()).isEqualTo(HttpMethod.POST);
    Request request = requestCaptor.getValue();
    assertThat(request.body()).isPresent();
    assertThat(request.body().get().contentType()).isEqualTo("text/plain");
    assertThat(request.headerParams().asMap()).containsExactly(new AbstractMap.SimpleImmutableEntry<>("Accept", ImmutableList.of("application/json")), new AbstractMap.SimpleImmutableEntry<>("Content-Length", ImmutableList.of("13")));
}
Also used : AbstractMap(java.util.AbstractMap) Endpoint(com.palantir.dialogue.Endpoint) Channel(com.palantir.dialogue.Channel) Request(com.palantir.dialogue.Request) Test(org.junit.Test)

Example 7 with Request

use of com.palantir.dialogue.Request in project dialogue by palantir.

the class ServiceImplementationGenerator method clientImpl.

private MethodSpec clientImpl(EndpointDefinition def) {
    List<ParameterSpec> params = def.arguments().stream().map(arg -> ParameterSpec.builder(ArgumentTypes.caseOf(arg.argType()).primitive((javaTypeName, _parameterSerializerMethodName, _isList) -> javaTypeName).rawRequestBody(typeName -> typeName).optional((optionalJavaType, _unused) -> optionalJavaType).mapType(typeName -> typeName).customType(typeName -> typeName), arg.argName().get()).build()).collect(Collectors.toList());
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(def.endpointName().get()).addModifiers(Modifier.PUBLIC).addParameters(params).addAnnotation(Override.class);
    methodBuilder.addCode("$T $L = $T.builder();", Request.Builder.class, REQUEST, Request.class);
    def.arguments().forEach(arg -> methodBuilder.addCode(generateParam(arg)));
    methodBuilder.returns(def.returns().returnType());
    boolean isAsync = def.returns().asyncInnerType().isPresent();
    String executeCode = isAsync ? "$L.clients().call($L, $L.build(), $L);" : "$L.clients().callBlocking($L, $L.build(), $L);";
    CodeBlock execute = CodeBlock.of(executeCode, serviceDefinition.conjureRuntimeArgName(), def.channelFieldName(), REQUEST, def.returns().deserializerFieldName());
    methodBuilder.addCode(!def.returns().isVoid() || isAsync ? "return $L" : "$L", execute);
    return methodBuilder.build();
}
Also used : OptionalType(com.palantir.dialogue.annotations.processor.data.ArgumentType.OptionalType) Modifier(javax.lang.model.element.Modifier) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) Serializer(com.palantir.dialogue.Serializer) ParameterEncoderType(com.palantir.dialogue.annotations.processor.data.ParameterEncoderType) Cases(com.palantir.dialogue.annotations.processor.data.ParameterType.Cases) ParameterSerializer(com.palantir.dialogue.annotations.ParameterSerializer) ErrorHandlingVoidDeserializer(com.palantir.dialogue.annotations.ErrorHandlingVoidDeserializer) Request(com.palantir.dialogue.Request) CodeBlock(com.squareup.javapoet.CodeBlock) DefaultParameterSerializer(com.palantir.dialogue.annotations.DefaultParameterSerializer) ParameterSpec(com.squareup.javapoet.ParameterSpec) ParameterTypes(com.palantir.dialogue.annotations.processor.data.ParameterTypes) Deserializer(com.palantir.dialogue.Deserializer) MethodSpec(com.squareup.javapoet.MethodSpec) EncoderType(com.palantir.dialogue.annotations.processor.data.ParameterEncoderType.EncoderType) ServiceDefinition(com.palantir.dialogue.annotations.processor.data.ServiceDefinition) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) ReturnType(com.palantir.dialogue.annotations.processor.data.ReturnType) ArgumentTypes(com.palantir.dialogue.annotations.processor.data.ArgumentTypes) TypeSpec(com.squareup.javapoet.TypeSpec) Collectors(java.util.stream.Collectors) ErrorHandlingDeserializerFactory(com.palantir.dialogue.annotations.ErrorHandlingDeserializerFactory) EndpointChannel(com.palantir.dialogue.EndpointChannel) List(java.util.List) ArgumentType(com.palantir.dialogue.annotations.processor.data.ArgumentType) TypeName(com.squareup.javapoet.TypeName) Optional(java.util.Optional) TypeMarker(com.palantir.dialogue.TypeMarker) ArgumentDefinition(com.palantir.dialogue.annotations.processor.data.ArgumentDefinition) EndpointDefinition(com.palantir.dialogue.annotations.processor.data.EndpointDefinition) ParameterSpec(com.squareup.javapoet.ParameterSpec) MethodSpec(com.squareup.javapoet.MethodSpec) Request(com.palantir.dialogue.Request) CodeBlock(com.squareup.javapoet.CodeBlock)

Example 8 with Request

use of com.palantir.dialogue.Request in project dialogue by palantir.

the class NoResponseTest method testConnectionClosedAfterDelay.

@Test
public void testConnectionClosedAfterDelay() {
    // This test closes the connection after taking some time to "process"
    // the request. We expect the client _not_ to retry in this case.
    AtomicInteger requests = new AtomicInteger();
    Undertow server = createStarted(new BlockingHandler(exchange -> {
        requests.incrementAndGet();
        Uninterruptibles.sleepUninterruptibly(Duration.ofSeconds(5));
        exchange.getConnection().close();
    }));
    try {
        Channel channel = create(defaultClientConfig(getPort(server)));
        assertThatThrownBy(channel.execute(TestEndpoint.POST, request)::get).hasCauseInstanceOf(SocketTimeoutException.class);
        assertThat(requests).as("Request mustn't be retried").hasValue(1);
    } finally {
        server.stop();
    }
}
Also used : BlockingHandler(io.undertow.server.handlers.BlockingHandler) OutputStream(java.io.OutputStream) Iterables(com.google.common.collect.Iterables) Uninterruptibles(com.google.common.util.concurrent.Uninterruptibles) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) Channel(com.palantir.dialogue.Channel) TestEndpoint(com.palantir.dialogue.TestEndpoint) InetSocketAddress(java.net.InetSocketAddress) TestConfigurations(com.palantir.dialogue.TestConfigurations) Undertow(io.undertow.Undertow) HttpHandler(io.undertow.server.HttpHandler) SslSocketFactories(com.palantir.conjure.java.config.ssl.SslSocketFactories) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) ImmutableList(com.google.common.collect.ImmutableList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SocketTimeoutException(java.net.SocketTimeoutException) Duration(java.time.Duration) Request(com.palantir.dialogue.Request) ClientConfigurations(com.palantir.conjure.java.client.config.ClientConfigurations) Response(com.palantir.dialogue.Response) IoUtils(org.xnio.IoUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BlockingHandler(io.undertow.server.handlers.BlockingHandler) Channel(com.palantir.dialogue.Channel) Undertow(io.undertow.Undertow) Test(org.junit.jupiter.api.Test)

Example 9 with Request

use of com.palantir.dialogue.Request in project dialogue by palantir.

the class ApacheHttpClientChannelsTest method testContentLength.

@SuppressWarnings("FutureReturnValueIgnored")
private void testContentLength(Optional<String> headerValue, Optional<RequestBody> body, long value) {
    try {
        endpoint.method = HttpMethod.POST;
        Request.Builder builder = Request.builder().from(request).body(body);
        headerValue.ifPresent(header -> builder.putHeaderParams(HttpHeaders.CONTENT_LENGTH, header));
        request = builder.build();
        channel.execute(endpoint, request);
        RecordedRequest recordedRequest = server.takeRequest();
        assertThat(recordedRequest.getMethod()).isEqualTo("POST");
        assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_LENGTH)).isEqualTo(Long.toString(value));
        assertThat(recordedRequest.getHeader(HttpHeaders.TRANSFER_ENCODING)).isNull();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Request(com.palantir.dialogue.Request) RecordedRequest(okhttp3.mockwebserver.RecordedRequest)

Example 10 with Request

use of com.palantir.dialogue.Request in project dialogue by palantir.

the class SimulationServer method execute.

@Override
public ListenableFuture<Response> execute(Endpoint endpoint, Request request) {
    Meter perEndpointRequests = MetricNames.requestMeter(simulation.taggedMetrics(), serverName, endpoint);
    activeRequests.inc();
    perEndpointRequests.mark();
    simulation.metricsReporter().report();
    for (ServerHandler handler : handlers) {
        long beforeNanos = simulation.clock().read();
        Optional<ListenableFuture<Response>> maybeResp = handler.maybeExecute(this, endpoint, request);
        if (!maybeResp.isPresent()) {
            continue;
        }
        ListenableFuture<Response> resp = maybeResp.get();
        DialogueFutures.addDirectCallback(resp, DialogueFutures.onSuccess(_ignored -> globalResponses.inc()));
        resp.addListener(() -> {
            activeRequests.dec();
            globalServerTimeNanos.inc(simulation.clock().read() - beforeNanos);
        }, DialogueFutures.safeDirectExecutor());
        if (log.isDebugEnabled()) {
            DialogueFutures.addDirectCallback(resp, DialogueFutures.onSuccess(result -> {
                log.debug("time={} server={} status={} id={}", Duration.ofNanos(simulation.clock().read()), serverName, result.code(), request != null ? request.headerParams().get(Benchmark.REQUEST_ID_HEADER) : null);
            }));
        }
        return resp;
    }
    log.error("No handler available for request {}", request);
    activeRequests.dec();
    return Futures.immediateFailedFuture(new SafeRuntimeException("No handler"));
}
Also used : TestResponse(com.palantir.dialogue.TestResponse) Response(com.palantir.dialogue.Response) Logger(org.slf4j.Logger) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ListMultimap(com.google.common.collect.ListMultimap) SafeRuntimeException(com.palantir.logsafe.exceptions.SafeRuntimeException) Predicate(java.util.function.Predicate) LoggerFactory(org.slf4j.LoggerFactory) Channel(com.palantir.dialogue.Channel) Function(java.util.function.Function) TimeUnit(java.util.concurrent.TimeUnit) Meter(com.codahale.metrics.Meter) TestResponse(com.palantir.dialogue.TestResponse) Futures(com.google.common.util.concurrent.Futures) DialogueFutures(com.palantir.dialogue.futures.DialogueFutures) ImmutableList(com.google.common.collect.ImmutableList) Duration(java.time.Duration) Counter(com.codahale.metrics.Counter) Endpoint(com.palantir.dialogue.Endpoint) Optional(java.util.Optional) ResponseAttachments(com.palantir.dialogue.ResponseAttachments) Request(com.palantir.dialogue.Request) Response(com.palantir.dialogue.Response) Preconditions(com.palantir.logsafe.Preconditions) InputStream(java.io.InputStream) SafeRuntimeException(com.palantir.logsafe.exceptions.SafeRuntimeException) Meter(com.codahale.metrics.Meter) ListenableFuture(com.google.common.util.concurrent.ListenableFuture)

Aggregations

Request (com.palantir.dialogue.Request)40 Test (org.junit.jupiter.api.Test)21 Channel (com.palantir.dialogue.Channel)14 Endpoint (com.palantir.dialogue.Endpoint)14 Response (com.palantir.dialogue.Response)13 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)9 TestResponse (com.palantir.dialogue.TestResponse)8 Test (org.junit.Test)8 TestEndpoint (com.palantir.dialogue.TestEndpoint)6 Optional (java.util.Optional)6 Futures (com.google.common.util.concurrent.Futures)5 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)5 RequestBody (com.palantir.dialogue.RequestBody)5 UrlBuilder (com.palantir.dialogue.UrlBuilder)5 OutputStream (java.io.OutputStream)5 Duration (java.time.Duration)5 ExecutionException (java.util.concurrent.ExecutionException)5 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)5 EnumSource (org.junit.jupiter.params.provider.EnumSource)5 ImmutableList (com.google.common.collect.ImmutableList)4