List of usage examples for com.fasterxml.jackson.databind.node ArrayNode size
public int size()
From source file:mobile.service.SelfInfoService.java
/** * ??????//from w w w.j a va 2s . co m * * @param index ????,0 */ public static ServiceResult deleteJobExpByIndex(int index) { User user = User.getFromSession(Context.current().session()); Expert expert = Expert.findByUserId(user.id); ArrayNode jobExpArrayNode = null; if (null == expert || StringUtils.isBlank(expert.jobExp) || index < 0) { return ServiceResult.error("234001", "????"); } else { jobExpArrayNode = (ArrayNode) Json.parse(expert.jobExp); if (index >= jobExpArrayNode.size()) { return ServiceResult.error("234001", "????"); } else { jobExpArrayNode.remove(index); } } ObjectNode jobExpNode = Json.newObject(); jobExpNode.set("jobExp", jobExpArrayNode); ObjectNodeResult objectNodeResult = Expert.saveExpertByJson(Context.current().session(), jobExpNode); return ServiceResult.create(objectNodeResult); }
From source file:mobile.service.SelfInfoService.java
/** * ?????//from w w w.java 2 s . c om * * @param index ???,0 */ public static ServiceResult deleteEduExpByIndex(int index) { User user = User.getFromSession(Context.current().session()); Expert expert = Expert.findByUserId(user.id); ArrayNode eduExpArrayNode = null; if (null == expert || StringUtils.isBlank(expert.educationExp) || index < 0) { return ServiceResult.error("232001", "???"); } else { eduExpArrayNode = (ArrayNode) Json.parse(expert.educationExp); if (index >= eduExpArrayNode.size()) { return ServiceResult.error("232001", "???"); } else { eduExpArrayNode.remove(index); } } ObjectNode eduExpNode = Json.newObject(); eduExpNode.set("educationExp", eduExpArrayNode); ObjectNodeResult objectNodeResult = Expert.saveExpertByJson(Context.current().session(), eduExpNode); return ServiceResult.create(objectNodeResult); }
From source file:net.opentsdb.ConfigReader.java
public static String[] load(final Config config, final String[] args) { InputStream is = null;//from w ww . j a v a 2 s . co m String[] noConfigArgs = {}; try { is = ConfigReader.class.getClassLoader().getResourceAsStream(CONFIG_PATH); ArrayNode an = (ArrayNode) JSON.getMapper().readTree(is); final LinkedHashMap<String, ConfigurationItem> citems = new LinkedHashMap<String, ConfigurationItem>( an.size()); final HashMap<String, ConfigurationItem> clOptions = new HashMap<String, ConfigurationItem>(); for (int i = 0; i < an.size(); i++) { JsonNode jn = an.get(i); ConfigurationItem ci = JSON.getMapper().convertValue(jn, ConfigurationItem.class); ci.resolve(); if (ci.getCl() != null) { clOptions.put(ci.getCl(), ci); } if (ci.getValue() != null) { //config.overrideConfig(ci.getKey(), ci.getValue().toString()); ci.validate(); citems.put(ci.getKey(), ci); } //System.out.println(ci.dump()); } final ArgP argp = newArgP(); noConfigArgs = argp.parse(args); final Map<String, String> argpOptions = argp.getParsed(); if (!argpOptions.isEmpty()) { for (Map.Entry<String, String> entry : argpOptions.entrySet()) { ConfigurationItem argCi = clOptions.get(entry.getKey()); if (argCi != null) { argCi.setValueAsText(entry.getValue()); citems.put(argCi.getKey(), argCi); } } } // Write the configuration to an OpenTSDB config for (ConfigurationItem configItem : citems.values()) { config.overrideConfig(configItem.getKey(), configItem.getValueStr()); } return noConfigArgs; } catch (Exception ex) { throw new RuntimeException("Failed to load resource [" + CONFIG_PATH + "]", ex); } }
From source file:com.msopentech.odatajclient.testservice.utils.Commons.java
public static InputStream getLinksAsJSON(final String entitySetName, final Map.Entry<String, Collection<String>> link) throws IOException { final ObjectNode links = new ObjectNode(JsonNodeFactory.instance); links.put(JSON_ODATAMETADATA_NAME, ODATA_METADATA_PREFIX + entitySetName + "/$links/" + link.getKey()); final ArrayNode uris = new ArrayNode(JsonNodeFactory.instance); for (String uri : link.getValue()) { final String absoluteURI; if (URI.create(uri).isAbsolute()) { absoluteURI = uri;//w w w . j a v a2 s . co m } else { absoluteURI = DEFAULT_SERVICE_URL + uri; } uris.add(new ObjectNode(JsonNodeFactory.instance).put("url", absoluteURI)); } if (uris.size() == 1) { links.setAll((ObjectNode) uris.get(0)); } else { links.set("value", uris); } return IOUtils.toInputStream(links.toString()); }
From source file:org.apache.olingo.fit.utils.Commons.java
public static InputStream getLinksAsJSON(final String entitySetName, final Map.Entry<String, Collection<String>> link) throws IOException { final ObjectNode links = new ObjectNode(JsonNodeFactory.instance); links.put(Constants.get(ConstantKey.JSON_ODATAMETADATA_NAME), Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + entitySetName + "/$links/" + link.getKey()); final ArrayNode uris = new ArrayNode(JsonNodeFactory.instance); for (String uri : link.getValue()) { final String absoluteURI; if (URI.create(uri).isAbsolute()) { absoluteURI = uri;/*from w w w .j a va 2 s . c o m*/ } else { absoluteURI = Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + uri; } uris.add(new ObjectNode(JsonNodeFactory.instance).put("url", absoluteURI)); } if (uris.size() == 1) { links.setAll((ObjectNode) uris.get(0)); } else { links.set("value", uris); } return IOUtils.toInputStream(links.toString(), Constants.ENCODING); }
From source file:com.blackberry.bdp.common.versioned.ZkVersioned.java
/** * Iterates over json1 which is intended to be a full representation of a complete JSON * structure. It compares nodes on json1 against nodes on json2 which should contain * either the same identical structure of json1 or a subset of JSON structure contained * in json1.// w w w .j a va 2 s .c o m * * If identically named nodes on json1 and json2 vary in type (ObjectNode vs ArrayNode * for example) then an exception is thrown since json2 must not contain any additional * structure than what is found in json1. * * Explicit Null Node Handling Regardless of Node type: * * This pertains to the value of a node being explicity equal to null. See further below * for handling of non-existent nodes * * If a node is null on json1 and not null on json2 then the node on json1 is set to the * value of the node on json2. * * If a node is not null on json1 and is null on json2 then the node on json1 is made null. * * Non-existent Node Handling: * * Since json1 is intended to be a full representation of a complete JSON structure * nodes on json2 that don't exist on json1 are completely ignored. Only if the same * node exists on both json1 and json2 will the structures be merged. * * ArrayNode Handling * * If the node being compared is an ArrayNode then the elements on json2 are iterated * over. If the index on json1 exists on json1 then the two elements are merged. If the * index doesn't exist on json1 then the element is added to the ArrayNode on json1. * Note: The existence of the element on json1 is determined by index and when an * element is added to json1 it's index increases by one. That shouldn't be a problem * though as for there to ever be more elements in json2, the index pointer will always * be one larger than the max index of json1. * * ArrayNode Handling when json1 contains more elements than json2: * * Elements are removed from json1 if they have higher indexes than the size of json2 * minus 1 * * @param json1 * @param json2 * @return * @throws com.blackberry.bdp.common.exception.JsonMergeException */ public static JsonNode merge(JsonNode json1, JsonNode json2) throws JsonMergeException { Iterator<String> json1Fields = json1.fieldNames(); LOG.info("Merged called on json1 ({}), json2 ({})", json1.getNodeType(), json2.getNodeType()); while (json1Fields.hasNext()) { String nodeName = json1Fields.next(); JsonNode json1Node = json1.get(nodeName); // Check if json2 has the node and run explicit null checks if (!json2.has(nodeName)) { LOG.info("Not comparing {} since it doesn't exist on json2", nodeName); continue; } else if (json1Node.isNull() && json2.hasNonNull(nodeName)) { ((ObjectNode) json1).replace(nodeName, json2.get(nodeName)); LOG.info("explicit null {} on json1 replaced with non-null from json2", nodeName); continue; } else if (json1.hasNonNull(nodeName) && json2.get(nodeName).isNull()) { ((ObjectNode) json1).replace(nodeName, json2.get(nodeName)); LOG.info("non-null {} on json1 replaced with explicitly null on json2", nodeName); continue; } JsonNode json2Node = json2.get(nodeName); if (json1Node.getNodeType().equals(json2Node.getNodeType()) == false) { throw new JsonMergeException(String.format("json1 (%s) cannot be merged with json2 (%s)", json1.getNodeType(), json2.getNodeType())); } LOG.info("need to compare \"{}\" which is a {}", nodeName, json1Node.getNodeType()); if (json1Node.isObject()) { LOG.info("Calling merge on object {}", nodeName); merge(json1Node, json2.get(nodeName)); } else if (json1Node instanceof ObjectNode) { throw new JsonMergeException("{} is instance of ObjectNode and wasn't isObject()--what gives?!"); } else if (json1Node.isArray()) { ArrayNode json1Array = (ArrayNode) json1Node; ArrayNode json2Array = (ArrayNode) json2Node; LOG.info("ArrayNode {} json1 has {} elements and json2 has {} elements", nodeName, json1Array.size(), json2Array.size()); int indexNo = 0; Iterator<JsonNode> json2Iter = json2Array.iterator(); while (json2Iter.hasNext()) { JsonNode json2Element = json2Iter.next(); if (json1Array.has(indexNo)) { LOG.info("Need to merge ArrayNode {} element {}", nodeName, indexNo); merge(json1Node.get(indexNo), json2Element); } else { LOG.info("ArrayNode {} element {} not found on json1, adding", nodeName, indexNo); json1Array.add(json2Element); } indexNo++; } while (json1Array.size() > json2Array.size()) { int indexToRemove = json1Array.size() - 1; json1Array.remove(indexToRemove); LOG.info("ArrayNode {} index {} on json1 removed since greater than size of json2 ({})", nodeName, indexToRemove, json2Array.size()); } } else { LOG.info("{} ({}) has fallen through known merge types", nodeName, json1Node.getNodeType()); ((ObjectNode) json1).replace(nodeName, json2Node); LOG.info("json1 node {} replaced with json2's node", nodeName); } } return json1; }
From source file:com.redhat.lightblue.util.JsonDoc.java
private static JsonNode modifyArrayNode(ArrayNode parentNode, JsonNode newValue, String last, Path p) { JsonNode oldValue;/*from www. j a v a2s .co m*/ ArrayNode arr = (ArrayNode) parentNode; int index; try { index = Integer.valueOf(last); } catch (NumberFormatException e) { throw new IllegalArgumentException(UtilConstants.ERR_EXPECTED_ARRAY_INDEX + p); } int size = arr.size(); while (size < index) { arr.addNull(); size++; } if (index < 0) { index = size + index; } if (index < size && newValue != null) { oldValue = arr.get(index); arr.set(index, newValue); } else if (newValue == null) { oldValue = arr.get(index); arr.remove(index); } else { oldValue = null; arr.add(newValue); } return oldValue; }
From source file:org.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java
public static ObjectNode createSchemaDesignObjectNode(final ObjectMapper objectMapper, final Schema schema) { final Context context = schema.getContext(); final SyntaxLoader syntaxLoader = context.getSyntaxLoader(); final SchemaLoader schemaLoader = context.getSchemaLoader(); final ObjectNode rootNode = objectMapper.createObjectNode(); final URI schemaUri = schema.getUri(); final Prototype prototype = schemaLoader.getPrototype(schemaUri); rootNode.put(PropertyName.uri.name(), syntaxLoader.formatSyntaxValue(schemaUri)); rootNode.put(PropertyName.title.name(), schema.getTitle()); rootNode.put(PropertyName.description.name(), schema.getDescription()); rootNode.put(PropertyName.version.name(), schema.getVersion()); final String titleSlotName = getTitleSlotName(schemaUri, schemaLoader); if (titleSlotName != null) { rootNode.put(PropertyName.titleSlotName.name(), titleSlotName); }/*from ww w . j ava 2s. c om*/ final UniqueName uniqueName = schema.getUniqueName(); final ObjectNode uniqueNameNode = objectMapper.createObjectNode(); uniqueNameNode.put(PropertyName.fullName.name(), uniqueName.getFullName()); uniqueNameNode.put(PropertyName.namespace.name(), uniqueName.getNamespace()); uniqueNameNode.put(PropertyName.localName.name(), uniqueName.getLocalName()); rootNode.put(PropertyName.uniqueName.name(), uniqueNameNode); final Set<URI> declaredBaseSchemaUris = prototype.getDeclaredBaseSchemaUris(); if (declaredBaseSchemaUris != null && !declaredBaseSchemaUris.isEmpty()) { final Set<URI> addedBaseSchemaUris = new LinkedHashSet<>(); final ArrayNode baseSchemasNode = objectMapper.createArrayNode(); rootNode.put(PropertyName.baseSchemas.name(), baseSchemasNode); for (final URI baseSchemaUri : declaredBaseSchemaUris) { if (!addedBaseSchemaUris.contains(baseSchemaUri)) { final ObjectNode baseSchemaNode = buildSchemaNode(objectMapper, baseSchemaUri, schemaLoader, addedBaseSchemaUris); baseSchemasNode.add(baseSchemaNode); addedBaseSchemaUris.add(baseSchemaUri); } } } final Set<String> keySlotNames = prototype.getDeclaredKeySlotNames(); if (keySlotNames != null && !keySlotNames.isEmpty()) { final ArrayNode keyPropertyNamesNode = objectMapper.createArrayNode(); for (final String keySlotName : keySlotNames) { keyPropertyNamesNode.add(keySlotName); } if (keyPropertyNamesNode.size() > 0) { rootNode.put(PropertyName.keyPropertyNames.name(), keyPropertyNamesNode); } } final Set<String> allKeySlotNames = prototype.getAllKeySlotNames(); final ArrayNode allKeySlotNamesNode = objectMapper.createArrayNode(); rootNode.put(PropertyName.allKeySlotNames.name(), allKeySlotNamesNode); final ObjectNode keySlotMap = objectMapper.createObjectNode(); rootNode.put(PropertyName.keys.name(), keySlotMap); final String uriSlotName = PropertyName.uri.name(); if (allKeySlotNames.contains(uriSlotName)) { allKeySlotNamesNode.add(uriSlotName); final ObjectNode slot = createSlot(objectMapper, prototype, uriSlotName); keySlotMap.put(uriSlotName, slot); } for (final String keySlotName : allKeySlotNames) { if (!Document.SLOT_NAME_URI.equals(keySlotName)) { allKeySlotNamesNode.add(keySlotName); final ObjectNode slot = createSlot(objectMapper, prototype, keySlotName); keySlotMap.put(keySlotName, slot); } } rootNode.put(PropertyName.keyCount.name(), keySlotMap.size()); final SortedSet<String> allSlotNames = prototype.getAllSlotNames(); if (allSlotNames != null && !allSlotNames.isEmpty()) { final ObjectNode slotMapNode = objectMapper.createObjectNode(); rootNode.put(PropertyName.slots.name(), slotMapNode); final ArrayNode propertyNamesNode = objectMapper.createArrayNode(); for (final String slotName : allSlotNames) { final ProtoSlot protoSlot = prototype.getProtoSlot(slotName); if (protoSlot instanceof LinkProtoSlot) { continue; } if (allKeySlotNames.contains(slotName)) { // Skip key slots (handled separately) continue; } if (protoSlot.getDeclaringSchemaUri().equals(schemaUri)) { propertyNamesNode.add(slotName); } final ObjectNode slotNode = createSlot(objectMapper, prototype, slotName); if (slotNode != null) { slotMapNode.put(slotName, slotNode); } } if (propertyNamesNode.size() > 0) { rootNode.put(PropertyName.propertyNames.name(), propertyNamesNode); } rootNode.put(PropertyName.slotCount.name(), slotMapNode.size()); } final Set<String> comparablePropertyNames = prototype.getComparableSlotNames(); if (comparablePropertyNames != null && !comparablePropertyNames.isEmpty()) { final ArrayNode comparablePropertyNamesNode = objectMapper.createArrayNode(); for (final String comparablePropertyName : comparablePropertyNames) { comparablePropertyNamesNode.add(comparablePropertyName); } if (comparablePropertyNamesNode.size() > 0) { rootNode.put(PropertyName.comparablePropertyNames.name(), comparablePropertyNamesNode); } } final Collection<LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots().values(); if (linkProtoSlots != null && !linkProtoSlots.isEmpty()) { final ArrayNode linkNamesNode = objectMapper.createArrayNode(); final ObjectNode linksMapNode = objectMapper.createObjectNode(); rootNode.put(PropertyName.links.name(), linksMapNode); for (final LinkProtoSlot linkProtoSlot : linkProtoSlots) { if (linkProtoSlot.getDeclaringSchemaUri().equals(schemaUri)) { linkNamesNode.add(linkProtoSlot.getName()); } final ObjectNode linkNode = objectMapper.createObjectNode(); String linkTitle = linkProtoSlot.getTitle(); if (linkTitle == null) { linkTitle = linkProtoSlot.getName(); } linkNode.put(PropertyName.name.name(), linkProtoSlot.getName()); linkNode.put(PropertyName.title.name(), linkTitle); final Method method = linkProtoSlot.getMethod(); final URI linkRelationUri = linkProtoSlot.getLinkRelationUri(); final URI declaringSchemaUri = linkProtoSlot.getDeclaringSchemaUri(); linkNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri)); final Keys linkRelationKeys = context.getApiLoader().buildDocumentKeys(linkRelationUri, schemaLoader.getLinkRelationSchemaUri()); final LinkRelation linkRelation = context.getModel(linkRelationKeys, schemaLoader.getLinkRelationDimensions()); linkNode.put(PropertyName.relationTitle.name(), linkRelation.getTitle()); linkNode.put(PropertyName.description.name(), linkProtoSlot.getDescription()); linkNode.put(PropertyName.method.name(), method.getProtocolGivenName()); linkNode.put(PropertyName.declaringSchemaUri.name(), syntaxLoader.formatSyntaxValue(declaringSchemaUri)); URI requestSchemaUri = linkProtoSlot.getRequestSchemaUri(); if (schemaLoader.getDocumentSchemaUri().equals(requestSchemaUri)) { if (SystemLinkRelation.self.getUri().equals(linkRelationUri) || SystemLinkRelation.save.getUri().equals(linkRelationUri)) { requestSchemaUri = schemaUri; } } if (requestSchemaUri == null && method == Method.Save) { requestSchemaUri = schemaUri; } if (requestSchemaUri != null) { linkNode.put(PropertyName.requestSchemaUri.name(), syntaxLoader.formatSyntaxValue(requestSchemaUri)); final Schema requestSchema = schemaLoader.load(requestSchemaUri); if (requestSchema != null) { linkNode.put(PropertyName.requestSchemaTitle.name(), requestSchema.getTitle()); } } URI responseSchemaUri = linkProtoSlot.getResponseSchemaUri(); if (schemaLoader.getDocumentSchemaUri().equals(responseSchemaUri)) { if (SystemLinkRelation.self.getUri().equals(linkRelationUri) || SystemLinkRelation.save.getUri().equals(linkRelationUri)) { responseSchemaUri = schemaUri; } } if (responseSchemaUri != null) { linkNode.put(PropertyName.responseSchemaUri.name(), syntaxLoader.formatSyntaxValue(responseSchemaUri)); final Schema responseSchema = schemaLoader.load(responseSchemaUri); if (responseSchema != null) { linkNode.put(PropertyName.responseSchemaTitle.name(), responseSchema.getTitle()); } } linksMapNode.put(linkTitle, linkNode); } if (linkNamesNode.size() > 0) { rootNode.put(PropertyName.linkNames.name(), linkNamesNode); } rootNode.put(PropertyName.linkCount.name(), linksMapNode.size()); } return rootNode; }
From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java
/** * Creates the JSON request body used to commit all of the parts of a multipart * upload request./*from w w w . j a va 2s . c o m*/ * * @param parts stream of tuples - this is a terminal operation that will close the stream * @return byte array containing JSON data */ static ImmutablePair<byte[], Integer> createCommitRequestBody( final Stream<? extends MantaMultipartUploadTuple> parts) { final JsonNodeFactory nodeFactory = MantaObjectMapper.NODE_FACTORY_INSTANCE; final ObjectNode objectNode = new ObjectNode(nodeFactory); final ArrayNode partsArrayNode = new ArrayNode(nodeFactory); objectNode.set("parts", partsArrayNode); try (Stream<? extends MantaMultipartUploadTuple> sorted = parts.sorted()) { sorted.forEach(tuple -> partsArrayNode.add(tuple.getEtag())); } Validate.isTrue(partsArrayNode.size() > 0, "Can't commit multipart upload with no parts"); try { return ImmutablePair.of(MantaObjectMapper.INSTANCE.writeValueAsBytes(objectNode), partsArrayNode.size()); } catch (IOException e) { String msg = "Error serializing JSON for commit MPU request body"; throw new MantaMultipartException(msg, e); } }
From source file:org.openlmis.fulfillment.util.CustomSortDeserializer.java
@Override public Sort deserialize(JsonParser parser, DeserializationContext context) throws IOException { ArrayNode node = parser.getCodec().readTree(parser); Sort.Order[] orders = new Sort.Order[node.size()]; int index = 0; for (JsonNode obj : node) { orders[index] = new Sort.Order(Sort.Direction.valueOf(obj.get("direction").asText()), obj.get("property").asText()); index++;//www . j a va 2 s . co m } return new Sort(orders); }