Search in sources :

Example 61 with HttpClient

use of io.vertx.core.http.HttpClient in project incubator-servicecomb-java-chassis by apache.

the class TestVertxHttpMethod method testCreateRequest.

@Test
public void testCreateRequest() {
    HttpClient client = mock(HttpClient.class);
    Invocation invocation = mock(Invocation.class);
    OperationMeta operationMeta = mock(OperationMeta.class);
    Endpoint endpoint = mock(Endpoint.class);
    URIEndpointObject address = mock(URIEndpointObject.class);
    when(invocation.getEndpoint()).thenReturn(endpoint);
    when(endpoint.getAddress()).thenReturn(address);
    when(address.isSslEnabled()).thenReturn(false);
    when(invocation.getOperationMeta()).thenReturn(operationMeta);
    RestOperationMeta swaggerRestOperation = mock(RestOperationMeta.class);
    when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(swaggerRestOperation);
    IpPort ipPort = mock(IpPort.class);
    when(ipPort.getPort()).thenReturn(10);
    when(ipPort.getHostOrIp()).thenReturn("ever");
    AsyncResponse asyncResp = mock(AsyncResponse.class);
    List<HttpMethod> methods = new ArrayList<>(Arrays.asList(HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PATCH));
    for (HttpMethod method : methods) {
        when(swaggerRestOperation.getHttpMethod()).thenReturn(method.toString());
        HttpClientRequest obj = VertxHttpMethod.INSTANCE.createRequest(client, invocation, ipPort, "good", asyncResp);
        Assert.assertNull(obj);
    }
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) Invocation(org.apache.servicecomb.core.Invocation) Endpoint(org.apache.servicecomb.core.Endpoint) RestOperationMeta(org.apache.servicecomb.common.rest.definition.RestOperationMeta) HttpClient(io.vertx.core.http.HttpClient) ArrayList(java.util.ArrayList) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) OperationMeta(org.apache.servicecomb.core.definition.OperationMeta) RestOperationMeta(org.apache.servicecomb.common.rest.definition.RestOperationMeta) URIEndpointObject(org.apache.servicecomb.foundation.common.net.URIEndpointObject) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) HttpMethod(io.vertx.core.http.HttpMethod) Test(org.junit.Test)

Example 62 with HttpClient

use of io.vertx.core.http.HttpClient in project incubator-servicecomb-java-chassis by apache.

the class TestConfigCenterClient method testConfigRefreshException.

@SuppressWarnings("unchecked")
@Test
public void testConfigRefreshException() {
    ConfigCenterConfigurationSourceImpl impl = new ConfigCenterConfigurationSourceImpl();
    Map<String, String> map = new HashMap<>();
    EventManager.register(new Object() {

        @Subscribe
        public void testMsg(Object event) {
            if (event instanceof ConnFailEvent) {
                map.put("result", "Fail event trigger");
            }
            if (event instanceof ConnSuccEvent) {
                map.put("result", "Succ event trigger");
            }
        }
    });
    impl.init(ConfigUtil.createLocalConfig());
    UpdateHandler updateHandler = impl.new UpdateHandler();
    HttpClientRequest request = Mockito.mock(HttpClientRequest.class);
    Mockito.when(request.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap());
    Buffer rsp = Mockito.mock(Buffer.class);
    Mockito.when(rsp.toString()).thenReturn("{\"application\":{\"2\":\"2\",\"aa\":\"1\"},\"vmalledge\":{\"aa\":\"3\"}}");
    HttpClientResponse event = Mockito.mock(HttpClientResponse.class);
    Mockito.when(event.bodyHandler(Mockito.any(Handler.class))).then(invocation -> {
        Handler<Buffer> handler = invocation.getArgumentAt(0, Handler.class);
        handler.handle(rsp);
        return null;
    });
    Mockito.when(event.statusCode()).thenReturn(400);
    Buffer buf = Mockito.mock(Buffer.class);
    Mockito.when(buf.toJsonObject()).thenReturn(new JsonObject("{\"action\":\"UPDATE\",\"key\":\"vmalledge\",\"value\":\"{\\\"aa\\\":\\\"3\\\"}\"}"));
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    Mockito.when(httpClient.get(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Handler.class))).then(invocation -> {
        Handler<HttpClientResponse> handler = invocation.getArgumentAt(3, Handler.class);
        handler.handle(event);
        return request;
    });
    new MockUp<HttpClientWithContext>() {

        @Mock
        public void runOnContext(RunHandler handler) {
            handler.run(httpClient);
        }
    };
    ConfigCenterClient cc = new ConfigCenterClient(updateHandler);
    ParseConfigUtils parseConfigUtils = new ParseConfigUtils(updateHandler);
    MemberDiscovery memberdis = new MemberDiscovery(Arrays.asList("http://configcentertest:30103"));
    ConfigRefresh refresh = cc.new ConfigRefresh(parseConfigUtils, memberdis);
    refresh.run();
    Assert.assertEquals("Fail event trigger", map.get("result"));
    Mockito.when(event.statusCode()).thenReturn(200);
    refresh.run();
    Assert.assertEquals("Succ event trigger", map.get("result"));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) UpdateHandler(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl.UpdateHandler) ConfigCenterConfigurationSourceImpl(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl) HashMap(java.util.HashMap) RunHandler(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext.RunHandler) UpdateHandler(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl.UpdateHandler) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) MockUp(mockit.MockUp) Subscribe(com.google.common.eventbus.Subscribe) RunHandler(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext.RunHandler) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ConfigRefresh(org.apache.servicecomb.config.client.ConfigCenterClient.ConfigRefresh) HttpClientResponse(io.vertx.core.http.HttpClientResponse) HttpClient(io.vertx.core.http.HttpClient) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 63 with HttpClient

