List of usage examples for com.fasterxml.jackson.databind.node ObjectNode ObjectNode
public ObjectNode(JsonNodeFactory paramJsonNodeFactory)
From source file:org.walkmod.conf.providers.yml.AddTransformationYMLAction.java
@Override public void doAction(JsonNode chainsNode) throws Exception { ArrayNode transformationsNode = null; boolean isMultiModule = chainsNode.has("modules"); ObjectMapper mapper = provider.getObjectMapper(); if (!isMultiModule) { boolean validChainName = chain != null && !"".equals(chain) && !"default".equals(chain); if (!chainsNode.has("chains")) { if (chainsNode.has("transformations")) { JsonNode aux = chainsNode.get("transformations"); if (aux.isArray()) { transformationsNode = (ArrayNode) aux; }// www . java 2 s .c o m if (!validChainName) { ObjectNode auxRoot = (ObjectNode) chainsNode; if (transformationsNode == null) { transformationsNode = new ArrayNode(mapper.getNodeFactory()); } auxRoot.set("transformations", transformationsNode); } else { // reset the root chainsNode = new ObjectNode(mapper.getNodeFactory()); ObjectNode auxRoot = (ObjectNode) chainsNode; // the default chain list added ObjectNode chainObject = new ObjectNode(mapper.getNodeFactory()); chainObject.set("name", new TextNode("default")); chainObject.set("transformations", transformationsNode); ArrayNode chainsListNode = new ArrayNode(mapper.getNodeFactory()); // the requested chain added ObjectNode newChain = new ObjectNode(mapper.getNodeFactory()); newChain.set("name", new TextNode(chain)); if (path != null && !"".equals(path.trim())) { ObjectNode readerNode = new ObjectNode(mapper.getNodeFactory()); newChain.set("reader", readerNode); populateWriterReader(readerNode, path, null, null, null, null); ObjectNode writerNode = new ObjectNode(mapper.getNodeFactory()); newChain.set("writer", writerNode); populateWriterReader(writerNode, path, null, null, null, null); } transformationsNode = new ArrayNode(mapper.getNodeFactory()); newChain.set("transformations", transformationsNode); if (before == null || !"default".equals(before)) { chainsListNode.add(chainObject); } chainsListNode.add(newChain); if (before != null && "default".equals(before)) { chainsListNode.add(chainObject); } auxRoot.set("chains", chainsListNode); } } else { ObjectNode auxRoot = (ObjectNode) chainsNode; transformationsNode = new ArrayNode(mapper.getNodeFactory()); boolean writeChainInfo = validChainName; if (!writeChainInfo) { writeChainInfo = path != null && !"".equals(path.trim()); chain = "default"; } if (writeChainInfo) { ArrayNode auxChainsList = new ArrayNode(mapper.getNodeFactory()); ObjectNode aux = new ObjectNode(mapper.getNodeFactory()); auxChainsList.add(aux); aux.set("name", new TextNode(chain)); if (path != null && !"".equals(path.trim())) { ObjectNode readerNode = new ObjectNode(mapper.getNodeFactory()); aux.set("reader", readerNode); populateWriterReader(readerNode, path, null, null, null, null); } auxRoot.set("chains", auxChainsList); if (path != null && !"".equals(path.trim())) { ObjectNode writerNode = new ObjectNode(mapper.getNodeFactory()); aux.set("writer", writerNode); populateWriterReader(writerNode, path, null, null, null, null); } auxRoot = aux; } auxRoot.set("transformations", transformationsNode); } } else { if (validChainName) { JsonNode aux = chainsNode.get("chains"); boolean found = false; if (aux.isArray()) { Iterator<JsonNode> it = aux.elements(); while (it.hasNext()) { JsonNode next = it.next(); if (next.has("name")) { String id = next.get("name").asText(); if (chain.equals(id)) { found = true; if (next.has("transformations")) { JsonNode auxTrans = next.get("transformations"); if (auxTrans.isArray()) { transformationsNode = (ArrayNode) auxTrans; } else { throw new Exception("The chain [" + chain + "] does not have a valid transformations node"); } } else if (next.isObject()) { ObjectNode auxNext = (ObjectNode) next; transformationsNode = new ArrayNode(mapper.getNodeFactory()); auxNext.set("transformations", transformationsNode); } else { throw new Exception( "The chain [" + chain + "] does not have a valid structure"); } } } } if (!found) { ChainConfig chainCfg = new ChainConfigImpl(); chainCfg.setName(chain); WalkerConfig walkerCfg = new WalkerConfigImpl(); List<TransformationConfig> transfs = new LinkedList<TransformationConfig>(); transfs.add(transformationCfg); walkerCfg.setTransformations(transfs); chainCfg.setWalkerConfig(walkerCfg); provider.addChainConfig(chainCfg, false, before); return; } } } else { ObjectNode node = new ObjectNode(mapper.getNodeFactory()); node.set("name", new TextNode(chain)); ArrayNode transNodes = new ArrayNode(mapper.getNodeFactory()); node.set("transformations", transNodes); ArrayNode array = (ArrayNode) chainsNode.get("chains"); array.add(node); ObjectNode transformationNode = new ObjectNode(mapper.getNodeFactory()); transNodes.add(transformationNode); createTransformation(transformationNode, transformationCfg); return; } } if (transformationsNode != null) { ObjectNode transformationNode = new ObjectNode(mapper.getNodeFactory()); if (order != null && order < transformationsNode.size()) { transformationsNode.insert(order, transformationNode); } else { transformationsNode.add(transformationNode); } createTransformation(transformationNode, transformationCfg); provider.write(chainsNode); return; } else if (chain != null) { throw new Exception("The chain [" + chain + "] does not exists"); } } }
From source file:org.walkmod.conf.providers.yml.AddIncludesOrExcludesYMLAction.java
@Override public void doAction(JsonNode node) throws Exception { if (chain == null) { chain = "default"; }//from www .j ava2 s. c om ObjectMapper mapper = provider.getObjectMapper(); if (node.has("chains")) { JsonNode chains = node.get("chains"); if (chains.isArray()) { ArrayNode chainsArray = (ArrayNode) chains; int limit = chainsArray.size(); ObjectNode selectedChain = null; for (int i = 0; i < limit && selectedChain == null; i++) { JsonNode chainNode = chainsArray.get(i); if (chainNode.has("name")) { if (chainNode.get("name").asText().equals(chain)) { selectedChain = (ObjectNode) chainNode; } } } if (selectedChain == null) { selectedChain = new ObjectNode(mapper.getNodeFactory()); selectedChain.set("name", new TextNode(chain)); chainsArray.add(selectedChain); } if (setToReader) { JsonNode reader = null; if (selectedChain.has("reader")) { reader = selectedChain.get("reader"); } else { reader = new ObjectNode(mapper.getNodeFactory()); selectedChain.set("reader", reader); } setIncludesOrExcludesList((ObjectNode) reader); } if (setToWriter) { JsonNode reader = null; if (selectedChain.has("writer")) { reader = selectedChain.get("writer"); } else { reader = new ObjectNode(mapper.getNodeFactory()); selectedChain.set("writer", reader); } setIncludesOrExcludesList((ObjectNode) reader); } } } else { ObjectNode root = (ObjectNode) node; if (node.has("transformations")) { JsonNode transformations = node.get("transformations"); root.remove("transformations"); ObjectNode chainNode = new ObjectNode(mapper.getNodeFactory()); chainNode.set("name", new TextNode("default")); chainNode.set("transformations", transformations); ArrayNode chains = new ArrayNode(mapper.getNodeFactory()); chains.add(chainNode); if (!chain.equals("default")) { chainNode = new ObjectNode(mapper.getNodeFactory()); chainNode.set("name", new TextNode(chain)); chains.add(chainNode); } ObjectNode reader = new ObjectNode(mapper.getNodeFactory()); setIncludesOrExcludesList(reader); chainNode.set("reader", reader); ObjectNode writer = new ObjectNode(mapper.getNodeFactory()); setIncludesOrExcludesList(writer); chainNode.set("writer", writer); root.set("chains", chains); } else if (!node.has("modules")) { ObjectNode chainNode = new ObjectNode(mapper.getNodeFactory()); chainNode.set("name", new TextNode("default")); ArrayNode chains = new ArrayNode(mapper.getNodeFactory()); chains.add(chainNode); ObjectNode reader = new ObjectNode(mapper.getNodeFactory()); setIncludesOrExcludesList(reader); chainNode.set("reader", reader); ObjectNode writer = new ObjectNode(mapper.getNodeFactory()); setIncludesOrExcludesList(writer); chainNode.set("writer", writer); root.set("chains", chains); } } provider.write(node); }
From source file:com.stratio.ingestion.sink.kafka.KafkaSinkTest.java
@Test public void test() throws EventDeliveryException, UnsupportedEncodingException { Transaction tx = channel.getTransaction(); tx.begin();//w w w.j a va 2 s . c o m ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance); jsonBody.put("myString", "foo"); jsonBody.put("myInt32", 32); Map<String, String> headers = new HashMap<String, String>(); headers.put("myString", "bar"); headers.put("myInt64", "64"); headers.put("myBoolean", "true"); headers.put("myDouble", "1.0"); headers.put("myNull", "foobar"); Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers); channel.put(event); tx.commit(); tx.close(); kafkaSink.process(); kafka.api.FetchRequest req = new FetchRequestBuilder().clientId(CLIENT_ID).addFetch("test", 0, 0L, 100) .build(); FetchResponse fetchResponse = simpleConsumer.fetch(req); ByteBufferMessageSet messageSet = fetchResponse.messageSet("test", 0); Assert.assertTrue(messageSet.sizeInBytes() > 0); for (MessageAndOffset messageAndOffset : messageSet) { ByteBuffer payload = messageAndOffset.message().payload(); byte[] bytes = new byte[payload.limit()]; payload.get(bytes); String message = new String(bytes, "UTF-8"); Assert.assertNotNull(message); Assert.assertEquals(message, "{\"myString\":\"foo\",\"myInt32\":32}"); } }
From source file:com.redhat.lightblue.hook.audit.AuditHookTest.java
/** * Very simple (and hacky) test of document processing. * * @throws Exception//from ww w.j a v a 2s . c om */ @Test public void updateWithId() throws Exception { // verify up front there is nothing in audit collection DBCollection auditColl = mongo.getDB().createCollection("audit", null); Assert.assertEquals(0, auditColl.find().count()); // parse audit and foo metadata EntityMetadata auditMetadata = parser.parseEntityMetadata(json(FileUtil.readFile(AUDIT_METADATA_FILENAME))); EntityMetadata fooMetadata = parser.parseEntityMetadata(json(FileUtil.readFile(FOO_METADATA_FILENAME))); // create audit hook configuration AuditHookConfiguration config = new AuditHookConfiguration("foo", "0.1.0-SNAPSHOT"); // ------------------------------------------------------------ // mock up document data List<HookDoc> processedDocuments = new ArrayList<>(); // need a json node for pre and post data. will create together to make easier ObjectNode pre = new ObjectNode(JsonNodeFactory.instance); ObjectNode post = new ObjectNode(JsonNodeFactory.instance); // only set _id on post, assumes the update input doesn't have the _id post.put("_id", "ID"); // will have a field "foo" on each with different values pre.put("foo", "old"); post.put("foo", "new"); // and field "bar" with same values pre.put("bar", "same"); post.put("bar", "same"); // important, metadata on hook doc is the entity metadata (foo), not audit metadata HookDoc hd = new HookDoc(fooMetadata, new JsonDoc(pre), new JsonDoc(post), CRUDOperation.UPDATE); processedDocuments.add(hd); // ------------------------------------------------------------ // create hook AuditHook hook = new AuditHook(); // process hook hook.processHook(auditMetadata, config, processedDocuments); // verify there's one audit in database // verify up front there is nothing in audit collection Assert.assertEquals(1, auditColl.find().count()); }
From source file:com.stratio.ingestion.sink.mongodb.MongoSinkTest.java
@Test public void basicTest() throws Exception { Transaction tx = channel.getTransaction(); tx.begin();//from w w w. ja v a2s . c o m ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance); jsonBody.put("myString", "foo"); jsonBody.put("myInt32", 32); Map<String, String> headers = new HashMap<String, String>(); headers.put("myString", "bar"); // Overwrites the value defined in JSON body headers.put("myInt64", "64"); headers.put("myBoolean", "true"); headers.put("myDouble", "1.0"); headers.put("myNull", null); Date myDate = new Date(); headers.put("myDate", Long.toString(myDate.getTime())); headers.put("myString2", "baz"); Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers); channel.put(event); tx.commit(); tx.close(); mongoSink.process(); DBObject result = fongo.getDB("test").getCollection("test").findOne(); // System.out.println(result.toString()); assertThat(result).isNotNull(); assertThat(result.get("myString")).isEqualTo("bar"); assertThat(result.get("myInt32")).isEqualTo(32); assertThat(result.get("myInt32")).isInstanceOf(Integer.class); assertThat(result.get("myInt64")).isEqualTo(64L); assertThat(result.get("myInt64")).isInstanceOf(Long.class); assertThat(result.get("myBoolean")).isEqualTo(true); assertThat(result.get("myDouble")).isEqualTo(1.0); assertThat(result.get("myNull")).isNull(); assertThat(result.get("myDate")).isEqualTo(myDate); assertThat(result.get("myString2")).isNull(); assertThat(result.get("myStringMapped")).isEqualTo("baz"); }
From source file:net.pterodactylus.sone.web.ajax.GetNotificationsAjaxPage.java
/** * Creates a JSON object from the given notification. * * @param request//from ww w. ja v a 2 s. c om * The request to load the session from * @param notification * The notification to create a JSON object * @return The JSON object */ private JsonNode createJsonNotification(FreenetRequest request, Notification notification) { ObjectNode jsonNotification = new ObjectNode(instance); jsonNotification.put("id", notification.getId()); StringWriter notificationWriter = new StringWriter(); try { if (notification instanceof TemplateNotification) { TemplateContext templateContext = webInterface.getTemplateContextFactory().createTemplateContext() .mergeContext(((TemplateNotification) notification).getTemplateContext()); templateContext.set("core", webInterface.getCore()); templateContext.set("currentSone", webInterface.getCurrentSone(request.getToadletContext(), false)); templateContext.set("localSones", webInterface.getCore().getLocalSones()); templateContext.set("request", request); templateContext.set("currentVersion", SonePlugin.VERSION); templateContext.set("hasLatestVersion", webInterface.getCore().getUpdateChecker().hasLatestVersion()); templateContext.set("latestEdition", webInterface.getCore().getUpdateChecker().getLatestEdition()); templateContext.set("latestVersion", webInterface.getCore().getUpdateChecker().getLatestVersion()); templateContext.set("latestVersionTime", webInterface.getCore().getUpdateChecker().getLatestVersionDate()); templateContext.set("notification", notification); ((TemplateNotification) notification).render(templateContext, notificationWriter); } else { notification.render(notificationWriter); } } catch (IOException ioe1) { /* StringWriter never throws, ignore. */ } jsonNotification.put("text", notificationWriter.toString()); jsonNotification.put("createdTime", notification.getCreatedTime()); jsonNotification.put("lastUpdatedTime", notification.getLastUpdatedTime()); jsonNotification.put("dismissable", notification.isDismissable()); return jsonNotification; }
From source file:com.stratio.ingestion.sink.kafka.KafkaSinkTestIT.java
@Test public void test() throws EventDeliveryException, UnsupportedEncodingException { Transaction tx = channel.getTransaction(); tx.begin();/*from w w w .ja v a 2s . c o m*/ ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance); jsonBody.put("myString", "foo"); jsonBody.put("myInt32", 32); Map<String, String> headers = new HashMap<String, String>(); headers.put("myString", "bar"); headers.put("myInt64", "64"); headers.put("myBoolean", "true"); headers.put("myDouble", "1.0"); headers.put("myNull", "foobar"); Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers); channel.put(event); tx.commit(); tx.close(); kafkaSink.process(); kafka.api.FetchRequest req = new FetchRequestBuilder().clientId(CLIENT_ID).addFetch("test", 0, 0L, 100) .build(); FetchResponse fetchResponse = simpleConsumer.fetch(req); ByteBufferMessageSet messageSet = fetchResponse.messageSet("test", 0); for (MessageAndOffset messageAndOffset : messageSet) { ByteBuffer payload = messageAndOffset.message().payload(); byte[] bytes = new byte[payload.limit()]; payload.get(bytes); String message = new String(bytes, "UTF-8"); Assert.assertNotNull(message); Assert.assertEquals(message, "{\"myString\":\"foo\",\"myInt32\":32}"); } }
From source file:es.bsc.amon.controller.EventsDBMapper.java
public ObjectNode storeEvent(ObjectNode event) { long timestamp = System.currentTimeMillis(); if (event.get(EventsDBMapper.TIMESTAMP) == null) { event.put(EventsDBMapper.TIMESTAMP, timestamp); } else {// w ww . java2 s .c om timestamp = event.get(EventsDBMapper.TIMESTAMP).asLong(); } DBObject dbo = (DBObject) JSON.parse(event.toString()); if (dbo.get(ENDTIME) == null) { dbo.put(ENDTIME, -1L); } colEvents.save(dbo); // return stored id and timestamp ObjectNode on = new ObjectNode(JsonNodeFactory.instance); on.put(_ID, dbo.get(_ID).toString()); on.put(TIMESTAMP, timestamp); return on; }
From source file:fr.paris.lutece.plugins.libraryelastic.business.search.BoolQuery.java
/** * {@inheritDoc}/*from w w w. j av a2 s . c om*/ */ @Override protected ObjectNode getNodeContent(JsonNodeFactory factory) { ObjectNode content = new ObjectNode(factory); if (CollectionUtils.isNotEmpty(_listMust)) { JsonNode must; if (_listMust.size() == 1) { must = _listMust.get(0).mapToNode(factory); } else { must = new ArrayNode(factory); for (AbstractSearchLeaf searchLeaf : _listMust) { ((ArrayNode) must).add(searchLeaf.mapToNode(factory)); } } content.set("must", must); } if (CollectionUtils.isNotEmpty(_listFilter)) { JsonNode filter; if (_listFilter.size() == 1) { filter = _listFilter.get(0).mapToNode(factory); } else { filter = new ArrayNode(factory); for (AbstractSearchLeaf searchLeaf : _listFilter) { ((ArrayNode) filter).add(searchLeaf.mapToNode(factory)); } } content.set("filter", filter); } if (CollectionUtils.isNotEmpty(_listShould)) { JsonNode should; if (_listShould.size() == 1) { should = _listShould.get(0).mapToNode(factory); } else { should = new ArrayNode(factory); for (AbstractSearchLeaf searchLeaf : _listShould) { ((ArrayNode) should).add(searchLeaf.mapToNode(factory)); } } content.set("should", should); } if (CollectionUtils.isNotEmpty(_listMustNot)) { JsonNode mustNot; if (_listMustNot.size() == 1) { mustNot = _listMustNot.get(0).mapToNode(factory); } else { mustNot = new ArrayNode(factory); for (AbstractSearchLeaf searchLeaf : _listMustNot) { ((ArrayNode) mustNot).add(searchLeaf.mapToNode(factory)); } } content.set("must_not", mustNot); } return content; }
From source file:io.syndesis.maven.ExtractConnectorDescriptorsMojo.java
@Override @SuppressWarnings("PMD.EmptyCatchBlock") public void execute() throws MojoExecutionException, MojoFailureException { ArrayNode root = new ArrayNode(JsonNodeFactory.instance); URLClassLoader classLoader = null; try {/*from www.ja v a 2 s. c o m*/ PluginDescriptor desc = (PluginDescriptor) getPluginContext().get("pluginDescriptor"); List<Artifact> artifacts = desc.getArtifacts(); ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest( session.getProjectBuildingRequest()); buildingRequest.setRemoteRepositories(remoteRepositories); for (Artifact artifact : artifacts) { ArtifactResult result = artifactResolver.resolveArtifact(buildingRequest, artifact); File jar = result.getArtifact().getFile(); classLoader = createClassLoader(jar); if (classLoader == null) { throw new IOException("Can not create classloader for " + jar); } ObjectNode entry = new ObjectNode(JsonNodeFactory.instance); addConnectorMeta(entry, classLoader); addComponentMeta(entry, classLoader); if (entry.size() > 0) { addGav(entry, artifact); root.add(entry); } } if (root.size() > 0) { saveCamelMetaData(root); } } catch (ArtifactResolverException | IOException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { if (classLoader != null) { try { classLoader.close(); } catch (IOException ignored) { } } } }