Search in sources :

Example 1 with HttpClientResponse

use of io.vertx.core.http.HttpClientResponse in project vert.x by eclipse.

the class HttpClientRequestImpl method handleNextRequest.

private void handleNextRequest(HttpClientResponse resp, HttpClientRequestImpl next, long timeoutMs) {
    next.handler(respHandler);
    next.exceptionHandler(exceptionHandler());
    exceptionHandler(null);
    next.endHandler(endHandler);
    next.pushHandler = pushHandler;
    next.followRedirects = followRedirects - 1;
    next.written = written;
    if (next.hostHeader == null) {
        next.hostHeader = hostHeader;
    }
    if (headers != null && next.headers == null) {
        next.headers().addAll(headers);
    }
    ByteBuf body;
    switch(next.method) {
        case GET:
            body = null;
            break;
        case OTHER:
            next.rawMethod = rawMethod;
            body = null;
            break;
        default:
            if (cachedChunks != null) {
                body = cachedChunks;
            } else {
                body = null;
            }
            break;
    }
    cachedChunks = null;
    Future<Void> fut = Future.future();
    fut.setHandler(ar -> {
        if (ar.succeeded()) {
            if (timeoutMs > 0) {
                next.setTimeout(timeoutMs);
            }
            next.write(body, true);
        } else {
            next.handleException(ar.cause());
        }
    });
    if (exceptionOccurred != null) {
        fut.fail(exceptionOccurred);
    } else if (completed) {
        fut.complete();
    } else {
        exceptionHandler(err -> {
            if (!fut.isComplete()) {
                fut.fail(err);
            }
        });
        completionHandler = v -> {
            if (!fut.isComplete()) {
                fut.complete();
            }
        };
    }
}
Also used : VertxInternal(io.vertx.core.impl.VertxInternal) MultiMap(io.vertx.core.MultiMap) HttpHeaders(io.vertx.core.http.HttpHeaders) Future(io.vertx.core.Future) Unpooled(io.netty.buffer.Unpooled) Nullable(io.vertx.codegen.annotations.Nullable) Objects(java.util.Objects) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) List(java.util.List) ByteBuf(io.netty.buffer.ByteBuf) Buffer(io.vertx.core.buffer.Buffer) HttpFrame(io.vertx.core.http.HttpFrame) HttpVersion(io.vertx.core.http.HttpVersion) HttpMethod(io.vertx.core.http.HttpMethod) HttpConnection(io.vertx.core.http.HttpConnection) Handler(io.vertx.core.Handler) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) NetSocket(io.vertx.core.net.NetSocket) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf)

Example 2 with HttpClientResponse

use of io.vertx.core.http.HttpClientResponse in project java-chassis by ServiceComb.

the class GrpcTransport method send.

