Example usage for com.fasterxml.jackson.core ObjectCodec readTree

List of usage examples for com.fasterxml.jackson.core ObjectCodec readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core ObjectCodec readTree.

Prototype

public abstract <T extends TreeNode> T readTree(JsonParser jp) throws IOException, JsonProcessingException;

Source Link

Document

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

Usage

From source file:org.dswarm.graph.json.deserializer.ResourceDeserializer.java

@Override
public Resource deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectCodec oc = jp.getCodec();

    if (oc == null) {

        return null;
    }//from   w  ww  . j ava  2 s. c o m

    final JsonNode node = oc.readTree(jp);

    if (node == null) {

        return null;
    }

    final Iterator<String> resourceUriFieldNames = node.fieldNames();

    if (resourceUriFieldNames == null || !resourceUriFieldNames.hasNext()) {

        return null;
    }

    final String resourceUri = resourceUriFieldNames.next();

    if (resourceUri == null) {

        return null;
    }

    final JsonNode resourceNode = node.get(resourceUri);

    if (resourceNode == null) {

        return null;
    }

    if (!ArrayNode.class.isInstance(resourceNode)) {

        throw new JsonParseException("expected a JSON array full of statement objects of the resource",
                jp.getCurrentLocation());
    }

    final Resource resource = new Resource(resourceUri);

    if (resourceNode.size() <= 0) {

        return resource;
    }

    for (final JsonNode statementNode : resourceNode) {

        final Statement statement = statementNode.traverse(oc).readValueAs(Statement.class);
        resource.addStatement(statement);
    }

    return resource;
}

From source file:com.pkrete.locationservice.admin.deserializers.OwnerJSONDeserializer.java

@Override
public Owner deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {

    LocatingStrategy strategy = null;//w  w  w . j a v  a2s  . c  om
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    // Parse id
    int id = node.get("id") == null ? 0 : node.get("id").intValue();
    // Parse code
    String code = node.get("code") == null ? "" : node.get("code").textValue();
    // Parse name
    String name = node.get("name") == null ? "" : node.get("name").textValue();
    // Parse color
    String color = node.get("color") == null ? "" : node.get("color").textValue();
    // Parse opacity
    String opacity = node.get("opacity") == null ? "" : node.get("opacity").textValue();
    // Parse locating strategy
    String strategyStr = node.get("locating_strategy") == null ? null
            : node.get("locating_strategy").textValue();
    // If strategyStr not null, convert from string to LocatingStrategy object
    if (strategyStr != null) {
        // Get converterService bean from Application Context
        ConverterService converterService = (ConverterService) ApplicationContextUtils.getApplicationContext()
                .getBean("converterService");
        // Convert strategyStr to LocatingStrategy object
        strategy = (LocatingStrategy) converterService.convert(strategyStr, LocatingStrategy.class,
                LocatingStrategy.INDEX);
    }
    // String for ip addresses
    String ips = null;
    // Does allowed_ips node exist
    if (node.path("allowed_ips") != null) {
        // Parse allowed ip addresses
        Iterator<JsonNode> ite = node.path("allowed_ips").elements();
        // Init ips variable
        ips = "";
        // Iterate ips
        while (ite.hasNext()) {
            // Get next ip node
            JsonNode temp = ite.next();
            // Add ip to the ips string
            ips += temp.textValue();
            // Add line break, if there are more ips to read
            if (ite.hasNext()) {
                ips += "\n";
            }
        }
    }
    // Variables for redirects
    List<PreprocessingRedirect> preprocessingRedirect = null;
    List<NotFoundRedirect> notFoundRedirect = null;

    // Does redirects node exist
    if (node.path("redirects") != null) {
        preprocessingRedirect = new ArrayList<PreprocessingRedirect>();
        notFoundRedirect = new ArrayList<NotFoundRedirect>();
        // Parse redirects
        Iterator<JsonNode> ite = node.path("redirects").elements();
        // Iterate redirects
        while (ite.hasNext()) {
            // Get next redirect
            JsonNode temp = ite.next();
            // Parse id
            int redirectId = temp.get("id") == null ? 0 : temp.get("id").intValue();
            // Parse type
            String redirectType = temp.get("type") == null ? "" : temp.get("type").textValue();
            // Parse operation
            String condition = temp.get("condition") == null ? "" : temp.get("condition").textValue();
            // Parse operation
            String operation = temp.get("operation") == null ? "" : temp.get("operation").textValue();
            // Is active
            boolean redirectActive = true;
            if (temp.get("is_active") != null) {
                // Parse is_active
                redirectActive = temp.get("is_active").asBoolean();
            }
            CallnoModification redirect = null;
            if (redirectType.equalsIgnoreCase("PREPROCESS")) {
                redirect = new PreprocessingRedirect();
            } else if (redirectType.equalsIgnoreCase("NOTFOUND")) {
                redirect = new NotFoundRedirect();
            } else {
                continue;
            }
            redirect.setId(redirectId);
            redirect.setCondition(condition);
            redirect.setOperation(operation);
            redirect.setIsActive(redirectActive);
            if (redirectType.equalsIgnoreCase("PREPROCESS")) {
                preprocessingRedirect.add((PreprocessingRedirect) redirect);
            } else if (redirectType.equalsIgnoreCase("NOTFOUND")) {
                notFoundRedirect.add((NotFoundRedirect) redirect);
            }
        }
    }
    // Create new Owner object
    Owner owner = new Owner(code, name);
    // Set values
    owner.setPreprocessingRedirects(preprocessingRedirect);
    owner.setNotFoundRedirects(notFoundRedirect);
    owner.setColor(color);
    owner.setOpacity(opacity);
    owner.setLocatingStrategy(strategy);
    owner.setAllowedIPs(ips);
    if (node.get("exporter_visible") != null && node.get("exporter_visible").booleanValue()) {
        // Parse exporter visible
        owner.setExporterVisible(node.get("exporter_visible").asBoolean());
    }
    // Return Owner
    return owner;
}

