@Override public E deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { JsonNode node = jp.readValueAsTree(); if (node == null) { return null; } try { return Enum.valueOf(enumClass, node.textValue()); } catch (IllegalArgumentException e) { log.info("Ignoring unknown {} value: {}", enumClass.getSimpleName(), node.textValue()); return fallbackValue; } }
private Set<Host> constructHostIds(Iterator<JsonNode> elements) { Set<Host> hostIds = Sets.newHashSet(); JsonNode n; while (elements.hasNext()) { n = elements.next(); hostIds.add(hostService.getHost(HostId.hostId(n.textValue()))); } return hostIds; }
@Override public ObjectId deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.readValueAsTree(); if (node == null) { return null; } if (node.getNodeType() == JsonNodeType.OBJECT) { return new ObjectId(node.get("$oid").asText()); } return new ObjectId(node.textValue()); }
public List<String> tagStrings(ArrayNode nodes, String location, ParseResult result) { if (nodes == null) return null; List<String> output = new ArrayList<String>(); for (JsonNode node : nodes) { if (node.getNodeType().equals(JsonNodeType.STRING)) { output.add(node.textValue()); } } return output; }
private static String buildMessage(final String key, final JsonNode params, final JsonNode data) { final ProcessingMessage message = new ProcessingMessage().setMessage(BUNDLE.getMessage(key)); if (params != null) { String name; JsonNode value; for (final JsonNode node : params) { name = node.textValue(); value = data.get(name); message.putArgument(name, valueToArgument(value)); } } return message.getMessage(); }
@Override public Criterion decodeCriterion(ObjectNode json) { JsonNode ethTypeNode = nullIsIllegal( json.get(CriterionCodec.ETH_TYPE), CriterionCodec.ETH_TYPE + MISSING_MEMBER_MESSAGE); int ethType; if (ethTypeNode.isInt()) { ethType = ethTypeNode.asInt(); } else { ethType = Integer.decode(ethTypeNode.textValue()); } return Criteria.matchEthType(ethType); }
/** * This method reads the JSON object array representation of employees from input file and then * navigates the employee objects to find objects that are not having email attribute. This * example update those object with dummy email and writes the modified contents in to * emp-array-modified.json file * * @param jsonFileName * @throws IOException */ public void findAndUpdateNode(String jsonFileName) throws IOException { // read json file InputStream inputStream = getClass().getResourceAsStream(jsonFileName); // create ObjectMapper instance ObjectMapper objectMapper = new ObjectMapper(); // read JSON like DOM Parser JsonNode rootNode = objectMapper.readTree(inputStream); if (rootNode.isArray()) { for (JsonNode objNode : rootNode) { System.out.println(objNode); JsonNode idNode = objNode.path("employeeId"); logger.log(Level.INFO, "id = " + idNode.asInt()); JsonNode emailNode = objNode.path("email"); logger.log(Level.INFO, "email = " + emailNode.textValue()); if (emailNode.textValue() == null) { ((ObjectNode) objNode).put("email", "unknown"); } objectMapper.writeValue(new File("emp-array-modified.json"), rootNode); } } }
@Override public JsonNode digest(final JsonNode schema) { final ObjectNode ret = FACTORY.objectNode(); final ArrayNode simpleTypes = FACTORY.arrayNode(); ret.put(keyword, simpleTypes); final ArrayNode schemas = FACTORY.arrayNode(); ret.put("schemas", schemas); final JsonNode node = schema.get(keyword); final EnumSet<NodeType> set = EnumSet.noneOf(NodeType.class); if (node.isTextual()) // Single type putType(set, node.textValue()); else { // More than one type, and possibly schemas final int size = node.size(); JsonNode element; for (int index = 0; index < size; index++) { element = node.get(index); if (element.isTextual()) putType(set, element.textValue()); else schemas.add(index); } } /* * If all types are there, no need to collect schemas */ if (EnumSet.complementOf(set).isEmpty()) schemas.removeAll(); /* * Note that as this is an enumset, order is guaranteed */ for (final NodeType type : set) simpleTypes.add(type.toString()); return ret; }
public Object extension(JsonNode jsonNode) { if (jsonNode.getNodeType().equals(JsonNodeType.BOOLEAN)) { return jsonNode.asBoolean(); } if (jsonNode.getNodeType().equals(JsonNodeType.STRING)) { return jsonNode.asText(); } if (jsonNode.getNodeType().equals(JsonNodeType.NUMBER)) { NumericNode n = (NumericNode) jsonNode; if (n.isLong()) { return jsonNode.asLong(); } if (n.isInt()) { return jsonNode.asInt(); } if (n.isBigDecimal()) { return jsonNode.textValue(); } if (n.isBoolean()) { return jsonNode.asBoolean(); } if (n.isFloat()) { return jsonNode.floatValue(); } if (n.isDouble()) { return jsonNode.doubleValue(); } if (n.isShort()) { return jsonNode.intValue(); } return jsonNode.asText(); } if (jsonNode.getNodeType().equals(JsonNodeType.ARRAY)) { ArrayNode an = (ArrayNode) jsonNode; List<Object> o = new ArrayList<Object>(); for (JsonNode i : an) { Object obj = extension(i); if (obj != null) { o.add(obj); } } return o; } return jsonNode; }
@Override public boolean matchesSafely(JsonNode jsonInstruction, Description description) { // check type final JsonNode jsonTypeNode = jsonInstruction.get("type"); final String jsonType = jsonTypeNode.textValue(); final String type = instruction.type().name(); if (!jsonType.equals(type)) { description.appendText("type was " + type); return false; } if (instruction instanceof ModMplsHeaderInstruction) { return matchModMplsHeaderInstruction(jsonInstruction, description); } else if (instruction instanceof OutputInstruction) { return matchOutputInstruction(jsonInstruction, description); } else if (instruction instanceof GroupInstruction) { return matchGroupInstruction(jsonInstruction, description); } else if (instruction instanceof MeterInstruction) { return matchMeterInstruction(jsonInstruction, description); } else if (instruction instanceof SetQueueInstruction) { return matchSetQueueInstruction(jsonInstruction, description); } else if (instruction instanceof ModOchSignalInstruction) { return matchModOchSingalInstruction(jsonInstruction, description); } else if (instruction instanceof ModEtherInstruction) { return matchModEtherInstruction(jsonInstruction, description); } else if (instruction instanceof ModVlanIdInstruction) { return matchModVlanIdInstruction(jsonInstruction, description); } else if (instruction instanceof ModVlanPcpInstruction) { return matchModVlanPcpInstruction(jsonInstruction, description); } else if (instruction instanceof ModIPInstruction) { return matchModIpInstruction(jsonInstruction, description); } else if (instruction instanceof ModIPv6FlowLabelInstruction) { return matchModIPv6FlowLabelInstruction(jsonInstruction, description); } else if (instruction instanceof ModMplsLabelInstruction) { return matchModMplsLabelInstruction(jsonInstruction, description); } else if (instruction instanceof ModOduSignalIdInstruction) { return matchModOduSingalIdInstruction(jsonInstruction, description); } else if (instruction instanceof NoActionInstruction) { return true; } return false; }
public Boolean getBoolean( String key, ObjectNode node, boolean required, String location, ParseResult result) { Boolean value = null; JsonNode v = node.get(key); if (node == null || v == null) { if (required) { result.missing(location, key); result.invalid(); } } else { if (v.getNodeType().equals(JsonNodeType.BOOLEAN)) { value = v.asBoolean(); } else if (v.getNodeType().equals(JsonNodeType.STRING)) { String stringValue = v.textValue(); return Boolean.parseBoolean(stringValue); } } return value; }
@DataProvider protected final Iterator<Object[]> getValueTests() { final List<Object[]> list = Lists.newArrayList(); String msg; JsonNode msgNode, msgData, msgParams; for (final JsonNode node : testNode) { msgNode = node.get("message"); msgData = node.get("msgData"); msgParams = node.get("msgParams"); msg = msgNode == null ? null : buildMessage(msgNode.textValue(), msgParams, msgData); list.add( new Object[] { node.get("digest"), node.get("data"), msg, node.get("valid").booleanValue(), msgData }); } return list.iterator(); }
public VisualStyle buildVisualStyle( final MappingFactoryManager factoryManager, final VisualStyleFactory factory, final VisualLexicon lexicon, final JsonNode rootNode) { final JsonNode title = rootNode.get(TITLE); final VisualStyle style = factory.createVisualStyle(title.textValue()); final JsonNode defaults = rootNode.get(DEFAULTS); final JsonNode mappings = rootNode.get(MAPPINGS); if (defaults != null) { parseDefaults(defaults, style, lexicon); } if (mappings != null) { parseMappings(mappings, style, lexicon, factoryManager); } return style; }
@Post public ObjectNode startProcessInstance(Representation entity) { try { if (authenticate(SecuredResource.ADMIN) == false) return null; String startParams = entity.getText(); JsonNode startJSON = new ObjectMapper().readTree(startParams); ArrayNode jobIdsJSON = (ArrayNode) startJSON.get("jobIds"); for (JsonNode jobId : jobIdsJSON) { ActivitiUtil.getManagementService().executeJob(jobId.textValue()); } ObjectNode successNode = new ObjectMapper().createObjectNode(); successNode.put("success", true); return successNode; } catch (Exception e) { if (e instanceof ActivitiException) { throw (ActivitiException) e; } else { throw new ActivitiException("Failed to execute jobs", e); } } }
public static Object toObject(JsonNode node) throws IOException { JsonNodeType type = node.getNodeType(); switch (type) { case ARRAY: List<Object> list = new ArrayList<>(); for (JsonNode child : node) { list.add(toObject(child)); } return list; case BINARY: return node.binaryValue(); case BOOLEAN: return node.booleanValue(); case NULL: return null; case NUMBER: return node.numberValue(); case OBJECT: case POJO: return toMap(node); default: return node.textValue(); } }
private static Object valueToArgument(final JsonNode value) { final NodeType type = NodeType.getNodeType(value); switch (type) { case STRING: return value.textValue(); case INTEGER: return value.bigIntegerValue(); case NUMBER: case NULL: case OBJECT: case ARRAY: return value; case BOOLEAN: return value.booleanValue(); // case ARRAY: // final List<Object> list = Lists.newArrayList(); // for (final JsonNode element: value) // list.add(valueToArgument(element)); // return list; default: throw new UnsupportedOperationException(); } }
public Parameter parameter(ObjectNode obj, String location, ParseResult result) { if (obj == null) { return null; } Parameter output = null; JsonNode ref = obj.get("$ref"); if (ref != null) { if (ref.getNodeType().equals(JsonNodeType.STRING)) { return refParameter((TextNode) ref, location, result); } else { result.invalidType(location, "$ref", "string", obj); return null; } } String l = null; JsonNode ln = obj.get("name"); if (ln != null) { l = ln.asText(); } else { l = "['unknown']"; } location += ".[" + l + "]"; String value = getString("in", obj, true, location, result); if (value != null) { String type = getString("type", obj, false, location, result); String format = getString("format", obj, false, location, result); AbstractSerializableParameter<?> sp = null; if ("query".equals(value)) { sp = new QueryParameter(); } else if ("header".equals(value)) { sp = new HeaderParameter(); } else if ("path".equals(value)) { sp = new PathParameter(); } else if ("formData".equals(value)) { sp = new FormParameter(); } if (sp != null) { // type is mandatory when sp != null getString("type", obj, true, location, result); Map<PropertyBuilder.PropertyId, Object> map = new HashMap<PropertyBuilder.PropertyId, Object>(); map.put(TYPE, type); map.put(FORMAT, format); String defaultValue = getString("default", obj, false, location, result); map.put(DEFAULT, defaultValue); sp.setDefault(defaultValue); Double dbl = getDouble("maximum", obj, false, location, result); if (dbl != null) { map.put(MAXIMUM, dbl); sp.setMaximum(dbl); } Boolean bl = getBoolean("exclusiveMaximum", obj, false, location, result); if (bl != null) { map.put(EXCLUSIVE_MAXIMUM, bl); sp.setExclusiveMaximum(bl); } dbl = getDouble("minimum", obj, false, location, result); if (dbl != null) { map.put(MINIMUM, dbl); sp.setMinimum(dbl); } bl = getBoolean("exclusiveMinimum", obj, false, location, result); if (bl != null) { map.put(EXCLUSIVE_MINIMUM, bl); sp.setExclusiveMinimum(bl); } map.put(MAX_LENGTH, getInteger("maxLength", obj, false, location, result)); map.put(MIN_LENGTH, getInteger("minLength", obj, false, location, result)); String pat = getString("pattern", obj, false, location, result); map.put(PATTERN, pat); sp.setPattern(pat); Integer iv = getInteger("maxItems", obj, false, location, result); map.put(MAX_ITEMS, iv); sp.setMaxItems(iv); iv = getInteger("minItems", obj, false, location, result); map.put(MIN_ITEMS, iv); sp.setMinItems(iv); map.put(UNIQUE_ITEMS, getBoolean("uniqueItems", obj, false, location, result)); ArrayNode an = getArray("enum", obj, false, location, result); if (an != null) { List<String> _enum = new ArrayList<String>(); for (JsonNode n : an) { _enum.add(n.textValue()); } sp.setEnum(_enum); map.put(ENUM, _enum); } Property prop = PropertyBuilder.build(type, format, map); if (prop != null) { sp.setProperty(prop); ObjectNode items = getObject("items", obj, false, location, result); if (items != null) { Property inner = schema(null, items, location, result); sp.setItems(inner); } } Set<String> keys = getKeys(obj); for (String key : keys) { if (key.startsWith("x-")) { sp.setVendorExtension(key, extension(obj.get(key))); } else if (!PARAMETER_KEYS.contains(key)) { result.extra(location, key, obj.get(key)); } } String collectionFormat = getString("collectionFormat", obj, false, location, result); sp.setCollectionFormat(collectionFormat); output = sp; } else if ("body".equals(value)) { output = Json.mapper().convertValue(obj, Parameter.class); } if (output != null) { value = getString("name", obj, true, location, result); output.setName(value); value = getString("description", obj, false, location, result); output.setDescription(value); Boolean required = getBoolean("required", obj, false, location, result); if (required != null) { output.setRequired(required); } } } return output; }
@Override protected void doHandleResponse(HttpResponse httpResponse) throws Exception { final Session session = SessionManager.getSession(getSyncAccountId()); Header tokenHeader = httpResponse.getFirstHeader("Sync-JWT"); if (tokenHeader != null) { session.setToken(tokenHeader.getValue()); } Map<String, DownloadFileHandler> handlers = (Map<String, DownloadFileHandler>) getParameterValue("handlers"); InputStream inputStream = null; try { HttpEntity httpEntity = httpResponse.getEntity(); inputStream = new CountingInputStream(httpEntity.getContent()) { @Override protected synchronized void afterRead(int n) { session.incrementDownloadedBytes(n); super.afterRead(n); } }; ZipInputStream zipInputStream = new ZipInputStream(inputStream); ZipEntry zipEntry = null; while ((zipEntry = zipInputStream.getNextEntry()) != null) { String zipEntryName = zipEntry.getName(); if (zipEntryName.equals("errors.json")) { JsonNode rootJsonNode = JSONUtil.readTree(zipInputStream); Iterator<Map.Entry<String, JsonNode>> fields = rootJsonNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); Handler<Void> handler = handlers.get(field.getKey()); JsonNode valueJsonNode = field.getValue(); JsonNode exceptionJsonNode = valueJsonNode.get("exception"); handler.handlePortalException(exceptionJsonNode.textValue()); } break; } DownloadFileHandler downloadFileHandler = handlers.get(zipEntryName); SyncFile syncFile = (SyncFile) downloadFileHandler.getParameterValue("syncFile"); if (downloadFileHandler.isUnsynced(syncFile)) { continue; } if (_logger.isTraceEnabled()) { _logger.trace( "Handling response {} file path {}", DownloadFileHandler.class.getSimpleName(), syncFile.getFilePathName()); } try { downloadFileHandler.copyFile( syncFile, Paths.get(syncFile.getFilePathName()), new CloseShieldInputStream(zipInputStream), false); } catch (Exception e) { if (!isEventCancelled()) { _logger.error(e.getMessage(), e); } } finally { downloadFileHandler.removeEvent(); } } } catch (Exception e) { if (!isEventCancelled() && _logger.isDebugEnabled()) { _logger.debug(e.getMessage(), e); } } finally { StreamUtil.cleanUp(inputStream); } }
private Schema asConnectSchema(JsonNode jsonSchema) { if (jsonSchema.isNull()) return null; Schema cached = toConnectSchemaCache.get(jsonSchema); if (cached != null) return cached; JsonNode schemaTypeNode = jsonSchema.get(JsonSchema.SCHEMA_TYPE_FIELD_NAME); if (schemaTypeNode == null || !schemaTypeNode.isTextual()) throw new DataException("Schema must contain 'type' field"); final SchemaBuilder builder; switch (schemaTypeNode.textValue()) { case JsonSchema.BOOLEAN_TYPE_NAME: builder = SchemaBuilder.bool(); break; case JsonSchema.INT8_TYPE_NAME: builder = SchemaBuilder.int8(); break; case JsonSchema.INT16_TYPE_NAME: builder = SchemaBuilder.int16(); break; case JsonSchema.INT32_TYPE_NAME: builder = SchemaBuilder.int32(); break; case JsonSchema.INT64_TYPE_NAME: builder = SchemaBuilder.int64(); break; case JsonSchema.FLOAT_TYPE_NAME: builder = SchemaBuilder.float32(); break; case JsonSchema.DOUBLE_TYPE_NAME: builder = SchemaBuilder.float64(); break; case JsonSchema.BYTES_TYPE_NAME: builder = SchemaBuilder.bytes(); break; case JsonSchema.STRING_TYPE_NAME: builder = SchemaBuilder.string(); break; case JsonSchema.ARRAY_TYPE_NAME: JsonNode elemSchema = jsonSchema.get(JsonSchema.ARRAY_ITEMS_FIELD_NAME); if (elemSchema == null) throw new DataException("Array schema did not specify the element type"); builder = SchemaBuilder.array(asConnectSchema(elemSchema)); break; case JsonSchema.MAP_TYPE_NAME: JsonNode keySchema = jsonSchema.get(JsonSchema.MAP_KEY_FIELD_NAME); if (keySchema == null) throw new DataException("Map schema did not specify the key type"); JsonNode valueSchema = jsonSchema.get(JsonSchema.MAP_VALUE_FIELD_NAME); if (valueSchema == null) throw new DataException("Map schema did not specify the value type"); builder = SchemaBuilder.map(asConnectSchema(keySchema), asConnectSchema(valueSchema)); break; case JsonSchema.STRUCT_TYPE_NAME: builder = SchemaBuilder.struct(); JsonNode fields = jsonSchema.get(JsonSchema.STRUCT_FIELDS_FIELD_NAME); if (fields == null || !fields.isArray()) throw new DataException("Struct schema's \"fields\" argument is not an array."); for (JsonNode field : fields) { JsonNode jsonFieldName = field.get(JsonSchema.STRUCT_FIELD_NAME_FIELD_NAME); if (jsonFieldName == null || !jsonFieldName.isTextual()) throw new DataException("Struct schema's field name not specified properly"); builder.field(jsonFieldName.asText(), asConnectSchema(field)); } break; default: throw new DataException("Unknown schema type: " + schemaTypeNode.textValue()); } JsonNode schemaOptionalNode = jsonSchema.get(JsonSchema.SCHEMA_OPTIONAL_FIELD_NAME); if (schemaOptionalNode != null && schemaOptionalNode.isBoolean() && schemaOptionalNode.booleanValue()) builder.optional(); else builder.required(); JsonNode schemaNameNode = jsonSchema.get(JsonSchema.SCHEMA_NAME_FIELD_NAME); if (schemaNameNode != null && schemaNameNode.isTextual()) builder.name(schemaNameNode.textValue()); JsonNode schemaVersionNode = jsonSchema.get(JsonSchema.SCHEMA_VERSION_FIELD_NAME); if (schemaVersionNode != null && schemaVersionNode.isIntegralNumber()) { builder.version(schemaVersionNode.intValue()); } JsonNode schemaDocNode = jsonSchema.get(JsonSchema.SCHEMA_DOC_FIELD_NAME); if (schemaDocNode != null && schemaDocNode.isTextual()) builder.doc(schemaDocNode.textValue()); JsonNode schemaParamsNode = jsonSchema.get(JsonSchema.SCHEMA_PARAMETERS_FIELD_NAME); if (schemaParamsNode != null && schemaParamsNode.isObject()) { Iterator<Map.Entry<String, JsonNode>> paramsIt = schemaParamsNode.fields(); while (paramsIt.hasNext()) { Map.Entry<String, JsonNode> entry = paramsIt.next(); JsonNode paramValue = entry.getValue(); if (!paramValue.isTextual()) throw new DataException("Schema parameters must have string values."); builder.parameter(entry.getKey(), paramValue.textValue()); } } JsonNode schemaDefaultNode = jsonSchema.get(JsonSchema.SCHEMA_DEFAULT_FIELD_NAME); if (schemaDefaultNode != null) builder.defaultValue(convertToConnect(builder, schemaDefaultNode)); Schema result = builder.build(); toConnectSchemaCache.put(jsonSchema, result); return result; }
private ViewObject processObjectNode(ObjectNode objectNode) { Set<ObjectId> nodeIds = null; Set<String> valueFields = new HashSet<>(); Map<String, ViewArray> arrayFields = new HashMap<>(); Map<String, ViewObject> refFields = new HashMap<>(); Map<String, ViewArray> backRefFields = new HashMap<>(); Map<String, ViewObject> latestBackRefFields = new HashMap<>(); for (Iterator<String> fieldIter = objectNode.fieldNames(); fieldIter.hasNext(); ) { String fieldName = fieldIter.next(); JsonNode value = objectNode.get(fieldName); if (value == null || value.isNull()) { throw new IllegalArgumentException( "All fields present in example view data must have associated values. Field " + fieldName + " does not."); } if (fieldName.equals(ReservedFields.VIEW_OBJECT_ID)) { String text = value.textValue(); if (isValidRefValue(text)) { nodeIds = parseObjectIds(text); } else { throw new IllegalArgumentException( "Encountered an instanceId that is not an objectId in string form." + value); } } else if (fieldName.equals(ReservedFields.VIEW_CLASS)) { // ignore } else if (fieldName.startsWith(ReservedFields.ALL_BACK_REF_FIELD_PREFIX)) { if (value.isArray() && value.size() == 1 && value.get(0).isObject()) { ViewArray viewArray = processArrayNode((ArrayNode) value); if (viewArray.element == null) { throw new IllegalArgumentException( "Back reference field " + fieldName + " does not contain valid example view data"); } backRefFields.put(removeFieldNameModifier(fieldName), viewArray); } else { throw new IllegalArgumentException( "Back-Reference fields (fields beginning with " + ReservedFields.ALL_BACK_REF_FIELD_PREFIX + ") must hold" + " values that are one element arrays of json objects. " + fieldName + " does not."); } } else if (fieldName.startsWith(ReservedFields.LATEST_BACK_REF_FIELD_PREFIX)) { if (!value.isObject()) { throw new IllegalArgumentException( "Latest Back reference field " + fieldName + " does not contain valid example view data"); } latestBackRefFields.put( removeFieldNameModifier(fieldName), processObjectNode((ObjectNode) value)); } else if (value.isArray()) { ViewArray viewArray = processArrayNode((ArrayNode) value); // if there was an object within the array, it is a refs field. // if not it's just an array of literal values and we treat it as // an opaque value field if (viewArray.element != null) { arrayFields.put(fieldName, processArrayNode((ArrayNode) value)); } else { valueFields.add(fieldName); } } else if (value.isObject()) { refFields.put(fieldName, processObjectNode((ObjectNode) value)); } else { valueFields.add(fieldName); } } return new ViewObject( nodeIds, valueFields, arrayFields, refFields, backRefFields, latestBackRefFields); }
/** * Gets the String value of the specified Entity property. * * @param name the name of the property * @return the property value. Returns null if the property has no value */ public String getStringProperty(String name) { JsonNode val = this.properties.get(name); return val != null ? val.textValue() : null; }