Search in sources :

Example 61 with HttpRequest

use of io.cdap.common.http.HttpRequest in project cdap by caskdata.

the class TestFrameworkTestRun method testAppWithServices.

@Category(SlowTests.class)
@Test
public void testAppWithServices() throws Exception {
    ApplicationManager applicationManager = deployApplication(AppWithServices.class);
    LOG.info("Deployed.");
    ServiceManager serviceManager = applicationManager.getServiceManager(AppWithServices.SERVICE_NAME).start();
    serviceManager.waitForRun(ProgramRunStatus.RUNNING, 10, TimeUnit.SECONDS);
    LOG.info("Service Started");
    URL serviceURL = serviceManager.getServiceURL(15, TimeUnit.SECONDS);
    Assert.assertNotNull(serviceURL);
    // Call the ping endpoint
    URL url = new URL(serviceURL, "ping2");
    HttpRequest request = HttpRequest.get(url).build();
    HttpResponse response = executeHttp(request);
    Assert.assertEquals(200, response.getResponseCode());
    // Call the failure endpoint
    url = new URL(serviceURL, "failure");
    request = HttpRequest.get(url).build();
    response = executeHttp(request);
    Assert.assertEquals(500, response.getResponseCode());
    Assert.assertTrue(response.getResponseBodyAsString().contains("Exception"));
    // Call the verify ClassLoader endpoint
    url = new URL(serviceURL, "verifyClassLoader");
    request = HttpRequest.get(url).build();
    response = executeHttp(request);
    Assert.assertEquals(200, response.getResponseCode());
    RuntimeMetrics serviceMetrics = serviceManager.getMetrics();
    serviceMetrics.waitForinput(3, 5, TimeUnit.SECONDS);
    Assert.assertEquals(3, serviceMetrics.getInput());
    Assert.assertEquals(2, serviceMetrics.getProcessed());
    Assert.assertEquals(1, serviceMetrics.getException());
    // in the AppWithServices the handlerName is same as the serviceName - "ServerService" handler
    RuntimeMetrics handlerMetrics = getMetricsManager().getServiceHandlerMetrics(NamespaceId.DEFAULT.getNamespace(), AppWithServices.APP_NAME, AppWithServices.SERVICE_NAME, AppWithServices.SERVICE_NAME);
    handlerMetrics.waitForinput(3, 5, TimeUnit.SECONDS);
    Assert.assertEquals(3, handlerMetrics.getInput());
    Assert.assertEquals(2, handlerMetrics.getProcessed());
    Assert.assertEquals(1, handlerMetrics.getException());
    // we can verify metrics, by adding getServiceMetrics in MetricsManager and then disabling the system scope test in
    // TestMetricsCollectionService
    LOG.info("DatasetUpdateService Started");
    Map<String, String> args = ImmutableMap.of(AppWithServices.WRITE_VALUE_RUN_KEY, AppWithServices.DATASET_TEST_VALUE, AppWithServices.WRITE_VALUE_STOP_KEY, AppWithServices.DATASET_TEST_VALUE_STOP);
    ServiceManager datasetWorkerServiceManager = applicationManager.getServiceManager(AppWithServices.DATASET_WORKER_SERVICE_NAME).start(args);
    WorkerManager datasetWorker = applicationManager.getWorkerManager(AppWithServices.DATASET_UPDATE_WORKER).start(args);
    datasetWorker.waitForRun(ProgramRunStatus.RUNNING, 10, TimeUnit.SECONDS);
    datasetWorkerServiceManager.waitForRun(ProgramRunStatus.RUNNING, 10, TimeUnit.SECONDS);
    ServiceManager noopManager = applicationManager.getServiceManager("NoOpService").start();
    noopManager.waitForRun(ProgramRunStatus.RUNNING, 10, TimeUnit.SECONDS);
    // We don't know when the datasetWorker run() method executed, hence need to retry on the service call
    // until it can get a value from a dataset, which was written out by the datasetWorker.
    AtomicInteger called = new AtomicInteger(0);
    AtomicInteger failed = new AtomicInteger(0);
    Tasks.waitFor(AppWithServices.DATASET_TEST_VALUE, new Callable<String>() {

        @Override
        public String call() throws Exception {
            URL url = noopManager.getServiceURL();
            String path = "ping/" + AppWithServices.DATASET_TEST_KEY;
            try {
                called.incrementAndGet();
                return new Gson().fromJson(callServiceGet(url, path), String.class);
            } catch (IOException e) {
                failed.incrementAndGet();
                LOG.debug("Exception when reading from service {}/{}", url, path, e);
            }
            return null;
        }
    }, 30, TimeUnit.SECONDS);
    // Validates the metrics emitted by the service call.
    handlerMetrics = getMetricsManager().getServiceHandlerMetrics(NamespaceId.DEFAULT.getNamespace(), AppWithServices.APP_NAME, "NoOpService", "NoOpHandler");
    handlerMetrics.waitForinput(called.get(), 5, TimeUnit.SECONDS);
    handlerMetrics.waitForProcessed(1, 5, TimeUnit.SECONDS);
    handlerMetrics.waitForException(failed.get(), 5, TimeUnit.SECONDS);
    // Test that a service can discover another service
    String path = String.format("discover/%s/%s", AppWithServices.APP_NAME, AppWithServices.DATASET_WORKER_SERVICE_NAME);
    url = new URL(serviceURL, path);
    request = HttpRequest.get(url).build();
    response = executeHttp(request);
    Assert.assertEquals(200, response.getResponseCode());
    datasetWorker.stop();
    datasetWorker.waitForStopped(10, TimeUnit.SECONDS);
    datasetWorkerServiceManager.stop();
    datasetWorkerServiceManager.waitForStopped(10, TimeUnit.SECONDS);
    LOG.info("DatasetUpdateService Stopped");
    serviceManager.stop();
    serviceManager.waitForStopped(10, TimeUnit.SECONDS);
    LOG.info("ServerService Stopped");
    // Since all worker are stopped, we can just hit the service to read the dataset. No retry needed.
    String result = callServiceGet(noopManager.getServiceURL(), "ping/" + AppWithServices.DATASET_TEST_KEY_STOP);
    String decodedResult = new Gson().fromJson(result, String.class);
    Assert.assertEquals(AppWithServices.DATASET_TEST_VALUE_STOP, decodedResult);
    result = callServiceGet(noopManager.getServiceURL(), "ping/" + AppWithServices.DATASET_TEST_KEY_STOP_2);
    decodedResult = new Gson().fromJson(result, String.class);
    Assert.assertEquals(AppWithServices.DATASET_TEST_VALUE_STOP_2, decodedResult);
}
Also used : HttpRequest(io.cdap.common.http.HttpRequest) ApplicationManager(io.cdap.cdap.test.ApplicationManager) RuntimeMetrics(io.cdap.cdap.api.metrics.RuntimeMetrics) HttpResponse(io.cdap.common.http.HttpResponse) Gson(com.google.gson.Gson) IOException(java.io.IOException) URL(java.net.URL) IOException(java.io.IOException) ConflictException(io.cdap.cdap.common.ConflictException) WorkerManager(io.cdap.cdap.test.WorkerManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServiceManager(io.cdap.cdap.test.ServiceManager) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Example 62 with HttpRequest

use of io.cdap.common.http.HttpRequest in project cdap by caskdata.

the class TestFrameworkTestRun method testTransactionHandlerService.

@Test
public void testTransactionHandlerService() throws Exception {
    ApplicationManager applicationManager = deployApplication(testSpace, AppWithServices.class);
    LOG.info("Deployed.");
    ServiceManager serviceManager = applicationManager.getServiceManager(AppWithServices.TRANSACTIONS_SERVICE_NAME).start();
    serviceManager.waitForRun(ProgramRunStatus.RUNNING, 10, TimeUnit.SECONDS);
    LOG.info("Service Started");
    final URL baseUrl = serviceManager.getServiceURL(15, TimeUnit.SECONDS);
    Assert.assertNotNull(baseUrl);
    // Make a request to write in a separate thread and wait for it to return.
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<Integer> requestFuture = executorService.submit(new Callable<Integer>() {

        @Override
        public Integer call() throws Exception {
            try {
                URL url = new URL(String.format("%s/write/%s/%s/%d", baseUrl, AppWithServices.DATASET_TEST_KEY, AppWithServices.DATASET_TEST_VALUE, 10000));
                HttpRequest request = HttpRequest.get(url).build();
                HttpResponse response = executeHttp(request);
                return response.getResponseCode();
            } catch (Exception e) {
                LOG.error("Request thread got exception.", e);
                throw Throwables.propagate(e);
            }
        }
    });
    // The dataset should not be written by the time this request is made, since the transaction to write
    // has not been committed yet.
    URL url = new URL(String.format("%s/read/%s", baseUrl, AppWithServices.DATASET_TEST_KEY));
    HttpRequest request = HttpRequest.get(url).build();
    HttpResponse response = executeHttp(request);
    Assert.assertEquals(204, response.getResponseCode());
    // Wait for the transaction to commit.
    Integer writeStatusCode = requestFuture.get();
    Assert.assertEquals(200, writeStatusCode.intValue());
    // Make the same request again. By now the transaction should've completed.
    request = HttpRequest.get(url).build();
    response = executeHttp(request);
    Assert.assertEquals(200, response.getResponseCode());
    Assert.assertEquals(AppWithServices.DATASET_TEST_VALUE, new Gson().fromJson(response.getResponseBodyAsString(), String.class));
    executorService.shutdown();
    serviceManager.stop();
    serviceManager.waitForStopped(10, TimeUnit.SECONDS);
    DataSetManager<KeyValueTable> dsManager = getDataset(testSpace.dataset(AppWithServices.TRANSACTIONS_DATASET_NAME));
    String value = Bytes.toString(dsManager.get().read(AppWithServices.DESTROY_KEY));
    Assert.assertEquals(AppWithServices.VALUE, value);
}
Also used : HttpRequest(io.cdap.common.http.HttpRequest) ApplicationManager(io.cdap.cdap.test.ApplicationManager) HttpResponse(io.cdap.common.http.HttpResponse) Gson(com.google.gson.Gson) URL(java.net.URL) IOException(java.io.IOException) ConflictException(io.cdap.cdap.common.ConflictException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServiceManager(io.cdap.cdap.test.ServiceManager) KeyValueTable(io.cdap.cdap.api.dataset.lib.KeyValueTable) ExecutorService(java.util.concurrent.ExecutorService) Test(org.junit.Test)

Example 63 with HttpRequest

use of io.cdap.common.http.HttpRequest in project cdap by caskdata.

the class DynamicPluginServiceTestRun method testDynamicPluginBodyProducer.

@Test
public void testDynamicPluginBodyProducer() throws Exception {
    // test that a plugin can be instantiated in the body producer chunk() and onFinish() methods
    // the good plugin should be found, so the response should be 'x'
    DynamicPluginServiceApp.PluginRequest requestBody = new DynamicPluginServiceApp.PluginRequest(ConstantFunction.NAME, Collections.singletonMap("value", "x"), ConstantFunction.NAME, Collections.singletonMap("value", "y"));
    URL producerUrl = baseURI.resolve("producer").toURL();
    HttpRequest request = HttpRequest.builder(HttpMethod.POST, producerUrl).withBody(GSON.toJson(requestBody)).build();
    HttpResponse response = executeHttp(request);
    Assert.assertEquals(200, response.getResponseCode());
    Assert.assertEquals("x", response.getResponseBodyAsString());
    URL onFinishUrl = baseURI.resolve("onFinishSuccessful").toURL();
    request = HttpRequest.builder(HttpMethod.GET, onFinishUrl).build();
    response = executeHttp(request);
    Assert.assertTrue(Boolean.valueOf(response.getResponseBodyAsString()));
}
Also used : HttpRequest(io.cdap.common.http.HttpRequest) HttpResponse(io.cdap.common.http.HttpResponse) URL(java.net.URL) Test(org.junit.Test)

Example 64 with HttpRequest

use of io.cdap.common.http.HttpRequest in project cdap by caskdata.

the class DynamicPluginServiceTestRun method testDynamicPluginContentConsumer.

@Test
public void testDynamicPluginContentConsumer() throws Exception {
    // test that a plugin can be instantiated in the content consumer finish method
    // the good plugin should be found, so the response should be 'x'
    DynamicPluginServiceApp.PluginRequest requestBody = new DynamicPluginServiceApp.PluginRequest(ConstantFunction.NAME, Collections.singletonMap("value", "x"), ConstantFunction.NAME, Collections.singletonMap("value", "y"));
    URL url = baseURI.resolve("consumer").toURL();
    HttpRequest request = HttpRequest.builder(HttpMethod.POST, url).withBody(GSON.toJson(requestBody)).build();
    HttpResponse response = executeHttp(request);
    Assert.assertEquals(200, response.getResponseCode());
    Assert.assertEquals("x", response.getResponseBodyAsString());
    // test that a plugin can be instantiated in the content consumer error method
    // the "good" plugin should not be found, so the response should be 'y'
    requestBody = new DynamicPluginServiceApp.PluginRequest("non-existent", Collections.singletonMap("value", "x"), ConstantFunction.NAME, Collections.singletonMap("value", "y"));
    request = HttpRequest.builder(HttpMethod.POST, url).withBody(GSON.toJson(requestBody)).build();
    response = executeHttp(request);
    Assert.assertEquals(400, response.getResponseCode());
    Assert.assertEquals("y", response.getResponseBodyAsString());
}
Also used : HttpRequest(io.cdap.common.http.HttpRequest) HttpResponse(io.cdap.common.http.HttpResponse) URL(java.net.URL) Test(org.junit.Test)

Example 65 with HttpRequest

use of io.cdap.common.http.HttpRequest in project cdap by caskdata.

the class DynamicPluginServiceTestRun method testServiceMacroEvaluator.

@Test
public void testServiceMacroEvaluator() throws Exception {
    // properties with macro
    Map<String, String> rawProperties = new HashMap<>();
    rawProperties.put("key1", "${macro1}");
    rawProperties.put("key2", "${macro2}");
    Map<String, String> macroProperties = new HashMap<>();
    macroProperties.put("macro1", "value1");
    macroProperties.put("macro2", "value2");
    URL url = baseURI.resolve(String.format("plugins/%s/macro", MacroFunction.NAME)).toURL();
    HttpRequest request = HttpRequest.builder(HttpMethod.POST, url).withBody(GSON.toJson(new DynamicPluginServiceApp.MacroPluginRequest(rawProperties, macroProperties))).build();
    HttpResponse response = executeHttp(request);
    Assert.assertEquals(200, response.getResponseCode());
    MacroFunction.MacroFunctionResult result = GSON.fromJson(response.getResponseBodyAsString(), MacroFunction.MacroFunctionResult.class);
    Assert.assertEquals(rawProperties, result.getRawProperties());
    Assert.assertEquals("value1", result.getConf().getKey1());
    Assert.assertEquals("value2", result.getConf().getKey2());
}
Also used : HttpRequest(io.cdap.common.http.HttpRequest) MacroFunction(io.cdap.cdap.service.function.MacroFunction) HashMap(java.util.HashMap) HttpResponse(io.cdap.common.http.HttpResponse) URL(java.net.URL) Test(org.junit.Test)

Aggregations

HttpRequest (io.cdap.common.http.HttpRequest)124 HttpResponse (io.cdap.common.http.HttpResponse)92 URL (java.net.URL)81 Test (org.junit.Test)33 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)14 IOException (java.io.IOException)14 AccessToken (io.cdap.cdap.security.authentication.client.AccessToken)13 DefaultHttpRequestConfig (io.cdap.cdap.common.http.DefaultHttpRequestConfig)10 BadRequestException (io.cdap.cdap.common.BadRequestException)9 NotFoundException (io.cdap.cdap.common.NotFoundException)8 TopicNotFoundException (io.cdap.cdap.api.messaging.TopicNotFoundException)5 ServiceManager (io.cdap.cdap.test.ServiceManager)5 TypeToken (com.google.gson.reflect.TypeToken)4 KeyValueTable (io.cdap.cdap.api.dataset.lib.KeyValueTable)4 ApplicationNotFoundException (io.cdap.cdap.common.ApplicationNotFoundException)4 ArtifactNotFoundException (io.cdap.cdap.common.ArtifactNotFoundException)4 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)4 TopicId (io.cdap.cdap.proto.id.TopicId)4 ApplicationManager (io.cdap.cdap.test.ApplicationManager)4 ByteBuffer (java.nio.ByteBuffer)4