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:de.ids_mannheim.korap.search.TestMetaFields.java

@Test
public void searchMetaFieldsNew() throws IOException {

    // Construct index
    KrillIndex ki = new KrillIndex();
    ki.addDoc(getClass().getResourceAsStream("/goe/AGX-00002.json"), false);
    ki.commit();/*  www  .j a v  a  2 s .c o  m*/

    String jsonString = getJsonString(getClass().getResource("/queries/metas/fields_no.jsonld").getFile());

    Krill ks = new Krill(jsonString);
    Result kr = ks.apply(ki);
    ObjectMapper mapper = new ObjectMapper();
    JsonNode res = mapper.readTree(kr.toJsonString());
    assertEquals(0, res.at("/matches/0/UID").asInt());
    assertEquals("GOE_AGX.00002", res.at("/matches/0/textSigle").asText());
    assertEquals("Maximen und Reflexionen", res.at("/matches/0/title").asText());
    assertEquals("1982", res.at("/matches/0/pubDate").asText());
    assertEquals("Goethe, Johann Wolfgang von", res.at("/matches/0/author").asText());
    assertEquals("GOE_AGX", res.at("/matches/0/docSigle").asText());
    assertEquals("GOE", res.at("/matches/0/corpusSigle").asText());
    assertEquals("Religion und Christentum", res.at("/matches/0/subTitle").asText());
    assertEquals("Mnchen", res.at("/matches/0/pubPlace").asText());
    assertEquals(
            "base/s=spans cnx/c=spans cnx/l=tokens cnx/m=tokens cnx/p=tokens cnx/s=spans cnx/syn=tokens corenlp/c=spans corenlp/ne=tokens corenlp/p=tokens corenlp/s=spans glemm/l=tokens mate/l=tokens mate/m=tokens mate/p=tokens opennlp/p=tokens opennlp/s=spans tt/l=tokens tt/p=tokens tt/s=spans xip/c=spans xip/l=tokens xip/p=tokens xip/s=spans",
            res.at("/matches/0/layerInfos").asText());
    assertTrue(res.at("/matches/0/textType").isMissingNode());
    assertEquals("match-GOE_AGX.00002-p7-8", res.at("/matches/0/matchID").asText());

    // All fields
    jsonString = getJsonString(getClass().getResource("/queries/metas/fields_all.jsonld").getFile());

    ks = new Krill(jsonString);
    kr = ks.apply(ki);
    mapper = new ObjectMapper();
    res = mapper.readTree(kr.toJsonString());
    assertEquals("Verlag C. H. Beck", res.at("/matches/0/publisher").asText());
    assertEquals("Aphorismus", res.at("/matches/0/textType").asText());
    assertEquals("Aphorismen", res.at("/matches/0/textTypeRef").asText());
    assertEquals(
            "Goethe, Johann Wolfgang von: Maximen und Reflexionen. Religion und Christentum, [Aphorismen], (Erstverffentlichung: Stuttgart ; Tbingen, 1827-1842), In: Goethe, Johann Wolfgang von: Goethes Werke, Bd. 12, Schriften zur Kunst. Schriften zur Literatur. Maximen und Reflexionen, Hrsg.: Trunz, Erich. Mnchen: Verlag C. H. Beck, 1982, S. 372-377",
            res.at("/matches/0/reference").asText());
    assertEquals("de", res.at("/matches/0/language").asText());
    assertEquals("opennlp#tokens", res.at("/matches/0/tokenSource").asText());
    assertEquals(
            "base base/paragraphs base/sentences connexor connexor/morpho connexor/phrase connexor/sentences connexor/syntax corenlp corenlp/constituency corenlp/morpho corenlp/namedentities corenlp/sentences glemm glemm/morpho mate mate/morpho opennlp opennlp/morpho opennlp/sentences treetagger treetagger/morpho treetagger/sentences xip xip/constituency xip/morpho xip/sentences",
            res.at("/matches/0/foundries").asText());
    assertEquals("Goethe-Korpus", res.at("/matches/0/corpusTitle").asText());
    assertEquals("QAO-NC", res.at("/matches/0/availability").asText());
    assertEquals("Goethe: Maximen und Reflexionen, (1827-1842)", res.at("/matches/0/docTitle").asText());
    assertEquals("1827", res.at("/matches/0/creationDate").asText());
    // assertEquals("372-377", res.at("/matches/0/pages").asText());
    assertEquals("match-GOE_AGX.00002-p7-8", res.at("/matches/0/matchID").asText());

    // @All fields
    jsonString = getJsonString(getClass().getResource("/queries/metas/fields_at_all.jsonld").getFile());

    ks = new Krill(jsonString);
    kr = ks.apply(ki);
    mapper = new ObjectMapper();
    res = mapper.readTree(kr.toJsonString());

    assertEquals("Verlag C. H. Beck", res.at("/matches/0/publisher").asText());
    assertEquals("Aphorismus", res.at("/matches/0/textType").asText());
    assertEquals("Aphorismen", res.at("/matches/0/textTypeRef").asText());
    assertEquals(
            "Goethe, Johann Wolfgang von: Maximen und Reflexionen. Religion und Christentum, [Aphorismen], (Erstverffentlichung: Stuttgart ; Tbingen, 1827-1842), In: Goethe, Johann Wolfgang von: Goethes Werke, Bd. 12, Schriften zur Kunst. Schriften zur Literatur. Maximen und Reflexionen, Hrsg.: Trunz, Erich. Mnchen: Verlag C. H. Beck, 1982, S. 372-377",
            res.at("/matches/0/reference").asText());
    assertEquals("de", res.at("/matches/0/language").asText());
    assertEquals("opennlp#tokens", res.at("/matches/0/tokenSource").asText());
    assertEquals(
            "base base/paragraphs base/sentences connexor connexor/morpho connexor/phrase connexor/sentences connexor/syntax corenlp corenlp/constituency corenlp/morpho corenlp/namedentities corenlp/sentences glemm glemm/morpho mate mate/morpho opennlp opennlp/morpho opennlp/sentences treetagger treetagger/morpho treetagger/sentences xip xip/constituency xip/morpho xip/sentences",
            res.at("/matches/0/foundries").asText());
    assertEquals("Goethe-Korpus", res.at("/matches/0/corpusTitle").asText());
    assertEquals("QAO-NC", res.at("/matches/0/license").asText());
    assertEquals("Goethe: Maximen und Reflexionen, (1827-1842)", res.at("/matches/0/docTitle").asText());
    assertEquals("1827", res.at("/matches/0/creationDate").asText());
    // assertEquals("372-377", res.at("/matches/0/pages").asText());
    assertEquals("match-GOE_AGX.00002-p7-8", res.at("/matches/0/matchID").asText());
}