use of io.vertx.core.http.HttpClient in project incubator-servicecomb-java-chassis by apache.

the class TestConfigCenterClient method testConnectServer.

@SuppressWarnings("unchecked")
@Test
public void testConnectServer() {
    HttpClientRequest request = Mockito.mock(HttpClientRequest.class);
    Mockito.when(request.method()).thenReturn(HttpMethod.GET);
    Mockito.when(request.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap());
    Buffer rsp = Mockito.mock(Buffer.class);
    Mockito.when(rsp.toJsonObject()).thenReturn(new JsonObject("{\"instances\":[{\"status\":\"UP\",\"endpoints\":[\"rest:0.0.0.0:30103\"],\"hostName\":\"125292-0.0.0.0\",\"serviceName\":\"configServer\",\"https\":false}]}"));
    HttpClientResponse event = Mockito.mock(HttpClientResponse.class);
    Mockito.when(event.bodyHandler(Mockito.any(Handler.class))).then(invocation -> {
        Handler<Buffer> handler = invocation.getArgumentAt(0, Handler.class);
        handler.handle(rsp);
        return null;
    });
    Mockito.when(event.statusCode()).thenReturn(200);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    Mockito.when(httpClient.get(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Handler.class))).then(invocation -> {
        Handler<HttpClientResponse> handler = invocation.getArgumentAt(3, Handler.class);
        handler.handle(event);
        return request;
    });
    new MockUp<HttpClientWithContext>() {

        @Mock
        public void runOnContext(RunHandler handler) {
            handler.run(httpClient);
        }
    };
    new MockUp<MemberDiscovery>() {

        @Mock
        public void refreshMembers(JsonObject members) {
            Assert.assertTrue(members.size() == 1);
        }
    };
    UpdateHandler updateHandler = new ConfigCenterConfigurationSourceImpl().new UpdateHandler();
    ConfigCenterClient cc = new ConfigCenterClient(updateHandler);
    cc.connectServer();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) UpdateHandler(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl.UpdateHandler) ConfigCenterConfigurationSourceImpl(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl) JsonObject(io.vertx.core.json.JsonObject) RunHandler(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext.RunHandler) UpdateHandler(org.apache.servicecomb.config.archaius.sources.ConfigCenterConfigurationSourceImpl.UpdateHandler) Handler(io.vertx.core.Handler) MockUp(mockit.MockUp) RunHandler(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext.RunHandler) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) HttpClient(io.vertx.core.http.HttpClient) Test(org.junit.Test)

Example 64 with HttpClient

use of io.vertx.core.http.HttpClient in project raml-module-builder by folio-org.

the class ClientGenerator method generateClassMeta.

