Example usage for com.fasterxml.jackson.databind ObjectMapper createObjectNode

List of usage examples for com.fasterxml.jackson.databind ObjectMapper createObjectNode

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper createObjectNode.

Prototype

@Override
public ObjectNode createObjectNode() 

Source Link

Document

Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

Usage

From source file:com.athena.dolly.cloudant.ChangesEventListener.java

@PostConstruct
public void attachment() {

    new Thread() {
        @Override/* w w  w .  j a  v a 2  s. c  o m*/
        public void run() {
            try {
                HttpClient httpClient = new StdHttpClient.Builder().url(url).username(username)
                        .password(password).connectionTimeout(5000).socketTimeout(30000).build();

                StdCouchDbInstance dbInst = new StdCouchDbInstance(httpClient);

                logger.info("=============================================================");
                logger.info("Cloudant Database connection is established");
                logger.info("=============================================================");

                CouchDbConnector conn = dbInst.createConnector("a_samsung_file", true);
                CouchDbConnector connSeq = dbInst.createConnector("a_seq", true);

                JsonNode a_samsung_file = (JsonNode) connSeq.find(JsonNode.class, "samsung_file");
                ChangesCommand cmd = null;
                if (a_samsung_file != null) {
                    logger.info("Since: " + a_samsung_file.get("seq").textValue());
                    cmd = new ChangesCommand.Builder().since(a_samsung_file.get("seq").textValue())
                            .includeDocs(true).build();
                } else {
                    cmd = new ChangesCommand.Builder().includeDocs(true).build();
                }

                int type = 2;

                if (type == 1) {
                    // Capture changed document
                    List<DocumentChange> changes = conn.changes(cmd);
                    logger.debug(cmd.toString());

                    for (DocumentChange change : changes) {
                        logger.info(change.getId() + ", " + change.getSequence());
                    }
                } else if (type == 2) {
                    // Event Catch
                    ChangesFeed feed = conn.changesFeed(cmd);
                    while (feed.isAlive()) {
                        DocumentChange change = null;
                        try {
                            logger.debug("Waiting event from cloudant database");

                            // Retry every 5 seconds
                            change = feed.next(5, TimeUnit.SECONDS);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        if (change != null) {
                            // Compare document is changed
                            DocumentChange newChange = null;
                            do {
                                String docId = change.getId();
                                JsonNode changedDoc = change.getDocAsNode();
                                logger.info(changedDoc + ", seq=" + change.getStringSequence());

                                /**********************************************************/
                                // Send signal to client with Netty Web Socket
                                /**********************************************************/
                                WebSocketServerHandler handler = AppContext
                                        .getBean(WebSocketServerHandler.class);
                                handler.sendMessageToClient(changedDoc);

                                try {
                                    newChange = feed.poll();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            } while (newChange != null);
                            try {
                                if (a_samsung_file == null) {
                                    ObjectMapper om = new ObjectMapper();
                                    a_samsung_file = om.createObjectNode();
                                    ((ObjectNode) a_samsung_file).put("_id", "samsung_file");
                                    ((ObjectNode) a_samsung_file).put("seq", change.getStringSequence());
                                    connSeq.create(a_samsung_file);
                                } else {
                                    ((ObjectNode) a_samsung_file).put("seq", change.getStringSequence());
                                    connSeq.update(a_samsung_file);
                                }
                            } catch (Exception e) {
                                a_samsung_file = (JsonNode) connSeq.find(JsonNode.class, "samsung_file");
                                e.printStackTrace();
                            }
                            logger.info("a_samsung_file.seq=" + a_samsung_file.get("seq"));
                        }
                    }
                    // end of if
                    feed.cancel();
                } else if (type == 3) {
                    ChangesFeed feed = conn.changesFeed(cmd);
                    logger.debug("Waiting...");
                    while (feed.isAlive()) {

                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

From source file:scott.barleyrs.rest.AdminService.java

private JsonNode toJsonSchema(ObjectMapper mapper, String namespace, EntityType entityType) {
    ObjectNode schemaRoot = mapper.createObjectNode();
    schemaRoot.put("title",
            "JSON Schema for namepsace " + namespace + " and entity " + entityType.getInterfaceName());
    schemaRoot.put("type", "object");
    /*/*  w w  w.ja v a  2 s . co  m*/
     * required section.
     */
    ArrayNode required = mapper.createArrayNode();
    for (NodeType nodeType : entityType.getNodeTypes()) {
        if (nodeType.isMandatory()) {
            required.add(nodeType.getName());
        }
    }
    schemaRoot.set("required", required);

    /*
     * properties section
     */
    ObjectNode properties = mapper.createObjectNode();
    for (NodeType nodeType : entityType.getNodeTypes()) {
        if (nodeType.getEnumSpec() != null) {
            ObjectNode prop = mapper.createObjectNode();
            prop.put("type", toJSONSchemaType(nodeType.getJavaType()));
            prop.set("enum", enumValuesAsJsonArray(mapper, nodeType.getEnumSpec()));
            properties.set(nodeType.getName(), prop);
        } else if (nodeType.getJavaType() != null) {
            ObjectNode prop = mapper.createObjectNode();
            prop.put("type", toJSONSchemaType(nodeType.getJavaType()));
            properties.set(nodeType.getName(), prop);
        } else if (nodeType.getColumnName() != null && nodeType.getRelationInterfaceName() != null) {
            ObjectNode prop = mapper.createObjectNode();
            prop.put("type", "string");
            properties.set(nodeType.getName(), prop);
        }
    }
    schemaRoot.set("properties", properties);
    return schemaRoot;
}

From source file:cn.org.once.cstack.controller.ScriptingController.java

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
public @ResponseBody JsonNode scriptingSave(@RequestBody ScriptRequest scriptRequest)
        throws ServiceException, IOException, CheckException {
    logger.info("Save");
    User user = authentificationUtils.getAuthentificatedUser();
    try {/*w w  w . j av  a 2s .com*/
        if (scriptRequest.getScriptName().isEmpty() || scriptRequest.getScriptContent().isEmpty())
            throw new CheckException("Name or content cannot be empty");

        Script script = new Script();

        List<Script> scripts = scriptingService.loadAllScripts();
        for (Script script1 : scripts) {
            if (script1.getTitle().equals(scriptRequest.getScriptName()))
                throw new CheckException("Script name already exists");
        }

        Date now = new Timestamp(Calendar.getInstance().getTimeInMillis());

        script.setCreationUserId(user.getId());
        script.setTitle(scriptRequest.getScriptName());
        script.setContent(scriptRequest.getScriptContent());
        script.setCreationDate(now);

        scriptingService.save(script);

        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.createObjectNode();
        ((ObjectNode) rootNode).put("id", script.getId());
        ((ObjectNode) rootNode).put("title", script.getTitle());
        ((ObjectNode) rootNode).put("content", script.getContent());
        ((ObjectNode) rootNode).put("creation_date", script.getCreationDate().toString());
        ((ObjectNode) rootNode).put("creation_user", user.getFirstName() + " " + user.getLastName());

        return rootNode;
    } finally {
        authentificationUtils.allowUser(user);
    }
}

From source file:cn.org.once.cstack.controller.ScriptingController.java

@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public @ResponseBody JsonNode scriptingUpdate(@PathVariable @RequestBody Integer id,
        @RequestBody ScriptRequest scriptRequest) throws ServiceException, CheckException {
    logger.info("Edit");
    User user = authentificationUtils.getAuthentificatedUser();
    try {/*from   w ww. j  a  va2 s.c  om*/
        if (scriptRequest.getScriptName().isEmpty() || scriptRequest.getScriptContent().isEmpty())
            throw new CheckException("Name or content cannot be empty");

        Script script = scriptingService.load(id);

        List<Script> scripts = scriptingService.loadAllScripts();
        for (Script script1 : scripts) {
            if (script1.getTitle().equals(scriptRequest.getScriptName())
                    && !script1.getTitle().equals(script.getTitle()))
                throw new CheckException("Script name already exists");
        }

        Date now = new Timestamp(Calendar.getInstance().getTimeInMillis());

        script.setCreationDate(now);
        script.setTitle(scriptRequest.getScriptName());
        script.setContent(scriptRequest.getScriptContent());

        scriptingService.save(script);

        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.createObjectNode();
        ((ObjectNode) rootNode).put("id", script.getId());
        ((ObjectNode) rootNode).put("title", script.getTitle());
        ((ObjectNode) rootNode).put("content", script.getContent());
        ((ObjectNode) rootNode).put("creation_date", script.getCreationDate().toString());
        ((ObjectNode) rootNode).put("creation_user", user.getFirstName() + " " + user.getLastName());

        return rootNode;
    } finally {
        authentificationUtils.allowUser(user);
    }
}

From source file:io.macgyver.neorx.rest.NeoRxClientIntegrationTest.java

@Test
public void testPrimitiveValues() throws JsonProcessingException, IOException {
    ObjectMapper m = new ObjectMapper();

    JsonNode n = m.createObjectNode().set("xyz", NullNode.getInstance());
    getClient().execCypher(/*from w w w  .j  av  a  2s  .c o  m*/
            "create (a:JUnit) set a={p}, a.javaNull={javaNull},a.nullVal={nullVal}, a.intVal={intVal},a.stringVal={stringVal} return a",
            "p", n, "stringVal", m.readTree("\"foo\""), "intVal", m.readTree("3"), "nullVal",
            NullNode.getInstance(), "javaNull", null);
}

From source file:net.floodlightcontroller.configuration.ConfigurationManager.java

/**
 * Collects the configuration information from all the configuration listener.
 * /*from   w w  w .  j  a v  a2  s.co  m*/
 * @return <b>JsonNode</b> A JSON node that contains all the configuration information.
 */
private ObjectNode createJsonRootNode() {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = mapper.createObjectNode();
    for (String name : configurationListener.keySet()) {
        if (configurationListener.get(name).getJsonConfig() != null) {
            rootNode.put(name, configurationListener.get(name).getJsonConfig());
        }
    }
    return rootNode;
}

From source file:com.gsma.mobileconnect.cache.DiscoveryCacheHashMapImplTest.java

@Test
public void add_withSubscriberId_shouldRemoveSubscriberId() {
    // GIVEN//from   w  ww.ja  v a  2s.  co m
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();

    String field = "field";
    String expectedFieldValue = "field_value";
    root.put(field, expectedFieldValue);

    String subscriberId = "subscriber_id";
    String expectedSubscriberIdValue = "subscriber_id_value";
    root.put(subscriberId, expectedSubscriberIdValue);
    DiscoveryCacheValue value = new DiscoveryCacheValue(new Date(Long.MAX_VALUE), root);

    DiscoveryCacheKey key = DiscoveryCacheKey.newWithDetails("a", "a");
    IDiscoveryCache cache = Factory.getDefaultDiscoveryCache();

    // WHEN
    cache.add(key, value);
    DiscoveryCacheValue cachedValue = cache.get(key);

    // THEN
    assertNotNull(cachedValue);
    assertNotEquals(value, cachedValue);
    assertNull(cachedValue.getValue().get(subscriberId));
    assertEquals(expectedFieldValue, cachedValue.getValue().get(field).textValue());

    // Original object should not be changed.
    assertEquals(expectedSubscriberIdValue, value.getValue().get(subscriberId).textValue());
}

From source file:net.sf.taverna.t2.activities.apiconsumer.ApiConsumerActivityFactory.java

@Override
public JsonNode getActivityConfigurationSchema() {
    ObjectMapper objectMapper = new ObjectMapper();
    try {//from w w  w.  j a  va2s . c o m
        return objectMapper.readTree(getClass().getResource("/schema.json"));
    } catch (IOException e) {
        return objectMapper.createObjectNode();
    }
}

From source file:org.activiti.editor.ui.NewModelPopupWindow.java

protected void addButtons() {

    // Create/*  w w  w  . j  ava  2s  .c  o m*/
    Button createButton = new Button(i18nManager.getMessage(Messages.PROCESS_NEW_POPUP_CREATE_BUTTON));
    createButton.setWidth("200px");
    createButton.addListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {

            if (StringUtils.isEmpty((String) nameTextField.getValue())) {
                nameTextField.setComponentError(new UserError("The name field is required."));
                return;
            }

            if (selectEditorComponent.isModelerPreferred()) {
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    ObjectNode editorNode = objectMapper.createObjectNode();
                    editorNode.put("id", "canvas");
                    editorNode.put("resourceId", "canvas");
                    ObjectNode stencilSetNode = objectMapper.createObjectNode();
                    stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
                    editorNode.put("stencilset", stencilSetNode);
                    Model modelData = repositoryService.newModel();

                    ObjectNode modelObjectNode = objectMapper.createObjectNode();
                    modelObjectNode.put(MODEL_NAME, (String) nameTextField.getValue());
                    modelObjectNode.put(MODEL_REVISION, 1);
                    String description = null;
                    if (StringUtils.isNotEmpty((String) descriptionTextArea.getValue())) {
                        description = (String) descriptionTextArea.getValue();
                    } else {
                        description = "";
                    }
                    modelObjectNode.put(MODEL_DESCRIPTION, description);
                    modelData.setMetaInfo(modelObjectNode.toString());
                    modelData.setName((String) nameTextField.getValue());

                    repositoryService.saveModel(modelData);
                    repositoryService.addModelEditorSource(modelData.getId(),
                            editorNode.toString().getBytes("utf-8"));

                    close();

                    ExplorerApp.get().getViewManager().showEditorProcessDefinitionPage(modelData.getId());
                    URL explorerURL = ExplorerApp.get().getURL();
                    URL url = new URL(explorerURL.getProtocol(), explorerURL.getHost(), explorerURL.getPort(),
                            explorerURL.getPath().replace("/ui", "") + "service/editor?id="
                                    + modelData.getId());
                    ExplorerApp.get().getMainWindow().open(new ExternalResource(url));

                } catch (Exception e) {
                    notificationManager.showErrorNotification("error", e);
                }
            } else {

                close();
                ExplorerApp.get().getViewManager().showSimpleTableProcessEditor(
                        (String) nameTextField.getValue(), (String) descriptionTextArea.getValue());

            }
        }
    });

    // Alignment
    HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.addComponent(createButton);
    addComponent(buttonLayout);
    windowLayout.setComponentAlignment(buttonLayout, Alignment.MIDDLE_CENTER);
}

From source file:org.forgerock.openicf.connectors.elastic.ElasticConnector.java

private byte[] attributesToBytes(Set<Attribute> attributes) {
    try {//from  ww  w.ja v  a 2s. co m
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode objectNode = mapper.createObjectNode();
        for (Attribute attr : attributes) {
            final List<Object> value = attr.getValue();
            objectNode.putPOJO(attr.getName(),
                    value != null && value.size() > 1 ? value : AttributeUtil.getSingleValue(attr));
        }
        return mapper.writeValueAsBytes(objectNode);
    } catch (JsonProcessingException e) {
        logger.error(e, null);
        return new byte[0];
    }
}