@Override
public void send(Invocation invocation, AsyncResponse asyncResp) throws Exception {
    HttpClientWithContext httpClientWithContext = clientMgr.findThreadBindClientPool();
    OperationMeta operationMeta = invocation.getOperationMeta();
    OperationProtobuf operationProtobuf = ProtobufManager.getOrCreateOperation(operationMeta);
    String cseContext = JsonUtils.writeValueAsString(invocation.getContext());
    // 在verticle之外的线程调用
    IpPort ipPort = (IpPort) invocation.getEndpoint().getAddress();
    Buffer requestBuf = GrpcCodec.encodeRequest(invocation, operationProtobuf);
    String url = "/" + invocation.getSchemaId() + "/" + operationMeta.getOperationId();
    Handler<HttpClientResponse> responseHandler = httpResponse -> {
        httpResponse.bodyHandler(responseBuf -> {
            invocation.getResponseExecutor().execute(() -> {
                try {
                    Response response = GrpcCodec.decodeResponse(invocation, operationProtobuf, httpResponse, responseBuf);
                    ResponseMeta responseMeta = operationMeta.findResponseMeta(response.getStatusCode());
                    for (String headerName : responseMeta.getHeaders().keySet()) {
                        for (String value : httpResponse.headers().getAll(headerName)) {
                            response.getHeaders().addHeader(headerName, value);
                        }
                    }
                    asyncResp.complete(response);
                } catch (Exception e) {
                    asyncResp.fail(invocation.getInvocationType(), e);
                }
            });
        });
    };
    // 从业务线程转移到网络线程中去发送
    httpClientWithContext.runOnContext(httpClient -> {
        HttpClientRequest httpClientRequest = httpClient.post(ipPort.getPort(), ipPort.getHostOrIp(), url, responseHandler);
        httpClientRequest.exceptionHandler(e -> {
            asyncResp.fail(invocation.getInvocationType(), e);
        });
        httpClientRequest.setTimeout(AbstractTransport.getRequestTimeout());
        httpClientRequest.putHeader(HEADER_CONTENT_TYPE, "application/grpc").putHeader(HEADER_TE, "trailers").putHeader(HEADER_USER_AGENT, "cse-client/1.0.0").putHeader(Const.CSE_CONTEXT, cseContext).putHeader(Const.DEST_MICROSERVICE, invocation.getMicroserviceName()).end(requestBuf);
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) JsonUtils(io.servicecomb.foundation.common.utils.JsonUtils) OperationMeta(io.servicecomb.core.definition.OperationMeta) OperationProtobuf(io.servicecomb.codec.protobuf.definition.OperationProtobuf) IpPort(io.servicecomb.foundation.common.net.IpPort) ResponseMeta(io.servicecomb.swagger.invocation.response.ResponseMeta) ProtobufManager(io.servicecomb.codec.protobuf.definition.ProtobufManager) JksOptions(io.vertx.core.net.JksOptions) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) AsyncResponse(io.servicecomb.core.AsyncResponse) Const(io.servicecomb.core.Const) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Component(org.springframework.stereotype.Component) VertxUtils(io.servicecomb.foundation.vertx.VertxUtils) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) HttpVersion(io.vertx.core.http.HttpVersion) AbstractTransport(io.servicecomb.core.transport.AbstractTransport) Response(io.servicecomb.core.Response) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Handler(io.vertx.core.Handler) ClientPoolManager(io.servicecomb.foundation.vertx.client.ClientPoolManager) Invocation(io.servicecomb.core.Invocation) IpPort(io.servicecomb.foundation.common.net.IpPort) AsyncResponse(io.servicecomb.core.AsyncResponse) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Response(io.servicecomb.core.Response) HttpClientRequest(io.vertx.core.http.HttpClientRequest) OperationProtobuf(io.servicecomb.codec.protobuf.definition.OperationProtobuf) ResponseMeta(io.servicecomb.swagger.invocation.response.ResponseMeta) HttpClientResponse(io.vertx.core.http.HttpClientResponse) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) OperationMeta(io.servicecomb.core.definition.OperationMeta)

Example 3 with HttpClientResponse

use of io.vertx.core.http.HttpClientResponse in project java-chassis by ServiceComb.

the class TestGrpcCodec method testDecodeResponse.

@Test
public void testDecodeResponse() {
    boolean status = false;
    try {
        RoutingContext routingContext = Mockito.mock(RoutingContext.class);
        OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
        OperationProtobuf operationProtobuf = Mockito.mock(OperationProtobuf.class);
        WrapSchema schema = ProtobufSchemaUtils.getOrCreateSchema(int.class);
        Mockito.when(operationProtobuf.getRequestSchema()).thenReturn(schema);
        Mockito.when(operationMeta.getExtData("protobuf")).thenReturn(operationProtobuf);
        Buffer bodyBuffer = Mockito.mock(Buffer.class);
        Mockito.when(routingContext.getBody()).thenReturn(bodyBuffer);
        HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
        Mockito.when(routingContext.request()).thenReturn(request);
        Mockito.when(request.getHeader(Const.CSE_CONTEXT)).thenReturn("{\"name\":\"test\"}");
        Invocation invocation = Mockito.mock(Invocation.class);
        Mockito.when(operationProtobuf.getResponseSchema()).thenReturn(Mockito.mock(WrapSchema.class));
        HttpClientResponse httpResponse = Mockito.mock(HttpClientResponse.class);
        Buffer buffer = Mockito.mock(Buffer.class);
        GrpcCodec.decodeResponse(invocation, operationProtobuf, httpResponse, buffer);
    } catch (Exception e) {
        status = true;
    }
    Assert.assertFalse(status);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) RoutingContext(io.vertx.ext.web.RoutingContext) Invocation(io.servicecomb.core.Invocation) OperationProtobuf(io.servicecomb.codec.protobuf.definition.OperationProtobuf) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) OperationMeta(io.servicecomb.core.definition.OperationMeta) WrapSchema(io.servicecomb.codec.protobuf.utils.WrapSchema) Test(org.junit.Test)

Example 4 with HttpClientResponse

use of io.vertx.core.http.HttpClientResponse in project java-chassis by ServiceComb.

the class ServiceRegistryClientImpl method unregisterMicroserviceInstance.

