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.n52.tamis.core.json.deserialize.processes.execute.SosTimeseriesInformationDeserializer.java

@Override
public SosTimeseriesInformation deserialize(JsonParser jsonParser, DeserializationContext deserContext)
        throws IOException, JsonProcessingException {
    logger.info("Start deserialization of SOS timeseries output.");

    SosTimeseriesInformation sosInformation = new SosTimeseriesInformation();

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

    /*/*from   ww  w  . jav  a 2  s . co m*/
     * feature of interest
     */
    String featureOfInterest = node.get("station").get("properties").get("id").asText();
    sosInformation.setFeatureOfInterest(featureOfInterest);

    /*
     * SOS base URL
     */
    String baseUrl = node.get("parameters").get("service").get("serviceUrl").asText();
    sosInformation.setSosUrl(baseUrl);

    /*
     * offering id
     */
    String offeringId = node.get("parameters").get("offering").get("id").asText();
    sosInformation.setOfferingId(offeringId);

    /*
     * procedure
     */
    String procedure = node.get("parameters").get("procedure").get("id").asText();
    sosInformation.setProcedure(procedure);

    /*
     * observed property
     */
    String observedProperty = node.get("parameters").get("phenomenon").get("id").asText();
    sosInformation.setObservedProperty(observedProperty);

    /*
     * temporal filter cannot be set. This must happen later!
     */

    logger.info("Deserialization of SOS timeseries output ended. Following object was constructed: \"{}\".",
            sosInformation);

    return sosInformation;
}

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

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

    if (node.get("id") == null) {
        return null;
    }/*from   ww  w.j  av  a 2s.com*/
    return GatewayTable.builder().id(node.get("id").asInt()).build();
}

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

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

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

    // create empty shortened CapabilitiesDocument.
    Processes_Tamis processes_short = new Processes_Tamis();

    /*//from w ww.  j av a 2 s  .c om
     * JSPON element "ProcessSummaries" is an array of process descriptions
     */
    JsonNode processSummaries = node.get("ProcessSummaries");

    transformAndAddProcessSummaries(processes_short, processSummaries);

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

    return processes_short;

}

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

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

    if (node.get("id") == null && node.get("type") == null) {
        return null;
    }/*ww  w  . ja  va 2s  .co m*/

    EXTERNAL_SERVER_TYPE type = EXTERNAL_SERVER_TYPE.fromString(node.get("type").asText());

    ExternalServer externalServer = null;
    switch (type) {
    case PHANT_IO:
        ExternalServerPhantIO extServerPhantIO = new ExternalServerPhantIO();
        extServerPhantIO.setUrl(node.get("url").asText());
        extServerPhantIO.setPublicKey(node.get("publicKey").asText());
        extServerPhantIO.setPrivateKey(node.get("privateKey").asText());
        extServerPhantIO.setTrustHostType(TRUST_HOST_TYPE.fromString(node.get("trustHostType").asText()));
        externalServer = extServerPhantIO;
        break;
    case EMONCMS:
        ExternalServerEmoncms extServerEmoncms = new ExternalServerEmoncms();
        extServerEmoncms.setUrl(node.get("url").asText());
        extServerEmoncms.setWriteApiKey(node.get("writeApiKey").asText());
        extServerEmoncms.setTrustHostType(TRUST_HOST_TYPE.fromString(node.get("trustHostType").asText()));
        externalServer = extServerEmoncms;
        break;
    case INFLUXDB:
        ExternalServerInfluxdb extServerInfluxdb = new ExternalServerInfluxdb();
        extServerInfluxdb.setUrl(node.get("url").asText());
        extServerInfluxdb.setDatabase(node.get("database").asText());
        if (node.get("username") != null) {
            extServerInfluxdb.setUsername(node.get("username").asText());
            extServerInfluxdb.setPassword(node.get("password").asText());
        }
        if (node.get("tags") != null) {
            extServerInfluxdb.setTags(node.get("tags").asText());
        }
        extServerInfluxdb.setTrustHostType(TRUST_HOST_TYPE.fromString(node.get("trustHostType").asText()));
        externalServer = extServerInfluxdb;
        break;
    default:
        break;
    }
    //Update RuleDefinition details
    if (node.get("id") != null) {
        externalServer.setId(node.get("id").asInt());
    }
    externalServer.setKeyFormat(node.get("keyFormat").asText());
    externalServer.setEnabled(node.get("enabled").asBoolean());
    externalServer.setName(node.get("name").asText());
    externalServer.setType(type);
    return externalServer;
}

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

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

    final ObjectCodec oc = jp.getCodec();

    if (oc == null) {

        return null;
    }// www .  j a  va 2 s.  c  om

    final JsonNode node = oc.readTree(jp);

    if (node == null) {

        return null;
    }

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

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

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

        return null;
    }

    final Model model = new Model();

    for (final JsonNode resourceNode : node) {

        final Resource resource = resourceNode.traverse(oc).readValueAs(Resource.class);
        model.addResource(resource);
    }

    return model;
}