From source file:org.mycontroller.standalone.api.jaxrs.mixins.RuleDefinitionMixin.java

@Override
public RuleDefinition deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectCodec objectCodec = jp.getCodec();
    JsonNode node = objectCodec.readTree(jp);

    CONDITION_TYPE conditionType = CONDITION_TYPE.fromString(node.get("conditionType").asText());
    DAMPENING_TYPE dampeningType = DAMPENING_TYPE.fromString(node.get("dampeningType").asText());

    RuleDefinition ruleDefinition = null;
    switch (conditionType) {
    case THRESHOLD:
        RuleDefinitionThreshold ruleDefinitionThreshold = new RuleDefinitionThreshold();
        ruleDefinitionThreshold.setOperator(OPERATOR.fromString(node.get("operator").asText()));
        ruleDefinitionThreshold.setDataType(DATA_TYPE.fromString(node.get("dataType").asText()));
        ruleDefinitionThreshold.setData(node.get("data").asText());
        ruleDefinition = ruleDefinitionThreshold;
        break;/*from  w  w  w. j a  v  a  2  s  .co m*/
    case THRESHOLD_RANGE:
        RuleDefinitionThresholdRange thresholdRange = new RuleDefinitionThresholdRange();
        thresholdRange.setInRange(node.get("inRange").booleanValue());
        thresholdRange.setIncludeOperatorLow(node.get("includeOperatorLow").asBoolean());
        thresholdRange.setIncludeOperatorHigh(node.get("includeOperatorHigh").asBoolean());
        thresholdRange.setThresholdLow(node.get("thresholdLow").asDouble());
        thresholdRange.setThresholdHigh(node.get("thresholdHigh").asDouble());
        ruleDefinition = thresholdRange;
        break;
    case COMPARE:
        RuleDefinitionCompare definitionCompare = new RuleDefinitionCompare();
        definitionCompare.setOperator(OPERATOR.fromString(node.get("operator").asText()));
        definitionCompare
                .setData2ResourceType(RESOURCE_TYPE.fromString(node.get("data2ResourceType").asText()));
        definitionCompare.setData2ResourceId(node.get("data2ResourceId").asInt());
        definitionCompare.setData2Multiplier(node.get("data2Multiplier").asDouble());
        ruleDefinition = definitionCompare;
        break;
    case STRING:
        RuleDefinitionString ruleDefinitionString = new RuleDefinitionString();
        ruleDefinitionString.setOperator(STRING_OPERATOR.fromString(node.get("operator").asText()));
        ruleDefinitionString.setPattern(node.get("pattern").asText());
        ruleDefinitionString.setIgnoreCase(node.get("ignoreCase").asBoolean());
        ruleDefinition = ruleDefinitionString;
        break;
    case STATE:
        RuleDefinitionState ruleDefinitionState = new RuleDefinitionState();
        ruleDefinitionState.setOperator(OPERATOR.fromString(node.get("operator").asText()));
        ruleDefinitionState.setState(STATE.fromString(node.get("state").asText()));
        ruleDefinition = ruleDefinitionState;
        break;
    case SCRIPT:
        RuleDefinitionScript ruleDefinitionScript = new RuleDefinitionScript();
        ruleDefinitionScript.setScriptFile(node.get("scriptFile").asText());
        if (node.get("scriptBindings") != null) {
            ruleDefinitionScript.setScriptBindings(RestUtils.getObjectMapper()
                    .convertValue(node.get("scriptBindings"), new TypeReference<HashMap<String, Object>>() {
                    }));
        }
        ruleDefinition = ruleDefinitionScript;
        break;
    default:

        break;
    }
    //Update RuleDefinition details
    if (node.get("id") != null) {
        ruleDefinition.setId(node.get("id").asInt());
    }
    ruleDefinition.setEnabled(node.get("enabled").asBoolean());
    ruleDefinition.setDisableWhenTrigger(node.get("disableWhenTrigger").asBoolean());
    ruleDefinition.setName(node.get("name").asText());
    ruleDefinition.setResourceType(RESOURCE_TYPE.fromString(node.get("resourceType").asText()));
    if (conditionType != CONDITION_TYPE.SCRIPT) {
        ruleDefinition.setResourceId(node.get("resourceId").asInt());
    } else {
        //For resource script file name will be reference. keep resourceId as -1
        ruleDefinition.setResourceId(-1);
    }
    ruleDefinition.setConditionType(conditionType);
    ruleDefinition.setIgnoreDuplicate(node.get("ignoreDuplicate").asBoolean());
    //ruleDefinition.setTriggered(node.get("triggered").booleanValue());
    List<Integer> operationIds = new ArrayList<>();
    if (node.get("operationIds") != null) {
        if (node.get("operationIds").isArray()) {
            for (final JsonNode nodeOperationId : node.get("operationIds")) {
                operationIds.add(nodeOperationId.asInt());
            }
        }
    }
    ruleDefinition.setOperationIds(operationIds);
    ruleDefinition.setDampeningType(DAMPENING_TYPE.fromString(node.get("dampeningType").asText()));

    Dampening dampening = null;

    JsonNode dampeningNode = node.get("dampening");

    switch (dampeningType) {
    case CONSECUTIVE:
        DampeningConsecutive dampeningConsecutive = new DampeningConsecutive();
        dampeningConsecutive.setConsecutiveMax(dampeningNode.get("consecutiveMax").asInt());
        dampening = dampeningConsecutive;
        break;
    case ACTIVE_TIME:
        DampeningActiveTime dampeningActiveTime = new DampeningActiveTime();
        dampeningActiveTime.setActiveTime(dampeningNode.get("activeTime").asLong());
        dampening = dampeningActiveTime;
        break;
    case LAST_N_EVALUATIONS:
        DampeningLastNEvaluations lastNEvaluations = new DampeningLastNEvaluations();
        lastNEvaluations.setOccurrencesMax(dampeningNode.get("occurrencesMax").asInt());
        lastNEvaluations.setEvaluationsMax(dampeningNode.get("evaluationsMax").asInt());
        dampening = lastNEvaluations;
        break;
    case NONE:
        DampeningNone dampeningNone = new DampeningNone();
        dampening = dampeningNone;
    default:
        break;
    }
    if (dampening != null) {
        dampening.setType(dampeningType);
        ruleDefinition.setDampening(dampening);
    }
    return ruleDefinition;
}

