List of usage examples for com.fasterxml.jackson.databind.node ObjectNode get
public JsonNode get(String paramString)
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
@Override protected InputStream replaceLink(final InputStream toBeChanged, final String linkName, final InputStream replacement) throws Exception { final ObjectMapper mapper = new ObjectMapper(); final ObjectNode toBeChangedNode = (ObjectNode) mapper.readTree(toBeChanged); final ObjectNode replacementNode = (ObjectNode) mapper.readTree(replacement); if (toBeChangedNode.get(linkName + JSON_NAVIGATION_SUFFIX) == null) { throw new NotFoundException(); }//from ww w. j a va 2 s . c o m toBeChangedNode.set(linkName, replacementNode.get(JSON_VALUE_NAME)); final JsonNode next = replacementNode.get(linkName + JSON_NEXTLINK_NAME); if (next != null) { toBeChangedNode.set(linkName + JSON_NEXTLINK_SUFFIX, next); } return IOUtils.toInputStream(toBeChangedNode.toString()); }
From source file:org.apache.nifi.processors.maxmind.DatabaseReader.java
/** * @param ipAddress IPv4 or IPv6 address to lookup. * @return An object of type T with the data for the IP address or null if no information could be found for the given IP address * @throws IOException if there is an error opening or reading from the file. *//*from w w w. j av a 2 s . co m*/ private <T> T get(InetAddress ipAddress, Class<T> cls, boolean hasTraits, String type) throws IOException, AddressNotFoundException { String databaseType = this.getMetadata().getDatabaseType(); if (!databaseType.contains(type)) { String caller = Thread.currentThread().getStackTrace()[2].getMethodName(); throw new UnsupportedOperationException( "Invalid attempt to open a " + databaseType + " database using the " + caller + " method"); } ObjectNode node = (ObjectNode) this.reader.get(ipAddress); if (node == null) { return null; } ObjectNode ipNode; if (hasTraits) { if (!node.has("traits")) { node.set("traits", this.om.createObjectNode()); } ipNode = (ObjectNode) node.get("traits"); } else { ipNode = node; } ipNode.put("ip_address", ipAddress.getHostAddress()); return this.om.treeToValue(node, cls); }
From source file:io.wcm.caravan.pipeline.impl.JsonPipelineCacheTest.java
@Test public void cacheMissAndStore() throws JSONException { CacheStrategy strategy = CacheStrategies.timeToLive(1, TimeUnit.SECONDS); JsonPipeline a = newPipelineWithResponseBody("{a: 123}"); JsonPipeline cached = a.addCachePoint(strategy); String cacheKey = "testService:GET(//testService/path)"; when(cacheAdapter.get(eq(cacheKey), anyObject())).thenReturn(Observable.empty()); String output = cached.getStringOutput().toBlocking().single(); // get must have been called to check if the document is available in the cache verify(cacheAdapter).get(eq(cacheKey), anyObject()); // put must have been called with an cache envelope version of the JSON, that contains an additional _cacheInfo verify(cacheAdapter).put(eq(cacheKey), Matchers.argThat(new BaseMatcher<String>() { @Override// w ww.j a va2 s. c o m public boolean matches(Object item) { ObjectNode storedNode = JacksonFunctions.stringToObjectNode(item.toString()); return storedNode.has("metadata") && storedNode.has("content") && storedNode.get("content").get("a").asInt() == 123; } @Override public void describeTo(Description description) { description.appendText("Expected storedObject to contain original value & _cacheInfo"); } }), anyObject()); // the _cacheInfo however should not be contained in the output JSONAssert.assertEquals("{a: 123}", output, JSONCompareMode.STRICT); }
From source file:com.almende.eve.protocol.jsonrpc.JSONRpc.java
/** * Cast a JSONArray or JSONObject params to the desired paramTypes. * /*from w w w .ja v a2s.c o m*/ * @param params * the params * @param annotatedParams * the annotated params * @param requestParams * the request params * @return the object[] */ private static Object[] castParams(final Object realDest, final ObjectNode params, final List<AnnotatedParam> annotatedParams, final RequestParams requestParams) { switch (annotatedParams.size()) { case 0: if (realDest != null) { return new Object[] { realDest }; } else { return new Object[0]; } /* -- Unreachable, explicit no break -- */ case 1: if (annotatedParams.get(0).getType().equals(ObjectNode.class) && annotatedParams.get(0).getAnnotations().size() == 0) { // the method expects one parameter of type JSONObject // feed the params object itself to it. if (realDest != null) { return new Object[] { realDest, params }; } else { return new Object[] { params }; } } /* -- Explicit no break -- */ default: final ObjectNode paramsObject = (ObjectNode) params; int offset = 0; if (realDest != null) { offset = 1; } final Object[] objects = new Object[annotatedParams.size() + offset]; if (realDest != null) { objects[0] = realDest; } for (int i = 0; i < annotatedParams.size(); i++) { final AnnotatedParam p = annotatedParams.get(i); final Annotation a = getRequestAnnotation(p, requestParams); if (a != null) { // this is a systems parameter objects[i + offset] = requestParams.get(a); } else { final String name = getName(p); if (name != null) { // this is a named parameter if (paramsObject.has(name)) { objects[i + offset] = TypeUtil.inject(paramsObject.get(name), p.getGenericType()); } else { if (isRequired(p)) { throw new ClassCastException("Required parameter '" + name + "' missing."); } else if (p.getType().isPrimitive()) { // TODO: should this test be moved to // isAvailable()? throw new ClassCastException("Parameter '" + name + "' cannot be both optional and " + "a primitive type (" + p.getType().getSimpleName() + ")"); } else { objects[i + offset] = null; } } } else { // this is a problem throw new ClassCastException("Name of parameter " + i + " not defined"); } } } return objects; } }
From source file:org.apache.taverna.scufl2.translator.t2flow.TestBeanshellActivityParser.java
@Test public void parseBeanshellScript() throws Exception { URL wfResource = getClass().getResource(WF_AS); assertNotNull("Could not find workflow " + WF_AS, wfResource); T2FlowParser parser = new T2FlowParser(); parser.setValidating(true);//from w w w . ja v a 2 s .com parser.setStrict(true); WorkflowBundle researchObj = parser.parseT2Flow(wfResource.openStream()); // System.out.println(researchObj.getProfiles().iterator().next() // .getConfigurations()); Profile profile = researchObj.getProfiles().getByName("taverna-2.1.0"); // Processors: [Workflow19, Echo_List, Concatenate_two_strings, // Concatenate_two_strings_2, Concatenate_two_strings_3, // Concatenate_two_strings_4, Create_Lots_Of_Strings, String_constant] Processor concat = researchObj.getMainWorkflow().getProcessors().getByName("Concatenate_two_strings"); Configuration concatConfig = scufl2Tools.configurationForActivityBoundToProcessor(concat, profile); Activity concatAct = (Activity) concatConfig.getConfigures(); assertEquals(ACTIVITY_URI, concatAct.getType()); ObjectNode configResource = concatConfig.getJsonAsObjectNode(); assertEquals(ACTIVITY_URI.resolve("#Config"), concatConfig.getType()); assertEquals( "http://ns.taverna.org.uk/2010/activity/localworker/org.embl.ebi.escience.scuflworkers.java.StringConcat", configResource.get("derivedFrom").asText()); String script = configResource.get("script").asText(); assertEquals("output = string1 + string2;", script); assertFalse(configResource.has("classLoader")); assertFalse(configResource.has("dependency")); Set<String> expectedInputs = new HashSet<String>(Arrays.asList("string1", "string2")); assertEquals(expectedInputs, concatAct.getInputPorts().getNames()); InputActivityPort s1 = concatAct.getInputPorts().getByName("string1"); assertEquals(0, s1.getDepth().intValue()); InputActivityPort s2 = concatAct.getInputPorts().getByName("string2"); assertEquals(0, s2.getDepth().intValue()); /** TODO: Update tests Set<PropertyResource> inputDef = configResource .getPropertiesAsResources( PORT_DEFINITION.resolve("#inputPortDefinition")); assertEquals(2, inputDef.size()); Set<URI> expectedPortUris = new HashSet<URI>(); for (InputActivityPort inPort : concatAct.getInputPorts()) { expectedPortUris.add(new URITools().relativeUriForBean(inPort, concatConfig)); } assertEquals(2, expectedPortUris.size()); assertEquals(2, inputDef.size()); for (PropertyResource portDef : inputDef) { assertEquals(PORT_DEFINITION.resolve("#InputPortDefinition"), portDef.getTypeURI()); assertNull(portDef.getResourceURI()); URI dataType = portDef.getPropertyAsResourceURI(PORT_DEFINITION .resolve("#dataType")); assertEquals("java", dataType.getScheme()); assertEquals("java.lang.String", dataType .getSchemeSpecificPart()); URI portURI = portDef.getPropertyAsResourceURI(PORT_DEFINITION .resolve("#definesInputPort")); assertTrue("Unknown port " + portURI, expectedPortUris.contains(portURI)); } // TODO: Is java class here OK? It's a beanshell script after all.. Set<String> expectedOutputs = new HashSet<String>( Arrays.asList("output")); assertEquals(expectedOutputs, concatAct.getOutputPorts().getNames()); OutputActivityPort out = concatAct.getOutputPorts().getByName("output"); assertEquals(0, out.getDepth().intValue()); Set<PropertyResource> outputDef = configResource .getPropertiesAsResources( PORT_DEFINITION.resolve("#outputPortDefinition")); assertEquals(1, outputDef.size()); PropertyResource out1Def = outputDef.iterator().next(); assertEquals(PORT_DEFINITION.resolve("#OutputPortDefinition"), out1Def.getTypeURI()); Set<URI> mimeTypes = out1Def.getPropertiesAsResourceURIs(PORT_DEFINITION .resolve("#expectedMimeType")); assertEquals(1, mimeTypes.size()); assertEquals(URI.create("http://purl.org/NET/mediatypes/text/plain"), mimeTypes.iterator().next()); */ Processor echoList = researchObj.getMainWorkflow().getProcessors().getByName("Echo_List"); Configuration echoConfig = scufl2Tools.configurationForActivityBoundToProcessor(echoList, profile); Activity echoAct = (Activity) echoConfig.getConfigures(); expectedInputs = new HashSet<String>(Arrays.asList("inputlist")); assertEquals(expectedInputs, echoAct.getInputPorts().getNames()); InputActivityPort inputList = echoAct.getInputPorts().getByName("inputlist"); assertEquals(1, inputList.getDepth().intValue()); /* TODO: Update tests expectedOutputs = new HashSet<String>(Arrays.asList("outputlist")); assertEquals(expectedOutputs, echoAct.getOutputPorts().getNames()); OutputActivityPort outputList = echoAct.getOutputPorts().getByName( "outputlist"); assertEquals(1, outputList.getDepth().intValue()); */ }
From source file:org.waarp.common.json.AdaptativeJsonHandler.java
/** * //ww w . jav a 2 s . c o m * @param node * @param field * @param defValue * @return the String if the field exists, else defValue */ public final String getValue(ObjectNode node, String field, String defValue) { JsonNode elt = node.get(field); if (elt != null) { String val = elt.asText(); if (val.equals("null")) { return defValue; } return val; } return defValue; }
From source file:org.waarp.common.json.AdaptativeJsonHandler.java
/** * //from w ww . j a va2s . co m * @param node * @param field * @param defValue * @return the byte array if the field exists, else defValue */ public final byte[] getValue(ObjectNode node, String field, byte[] defValue) { JsonNode elt = node.get(field); if (elt != null) { try { return elt.binaryValue(); } catch (IOException e) { return defValue; } } return defValue; }
From source file:com.addthis.codec.jackson.CodecTypeDeserializer.java
@Nullable private Object _deserializeObjectFromInlinedType(ObjectNode objectNode, ObjectCodec objectCodec, DeserializationContext ctxt) throws IOException { String matched = null;/* w w w . j a v a 2 s .c om*/ for (String alias : pluginMap.inlinedAliases()) { if (objectNode.get(alias) != null) { if (matched != null) { String message = String.format( "no type specified, more than one key, and both %s and %s match for inlined types.", matched, alias); JsonMappingException exception = ctxt.instantiationException(_baseType.getRawClass(), message); exception.prependPath(_baseType, matched); throw exception; } matched = alias; } } if (matched != null) { ConfigObject aliasDefaults = pluginMap.aliasDefaults(matched); JsonNode configValue = objectNode.get(matched); String primaryField = (String) aliasDefaults.get("_primary").unwrapped(); objectNode.remove(matched); Jackson.setAt(objectNode, configValue, primaryField); Jackson.merge(objectNode, Jackson.configConverter(aliasDefaults)); if (_typeIdVisible) { objectNode.put(_typePropertyName, matched); } try { JsonDeserializer<Object> deser = _findDeserializer(ctxt, matched); JsonParser treeParser = objectCodec.treeAsTokens(objectNode); treeParser.nextToken(); return deser.deserialize(treeParser, ctxt); } catch (IOException cause) { IOException unwrapped = Jackson.maybeUnwrapPath(primaryField, cause); if (unwrapped != cause) { throw wrapWithPath(unwrapped, idRes.typeFromId(ctxt, matched), matched); } else { throw unwrapped; } } } else { return null; } }
From source file:com.attribyte.essem.MGraphResponseGenerator.java
@Override public boolean generateGraph(GraphQuery graphQuery, Response esResponse, EnumSet<Option> options, RateUnit rateUnit, HttpServletResponse response) throws IOException { ObjectNode esResponseObject = mapper .readTree(parserFactory.createParser(esResponse.getBody().toByteArray())); ArrayNode targetGraph = JsonNodeFactory.instance.arrayNode(); List<String> fields = ImmutableList.copyOf(graphQuery.searchRequest.fields); if (graphQuery.isAggregation) { JsonNode aggregations = esResponseObject.get("aggregations"); if (aggregations != null && aggregations.isObject()) { String error = parseGraphAggregation(aggregations, fields, options, rateUnit, targetGraph); if (error != null) { response.sendError(500, error); return false; } else { generateGraph(targetGraph, response); return true; }//w w w . j a v a2 s . co m } else { response.sendError(500, "No graph!"); return false; } } else { parseGraph(esResponseObject, fields, options, rateUnit, targetGraph); generateGraph(targetGraph, response); return true; } }