Search in sources :

Example 56 with TypeToken

use of com.google.gson.reflect.TypeToken in project cdap by caskdata.

the class SparkTest method testSparkHttpService.

@Test
public void testSparkHttpService() throws Exception {
    ApplicationManager applicationManager = deploy(TestSparkApp.class);
    SparkManager sparkManager = applicationManager.getSparkManager(SparkServiceProgram.class.getSimpleName()).start();
    URL url = sparkManager.getServiceURL(5, TimeUnit.MINUTES);
    Assert.assertNotNull(url);
    // GET request to sum n numbers.
    URL sumURL = url.toURI().resolve("sum?n=" + Joiner.on("&n=").join(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).toURL();
    HttpURLConnection urlConn = (HttpURLConnection) sumURL.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    try (InputStream is = urlConn.getInputStream()) {
        Assert.assertEquals(55, Integer.parseInt(new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8)));
    }
    URL wordcountURL = url.toURI().resolve("wordcount").toURL();
    urlConn = (HttpURLConnection) wordcountURL.openConnection();
    // POST lines of sentences
    urlConn.setDoOutput(true);
    urlConn.setChunkedStreamingMode(10);
    List<String> messages = new ArrayList<>();
    try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8"))) {
        for (int i = 0; i < 10; i++) {
            writer.printf("Message number %d\n", i);
            messages.add("Message number " + i);
        }
    }
    Assert.assertEquals(200, urlConn.getResponseCode());
    try (Reader reader = new InputStreamReader(urlConn.getInputStream(), "UTF-8")) {
        Map<String, Integer> result = new Gson().fromJson(reader, new TypeToken<Map<String, Integer>>() {
        }.getType());
        // Do a wordcount locally to get the expected result
        Map<String, Integer> expected = messages.stream().flatMap((Function<String, Stream<String>>) s -> Arrays.stream(s.split("\\s+"))).map(s -> Maps.immutableEntry(s, 1)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1 + v2));
        Assert.assertEquals(expected, result);
    }
    sparkManager.stop();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) FormatSpecification(co.cask.cdap.api.data.format.FormatSpecification) Arrays(java.util.Arrays) StreamProperties(co.cask.cdap.proto.StreamProperties) TypeToken(com.google.gson.reflect.TypeToken) ScalaSparkLogParser(co.cask.cdap.spark.app.ScalaSparkLogParser) KeyValue(co.cask.cdap.api.dataset.lib.KeyValue) URL(java.net.URL) TransactionSpark(co.cask.cdap.spark.app.TransactionSpark) LoggerFactory(org.slf4j.LoggerFactory) SparkManager(co.cask.cdap.test.SparkManager) FileSetArguments(co.cask.cdap.api.dataset.lib.FileSetArguments) StreamSQLSpark(co.cask.cdap.spark.app.StreamSQLSpark) StringLengthUDT(co.cask.cdap.spark.app.plugin.StringLengthUDT) Tasks(co.cask.cdap.common.utils.Tasks) CharStreams(com.google.common.io.CharStreams) Gson(com.google.gson.Gson) Map(java.util.Map) Locations(co.cask.cdap.common.io.Locations) DirUtils(co.cask.cdap.common.utils.DirUtils) SparkLogParser(co.cask.cdap.spark.app.SparkLogParser) ClassRule(org.junit.ClassRule) TestFrameworkTestBase(co.cask.cdap.test.base.TestFrameworkTestBase) PrintWriter(java.io.PrintWriter) Application(co.cask.cdap.api.app.Application) ImmutableSet(com.google.common.collect.ImmutableSet) IdentityHashMap(java.util.IdentityHashMap) ImmutableMap(com.google.common.collect.ImmutableMap) Person(co.cask.cdap.spark.app.Person) ApplicationManager(co.cask.cdap.test.ApplicationManager) Set(java.util.Set) RuntimeArguments(co.cask.cdap.api.common.RuntimeArguments) Scope(co.cask.cdap.api.common.Scope) Reader(java.io.Reader) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) Stream(java.util.stream.Stream) StringLengthFunc(co.cask.cdap.spark.app.plugin.StringLengthFunc) Predicate(com.google.common.base.Predicate) DataSetManager(co.cask.cdap.test.DataSetManager) ByteStreams(com.google.common.io.ByteStreams) KeyValueTable(co.cask.cdap.api.dataset.lib.KeyValueTable) ScalaClassicSparkProgram(co.cask.cdap.spark.app.ScalaClassicSparkProgram) CloseableIterator(co.cask.cdap.api.dataset.lib.CloseableIterator) Joiner(com.google.common.base.Joiner) NamespaceId(co.cask.cdap.proto.id.NamespaceId) Iterables(com.google.common.collect.Iterables) SparkServiceProgram(co.cask.cdap.spark.app.SparkServiceProgram) BeforeClass(org.junit.BeforeClass) Location(org.apache.twill.filesystem.Location) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) Function(java.util.function.Function) FileSet(co.cask.cdap.api.dataset.lib.FileSet) StreamManager(co.cask.cdap.test.StreamManager) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) ScheduleId(co.cask.cdap.proto.id.ScheduleId) Schema(co.cask.cdap.api.data.schema.Schema) ProgramRunStatus(co.cask.cdap.proto.ProgramRunStatus) DatasetSQLSpark(co.cask.cdap.spark.app.DatasetSQLSpark) ScalaDynamicSpark(co.cask.cdap.spark.app.ScalaDynamicSpark) PythonSpark(co.cask.cdap.spark.app.PythonSpark) OutputStreamWriter(java.io.OutputStreamWriter) Constants(co.cask.cdap.common.conf.Constants) PrintStream(java.io.PrintStream) Charsets(com.google.common.base.Charsets) Logger(org.slf4j.Logger) PluggableFunc(co.cask.cdap.spark.app.plugin.PluggableFunc) Files(java.nio.file.Files) Bytes(co.cask.cdap.api.common.Bytes) Test(org.junit.Test) IOException(java.io.IOException) ScalaStreamFormatSpecSpark(co.cask.cdap.spark.app.ScalaStreamFormatSpecSpark) TestConfiguration(co.cask.cdap.test.TestConfiguration) Maps(com.google.common.collect.Maps) InputStreamReader(java.io.InputStreamReader) SparkAppUsingGetDataset(co.cask.cdap.spark.app.SparkAppUsingGetDataset) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) URLEncoder(java.net.URLEncoder) WorkflowManager(co.cask.cdap.test.WorkflowManager) ObjectMappedTable(co.cask.cdap.api.dataset.lib.ObjectMappedTable) ClassicSparkProgram(co.cask.cdap.spark.app.ClassicSparkProgram) TestSparkApp(co.cask.cdap.spark.app.TestSparkApp) Assert(org.junit.Assert) Collections(java.util.Collections) StreamFormatSpecSpark(co.cask.cdap.spark.app.StreamFormatSpecSpark) InputStream(java.io.InputStream) ApplicationManager(co.cask.cdap.test.ApplicationManager) SparkManager(co.cask.cdap.test.SparkManager) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) TypeToken(com.google.gson.reflect.TypeToken) OutputStreamWriter(java.io.OutputStreamWriter) Stream(java.util.stream.Stream) PrintStream(java.io.PrintStream) InputStream(java.io.InputStream) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 57 with TypeToken

