List of usage examples for com.fasterxml.jackson.core JsonParser getCodec
public abstract ObjectCodec getCodec();
From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertyDeserializer.java
@Override protected JSONProperty doDeserializeV3(final JsonParser parser, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser); final JSONProperty property = new JSONProperty(); if (tree.hasNonNull(ODataConstants.JSON_METADATA)) { property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue())); tree.remove(ODataConstants.JSON_METADATA); }// www . ja v a2 s.c o m try { final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.newDocument(); Element content = document.createElement(ODataConstants.ELEM_PROPERTY); if (property.getMetadata() != null) { final String metadataURI = property.getMetadata().toASCIIString(); final int dashIdx = metadataURI.lastIndexOf('#'); if (dashIdx != -1) { content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1)); } } JsonNode subtree = null; if (tree.has(ODataConstants.JSON_VALUE)) { if (tree.has(ODataConstants.JSON_TYPE) && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText()); } final JsonNode value = tree.get(ODataConstants.JSON_VALUE); if (value.isValueNode()) { content.appendChild(document.createTextNode(value.asText())); } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { subtree = tree.objectNode(); ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE)); if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE)); } } else { subtree = tree.get(ODataConstants.JSON_VALUE); } } else { subtree = tree; } if (subtree != null) { DOMTreeUtilsV3.buildSubtree(content, subtree); } final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE); if (children.size() == 1) { final Element value = (Element) children.iterator().next(); if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) { if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { value.setAttribute(ODataConstants.ATTR_M_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE)); } content = value; } } property.setContent(content); } catch (ParserConfigurationException e) { throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e); } return property; }
From source file:com.github.jonpeterson.jackson.module.interceptor.JsonInterceptingDeserializer.java
@Override public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { JsonNode jsonNode = parser.readValueAsTree(); for (JsonInterceptor interceptor : interceptors) jsonNode = interceptor.intercept(jsonNode, context.getNodeFactory()); JsonParser postInterceptionParser = new TreeTraversingParser(jsonNode, parser.getCodec()); postInterceptionParser.nextToken();/* w w w . j a va 2 s .c o m*/ return delegate.deserialize(postInterceptionParser, context); }
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 av a 2 s . co m*/ 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.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 ww w . j a v a 2 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: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}. *///from w ww.j a va 2s .co 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.apache.streams.jackson.MemoryUsageDeserializer.java
@Override public MemoryUsageBroadcast deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { try {// ww w .ja v a 2s . co m MBeanServer server = ManagementFactory.getPlatformMBeanServer(); MemoryUsageBroadcast memoryUsageBroadcast = new MemoryUsageBroadcast(); JsonNode attributes = jsonParser.getCodec().readTree(jsonParser); ObjectName name = new ObjectName(attributes.get("canonicalName").asText()); MBeanInfo info = server.getMBeanInfo(name); memoryUsageBroadcast.setName(name.toString()); for (MBeanAttributeInfo attribute : Arrays.asList(info.getAttributes())) { switch (attribute.getName()) { case "Verbose": memoryUsageBroadcast.setVerbose((boolean) server.getAttribute(name, attribute.getName())); break; case "ObjectPendingFinalizationCount": memoryUsageBroadcast.setObjectPendingFinalizationCount( Long.parseLong(server.getAttribute(name, attribute.getName()).toString())); break; case "HeapMemoryUsage": memoryUsageBroadcast.setHeapMemoryUsage( (Long) ((CompositeDataSupport) server.getAttribute(name, attribute.getName())) .get("used")); break; case "NonHeapMemoryUsage": memoryUsageBroadcast.setNonHeapMemoryUsage( (Long) ((CompositeDataSupport) server.getAttribute(name, attribute.getName())) .get("used")); break; } } return memoryUsageBroadcast; } catch (Exception e) { LOGGER.error("Exception trying to deserialize MemoryUsageDeserializer object: {}", e); return null; } }
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 ww w. j a va 2s. c o 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.apache.streams.jackson.DatumStatusCounterDeserializer.java
@Override public DatumStatusCounterBroadcast deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { try {/*from ww w .jav a2s.c om*/ MBeanServer server = ManagementFactory.getPlatformMBeanServer(); DatumStatusCounterBroadcast datumStatusCounterBroadcast = new DatumStatusCounterBroadcast(); JsonNode attributes = jsonParser.getCodec().readTree(jsonParser); ObjectName name = new ObjectName(attributes.get("canonicalName").asText()); MBeanInfo info = server.getMBeanInfo(name); datumStatusCounterBroadcast.setName(name.toString()); for (MBeanAttributeInfo attribute : Arrays.asList(info.getAttributes())) { try { switch (attribute.getName()) { case "Failed": datumStatusCounterBroadcast .setFailed((boolean) server.getAttribute(name, attribute.getName())); break; case "Passed": datumStatusCounterBroadcast .setPassed((boolean) server.getAttribute(name, attribute.getName())); break; } } catch (Exception e) { LOGGER.error("Exception trying to deserialize DatumStatusCounterBroadcast object: {}", e); } } return datumStatusCounterBroadcast; } catch (Exception e) { LOGGER.error("Exception trying to deserialize DatumStatusCounterBroadcast object: {}", e); return null; } }
From source file:com.hp.autonomy.searchcomponents.hod.search.fields.HodSearchResultDeserializer.java
@Override public HodSearchResult deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException { final FieldsInfo fieldsInfo = configService.getConfig().getFieldsInfo(); final Map<String, FieldInfo<?>> fieldConfig = fieldsInfo.getFieldConfigByName(); final JsonNode node = jsonParser.getCodec().readTree(jsonParser); final Map<String, FieldInfo<?>> fieldMap = new HashMap<>(fieldConfig.size()); for (final FieldInfo<?> fieldInfo : fieldConfig.values()) { for (final String name : fieldInfo.getNames()) { final String[] stringValues = parseAsStringArray(node, name); if (ArrayUtils.isNotEmpty(stringValues)) { final List<Object> values = new ArrayList<>(stringValues.length); for (final String stringValue : stringValues) { final Object value = fieldInfo.getType().parseValue(fieldInfo.getType().getType(), stringValue); values.add(value);// w w w. ja v a 2s . c om } fieldMap.put(fieldInfo.getId(), new FieldInfo<>(fieldInfo.getId(), Collections.singleton(name), fieldInfo.getType(), values)); } } } return new HodSearchResult.Builder().setReference(parseAsString(node, "reference")) .setIndex(parseAsString(node, "index")).setTitle(parseAsString(node, "title")) .setSummary(parseAsString(node, "summary")).setWeight(parseAsDouble(node, "weight")) .setFieldMap(fieldMap).setDate(parseAsDateFromArray(node, "date")) .setPromotionCategory(parsePromotionCategory(node, "promotion")).build(); }
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 .j a v a2s. com * 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; }