Example usage for com.fasterxml.jackson.databind ObjectMapper readTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readTree.

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:com.apteligent.ApteligentJavaClient.java

/**
 * @param appID appId (string, optional): The app to retrieve data about,
 * @param metricType The metric to retrieve
 * @param duration can only be 1440 (24 hours) or 43200 (1 month)
 * @return Error object//from  ww  w  .j  a v a2 s.c  o  m
 */
public CrashSummary getErrorGraph(String appID, CrashSummary.MetricType metricType, int duration) {

    // { "params": {"duration": 43200, "graph": "crashes", "appId": "4f2cc6dfb09315234e000639"}}
    //String responseStr = "{\"data\": {\"start\": \"2014-11-13T00:00:00\", \"interval\": 86400, \"end\": \"2014-12-13T00:00:00\", \"series\": [{\"points\": [0, 3, 2, 0, 2, 3, 2, 3, 0, 6, 0, 0, 0, 1, 0, 0, 6, 2, 0, 1, 0, 0, 4, 1, 0, 0, 1, 2, 0, 0], \"name\": \"crashes\"}]}, \"params\": {\"duration\": 43200, \"graph\": \"crashes\", \"appId\": \"4f2cc6dfb09315234e000639\"}}";

    String params = "{ \"params\": " + "{\"duration\": " + duration + "," + " \"graph\": \""
            + metricType.toString() + "\"," + " \"appId\": \"" + appID + "\"}" + "}";

    System.out.println(params);
    CrashSummary crashSummary = null;
    try {
        HttpsURLConnection conn = sendPostRequest(API_ERROR_GRAPH, params);
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        TreeNode node = mapper.readTree(jp);
        crashSummary = mapper.treeToValue(node.get("data"), CrashSummary.class);
        if (crashSummary != null) {
            crashSummary.setParams(appID, metricType, duration);
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return crashSummary;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java

License:asdf

@Before
public void before() throws Exception {
    closeableHttpClient = HttpClientBuilder.create().build();

    String resourcePath = "internal/api/1.3/steering.json";
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);

    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }//w  w  w .  ja  v a 2s.  c  o m

    ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
    JsonNode steeringNode = objectMapper.readTree(inputStream).get("response").get(0);

    steeringDeliveryServiceId = steeringNode.get("deliveryService").asText();
    Iterator<JsonNode> iterator = steeringNode.get("targets").iterator();
    while (iterator.hasNext()) {
        JsonNode target = iterator.next();
        steeredDeliveryServices.add(target.get("deliveryService").asText());
    }

    resourcePath = "publish/CrConfig.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    JsonNode jsonNode = objectMapper.readTree(inputStream);

    deliveryServiceId = null;

    Iterator<String> deliveryServices = jsonNode.get("deliveryServices").fieldNames();
    while (deliveryServices.hasNext() && deliveryServiceId == null) {
        String dsId = deliveryServices.next();

        JsonNode deliveryServiceNode = jsonNode.get("deliveryServices").get(dsId);

        if (deliveryServiceNode.has("steeredDeliveryServices")) {
            continue;
        }

        JsonNode dispersionNode = deliveryServiceNode.get("dispersion");

        if (dispersionNode == null || dispersionNode.get("limit").asInt() != 1
                && dispersionNode.get("shuffled").asText().equals("true")) {
            continue;
        }

        Iterator<JsonNode> matchsets = deliveryServiceNode.get("matchsets").iterator();
        while (matchsets.hasNext() && deliveryServiceId == null) {
            if ("HTTP".equals(matchsets.next().get("protocol").asText())) {
                deliveryServiceId = dsId;
            }
        }

        if (deliveryServiceId == null) {
            System.out.println("Skipping " + deliveryServiceId + " no http protocol matchset");
        }
    }

    assertThat(deliveryServiceId, not(nullValue()));
    assertThat(steeringDeliveryServiceId, not(nullValue()));
    assertThat(steeredDeliveryServices.isEmpty(), equalTo(false));

    resourcePath = "czf.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    jsonNode = objectMapper.readTree(inputStream);

    JsonNode network = jsonNode.get("coverageZones").get(jsonNode.get("coverageZones").fieldNames().next())
            .get("network");

    for (int i = 0; i < network.size(); i++) {
        String cidrString = network.get(i).asText();
        CidrAddress cidrAddress = CidrAddress.fromString(cidrString);
        if (cidrAddress.getNetmaskLength() == 24) {
            byte[] hostBytes = cidrAddress.getHostBytes();
            ipAddressInCoverageZone = String.format("%d.%d.%d.123", hostBytes[0], hostBytes[1], hostBytes[2]);
            break;
        }
    }

    assertThat(ipAddressInCoverageZone.length(), greaterThan(0));
}

From source file:com.gsma.mobileconnect.utils.JsonUtilsTest.java

@Test
public void parseOperatorIdentifiedDiscoveryResult_withValidOperatorIdentifiedDiscoveryResult_shouldSucceed()
        throws IOException {
    // GIVEN/*from   w ww. j a v  a 2 s  . c  o m*/
    String expectedClientId = "EXPECTED CLIENT_ID";
    String expectedClientSecret = "EXPECTED CLIENT_SECRET";
    String expectedAuthorizationHref = "EXPECTED AUTHORIZATION_HREF";
    String expectedTokenHref = "EXPECTED TOKEN_HREF";
    String expectedUserInfoHref = "EXPECTED USER_INFO_HREF";
    String expectedPremiumInfoHref = "EXPECTED PREMIUM_INFO_HREF";
    String jsonStr = "{ \"response\": {" + " \"client_id\": \"" + expectedClientId + "\", "
            + " \"client_secret\": \"" + expectedClientSecret + "\", " + " \"apis\": {" + " \"operatorid\": {"
            + " \"link\": [" + " { \"rel\": \"authorization\", " + " \"href\": \"" + expectedAuthorizationHref
            + "\"}, " + " { \"rel\": \"token\", " + " \"href\": \"" + expectedTokenHref + "\"}, "
            + " { \"rel\": \"userinfo\", " + " \"href\": \"" + expectedUserInfoHref + "\"}, "
            + " { \"rel\": \"premiuminfo\", " + " \"href\": \"" + expectedPremiumInfoHref + "\"} " + "]}}}}";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(jsonStr);

    // WHEN
    ParsedOperatorIdentifiedDiscoveryResult parsedOperatorIdentifiedDiscoveryResult = JsonUtils
            .parseOperatorIdentifiedDiscoveryResult(root);

    // THEN
    assertNotNull(parsedOperatorIdentifiedDiscoveryResult);
    assertEquals(expectedClientId, parsedOperatorIdentifiedDiscoveryResult.getClientId());
    assertEquals(expectedClientSecret, parsedOperatorIdentifiedDiscoveryResult.getClientSecret());
    assertEquals(expectedAuthorizationHref, parsedOperatorIdentifiedDiscoveryResult.getAuthorizationHref());
    assertEquals(expectedTokenHref, parsedOperatorIdentifiedDiscoveryResult.getTokenHref());
    assertEquals(expectedUserInfoHref, parsedOperatorIdentifiedDiscoveryResult.getUserInfoHref());
    assertEquals(expectedPremiumInfoHref, parsedOperatorIdentifiedDiscoveryResult.getPremiumInfoHref());
}

From source file:org.apache.spark.streaming.amqp.JavaAMQPBrokerStreamSuite.java

@Test
public void testAMQPReceiveBinaryBody() {

    Function converter = new JavaAMQPJsonFunction();

    String sendMessage = "Spark Streaming & AMQP";
    JavaReceiverInputDStream<String> receiveStream = AMQPUtils.createStream(this.jssc,
            this.amqpTestUtils.host(), this.amqpTestUtils.port(), this.address, converter,
            StorageLevel.MEMORY_ONLY());

    JavaDStream<String> binaryStream = receiveStream.map(jsonMsg -> {

        ObjectMapper mapper = new ObjectMapper();

        String body = new String(
                Base64.getDecoder().decode(mapper.readTree(jsonMsg).get("body").get("section").asText()));

        return body;
    });//from w w w  .  j a  v  a 2 s  .  co  m

    List<String> receivedMessage = new ArrayList<>();
    binaryStream.foreachRDD(rdd -> {
        if (!rdd.isEmpty()) {
            receivedMessage.add(rdd.first());
        }
    });

    jssc.start();

    this.amqpTestUtils.sendBinaryMessage(address, sendMessage.getBytes());

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    assert (receivedMessage.get(0).equals(sendMessage));

    jssc.stop();
}

From source file:com.spotify.helios.cli.command.JobCreateCommandTest.java

/**
 * Test that when the environment variables we have defaults for are set, they are picked up in
 * the job metadata./*w  ww  .j  a v a 2s  . c  o  m*/
 */
@Test
public void testMetadataPicksUpEnvVars() throws Exception {
    envVars.put("GIT_COMMIT", "abcdef1234");

    when(options.getString("id")).thenReturn(JOB_ID);
    when(options.getString("image")).thenReturn("busybox:latest");

    when(options.getList("metadata")).thenReturn(Lists.<Object>newArrayList("foo=bar"));

    final int ret = runCommand();

    assertEquals(0, ret);
    final String output = baos.toString();

    final String expectedOutputPrefix = "Creating job: ";
    assertThat(output, startsWith(expectedOutputPrefix));

    final ObjectMapper objectMapper = new ObjectMapper();

    final String jsonFromOutput = output.split("\n")[0].substring(expectedOutputPrefix.length());
    final JsonNode jsonNode = objectMapper.readTree(jsonFromOutput);

    final ArrayList<String> fieldNames = Lists.newArrayList(jsonNode.fieldNames());
    assertThat(fieldNames, hasItem("metadata"));

    assertThat(jsonNode.get("metadata").isObject(), equalTo(true));

    final ObjectNode metadataNode = (ObjectNode) jsonNode.get("metadata");
    assertThat(metadataNode.get("foo").asText(), equalTo("bar"));
    assertThat(metadataNode.get("GIT_COMMIT").asText(), equalTo("abcdef1234"));
}

From source file:com.nextgenactionscript.vscode.project.ASConfigProjectConfigStrategy.java

public ProjectOptions getOptions() {
    changed = false;//from www .  j  av  a 2 s. c om
    if (asconfigPath == null) {
        return null;
    }
    File asconfigFile = asconfigPath.toFile();
    if (!asconfigFile.exists()) {
        return null;
    }
    Path projectRoot = asconfigPath.getParent();
    ProjectType type = ProjectType.APP;
    String config = null;
    String[] files = null;
    String additionalOptions = null;
    CompilerOptions compilerOptions = new CompilerOptions();
    try (InputStream schemaInputStream = getClass().getResourceAsStream("/schemas/asconfig.schema.json")) {
        JsonSchemaFactory factory = new JsonSchemaFactory();
        JsonSchema schema = factory.getSchema(schemaInputStream);
        String contents = FileUtils.readFileToString(asconfigFile);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree(contents);
        Set<ValidationMessage> errors = schema.validate(json);
        if (!errors.isEmpty()) {
            System.err.println("Failed to validate asconfig.json.");
            for (ValidationMessage error : errors) {
                System.err.println(error.toString());
            }
            return null;
        } else {
            if (json.has(ProjectOptions.TYPE)) //optional, defaults to "app"
            {
                String typeString = json.get(ProjectOptions.TYPE).asText();
                type = ProjectType.fromToken(typeString);
            }
            config = json.get(ProjectOptions.CONFIG).asText();
            if (json.has(ProjectOptions.FILES)) //optional
            {
                JsonNode jsonFiles = json.get(ProjectOptions.FILES);
                int fileCount = jsonFiles.size();
                files = new String[fileCount];
                for (int i = 0; i < fileCount; i++) {
                    String pathString = jsonFiles.get(i).asText();
                    Path filePath = projectRoot.resolve(pathString);
                    files[i] = filePath.toString();
                }
            }
            if (json.has(ProjectOptions.COMPILER_OPTIONS)) //optional
            {
                JsonNode jsonCompilerOptions = json.get(ProjectOptions.COMPILER_OPTIONS);
                if (jsonCompilerOptions.has(CompilerOptions.DEBUG)) {
                    compilerOptions.debug = jsonCompilerOptions.get(CompilerOptions.DEBUG).asBoolean();
                }
                if (jsonCompilerOptions.has(CompilerOptions.DEFINE)) {
                    HashMap<String, String> defines = new HashMap<>();
                    JsonNode jsonDefine = jsonCompilerOptions.get(CompilerOptions.DEFINE);
                    for (int i = 0, count = jsonDefine.size(); i < count; i++) {
                        JsonNode jsonNamespace = jsonDefine.get(i);
                        String name = jsonNamespace.get(CompilerOptions.DEFINE_NAME).asText();
                        Object value = jsonNamespace.get(CompilerOptions.DEFINE_VALUE).asText();
                        if (value instanceof String) {
                            value = "\"" + value + "\"";
                        }
                        defines.put(name, value.toString());
                    }
                    compilerOptions.defines = defines;
                }
                if (jsonCompilerOptions.has(CompilerOptions.EXTERNAL_LIBRARY_PATH)) {
                    JsonNode jsonExternalLibraryPath = jsonCompilerOptions
                            .get(CompilerOptions.EXTERNAL_LIBRARY_PATH);
                    ArrayList<File> externalLibraryPath = new ArrayList<>();
                    for (int i = 0, count = jsonExternalLibraryPath.size(); i < count; i++) {
                        String pathString = jsonExternalLibraryPath.get(i).asText();
                        Path filePath = projectRoot.resolve(pathString);
                        externalLibraryPath.add(filePath.toFile());
                    }
                    compilerOptions.externalLibraryPath = externalLibraryPath;
                }
                if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_CLASSES)) {
                    JsonNode jsonIncludeClasses = jsonCompilerOptions.get(CompilerOptions.INCLUDE_CLASSES);
                    ArrayList<String> includeClasses = new ArrayList<>();
                    for (int i = 0, count = jsonIncludeClasses.size(); i < count; i++) {
                        String qualifiedName = jsonIncludeClasses.get(i).asText();
                        includeClasses.add(qualifiedName);
                    }
                    compilerOptions.includeClasses = includeClasses;
                }
                if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_NAMESPACES)) {
                    JsonNode jsonIncludeNamespaces = jsonCompilerOptions
                            .get(CompilerOptions.INCLUDE_NAMESPACES);
                    ArrayList<String> includeNamespaces = new ArrayList<>();
                    for (int i = 0, count = jsonIncludeNamespaces.size(); i < count; i++) {
                        String namespaceURI = jsonIncludeNamespaces.get(i).asText();
                        includeNamespaces.add(namespaceURI);
                    }
                    compilerOptions.includeNamespaces = includeNamespaces;
                }
                if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_SOURCES)) {
                    JsonNode jsonIncludeSources = jsonCompilerOptions.get(CompilerOptions.INCLUDE_SOURCES);
                    ArrayList<File> includeSources = new ArrayList<>();
                    for (int i = 0, count = jsonIncludeSources.size(); i < count; i++) {
                        String pathString = jsonIncludeSources.get(i).asText();
                        Path filePath = projectRoot.resolve(pathString);
                        includeSources.add(filePath.toFile());
                    }
                    compilerOptions.includeSources = includeSources;
                }
                if (jsonCompilerOptions.has(CompilerOptions.JS_OUTPUT_TYPE)) {
                    String jsonJSOutputType = jsonCompilerOptions.get(CompilerOptions.JS_OUTPUT_TYPE).asText();
                    compilerOptions.jsOutputType = jsonJSOutputType;
                }
                if (jsonCompilerOptions.has(CompilerOptions.NAMESPACE)) {
                    JsonNode jsonLibraryPath = jsonCompilerOptions.get(CompilerOptions.NAMESPACE);
                    ArrayList<MXMLNamespaceMapping> namespaceMappings = new ArrayList<>();
                    for (int i = 0, count = jsonLibraryPath.size(); i < count; i++) {
                        JsonNode jsonNamespace = jsonLibraryPath.get(i);
                        String uri = jsonNamespace.get(CompilerOptions.NAMESPACE_URI).asText();
                        String manifest = jsonNamespace.get(CompilerOptions.NAMESPACE_MANIFEST).asText();
                        MXMLNamespaceMapping mapping = new MXMLNamespaceMapping(uri, manifest);
                        namespaceMappings.add(mapping);
                    }
                    compilerOptions.namespaceMappings = namespaceMappings;
                }
                if (jsonCompilerOptions.has(CompilerOptions.LIBRARY_PATH)) {
                    JsonNode jsonLibraryPath = jsonCompilerOptions.get(CompilerOptions.LIBRARY_PATH);
                    ArrayList<File> libraryPath = new ArrayList<>();
                    for (int i = 0, count = jsonLibraryPath.size(); i < count; i++) {
                        String pathString = jsonLibraryPath.get(i).asText();
                        Path filePath = projectRoot.resolve(pathString);
                        libraryPath.add(filePath.toFile());
                    }
                    compilerOptions.libraryPath = libraryPath;
                }
                if (jsonCompilerOptions.has(CompilerOptions.SOURCE_PATH)) {
                    JsonNode jsonSourcePath = jsonCompilerOptions.get(CompilerOptions.SOURCE_PATH);
                    ArrayList<File> sourcePath = new ArrayList<>();
                    for (int i = 0, count = jsonSourcePath.size(); i < count; i++) {
                        String pathString = jsonSourcePath.get(i).asText();
                        Path filePath = projectRoot.resolve(pathString);
                        sourcePath.add(filePath.toFile());
                    }
                    compilerOptions.sourcePath = sourcePath;
                }
                if (jsonCompilerOptions.has(CompilerOptions.WARNINGS)) {
                    compilerOptions.warnings = jsonCompilerOptions.get(CompilerOptions.WARNINGS).asBoolean();
                }
            }
            //these options are formatted as if sent in through the command line
            if (json.has(ProjectOptions.ADDITIONAL_OPTIONS)) //optional
            {
                additionalOptions = json.get(ProjectOptions.ADDITIONAL_OPTIONS).asText();
            }
        }
    } catch (Exception e) {
        System.err.println("Failed to parse asconfig.json: " + e);
        e.printStackTrace();
        return null;
    }
    //in a library project, the files field will be treated the same as the
    //include-sources compiler option
    if (type == ProjectType.LIB && files != null) {
        if (compilerOptions.includeSources == null) {
            compilerOptions.includeSources = new ArrayList<>();
        }
        for (int i = 0, count = files.length; i < count; i++) {
            String filePath = files[i];
            compilerOptions.includeSources.add(new File(filePath));
        }
        files = null;
    }
    ProjectOptions options = new ProjectOptions();
    options.type = type;
    options.config = config;
    options.files = files;
    options.compilerOptions = compilerOptions;
    options.additionalOptions = additionalOptions;
    return options;
}