@Override
public boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId) {
    Holder<HttpClientResponse> holder = new Holder<>();
    IpPort ipPort = IpPortManager.INSTANCE.get();
    StringBuilder url = new StringBuilder(Const.MS_API_PATH);
    url.append(Const.MICROSERVICE_PATH).append("/").append(microserviceId).append(Const.INSTANCES_PATH).append("/").append(microserviceInstanceId);
    CountDownLatch countDownLatch = new CountDownLatch(1);
    RestUtils.delete(ipPort, url.toString(), new RequestParam(), syncHandler(countDownLatch, HttpClientResponse.class, holder));
    try {
        countDownLatch.await();
        if (holder.value != null) {
            if (holder.value.statusCode() == Status.OK.getStatusCode()) {
                return true;
            }
            LOGGER.warn(holder.value.statusMessage());
        }
    } catch (Exception e) {
        LOGGER.error("unregister microservice instance {}/{} failed", microserviceId, microserviceInstanceId, e);
    }
    return false;
}
Also used : Holder(javax.xml.ws.Holder) HttpClientResponse(io.vertx.core.http.HttpClientResponse) IpPort(io.servicecomb.foundation.common.net.IpPort) CountDownLatch(java.util.concurrent.CountDownLatch) ClientException(io.servicecomb.serviceregistry.client.ClientException)

Example 5 with HttpClientResponse

use of io.vertx.core.http.HttpClientResponse in project java-chassis by ServiceComb.

the class ServiceRegistryClientImpl method updateMicroserviceProperties.

@Override
public boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties) {
    Holder<HttpClientResponse> holder = new Holder<>();
    IpPort ipPort = IpPortManager.INSTANCE.get();
    StringBuilder url = new StringBuilder(Const.MS_API_PATH);
    url.append(Const.MICROSERVICE_PATH).append("/").append(microserviceId).append(Const.PROPERTIES_PATH);
    try {
        UpdatePropertiesRequest request = new UpdatePropertiesRequest();
        request.setProperties(serviceProperties);
        byte[] body = JsonUtils.writeValueAsBytes(request);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("update properties of microservice: {}", new String(body, Charset.defaultCharset()));
        }
        CountDownLatch countDownLatch = new CountDownLatch(1);
        RestUtils.put(ipPort, url.toString(), new RequestParam().setBody(body), syncHandler(countDownLatch, HttpClientResponse.class, holder));
        countDownLatch.await();
        if (holder.value != null) {
            if (holder.value.statusCode() == Status.OK.getStatusCode()) {
                return true;
            }
            LOGGER.warn(holder.value.statusMessage());
        }
    } catch (Exception e) {
        LOGGER.error("update properties of microservice {} failed", microserviceId, e);
    }
    return false;
}
Also used : Holder(javax.xml.ws.Holder) HttpClientResponse(io.vertx.core.http.HttpClientResponse) IpPort(io.servicecomb.foundation.common.net.IpPort) UpdatePropertiesRequest(io.servicecomb.serviceregistry.api.request.UpdatePropertiesRequest) CountDownLatch(java.util.concurrent.CountDownLatch) ClientException(io.servicecomb.serviceregistry.client.ClientException)

Aggregations

HttpClientResponse (io.vertx.core.http.HttpClientResponse)14 IpPort (io.servicecomb.foundation.common.net.IpPort)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 Invocation (io.servicecomb.core.Invocation)5 OperationMeta (io.servicecomb.core.definition.OperationMeta)5 ClientException (io.servicecomb.serviceregistry.client.ClientException)5 Buffer (io.vertx.core.buffer.Buffer)5 Holder (javax.xml.ws.Holder)5 Handler (io.vertx.core.Handler)4 HttpClientRequest (io.vertx.core.http.HttpClientRequest)4 Test (org.junit.Test)4 OperationProtobuf (io.servicecomb.codec.protobuf.definition.OperationProtobuf)3 ProduceProcessor (io.servicecomb.common.rest.codec.produce.ProduceProcessor)3 AsyncResponse (io.servicecomb.core.AsyncResponse)3 Response (io.servicecomb.core.Response)3 WrapSchema (io.servicecomb.codec.protobuf.utils.WrapSchema)2 RestOperationMeta (io.servicecomb.common.rest.definition.RestOperationMeta)2 URLPathBuilder (io.servicecomb.common.rest.definition.path.URLPathBuilder)2 Endpoint (io.servicecomb.core.Endpoint)2 UpdatePropertiesRequest (io.servicecomb.serviceregistry.api.request.UpdatePropertiesRequest)2