From source file:de.ids_mannheim.korap.search.TestMetaFields.java

@Test
public void searchCollectionFields() throws IOException {
    KrillIndex ki = new KrillIndex();
    FieldDocument fd = new FieldDocument();
    fd.addString("corpusSigle", "ABC");
    fd.addString("docSigle", "ABC-123");
    fd.addString("textSigle", "ABC-123-0001");
    fd.addText("title", "Die Wahlverwandschaften");
    fd.addText("author", "Johann Wolfgang von Goethe");
    fd.addKeyword("textClass", "reisen wissenschaft");
    fd.addInt("pubDate", 20130617);
    fd.addTV("tokens", "abc",
            "[(0-1)s:a|i:a|_0#0-1|-:t$<i>10]" + "[(1-2)s:b|i:b|_1#1-2]" + "[(2-3)s:c|i:c|_2#2-3]");
    ki.addDoc(fd);//from www .  ja v a  2s . com

    FieldDocument fd2 = new FieldDocument();
    fd2.addString("corpusSigle", "ABC");
    fd2.addString("docSigle", "ABC-125");
    fd2.addString("textSigle", "ABC-125-0001");
    fd2.addText("title", "Die Glocke");
    fd2.addText("author", "Schiller, Friedrich");
    fd2.addKeyword("textClass", "Reisen geschichte");
    fd2.addInt("pubDate", 20130203);
    fd2.addTV("tokens", "abc",
            "[(0-1)s:a|i:a|_0#0-1|-:t$<i>10]" + "[(1-2)s:b|i:b|_1#1-2]" + "[(2-3)s:c|i:c|_2#2-3]");
    ki.addDoc(fd2);
    ki.commit();

    // textClass = reisen & wissenschaft
    String jsonString = getJsonString(
            getClass().getResource("/queries/collections/collection_textClass.jsonld").getFile());
    Krill ks = new Krill(jsonString);
    KrillCollection kc = ks.getCollection();
    kc.setIndex(ki);
    assertEquals(1, kc.numberOf("documents"));

    // textClass = reisen
    jsonString = getJsonString(
            getClass().getResource("/queries/collections/collection_textClass_2.jsonld").getFile());
    ks = new Krill(jsonString);
    kc = ks.getCollection();
    kc.setIndex(ki);
    assertEquals(2, kc.numberOf("documents"));

    /*
    TokenStream ts = fd2.doc.getField("author").tokenStream(
    (Analyzer) ki.writer().getAnalyzer(),
    (TokenStream) null
                                                          );
    // OffsetAttribute offsetAttribute = ts.addAttribute(OffsetAttribute.class);
    CharTermAttribute charTermAttribute = ts.addAttribute(CharTermAttribute.class);
            
    ts.reset();
    while (ts.incrementToken()) {
    String term = charTermAttribute.toString();
    System.err.println(">>" + term + "<<");
    };
    */

    // author = wolfgang
    jsonString = getJsonString(
            getClass().getResource("/queries/collections/collection_goethe.jsonld").getFile());
    ks = new Krill(jsonString);
    kc = ks.getCollection();
    kc.setIndex(ki);
    assertEquals(1, kc.numberOf("documents"));

    // author = Wolfgang
    jsonString = getJsonString(
            getClass().getResource("/queries/collections/collection_goethe_2.jsonld").getFile());
    ks = new Krill(jsonString);
    kc = ks.getCollection();
    kc.setIndex(ki);
    assertEquals(1, kc.numberOf("documents"));

    Result kr = ks.apply(ki);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode res = mapper.readTree(kr.toJsonString());
    assertEquals(1, res.at("/meta/totalResults").asInt());
}