From source file:org.codehaus.modello.generator.jackson.JacksonVerifier.java

private void compareJsonText(String expectedJson, String actualJson) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    JsonNode expected = mapper.readTree(expectedJson.trim());
    JsonNode actual = mapper.readTree(actualJson.trim());

    Assert.assertEquals(expected, actual);
}

From source file:org.opendaylight.alto.core.northbound.route.endpointproperty.impl.AltoNorthboundRouteEndpointpropertyTest.java

@Test
public void testBuildOutput() throws IOException, ExecutionException, InterruptedException {
    AltoNorthboundRouteEndpointproperty anbreSpy = spy(anbre);
    InstanceIdentifier<ContextTag> ctagIID = InstanceIdentifier.create(ContextTag.class);

    AltoModelEndpointpropertyService epService = mock(AltoModelEndpointpropertyService.class);
    Future<RpcResult<QueryOutput>> future = mock(Future.class);
    RpcResult<QueryOutput> rpcResult = mock(RpcResult.class);

    LinkedList<EndpointProperty> eppist = new LinkedList<>();

    SourceBuilder sourceBuilder = new SourceBuilder();
    Source THE_FIRST_SOURCE = sourceBuilder
            .setAddress(new Ipv4Builder().setIpv4(new Ipv4Address(THE_FIRST_IPv4_ADDRESS)).build()).build();
    Source THE_SECOND_SOURCE = sourceBuilder
            .setAddress(new Ipv4Builder().setIpv4(new Ipv4Address(THE_SECOND_IPv4_ADDRESS)).build()).build();

    EndpointPropertyBuilder epBuilder = new EndpointPropertyBuilder();
    List<Properties> THE_FIRST_LIST_PROPERTIES = new LinkedList<>();
    List<Properties> THE_SECOND_LIST_PROPERTIES = new LinkedList<>();

    PropertiesBuilder propertiesBuilder = new PropertiesBuilder();
    PropertyContainerBuilder pcBuilder = new PropertyContainerBuilder();

    PidName pidName = new PidName("PID1");
    PidNameBuilder pidNameBuilder = new PidNameBuilder();
    pidNameBuilder.setValue(pidName);/*from  w  w w. ja  v a  2 s  .c om*/
    pcBuilder.setProperty(new OutputResourceSpecificPropertyBuilder()
            .setResourceSpecificProperty(new SpecificEndpointProperty(DEFAULT_NETWORKMAP)).build());
    propertiesBuilder.setPropertyContainer(pcBuilder.build()).setPropertyValue(pidNameBuilder.build());
    THE_FIRST_LIST_PROPERTIES.add(propertiesBuilder.build());

    pcBuilder.setProperty(new OutputGlobalPropertyBuilder()
            .setGlobalProperty(new GlobalEndpointProperty(DEFAULT_GLOBAL_PROPERTY_NAME)).build());
    PidName fackGlobalProperty = new PidName("1");
    pidNameBuilder.setValue(fackGlobalProperty);
    propertiesBuilder.setPropertyContainer(pcBuilder.build()).setPropertyValue(pidNameBuilder.build());
    THE_FIRST_LIST_PROPERTIES.add(propertiesBuilder.build());

    pidName = new PidName("PID3");
    pidNameBuilder.setValue(pidName);
    pcBuilder.setProperty(new OutputResourceSpecificPropertyBuilder()
            .setResourceSpecificProperty(new SpecificEndpointProperty(DEFAULT_NETWORKMAP)).build());
    propertiesBuilder.setPropertyContainer(pcBuilder.build()).setPropertyValue(pidNameBuilder.build());
    THE_SECOND_LIST_PROPERTIES.add(propertiesBuilder.build());

    eppist.add(epBuilder.setSource(THE_FIRST_SOURCE).setProperties(THE_FIRST_LIST_PROPERTIES).build());
    eppist.add(epBuilder.setSource(THE_SECOND_SOURCE).setProperties(THE_SECOND_LIST_PROPERTIES).build());

    EndpointPropertyMapBuilder endpointPropertyMapBuilder = new EndpointPropertyMapBuilder();
    endpointPropertyMapBuilder.setEndpointProperty(eppist);

    EndpointPropertymapDataBuilder endpointPropertymapDataBuilder = new EndpointPropertymapDataBuilder();
    endpointPropertymapDataBuilder.setEndpointPropertyMap(endpointPropertyMapBuilder.build());

    EndpointpropertyResponseBuilder endpointpropertyResponseBuilder = new EndpointpropertyResponseBuilder();
    endpointpropertyResponseBuilder.setEndpointpropertyData(endpointPropertymapDataBuilder.build());

    QueryOutputBuilder queryOutputBuilder = new QueryOutputBuilder();
    queryOutputBuilder.setType(ResourceTypeEndpointproperty.class)
            .setResponse(endpointpropertyResponseBuilder.build());
    when(rpcResult.getResult()).thenReturn(queryOutputBuilder.build());
    when(future.get()).thenReturn(rpcResult);
    when(epService.query((QueryInput) anyObject())).thenReturn(future);
    anbreSpy.setMapService(epService);
    anbreSpy.setDataBroker(new DataBroker() {
        @Override
        public ReadOnlyTransaction newReadOnlyTransaction() {
            return null;
        }

        @Override
        public ReadWriteTransaction newReadWriteTransaction() {
            return null;
        }

        @Override
        public WriteTransaction newWriteOnlyTransaction() {
            return null;
        }

        @Override
        public ListenerRegistration<DataChangeListener> registerDataChangeListener(
                LogicalDatastoreType logicalDatastoreType, InstanceIdentifier<?> instanceIdentifier,
                DataChangeListener dataChangeListener, DataChangeScope dataChangeScope) {
            return null;
        }

        @Override
        public BindingTransactionChain createTransactionChain(
                TransactionChainListener transactionChainListener) {
            return null;
        }

        @Nonnull
        @Override
        public <T extends DataObject, L extends DataTreeChangeListener<T>> ListenerRegistration<L> registerDataTreeChangeListener(
                @Nonnull DataTreeIdentifier<T> dataTreeIdentifier, @Nonnull L l) {
            return null;
        }
    });
    doReturn(ctagIID).when(anbreSpy).getResourceByPath(eq(PATH), (ReadOnlyTransaction) anyObject());
    RFC7285EndpointPropertyMap.Meta meta = new RFC7285EndpointPropertyMap.Meta();
    RFC7285VersionTag vtag = new RFC7285VersionTag();
    vtag.rid = DEFAULT_RID;
    vtag.tag = DEFAULT_TAG;
    meta.netmap_tags = new LinkedList<>();
    meta.netmap_tags.add(vtag);
    doReturn(meta).when(anbreSpy).buildMeta((InstanceIdentifier<?>) anyObject());

    anbreSpy.init();
    Response response = anbreSpy.getEndpointProperty(PATH, ENDPOINTPROPERTY_FILTER);
    String stringResponse = response.getEntity().toString();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode responseNode = mapper.readTree(stringResponse);
    JsonNode endpointProperties = responseNode.get(FIELD_ENDPOINT_PROPERTIES);
    JsonNode expectedEndpointProperties = mapper.readTree(TARGET_ENDPOINT_PREOPERTIES);

    assertEquals(expectedEndpointProperties, endpointProperties);
}