From source file:org.dswarm.common.model.deserializer.ContentSchemaDeserializer.java

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

    final ObjectCodec oc = jp.getCodec();

    if (oc == null) {

        return null;
    }/*from w w w  .  jav  a  2 s  . com*/

    final JsonNode node = oc.readTree(jp);

    if (node == null) {

        return null;
    }

    final JsonNode recordIdentifierAttributePathNode = node.get("record_identifier_attribute_path");
    final AttributePath recordIdentifierAttributePath = AttributePathUtil
            .parseAttributePathNode(recordIdentifierAttributePathNode, attributeMap, attributePathMap);

    final JsonNode keyAttributePathsNode = node.get("key_attribute_paths");
    final LinkedList<AttributePath> keyAttributePaths = AttributePathUtil
            .parseAttributePathsNode(keyAttributePathsNode, attributeMap, attributePathMap);

    final JsonNode valueAttributePathNode = node.get("value_attribute_path");
    final AttributePath valueAttributePath = AttributePathUtil.parseAttributePathNode(valueAttributePathNode,
            attributeMap, attributePathMap);

    return new ContentSchema(recordIdentifierAttributePath, keyAttributePaths, valueAttributePath);
}

From source file:org.numenta.nupic.algorithms.CLAClassifierDeserializer.java

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

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

    CLAClassifier retVal = new CLAClassifier();
    retVal.alpha = node.get("alpha").asDouble();
    retVal.actValueAlpha = node.get("actValueAlpha").asDouble();
    retVal.learnIteration = node.get("learnIteration").asInt();
    retVal.recordNumMinusLearnIteration = node.get("recordNumMinusLearnIteration").asInt();
    retVal.maxBucketIdx = node.get("maxBucketIdx").asInt();

    String[] steps = node.get("steps").asText().split(",");
    TIntList t = new TIntArrayList();
    for (String step : steps) {
        t.add(Integer.parseInt(step));
    }//ww w .  j  a v  a  2 s. c o  m
    retVal.steps = t;

    String[] tupleStrs = node.get("patternNZHistory").asText().split(";");
    Deque<Tuple> patterns = new Deque<Tuple>(tupleStrs.length);
    for (String tupleStr : tupleStrs) {
        String[] tupleParts = tupleStr.split("-");
        int iteration = Integer.parseInt(tupleParts[0]);
        String pattern = tupleParts[1].substring(1, tupleParts[1].indexOf("]")).trim();
        String[] indexes = pattern.split(",");
        int[] indices = new int[indexes.length];
        for (int i = 0; i < indices.length; i++) {
            indices[i] = Integer.parseInt(indexes[i].trim());
        }
        Tuple tup = new Tuple(iteration, indices);
        patterns.append(tup);
    }
    retVal.patternNZHistory = patterns;

    Map<Tuple, BitHistory> bitHistoryMap = new HashMap<Tuple, BitHistory>();
    String[] bithists = node.get("activeBitHistory").asText().split(";");
    for (String bh : bithists) {
        String[] parts = bh.split("-");

        String[] left = parts[0].split(",");
        Tuple iteration = new Tuple(Integer.parseInt(left[0].trim()), Integer.parseInt(left[1].trim()));

        BitHistory bitHistory = new BitHistory();
        String[] right = parts[1].split("=");
        bitHistory.id = right[0].trim();

        TDoubleList dubs = new TDoubleArrayList();
        String[] stats = right[1].substring(1, right[1].indexOf("}")).trim().split(",");
        for (int i = 0; i < stats.length; i++) {
            dubs.add(Double.parseDouble(stats[i].trim()));
        }
        bitHistory.stats = dubs;

        bitHistory.lastTotalUpdate = Integer.parseInt(right[2].trim());

        bitHistoryMap.put(iteration, bitHistory);
    }
    retVal.activeBitHistory = bitHistoryMap;

    ArrayNode jn = (ArrayNode) node.get("actualValues");
    List<Object> l = new ArrayList<Object>();
    for (int i = 0; i < jn.size(); i++) {
        JsonNode n = jn.get(i);
        try {
            double d = Double.parseDouble(n.asText().trim());
            l.add(d);
        } catch (Exception e) {
            l.add(n.asText().trim());
        }
    }
    retVal.actualValues = l;

    //Go back and set the classifier on the BitHistory objects
    for (Tuple tuple : bitHistoryMap.keySet()) {
        bitHistoryMap.get(tuple).classifier = retVal;
    }

    return retVal;
}