From source file:net.maurerit.zkb.KillParser.java

public List<Kill> parse(InputStream is, boolean isXml) throws IOException {
    List<Kill> kills = new ArrayList<Kill>();

    ObjectMapper mapper;
    if (isXml) {/*ww w .j  av  a2  s  .c  o m*/
        mapper = new XmlMapper();
    } else {
        mapper = new ObjectMapper();
    }

    TreeNode root = mapper.readTree(is);

    if (root instanceof ArrayNode) {
        ArrayNode rootCasted = (ArrayNode) root;
        for (int idx = 0; idx < rootCasted.size(); idx++) {
            kills.add(parseKill(rootCasted.get(idx)));
        }
    }

    return kills;
}

From source file:org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver.java

private Object readPutForUpdate(IncomingRequest request, ObjectMapper mapper, Object existingObject) {

    try {/*from   www .  j a  v a2 s.  c  o  m*/

        JsonPatchHandler handler = new JsonPatchHandler(mapper, reader);
        JsonNode jsonNode = mapper.readTree(request.getBody());

        return handler.applyPut((ObjectNode) jsonNode, existingObject);

    } catch (Exception o_O) {
        throw new HttpMessageNotReadableException(String.format(ERROR_MESSAGE, existingObject.getClass()), o_O);
    }
}