From source file:org.n52.tamis.core.json.deserialize.processes.SingleProcessDescriptionDeserializer.java

@Override
public ProcessDescription_singleProcess deserialize(JsonParser jsonParser, DeserializationContext arg1)
        throws IOException, JsonProcessingException {
    logger.info("Start deserialization of extended WPS singleProcessDescription document.");

    // initialization
    ObjectCodec codec = jsonParser.getCodec();
    JsonNode node = codec.readTree(jsonParser);

    // create empty shortened CapabilitiesDocument.
    ProcessDescription_singleProcess singleProcessDescription_short = new ProcessDescription_singleProcess();

    /*/*  w  ww . j  a  v  a2s  .c o m*/
     * JSPON element "ProcessSummaries" is an array of process descriptions
     */
    JsonNode process = node.get("ProcessOffering").get("Process");

    /*
     * label
     */
    singleProcessDescription_short.setLabel(process.get("Title").asText());

    /*
     * ID
     */
    singleProcessDescription_short.setId(process.get("Identifier").asText());

    /*
     * description
     */
    if (process.has("Abstract"))
        singleProcessDescription_short.setDescription(process.get("Abstract").asText());
    else {
        // just set the title/label as description
        singleProcessDescription_short.setDescription(singleProcessDescription_short.getLabel());
    }

    // array of Input elements
    JsonNode inputs = process.get("Input");

    transformAndAddInputs(singleProcessDescription_short, inputs);

    /*
     * TODO are multiple outputs possible?
     */
    JsonNode outputs = process.get("Output");

    transformAndAddOutputs(singleProcessDescription_short, outputs);

    logger.info("Deserialization ended! The following processes description instance was created: {}",
            singleProcessDescription_short);

    return singleProcessDescription_short;
}

