List of usage examples for com.fasterxml.jackson.databind.node ObjectNode get
public JsonNode get(String paramString)
From source file:scott.barleyrs.rest.CrudService.java
private Entity toEntity(EntityContext ctx, ObjectNode jsObject, EntityType entityType) { Object keyValue = getEntityKey(jsObject, entityType); Entity entity = newEntityInCorrectState(ctx, entityType, keyValue); for (Iterator<String> i = jsObject.fieldNames(); i.hasNext();) { String fieldName = i.next(); JsonNode jsNode = jsObject.get(fieldName); if (jsNode == null || jsNode.isNull()) { continue; }/*from w w w .j av a2 s. c o m*/ Node eNode = entity.getChild(fieldName); if (eNode instanceof ValueNode) { ((ValueNode) eNode).setValue(convert(eNode.getNodeType(), jsNode.asText(), true)); } else if (eNode instanceof RefNode) { RefNode refNode = ((RefNode) eNode); if (jsNode.isValueNode()) { /* * we just refer to a key so set it */ refNode.setEntityKey(convert(eNode.getNodeType(), jsNode.asText(), true)); } else if (jsNode.isObject()) { /* * we refer to a whole object definition, so convert it to an entity. */ Entity reference = toEntity(ctx, ((ObjectNode) jsNode), refNode.getEntityType()); refNode.setReference(reference); } else { throw new IllegalStateException("Unexpected JSON node type '" + jsNode + "'"); } } else if (eNode instanceof ToManyNode) { ToManyNode toManyNode = (ToManyNode) eNode; if (!jsNode.isArray()) { throw new IllegalArgumentException("Expected as JSON array for field '" + fieldName + "'"); } for (Iterator<JsonNode> iel = ((ArrayNode) jsNode).elements(); iel.hasNext();) { JsonNode element = iel.next(); if (element.isValueNode()) { /* * we just refer to a key so set it */ Object key = convertForKey(toManyNode.getEntityType(), element.asText()); Entity e = ctx.getOrCreateBasedOnKeyGenSpec(toManyNode.getEntityType(), key); toManyNode.add(e); } else if (element.isObject()) { /* * we just refer to a JSON object so convert it to an entity */ Entity reference = toEntity(ctx, ((ObjectNode) element), toManyNode.getEntityType()); toManyNode.add(reference); } else { throw new IllegalStateException("Unexpected JSON node type '" + jsNode + "'"); } } } } return entity; }
From source file:com.almende.eve.transport.http.AgentServlet.java
/** * Do hand shake.//from ww w.jav a2 s. co m * * @param req * the req * @return the handshake */ private Handshake doHandShake(final HttpServletRequest req) { final String tokenTupple = req.getHeader("X-Eve-Token"); if (tokenTupple == null) { return Handshake.NAK; } try { final String senderUrl = req.getHeader("X-Eve-SenderUrl"); if (senderUrl != null && !senderUrl.equals("")) { final ObjectNode tokenObj = (ObjectNode) JOM.getInstance().readTree(tokenTupple); final HttpGet httpGet = new HttpGet(senderUrl); httpGet.setHeader("X-Eve-requestToken", tokenObj.get("time").textValue()); final HttpResponse response = ApacheHttpClient.get().execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) { if (tokenObj.get("token").textValue() .equals(response.getLastHeader("X-Eve-replyToken").getValue())) { return Handshake.OK; } } else { LOG.log(Level.WARNING, "Failed to receive valid handshake:" + response); } } } catch (final Exception e) { LOG.log(Level.WARNING, "", e); } return Handshake.INVALID; }
From source file:com.almende.dht.rpc.DHT.java
/** * Iterative_find_value./* ww w . jav a2 s.c om*/ * * @param key * the key * @param multiple * the multiple * @return the object node */ public JsonNode iterative_find_value(final Key key, final boolean multiple) { final JsonNode[] result = new JsonNode[1]; final TreeMap<Key, Node> shortList = new TreeMap<Key, Node>(); final Set<Node> tried = new HashSet<Node>(); insert(shortList, key, rt.getClosestNodes(key, Constants.A)); final int[] noInFlight = new int[1]; noInFlight[0] = 0; boolean keepGoing = true; while (keepGoing) { while (noInFlight[0] > 0 && result[0] == null) { synchronized (shortList) { try { shortList.wait(100); } catch (InterruptedException e) { } } } List<Node> copy = Arrays.asList(shortList.values().toArray(new Node[0])); Collections.sort(copy); final Iterator<Node> iter = copy.iterator(); int count = 0; while (iter.hasNext() && count < Constants.A) { final Node next = iter.next(); if (tried.contains(next)) { continue; } count++; tried.add(next); try { ObjectNode params = JOM.createObjectNode(); params.set("me", JOM.getInstance().valueToTree(rt.getMyKey())); params.set("key", JOM.getInstance().valueToTree(key)); params.put("multiple", multiple); AsyncCallback<ObjectNode> callback = new AsyncCallback<ObjectNode>() { @Override public void onSuccess(ObjectNode res) { if (res.has("value")) { result[0] = (ObjectNode) res.get("value"); } else if (res.has("values")) { result[0] = (ArrayNode) res.get("values"); } else { List<Node> nodes = NODELIST.inject(res.get("nodes")); synchronized (shortList) { insert(shortList, key, nodes); } } rt.seenNode(next); synchronized (shortList) { noInFlight[0]--; shortList.notifyAll(); } } @Override public void onFailure(Exception exception) { synchronized (shortList) { shortList.remove(key.dist(next.getKey())); noInFlight[0]--; shortList.notifyAll(); LOG.log(Level.WARNING, noInFlight[0] + ":OnFailure called:" + next.getUri(), exception); } } }; caller.call(next.getUri(), "dht.find_value", params, callback); synchronized (shortList) { noInFlight[0]++; } } catch (IOException e) { synchronized (shortList) { shortList.remove(key.dist(next.getKey())); } continue; } } if (count == 0) { keepGoing = false; } } if (result[0] == null) { return JOM.createNullNode(); } else { return result[0]; } }
From source file:org.eel.kitchen.jsonschema.validator.JsonResolverTest.java
@Test public void crossContextDanglingRefIsDetected() { JsonNode node;// w w w . ja v a 2 s . c o m final String location1 = "http://foo.bar/helloword"; final String location2 = "zookeeper://127.0.0.1:9000/acrylic#"; final String ref1 = location2 + "/x"; final String ref2 = location1 + "#/b"; final ObjectNode schema1 = factory.objectNode(); schema1.put("id", location1); node = factory.objectNode().put("$ref", ref1); schema1.put("a", node); final ObjectNode schema2 = factory.objectNode(); schema2.put("id", location2); node = factory.objectNode().put("$ref", ref2); schema2.put("x", node); registry.register(schema2); container = registry.register(schema1); schemaNode = new SchemaNode(container, schema1.get("a")); try { resolver.resolve(schemaNode); } catch (JsonSchemaException e) { msg = e.getValidationMessage(); verifyMessageParams(msg, Domain.REF_RESOLVING, "$ref"); assertEquals(msg.getMessage(), "dangling JSON Reference"); assertEquals(msg.getInfo("ref"), factory.textNode(ref2)); } }
From source file:org.eel.kitchen.jsonschema.validator.JsonResolverTest.java
@Test public void crossContextRefLoopIsDetected() { final ArrayNode path = factory.arrayNode(); JsonNode node;// w ww . jav a 2s . com final String location1 = "http://foo.bar/helloword"; final String location2 = "zookeeper://127.0.0.1:9000/acrylic#"; final String ref1 = location2 + "/x"; final String ref2 = location1 + "#/a"; path.add(ref1); path.add(ref2); final ObjectNode schema1 = factory.objectNode(); schema1.put("id", location1); node = factory.objectNode().put("$ref", ref1); schema1.put("a", node); final ObjectNode schema2 = factory.objectNode(); schema2.put("id", location2); node = factory.objectNode().put("$ref", ref2); schema2.put("x", node); registry.register(schema2); container = registry.register(schema1); schemaNode = new SchemaNode(container, schema1.get("a")); try { resolver.resolve(schemaNode); } catch (JsonSchemaException e) { msg = e.getValidationMessage(); verifyMessageParams(msg, Domain.REF_RESOLVING, "$ref"); assertEquals(msg.getMessage(), "ref loop detected"); assertEquals(msg.getInfo("path"), path); } }
From source file:org.dswarm.graph.resources.XMLResource.java
@POST @Path("/get") @Consumes(MediaType.APPLICATION_JSON)//www. ja v a 2 s . co m @Produces(MediaType.APPLICATION_XML) public Response readXML(final String jsonObjectString, @Context final GraphDatabaseService database) throws DMPGraphException { XMLResource.LOG.debug("try to read XML records from graph db"); final ObjectNode json; try { json = objectMapper.readValue(jsonObjectString, ObjectNode.class); } catch (final IOException e) { final String message = "could not deserialise request JSON for read from graph DB request"; XMLResource.LOG.debug(message); throw new DMPGraphException(message, e); } final String recordClassUri = json.get(DMPStatics.RECORD_CLASS_URI_IDENTIFIER).asText(); final String dataModelUri = json.get(DMPStatics.DATA_MODEL_URI_IDENTIFIER).asText(); final JsonNode rootAttributePathNode = json.get(DMPStatics.ROOT_ATTRIBUTE_PATH_IDENTIFIER); final Optional<AttributePath> optionalRootAttributePath = Optional .fromNullable(AttributePathUtil.parseAttributePathNode(rootAttributePathNode)); final Optional<String> optionalRecordTag; final JsonNode recordTagNode = json.get(DMPStatics.RECORD_TAG_IDENTIFIER); if (recordTagNode != null) { optionalRecordTag = Optional.fromNullable(recordTagNode.asText()); } else { optionalRecordTag = Optional.absent(); } final JsonNode versionNode = json.get(DMPStatics.VERSION_IDENTIFIER); final Optional<Integer> optionalVersion; if (versionNode != null) { optionalVersion = Optional.fromNullable(versionNode.asInt()); } else { optionalVersion = Optional.absent(); } final JsonNode allVersionsNode = json.get(DMPStatics.ALL_VERSIONS_IDENTIFIER); final Optional<Boolean> optionalAllversion; if (allVersionsNode != null) { optionalAllversion = Optional.fromNullable(allVersionsNode.asBoolean()); } else { optionalAllversion = Optional.absent(); } final Optional<JsonNode> optionalOriginalDataTypeNode = Optional .fromNullable(json.get(DMPStatics.ORIGINAL_DATA_TYPE_IDENTIFIER)); final Optional<String> optionalOriginalDataType; if (optionalOriginalDataTypeNode.isPresent()) { final Optional<String> optionalOriginalDataTypeFromJSON = Optional .fromNullable(optionalOriginalDataTypeNode.get().asText()); if (optionalOriginalDataTypeFromJSON.isPresent()) { optionalOriginalDataType = optionalOriginalDataTypeFromJSON; } else { optionalOriginalDataType = Optional.absent(); } } else { optionalOriginalDataType = Optional.absent(); } LOG.debug("try to read XML records for data model uri = '{}' and record class uri = '{}' from graph db", dataModelUri, recordClassUri); final TransactionHandler tx = new Neo4jTransactionHandler(database); final NamespaceIndex namespaceIndex = new NamespaceIndex(database, tx); final XMLReader xmlReader = new PropertyGraphXMLReader(optionalRootAttributePath, optionalRecordTag, recordClassUri, dataModelUri, optionalVersion, optionalAllversion, optionalOriginalDataType, database, tx, namespaceIndex); final StreamingOutput stream = new StreamingOutput() { @Override public void write(final OutputStream os) throws IOException, WebApplicationException { try { final BufferedOutputStream bos = new BufferedOutputStream(os, 1024); final Optional<XMLStreamWriter> optionalWriter = xmlReader.read(bos); if (optionalWriter.isPresent()) { optionalWriter.get().flush(); optionalWriter.get().close(); LOG.debug( "finished reading '{}' XML records for data model uri = '{}' and record class uri = '{}' from graph db", xmlReader.recordCount(), dataModelUri, recordClassUri); } else { bos.close(); os.close(); LOG.debug( "couldn't find any XML records for data model uri = '{}' and record class uri = '{}' from graph db", dataModelUri, recordClassUri); } } catch (final DMPGraphException | XMLStreamException e) { throw new WebApplicationException(e); } } }; return Response.ok(stream, MediaType.APPLICATION_XML_TYPE).build(); }
From source file:io.wcm.caravan.pipeline.impl.operators.MergeTransformer.java
@Override public Observable<JsonPipelineOutput> call(Observable<JsonPipelineOutput> primaryOutput) { return primaryOutput.zipWith(secondaryOutput, (primaryModel, secondaryModel) -> { log.debug("zipping object from secondary source into target property " + targetProperty); JsonNode jsonFromPrimary = primaryModel.getPayload(); JsonNode jsonFromSecondary = secondaryModel.getPayload(); if (!(jsonFromPrimary.isObject())) { throw new JsonPipelineOutputException( "Only pipelines with JSON *Objects* can be used as a target for a merge operation, but response data for " + primaryDescriptor + " contained " + jsonFromPrimary.getClass().getSimpleName()); }//from w w w .j ava 2 s . c o m // start with cloning the the response of the primary pipeline ObjectNode mergedObject = jsonFromPrimary.deepCopy(); // if a target property is specified, the JSON to be merged is inserted into this property if (isNotBlank(targetProperty)) { if (!mergedObject.has(targetProperty)) { // the target property does not exist yet, so we just can set the property mergedObject.set(targetProperty, jsonFromSecondary); } else { // the target property already exists - let's hope we can merge! JsonNode targetNode = mergedObject.get(targetProperty); if (!targetNode.isObject()) { throw new JsonPipelineOutputException( "When merging two pipelines into the same target property, both most contain JSON *Object* responses"); } if (!(jsonFromSecondary.isObject())) { throw new JsonPipelineOutputException( "Only pipelines with JSON *Object* responses can be merged into an existing target property"); } mergeAllPropertiesInto((ObjectNode) jsonFromSecondary, (ObjectNode) targetNode); } } else { // if no target property is specified, all properties of the secondary pipeline are copied into the merged object if (!(jsonFromSecondary.isObject())) { throw new JsonPipelineOutputException( "Only pipelines with JSON *Object* responses can be merged without specify a target property"); } mergeAllPropertiesInto((ObjectNode) jsonFromSecondary, mergedObject); } return primaryModel.withPayload(mergedObject) .withMaxAge(Math.min(primaryModel.getMaxAge(), secondaryModel.getMaxAge())); }); }
From source file:com.almende.eve.agent.google.GoogleTaskAgent.java
/** * Create a task./* w w w .j a v a2s .c o m*/ * * @param task * JSON structure containing the task * @param taskListId * the task list id * @return createdTask JSON structure with the created task * @throws Exception * the exception */ @Override public ObjectNode createTask(@Name("task") final ObjectNode task, @Optional @Name("taskListId") String taskListId) throws Exception { if (taskListId == null) { taskListId = getDefaultTaskList(); } // built url final String url = CALENDAR_URI + "lists/" + taskListId + "/tasks"; // perform POST request final ObjectMapper mapper = JOM.getInstance(); final String body = mapper.writeValueAsString(task); final Map<String, String> headers = getAuthorizationHeaders(); headers.put("Content-Type", "application/json"); final String resp = HttpUtil.post(url, body, headers); final ObjectNode createdTask = mapper.readValue(resp, ObjectNode.class); // check for errors if (createdTask.has("error")) { final ObjectNode error = (ObjectNode) createdTask.get("error"); throw new JSONRPCException(error); } LOG.info("createTask=" + JOM.getInstance().writeValueAsString(createdTask)); return createdTask; }