use of com.google.gson.reflect.TypeToken in project cdap by caskdata.

the class ServiceArtifactTestRun method testServiceArtifact.

@Test
public void testServiceArtifact() throws Exception {
    ApplicationManager appManager = deployWithArtifact(ServiceArtifactApp.class, artifactJar);
    ServiceManager serviceManager = appManager.getServiceManager("artifact").start();
    URL serviceURL = serviceManager.getServiceURL(30, TimeUnit.SECONDS);
    Assert.assertNotNull(serviceURL);
    URL listURL = serviceURL.toURI().resolve("list").toURL();
    try (Reader reader = new InputStreamReader(listURL.openStream(), StandardCharsets.UTF_8)) {
        List<ArtifactInfo> artifacts = new Gson().fromJson(reader, new TypeToken<List<ArtifactInfo>>() {
        }.getType());
        // It should have the test app, and two plugin artifacts
        Assert.assertEquals(3, artifacts.size());
        Assert.assertTrue(artifacts.stream().anyMatch(info -> info.getName().equals(ServiceArtifactApp.class.getSimpleName())));
        Assert.assertTrue(artifacts.stream().anyMatch(info -> info.getName().equals("dummybase")));
        Assert.assertTrue(artifacts.stream().anyMatch(info -> info.getName().equals("dummy")));
    }
    URL loadURL = serviceURL.toURI().resolve("load?parent=dummybase&plugin=dummy&class=" + DummyPlugin.class.getName()).toURL();
    HttpURLConnection urlConn = (HttpURLConnection) loadURL.openConnection();
    Assert.assertEquals(200, urlConn.getResponseCode());
    try (Reader reader = new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8)) {
        Assert.assertEquals(DummyPlugin.class.getName(), CharStreams.toString(reader));
    }
    serviceManager.stop();
    serviceManager.waitForStatus(false);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) NamespaceId(co.cask.cdap.proto.id.NamespaceId) TypeToken(com.google.gson.reflect.TypeToken) BeforeClass(org.junit.BeforeClass) URL(java.net.URL) JarEntry(java.util.jar.JarEntry) CharStreams(com.google.common.io.CharStreams) Gson(com.google.gson.Gson) ClassRule(org.junit.ClassRule) JarOutputStream(java.util.jar.JarOutputStream) Constants(co.cask.cdap.common.conf.Constants) TestFrameworkTestBase(co.cask.cdap.test.base.TestFrameworkTestBase) Service(co.cask.cdap.api.service.Service) ArtifactInfo(co.cask.cdap.api.artifact.ArtifactInfo) ApplicationManager(co.cask.cdap.test.ApplicationManager) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) IOException(java.io.IOException) Reader(java.io.Reader) TestConfiguration(co.cask.cdap.test.TestConfiguration) InputStreamReader(java.io.InputStreamReader) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ByteStreams(com.google.common.io.ByteStreams) ArtifactManager(co.cask.cdap.api.artifact.ArtifactManager) ServiceManager(co.cask.cdap.test.ServiceManager) Assert(org.junit.Assert) ApplicationManager(co.cask.cdap.test.ApplicationManager) InputStreamReader(java.io.InputStreamReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) ArtifactInfo(co.cask.cdap.api.artifact.ArtifactInfo) ServiceManager(co.cask.cdap.test.ServiceManager) TypeToken(com.google.gson.reflect.TypeToken) Test(org.junit.Test)