From source file:org.dswarm.graph.json.deserializer.StatementDeserializer.java

@Override
public Statement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {

    final ObjectCodec oc = jp.getCodec();

    if (oc == null) {

        return null;
    }//from   w w  w  . j a  v  a2  s.  co  m

    final JsonNode node = oc.readTree(jp);

    if (node == null) {

        return null;
    }

    final JsonNode idNode = node.get("id");

    Long id = null;

    if (idNode != null) {

        try {

            id = idNode.asLong();
        } catch (final Exception e) {

            id = null;
        }
    }

    final JsonNode uuidNode = node.get("uuid");

    String uuid = null;

    if (uuidNode != null && JsonNodeType.NULL != uuidNode.getNodeType()) {

        uuid = uuidNode.asText();
    }

    final JsonNode subjectNode = node.get("s");

    if (subjectNode == null) {

        throw new JsonParseException("expected JSON node that represents the subject of a statement",
                jp.getCurrentLocation());
    }

    final Node subject;

    if (subjectNode.get("uri") != null) {

        // resource node
        subject = subjectNode.traverse(oc).readValueAs(ResourceNode.class);
    } else {

        // bnode
        subject = subjectNode.traverse(oc).readValueAs(Node.class);
    }

    final JsonNode predicateNode = node.get("p");

    if (predicateNode == null) {

        throw new JsonParseException("expected JSON node that represents the predicate of a statement",
                jp.getCurrentLocation());
    }

    final Predicate predicate = predicateNode.traverse(oc).readValueAs(Predicate.class);

    final JsonNode objectNode = node.get("o");

    if (objectNode == null) {

        throw new JsonParseException("expected JSON node that represents the object of a statement",
                jp.getCurrentLocation());
    }

    final Node object;

    if (objectNode.get("uri") != null) {

        // resource node
        object = objectNode.traverse(oc).readValueAs(ResourceNode.class);
    } else if (objectNode.get("v") != null) {

        // literal node
        object = objectNode.traverse(oc).readValueAs(LiteralNode.class);
    } else {

        // bnode
        object = objectNode.traverse(oc).readValueAs(Node.class);
    }

    final JsonNode orderNode = node.get("order");

    Long order = null;

    if (orderNode != null) {

        try {

            order = orderNode.asLong();
        } catch (final Exception e) {

            order = null;
        }
    }

    final JsonNode evidenceNode = node.get("evidence");

    String evidence = null;

    if (evidenceNode != null) {

        evidence = evidenceNode.asText();
    }

    final JsonNode confidenceNode = node.get("confidence");

    String confidence = null;

    if (confidenceNode != null) {

        confidence = confidenceNode.asText();
    }

    final Statement statement = new Statement(subject, predicate, object);

    if (id != null) {

        statement.setId(id);
    }

    if (uuid != null) {

        statement.setUUID(uuid);
    }

    if (order != null) {

        statement.setOrder(order);
    }

    if (evidence != null) {

        statement.setEvidence(evidence);
    }

    if (confidence != null) {

        statement.setConfidence(confidence);
    }

    return statement;
}