From source file:io.seldon.external.ExternalPredictionServer.java

public JsonNode predict(String client, JsonNode jsonNode, OptionsHolder options) {
    long timeNow = System.currentTimeMillis();
    URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME));
    try {/*from   www  . j  a v a2 s.  c om*/
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort())
                .setPath(uri.getPath()).setParameter("client", client)
                .setParameter("json", jsonNode.toString());

        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new APIException(APIException.GENERIC_ERROR);
    }
    HttpContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(uri);
    try {
        if (logger.isDebugEnabled())
            logger.debug("Requesting " + httpGet.getURI().toString());
        CloseableHttpResponse resp = httpClient.execute(httpGet, context);
        try {
            if (resp.getStatusLine().getStatusCode() == 200) {
                ObjectMapper mapper = new ObjectMapper();
                JsonFactory factory = mapper.getFactory();
                JsonParser parser = factory.createParser(resp.getEntity().getContent());
                JsonNode actualObj = mapper.readTree(parser);

                return actualObj;
            } else {
                logger.error(
                        "Couldn't retrieve prediction from external prediction server -- bad http return code: "
                                + resp.getStatusLine().getStatusCode());
                throw new APIException(APIException.GENERIC_ERROR);
            }
        } finally {
            if (resp != null)
                resp.close();
            if (logger.isDebugEnabled())
                logger.debug(
                        "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms");
        }
    } catch (IOException e) {
        logger.error("Couldn't retrieve prediction from external prediction server - ", e);
        throw new APIException(APIException.GENERIC_ERROR);
    } catch (Exception e) {
        logger.error("Couldn't retrieve prediction from external prediction server - ", e);
        throw new APIException(APIException.GENERIC_ERROR);
    } finally {

    }

}