Example 58 with TypeToken

use of com.google.gson.reflect.TypeToken in project cdap by caskdata.

the class MetricsHandlerTestRun method verifySearchMetricResult.

private void verifySearchMetricResult(String url, List<String> expectedValues) throws Exception {
    HttpResponse response = doPost(url, null);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    String result = EntityUtils.toString(response.getEntity());
    List<String> reply = GSON.fromJson(result, new TypeToken<List<String>>() {
    }.getType());
    reply = removeMetricsSystemMetrics(reply);
    Assert.assertEquals(expectedValues.size(), reply.size());
    for (int i = 0; i < expectedValues.size(); i++) {
        Assert.assertEquals(expectedValues.get(i), reply.get(i));
    }
}
Also used : TypeToken(com.google.gson.reflect.TypeToken) HttpResponse(org.apache.http.HttpResponse)

Example 59 with TypeToken

use of com.google.gson.reflect.TypeToken in project cdap by caskdata.

the class DecisionTreeRegressionAppTest method test.

@Test
public void test() throws Exception {
    // Deploy the Application
    ApplicationManager appManager = deployApplication(DecisionTreeRegressionApp.class);
    // Start the Service
    ServiceManager serviceManager = appManager.getServiceManager(ModelDataService.SERVICE_NAME).start();
    serviceManager.waitForStatus(true, 30, 1);
    URL serviceURL = serviceManager.getServiceURL(15, TimeUnit.SECONDS);
    URL addDataURL = new URL(serviceURL, "labels");
    HttpRequest request = HttpRequest.builder(HttpMethod.PUT, addDataURL).withBody(new InputSupplier<InputStream>() {

        @Override
        public InputStream getInput() throws IOException {
            return getClass().getClassLoader().getResourceAsStream("sample_libsvm_data.txt");
        }
    }).build();
    HttpResponse response = HttpRequests.execute(request);
    Assert.assertEquals(200, response.getResponseCode());
    // Start a Spark Program
    SparkManager sparkManager = appManager.getSparkManager(ModelTrainer.NAME).start();
    sparkManager.waitForRun(ProgramRunStatus.COMPLETED, 60, TimeUnit.SECONDS);
    // Check that there is a new model
    URL listModelsURL = new URL(serviceURL, "models");
    request = HttpRequest.builder(HttpMethod.GET, listModelsURL).build();
    response = HttpRequests.execute(request);
    Assert.assertEquals(200, response.getResponseCode());
    List<String> models = GSON.fromJson(response.getResponseBodyAsString(), new TypeToken<List<String>>() {
    }.getType());
    Assert.assertEquals(1, models.size());
    // Check that there is some model metadata
    String modelId = models.get(0);
    URL modelMetaURL = new URL(serviceURL, "models/" + modelId);
    request = HttpRequest.builder(HttpMethod.GET, modelMetaURL).build();
    response = HttpRequests.execute(request);
    Assert.assertEquals(200, response.getResponseCode());
    ModelMeta meta = GSON.fromJson(response.getResponseBodyAsString(), ModelMeta.class);
    Assert.assertNotNull(meta);
    Assert.assertEquals(0.7, meta.getTrainingPercentage(), 0.000001);
    Assert.assertEquals(692, meta.getNumFeatures());
    // Check that the corresponding model file exists
    DataSetManager<FileSet> modelFiles = getDataset(DecisionTreeRegressionApp.MODEL_DATASET);
    Assert.assertTrue(modelFiles.get().getBaseLocation().append(modelId).exists());
}
Also used : HttpRequest(co.cask.common.http.HttpRequest) ApplicationManager(co.cask.cdap.test.ApplicationManager) SparkManager(co.cask.cdap.test.SparkManager) FileSet(co.cask.cdap.api.dataset.lib.FileSet) HttpResponse(co.cask.common.http.HttpResponse) URL(java.net.URL) ServiceManager(co.cask.cdap.test.ServiceManager) TypeToken(com.google.gson.reflect.TypeToken) InputSupplier(com.google.common.io.InputSupplier) Test(org.junit.Test)