From source file:eu.europa.ec.fisheries.uvms.reporting.service.util.ReportDeserializer.java

@Override
public ReportDTO deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {

    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);

    ReportTypeEnum reportTypeEnum = node.get(REPORT_TYPE) != null
            ? ReportTypeEnum.getReportTypeEnum(node.get(REPORT_TYPE).textValue())
            : ReportTypeEnum.STANDARD;//from   ww w.  j  a v  a  2s . com

    List<FilterDTO> filterDTOList = new ArrayList<>();

    JsonNode reportIdNode = node.get(ID);
    Long reportId = null;
    if (reportIdNode != null) {
        reportId = reportIdNode.longValue();
    }

    JsonNode filterNode = node.get(FILTER_EXPRESSION);

    if (filterNode != null) {
        addVmsFilters(filterNode.get("vms"), filterDTOList, reportId);
        addAssets(filterNode.get(ASSETS), filterDTOList, reportId);
        addArea(filterNode.get("areas"), filterDTOList, reportId);
        addCommon(filterNode.get("common"), filterDTOList, reportId);
        addFaFilters(filterNode.get("fa"), filterDTOList, reportId);
        if (ReportTypeEnum.SUMMARY.equals(reportTypeEnum)) {
            addGroupCriteria(filterNode.get("criteria"), filterDTOList, reportId, jsonParser);
        }
    }

    boolean withMap = false;
    JsonNode witMapNode = node.get(WITH_MAP);
    if (witMapNode != null) {
        withMap = witMapNode.booleanValue();
    }

    VisibilityEnum visibilityEnum = null;
    JsonNode visibilityNode = node.get(VISIBILITY);
    if (visibilityNode != null) {
        String s = visibilityNode.textValue();
        if (s != null) {
            visibilityEnum = VisibilityEnum.valueOf(s.toUpperCase());
        }
    }

    String nameValue = null;
    JsonNode nameNode = node.get(NAME);
    if (nameNode != null) {
        nameValue = nameNode.textValue();
    }

    JsonNode createdOnNode = node.get(CREATED_ON);
    String createdOnValue = null;
    if (createdOnNode != null) {
        createdOnValue = createdOnNode.textValue();
    }

    JsonNode editableNode = node.get("editable");
    boolean editableValue = false;
    if (createdOnNode != null) {
        editableValue = editableNode.booleanValue();
    }

    ReportDTO build = ReportDTO.builder()
            .description(node.get(DESC) != null ? node.get(DESC).textValue() : null)
            .id(node.get(ID) != null ? node.get(ID).longValue() : null).name(nameValue).withMap(withMap)
            .createdBy(node.get(CREATED_BY) != null ? node.get(CREATED_BY).textValue() : null)
            .filters(filterDTOList).visibility(visibilityEnum)
            .mapConfiguration(createMapConfigurationDTO(withMap, node.get(MAP_CONFIGURATION))).build();
    build.setReportTypeEnum(reportTypeEnum);
    build.setAudit(new AuditDTO(createdOnValue));
    build.setEditable(editableValue);
    return build;
}