public void generateClassMeta(String className, Object globalPath) {
    String mapType = System.getProperty("json.type");
    if (mapType != null) {
        if (mapType.equals("mongo")) {
            mappingType = "mongo";
        }
    }
    this.globalPath = "GLOBAL_PATH";
    /* Adding packages here */
    JPackage jp = jCodeModel._package(RTFConsts.CLIENT_GEN_PACKAGE);
    try {
        /* Giving Class Name to Generate */
        this.className = className.substring(RTFConsts.INTERFACE_PACKAGE.length() + 1, className.indexOf("Resource"));
        jc = jp._class(this.className + CLIENT_CLASS_SUFFIX);
        JDocComment com = jc.javadoc();
        com.add("Auto-generated code - based on class " + className);
        /* class variable to root url path to this interface */
        JFieldVar globalPathVar = jc.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, String.class, "GLOBAL_PATH");
        globalPathVar.init(JExpr.lit("/" + (String) globalPath));
        /* class variable tenant id */
        tenantId = jc.field(JMod.PRIVATE, String.class, "tenantId");
        token = jc.field(JMod.PRIVATE, String.class, "token");
        /* class variable to http options */
        JFieldVar options = jc.field(JMod.PRIVATE, HttpClientOptions.class, "options");
        /* class variable to http client */
        httpClient = jc.field(JMod.PRIVATE, HttpClient.class, "httpClient");
        /* constructor, init the httpClient - allow to pass keep alive option */
        JMethod consructor = constructor(JMod.PUBLIC);
        JVar host = consructor.param(String.class, "host");
        JVar port = consructor.param(int.class, "port");
        JVar param = consructor.param(String.class, "tenantId");
        JVar token = consructor.param(String.class, "token");
        JVar keepAlive = consructor.param(boolean.class, "keepAlive");
        JVar connTO = consructor.param(int.class, "connTO");
        JVar idleTO = consructor.param(int.class, "idleTO");
        /* populate constructor */
        JBlock conBody = consructor.body();
        conBody.assign(JExpr._this().ref(tenantId), param);
        conBody.assign(JExpr._this().ref(token), token);
        conBody.assign(options, JExpr._new(jCodeModel.ref(HttpClientOptions.class)));
        conBody.invoke(options, "setLogActivity").arg(JExpr.TRUE);
        conBody.invoke(options, "setKeepAlive").arg(keepAlive);
        conBody.invoke(options, "setDefaultHost").arg(host);
        conBody.invoke(options, "setDefaultPort").arg(port);
        conBody.invoke(options, "setConnectTimeout").arg(connTO);
        conBody.invoke(options, "setIdleTimeout").arg(idleTO);
        JExpression vertx = jCodeModel.ref("org.folio.rest.tools.utils.VertxUtils").staticInvoke("getVertxFromContextOrNew");
        conBody.assign(httpClient, vertx.invoke("createHttpClient").arg(options));
        /* constructor, init the httpClient */
        JMethod consructor2 = constructor(JMod.PUBLIC);
        JVar hostVar = consructor2.param(String.class, "host");
        JVar portVar = consructor2.param(int.class, "port");
        JVar tenantIdVar = consructor2.param(String.class, "tenantId");
        JVar tokenVar = consructor2.param(String.class, "token");
        JBlock conBody2 = consructor2.body();
        conBody2.invoke("this").arg(hostVar).arg(portVar).arg(tenantIdVar).arg(tokenVar).arg(JExpr.TRUE).arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
        JMethod consructor1 = constructor(JMod.PUBLIC);
        JVar hostVar1 = consructor1.param(String.class, "host");
        JVar portVar1 = consructor1.param(int.class, "port");
        JVar tenantIdVar1 = consructor1.param(String.class, "tenantId");
        JVar tokenVar1 = consructor1.param(String.class, "token");
        JVar keepAlive1 = consructor1.param(boolean.class, "keepAlive");
        JBlock conBody1 = consructor1.body();
        conBody1.invoke("this").arg(hostVar1).arg(portVar1).arg(tenantIdVar1).arg(tokenVar1).arg(keepAlive1).arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
        /* constructor, init the httpClient */
        JMethod consructor3 = constructor(JMod.PUBLIC);
        JBlock conBody3 = consructor3.body();
        conBody3.invoke("this").arg("localhost").arg(JExpr.lit(8081)).arg("folio_demo").arg("folio_demo").arg(JExpr.FALSE).arg(JExpr.lit(2000)).arg(JExpr.lit(5000));
        consructor3.javadoc().add("Convenience constructor for tests ONLY!<br>Connect to localhost on 8081 as folio_demo tenant.");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}
Also used : JFieldVar(com.sun.codemodel.JFieldVar) HttpClient(io.vertx.core.http.HttpClient) JPackage(com.sun.codemodel.JPackage) JBlock(com.sun.codemodel.JBlock) JExpression(com.sun.codemodel.JExpression) JMethod(com.sun.codemodel.JMethod) JDocComment(com.sun.codemodel.JDocComment) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JVar(com.sun.codemodel.JVar)

Example 65 with HttpClient

use of io.vertx.core.http.HttpClient in project vertx-micrometer-metrics by vert-x3.

the class VertxHttpClientServerMetricsTest method runClientRequests.

private void runClientRequests(TestContext ctx, boolean ws) throws InterruptedException {
    Async clientsFinished = ctx.async(concurrentClients);
    for (int i = 0; i < concurrentClients; i++) {
        ForkJoinPool.commonPool().execute(() -> {
            HttpClient httpClient = vertx.createHttpClient();
            createdClients.add(httpClient);
            httpRequest(httpClient, ctx);
            if (ws) {
                wsRequest(httpClient, ctx);
            }
            clientsFinished.countDown();
        });
    }
    clientsFinished.awaitSuccess();
}
Also used : Async(io.vertx.ext.unit.Async) HttpClient(io.vertx.core.http.HttpClient)

Aggregations

HttpClient (io.vertx.core.http.HttpClient)77 Test (org.junit.Test)47 HttpClientRequest (io.vertx.core.http.HttpClientRequest)36 HttpClientOptions (io.vertx.core.http.HttpClientOptions)25 Vertx (io.vertx.core.Vertx)22 HttpMethod (io.vertx.core.http.HttpMethod)22 JsonObject (io.vertx.core.json.JsonObject)22 Handler (io.vertx.core.Handler)18 Buffer (io.vertx.core.buffer.Buffer)18 HttpClientResponse (io.vertx.core.http.HttpClientResponse)16 TimeUnit (java.util.concurrent.TimeUnit)16 HttpServer (io.vertx.core.http.HttpServer)15 Async (io.vertx.ext.unit.Async)15 Before (org.junit.Before)15 File (java.io.File)14 CountDownLatch (java.util.concurrent.CountDownLatch)14 URL (java.net.URL)12 HttpServerOptions (io.vertx.core.http.HttpServerOptions)11 IOException (java.io.IOException)10 List (java.util.List)10