From source file:com.openplatform.udm.javamodel.CandidateSchemaTest.java

/**
 * Populated java model to json./*from w w w  . j  a va2  s .  co  m*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void populatedJavaModelToJson() throws IOException {
    //ASSIGN & ACT
    Candidate candidate = new Candidate();

    Person person = new Person();
    person.setGivenName("James");
    person.setFamilyName("McGregor");

    List<PersonCompetency> personCompetencies = new ArrayList<PersonCompetency>();
    PersonCompetency personCompetency = new PersonCompetency();
    personCompetency.setCompetencyID("IPS");
    personCompetency.setCompetencyName("Interpersonal skills");
    PersonCompetency personCompetency2 = new PersonCompetency();
    personCompetency2.setCompetencyID("CAR");
    personCompetency2.setCompetencyName("Consistency and Reliability");
    personCompetency2.setCompetencyLevel("High");
    personCompetencies.add(personCompetency);
    personCompetencies.add(personCompetency2);

    List<WorkEligibility> workEligibilities = new ArrayList<WorkEligibility>();
    WorkEligibility workEligibility = new WorkEligibility();
    CountryCode wecc = new CountryCode();
    wecc.setName("United Kingdom");
    wecc.setCode("UK");
    workEligibility.setCountryCode(wecc);
    workEligibility.setPermanent(true);
    workEligibilities.add(workEligibility);

    List<PositionHistory> positionHistories = new ArrayList<PositionHistory>();
    PositionHistory positionHistory = new PositionHistory();
    positionHistory.setEmployer("Credit Suisse");
    positionHistory.setPositionTitle("Business Analyst");
    positionHistory.setStartDate("1980-02-01");
    positionHistories.add(positionHistory);

    List<Certification> certifications = new ArrayList<Certification>();
    Certification certification = new Certification();
    Code ctcCode = new Code();
    ctcCode.setName("Oracle Java Certification Associate");
    ctcCode.setCode("OJCA");
    certification.setCertificationTypeCode(ctcCode);
    certification.setCertificationName("Oracle Java Certification Associate");
    certifications.add(certification);

    List<License> licenses = new ArrayList<License>();
    License license = new License();
    Code ltcCode = new Code();
    ltcCode.setName("Driver's Licence Code");
    ltcCode.setCode("DLIC");
    license.setLicenseTypeCode(ltcCode);
    license.setLicenseName("Driver's Licence");
    licenses.add(license);

    List<EmploymentReference> employmentReferences = new ArrayList<EmploymentReference>();
    EmploymentReference employmentReference = new EmploymentReference();
    employmentReference.setFormattedName("David Smith");
    employmentReferences.add(employmentReference);

    List<Code> specialCommitments = new ArrayList<Code>();
    Code specialCommitment = new Code();
    specialCommitment.setCode("CHAR");
    specialCommitment.setName("Chair person for non-profit organisation");
    specialCommitments.add(specialCommitment);

    List<Attachment> attachments = new ArrayList<Attachment>();
    Attachment attachment = new Attachment();
    attachment.setFileName("CoverLetter.doc");
    attachments.add(attachment);

    candidate.setPerson(person);
    candidate.setPersonCompetency(personCompetencies);
    candidate.setWorkEligibility(workEligibilities);
    candidate.setPositionHistory(positionHistories);
    candidate.setCertification(certifications);
    candidate.setLicense(licenses);
    candidate.setEmploymentReferences(employmentReferences);
    candidate.setSpecialCommitment(specialCommitments);
    candidate.setAttachment(attachments);

    File inputJson = new File(filePathCandidatePartial);
    String outputJson = Transformer.toJSON(candidate);

    ObjectMapper diffMapper = new ObjectMapper();
    JsonNode tree1 = diffMapper.readTree(inputJson);
    JsonNode tree2 = diffMapper.readTree(outputJson);

    //ASSERT
    org.junit.Assert.assertEquals(tree1, tree2);
}

From source file:com.marklogic.client.functionaltest.TestPOJOwithQBEQueryDef.java

@Test(expected = ClassCastException.class)
public void testPOJOcombinedSearchforNumberWithStringHandle() throws JsonProcessingException, IOException {
    PojoRepository<Artifact, Long> products = client.newPojoRepository(Artifact.class, Long.class);
    PojoPage<Artifact> p;/*from ww w. ja v a 2s.co  m*/
    this.loadSimplePojos(products);

    QueryManager queryMgr = client.newQueryManager();
    String queryAsString = "{\"search\":{\"query\":{"
            + "\"range-constraint-query\":{\"constraint-name\":\"id\", \"value\":[5,10,15,20,25,30]}},"
            + "\"options\":{\"return-metrics\":false, \"constraint\":{\"name\":\"id\", \"range\":{\"type\": \"xs:long\",\"json-property\":\"id\"}}}"
            + "}}";
    PojoQueryDefinition qd = (PojoQueryDefinition) queryMgr
            .newRawCombinedQueryDefinition(new StringHandle(queryAsString).withFormat(Format.JSON));

    StringHandle results = new StringHandle();
    JacksonHandle jh = new JacksonHandle();
    p = products.search(qd, 1, jh);

    long pageNo = 1, count = 0;
    do {
        count = 0;
        p = products.search(qd, pageNo, results.withFormat(Format.JSON));

        while (p.iterator().hasNext()) {
            Artifact a = p.iterator().next();
            validateArtifact(a);
            count++;
        }
        assertEquals("Page total results", count, p.getTotalSize());
        pageNo = pageNo + p.getPageSize();
        System.out.println(results.get().toString());
    } while (!p.isLastPage() && pageNo < p.getTotalSize());
    assertFalse("String handle is not empty", results.get().isEmpty());
    assertTrue("String handle contains results", results.get().contains("results"));
    assertTrue("String handle contains format", results.get().contains("\"format\":\"json\""));
    ObjectMapper mapper = new ObjectMapper();
    JsonNode actNode = mapper.readTree(results.get()).get("total");
    assertEquals("Total search results resulted are ", 6, actNode.asInt());
}