From source file:org.n52.tamis.core.json.deserialize.capabilities.CapabilitiesDeserializer.java

/**
 * Parses the extended capabilities document and creates the shortened
 * document as instance of {@link Capabilities_Tamis}.
 *///  w  ww .  j  a va 2s . c o  m
@Override
public Capabilities_Tamis deserialize(JsonParser jsonParser, DeserializationContext desContext)
        throws IOException, JsonProcessingException {
    logger.info("Start deserialization of extended WPS capabilities document.");

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

    // create empty shortened CapabilitiesDocument.
    Capabilities_Tamis capabilities_short = new Capabilities_Tamis();

    /*
     * id
     * 
     * TODO FIXME how to determine the id?
     */
    JsonNode capabilitiesNode = node.get("Capabilities");
    JsonNode serviceIdentificationNode = capabilitiesNode.get("ServiceIdentification");

    capabilities_short.setId(SERVICE_ID_CONSTANT);

    /*
     * label
     */
    String title = serviceIdentificationNode.get("Title").asText();

    capabilities_short.setLabel(title);

    /*
     * type
     */
    String serviceType = serviceIdentificationNode.get("ServiceType").asText();

    capabilities_short.setType(serviceType);

    /*
     * url
     * 
     * url is not set here! Insteadt URL will be set by
     * CapabilitiesForwarder, since there the baseURL can be extracted from
     * the HttpServletRequest object.
     */

    /*
     * e-mail contact
     */
    JsonNode serviceContact = capabilitiesNode.get("ServiceProvider").get("ServiceContact");
    JsonNode contactInfo = serviceContact.get("ContactInfo");

    if (contactInfo.has("Address")) {
        JsonNode address = contactInfo.get("Address");

        if (address.has("ElectronicMailAddress")) {
            String mailAdress = address.get("ElectronicMailAddress").asText();
            capabilities_short.setContact(mailAdress);
        }
    }

    else if (serviceContact.has("IndividualName"))
        capabilities_short.setContact(serviceContact.get("IndividualName").asText());

    else
        capabilities_short.setContact("N/A");

    logger.info("Deserialization ended! The following capabilities instance was created: {}",
            capabilities_short);

    return capabilities_short;
}

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

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

    if (node.get("id") == null && node.get("type") == null) {
        return null;
    }/*from w  w  w  .j  av a  2 s  .c  o m*/

    GATEWAY_TYPE gatewayType = GATEWAY_TYPE.fromString(node.get("type").asText());

    Gateway gateway = null;
    switch (gatewayType) {
    case SERIAL:
        GatewaySerial gatewaySerial = new GatewaySerial();
        gatewaySerial.setDriver(SERIAL_PORT_DRIVER.fromString(node.get("driver").asText()));
        gatewaySerial.setPortName(node.get("portName").asText());
        gatewaySerial.setBaudRate(node.get("baudRate").asInt());
        gatewaySerial.setRetryFrequency(node.get("retryFrequency").asLong());
        gateway = gatewaySerial;
        break;
    case ETHERNET:
        GatewayEthernet gatewayEthernet = new GatewayEthernet();
        gatewayEthernet.setHost(node.get("host").asText());
        gatewayEthernet.setPort(node.get("port").asInt());
        gatewayEthernet.setAliveFrequency(node.get("aliveFrequency").asLong());
        gateway = gatewayEthernet;
        break;
    case MQTT:
        GatewayMQTT gatewayMQTT = new GatewayMQTT();
        gatewayMQTT.setBrokerHost(node.get("brokerHost").asText());
        gatewayMQTT.setClientId(node.get("clientId").asText());
        gatewayMQTT.setTopicsPublish(node.get("topicsPublish").asText());
        gatewayMQTT.setTopicsSubscribe(node.get("topicsSubscribe").asText());
        gatewayMQTT.setUsername(node.get("username").asText());
        gatewayMQTT.setPassword(node.get("password").asText());
        gateway = gatewayMQTT;
        break;
    case PHANT_IO:
        GatewayPhantIO gatewayPhantIO = new GatewayPhantIO();
        gatewayPhantIO.setUrl(node.get("url").asText());
        gatewayPhantIO.setTrustHostType(TRUST_HOST_TYPE.fromString(node.get("trustHostType").asText()));
        gatewayPhantIO.setPublicKey(node.get("publicKey").asText());
        if (node.get("privateKey") != null) {
            gatewayPhantIO.setPrivateKey(node.get("privateKey").asText());
        }
        gatewayPhantIO.setPollFrequency(node.get("pollFrequency").asInt());
        gatewayPhantIO.setRecordsLimit(node.get("recordsLimit").asLong());
        gatewayPhantIO.setLastUpdate(System.currentTimeMillis() - (McUtils.SECOND * 10));
        gateway = gatewayPhantIO;
    default:
        break;
    }
    //Update RuleDefinition details
    if (node.get("id") != null) {
        gateway.setId(node.get("id").asInt());
    }
    gateway.setEnabled(node.get("enabled").asBoolean());
    gateway.setName(node.get("name").asText());
    gateway.setType(gatewayType);
    gateway.setNetworkType(NETWORK_TYPE.fromString(node.get("networkType").asText()));
    return gateway;
}

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

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

    OPERATION_TYPE operationType = OPERATION_TYPE.fromString(node.get("type").asText());

    Operation operation = null;//from   w  ww .  j  a v a2  s  .  c  om
    switch (operationType) {
    case EXECUTE_SCRIPT:
        OperationExecuteScript operationExecuteScript = new OperationExecuteScript();
        operationExecuteScript.setScriptFile(node.get("scriptFile").asText());
        if (node.get("scriptBindings") != null) {
            operationExecuteScript.setScriptBindings(RestUtils.getObjectMapper()
                    .convertValue(node.get("scriptBindings"), new TypeReference<HashMap<String, Object>>() {
                    }));
        }
        operation = operationExecuteScript;
        break;
    case SEND_EMAIL:
        OperationSendEmail operationSendEmail = new OperationSendEmail();
        operationSendEmail.setEmailSubject(node.get("emailSubject").asText());
        operationSendEmail.setToEmailAddresses(node.get("toEmailAddresses").asText());
        operationSendEmail.setTemplate(node.get("template").asText());
        operation = operationSendEmail;
        break;
    case SEND_PAYLOAD:
        OperationSendPayload operationSendPayload = new OperationSendPayload();
        operationSendPayload.setResourceType(RESOURCE_TYPE.fromString(node.get("resourceType").asText()));
        operationSendPayload.setResourceId(node.get("resourceId").asInt());
        operationSendPayload.setPayload(node.get("payload").asText());
        if (node.get("delayTime") != null) {
            operationSendPayload.setDelayTime(node.get("delayTime").asLong());
        } else {
            operationSendPayload.setDelayTime(0L);
        }
        operation = operationSendPayload;
        break;
    case REQUEST_PAYLOAD:
        OperationRequestPayload operationRequestPayload = new OperationRequestPayload();
        operationRequestPayload.setResourceType(RESOURCE_TYPE.fromString(node.get("resourceType").asText()));
        operationRequestPayload.setResourceId(node.get("resourceId").asInt());
        operation = operationRequestPayload;
        break;
    case SEND_PUSHBULLET_NOTE:
        OperationSendPushbulletNote operationSendPushbulletNote = new OperationSendPushbulletNote();
        operationSendPushbulletNote.setTitle(node.get("title").asText());
        if (node.get("idens") != null) {
            operationSendPushbulletNote.setIdens(node.get("idens").asText());
        }
        if (node.get("body") != null) {
            operationSendPushbulletNote.setBody(node.get("body").asText());
        }
        operation = operationSendPushbulletNote;
        break;
    case SEND_SMS:
        OperationSendSMS operationSendSMS = new OperationSendSMS();
        operationSendSMS.setToPhoneNumbers(node.get("toPhoneNumbers").asText());
        operationSendSMS.setCustomMessage(node.get("customMessage").asText());
        operation = operationSendSMS;
        break;
    default:
        break;
    }
    //Update RuleDefinition details
    if (node.get("id") != null) {
        operation.setId(node.get("id").asInt());
    }
    operation.setEnabled(node.get("enabled").asBoolean());
    operation.setName(node.get("name").asText());
    operation.setType(operationType);
    //operation.setUser(User.builder().id(node.get("user").get("id").intValue()).build());
    return operation;
}