Example 60 with TypeToken

use of com.google.gson.reflect.TypeToken in project cdap by caskdata.

the class DatasetInstanceHandlerTest method getInstanceProperties.

private ObjectResponse<Map<String, String>> getInstanceProperties(String instanceName) throws IOException {
    HttpRequest request = HttpRequest.get(getUrl("/data/datasets/" + instanceName + "/properties")).build();
    HttpResponse response = HttpRequests.execute(request);
    return ObjectResponse.fromJsonBody(response, new TypeToken<Map<String, String>>() {
    }.getType());
}
Also used : HttpRequest(co.cask.common.http.HttpRequest) TypeToken(com.google.gson.reflect.TypeToken) HttpResponse(co.cask.common.http.HttpResponse)

Aggregations

TypeToken (com.google.gson.reflect.TypeToken)418 Gson (com.google.gson.Gson)178 Test (org.junit.Test)99 IOException (java.io.IOException)83 Map (java.util.Map)71 List (java.util.List)56 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)54 ArrayList (java.util.ArrayList)53 HashMap (java.util.HashMap)52 GsonBuilder (com.google.gson.GsonBuilder)45 File (java.io.File)34 Notebook (org.apache.zeppelin.notebook.Notebook)32 Type (java.lang.reflect.Type)31 FileNotFoundException (java.io.FileNotFoundException)29 Paragraph (org.apache.zeppelin.notebook.Paragraph)27 RestResponse (com.google.gerrit.acceptance.RestResponse)24 JsonElement (com.google.gson.JsonElement)24 JsonObject (com.google.gson.JsonObject)24 OutputStreamWriter (java.io.OutputStreamWriter)22 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)21