From source file:com.marklogic.entityservices.tests.TestInstanceConverterGenerator.java

private String moduleImport(String entityType) {
    InputStream is = this.getClass().getResourceAsStream("/json-models/" + entityType);
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode controlFile = null;/*from w  w  w  .  j  a v  a 2s  .c  o  m*/
    try {
        controlFile = (ObjectNode) mapper.readTree(is);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    JsonNode baseUriNode = controlFile.get("info").get("baseUri");
    String baseUri = null;
    if (baseUriNode == null) {
        baseUri = "http://example.org/";
    } else {
        baseUri = baseUriNode.asText();
    }
    String uriPrefix = baseUri;
    if (!baseUri.matches(".*[#/]$")) {
        uriPrefix += "#";
    }

    String entityTypeName = entityType.replace(".json", "");
    String moduleName = "/ext/" + entityTypeName + ".xqy";

    return "import module namespace conv = \"" + uriPrefix + entityTypeName + "\" at \"" + moduleName + "\"; ";
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.services.ElasticsearchIndexService.java

/** Check if a new mapping based on a schema is equivalent to a mapping previously stored (from a schema) 
 * @param stored_mapping/*from  w w  w. j a  v a2s  .  c o  m*/
 * @param new_mapping
 * @param mapper
 * @return
 * @throws JsonProcessingException
 * @throws IOException
 */
protected static boolean mappingsAreEquivalent(final IndexTemplateMetaData stored_mapping,
        final JsonNode new_mapping, final ObjectMapper mapper) throws JsonProcessingException, IOException {

    final ObjectNode stored_json_mappings = StreamSupport.stream(stored_mapping.mappings().spliterator(), false)
            .reduce(mapper.createObjectNode(), Lambdas.wrap_u(
                    (acc, kv) -> (ObjectNode) acc.setAll((ObjectNode) mapper.readTree(kv.value.string()))),
                    (acc1, acc2) -> acc1); // (can't occur)

    final JsonNode new_json_mappings = Optional.ofNullable(new_mapping.get("mappings"))
            .orElse(mapper.createObjectNode());

    final JsonNode stored_json_settings = mapper.convertValue(Optional.ofNullable(stored_mapping.settings())
            .orElse(ImmutableSettings.settingsBuilder().build()).getAsMap(), JsonNode.class);

    final JsonNode new_json_settings = Optional.ofNullable(new_mapping.get("settings"))
            .orElse(mapper.createObjectNode());

    final ObjectNode stored_json_aliases = StreamSupport
            .stream(Optional.ofNullable(
                    stored_mapping.aliases()).orElse(
                            ImmutableOpenMap.of())
                    .spliterator(), false)
            .reduce(mapper.createObjectNode(), Lambdas.wrap_u((acc, kv) -> (ObjectNode) acc.set(kv.key,
                    kv.value.filteringRequired() ? mapper.createObjectNode().set("filter",
                            mapper.readTree(kv.value.filter().string())) : mapper.createObjectNode())),
                    (acc1, acc2) -> acc1); // (can't occur)

    final JsonNode new_json_aliases = Optional.ofNullable(new_mapping.get("aliases"))
            .orElse(mapper.createObjectNode());

    return stored_json_mappings.equals(new_json_mappings) && stored_json_settings.equals(new_json_settings)
            && stored_json_aliases.equals(new_json_aliases);
}

From source file:org.jboss.pnc.environment.docker.DockerEnvironmentDriver.java

/**
 * Get container port mapping from Docker daemon REST interface.
 * //from  w  ww  .j av  a 2 s . c  o m
 * @param containerId ID of running container
 * @return Map with pairs containerPort:publicPort
 * @throws Exception Thrown if data could not be obtained from Docker daemon or are corrupted
 */
private Map<String, HostPortMapping> getContainerPortMappings(String containerId) throws Exception {
    Map<String, HostPortMapping> resultMap = new HashMap<>();
    String response = HttpUtils.processGetRequest(String.class,
            dockerEndpoint + "/containers/" + containerId + "/json");

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootNode = objectMapper.readTree(response);
    JsonNode networkSettingsNode = rootNode.path("NetworkSettings");
    JsonNode portsNode = networkSettingsNode.path("Ports");

    Map<String, List<HostPortMapping>> portsMap = objectMapper.readValue(portsNode.traverse(),
            new TypeReference<Map<String, List<HostPortMapping>>>() {
            });

    for (Map.Entry<String, List<HostPortMapping>> entry : portsMap.entrySet()) {
        resultMap.put(entry.getKey().substring(0, entry.getKey().indexOf("/")), entry.getValue().get(0));
    }

    return resultMap;
}

From source file:com.liferay.sync.engine.documentlibrary.handler.BaseJSONHandler.java

protected String getException(String response) {
    ObjectMapper objectMapper = new ObjectMapper();

    JsonNode responseJsonNode = null;//  ww w  .j av  a  2s . co m

    try {
        response = StringEscapeUtils.unescapeJava(response);

        responseJsonNode = objectMapper.readTree(response);
    } catch (Exception e) {
        return "";
    }

    JsonNode errorJsonNode = responseJsonNode.get("error");

    if (errorJsonNode == null) {
        JsonNode exceptionJsonNode = responseJsonNode.get("exception");

        if (exceptionJsonNode == null) {
            return "";
        }

        return exceptionJsonNode.asText();
    }

    JsonNode typeJsonNode = errorJsonNode.get("type");

    return typeJsonNode.asText();
}