Example usage for com.fasterxml.jackson.databind.node ObjectNode toString

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode toString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode toString.

Prototype

public String toString() 

Source Link

Usage

From source file:org.activiti.rest.service.api.identity.UserInfoResourceTest.java

/**
 * Test update info for a user.//ww  w.j a v  a 2s .  c  o  m
 */
public void testUpdateUserInfo() throws Exception {
    User savedUser = null;
    try {
        User newUser = identityService.newUser("testuser");
        newUser.setFirstName("Fred");
        newUser.setLastName("McDonald");
        newUser.setEmail("no-reply@activiti.org");
        identityService.saveUser(newUser);
        savedUser = newUser;

        identityService.setUserInfo(newUser.getId(), "key1", "Value 1");

        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("value", "Updated value");

        HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_INFO, newUser.getId(), "key1"));
        httpPut.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertEquals("key1", responseNode.get("key").textValue());
        assertEquals("Updated value", responseNode.get("value").textValue());

        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_INFO, newUser.getId(), "key1")));

        // Check if info is actually updated
        assertEquals("Updated value", identityService.getUserInfo(newUser.getId(), "key1"));

    } finally {

        // Delete user after test passes or fails
        if (savedUser != null) {
            identityService.deleteUser(savedUser.getId());
        }
    }
}

From source file:edu.nwpu.gemfire.monitor.data.DataBrowser.java

/**
 * generateQueryKey method stores queries in query history file.
 * /*from   w  w w.j a va  2s .  co m*/
 * @return Boolean true is operation is successful, false otherwise
 */
private boolean storeQueriesInFile(ObjectNode queries) {
    boolean operationStatus = false;
    FileOutputStream fileOut = null;

    File file = new File(Repository.get().getPulseConfig().getQueryHistoryFileName());
    try {
        fileOut = new FileOutputStream(file);

        // if file does not exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        // get the content in bytes
        byte[] contentInBytes = queries.toString().getBytes();

        fileOut.write(contentInBytes);
        fileOut.flush();

        operationStatus = true;
    } catch (FileNotFoundException e) {

        if (LOGGER.fineEnabled()) {
            LOGGER.fine(resourceBundle.getString("LOG_MSG_DATA_BROWSER_QUERY_HISTORY_FILE_NOT_FOUND") + " : "
                    + e.getMessage());
        }
    } catch (IOException e) {
        if (LOGGER.infoEnabled()) {
            LOGGER.info(e.getMessage());
        }
    } finally {
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (IOException e) {
                if (LOGGER.infoEnabled()) {
                    LOGGER.info(e.getMessage());
                }
            }
        }
    }
    return operationStatus;
}

From source file:org.activiti.rest.service.api.identity.UserInfoResourceTest.java

public void testCreateUserInfoExceptions() throws Exception {
    User savedUser = null;//from ww  w.ja v a 2s . c o m
    try {
        User newUser = identityService.newUser("testuser");
        newUser.setFirstName("Fred");
        newUser.setLastName("McDonald");
        newUser.setEmail("no-reply@activiti.org");
        identityService.saveUser(newUser);
        savedUser = newUser;

        // Test creating without value
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("key", "key1");

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_INFO_COLLECTION, "testuser"));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

        // Test creating without key
        requestNode = objectMapper.createObjectNode();
        requestNode.put("value", "The value");

        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

        // Test creating an already existing info
        identityService.setUserInfo(newUser.getId(), "key1", "The value");
        requestNode = objectMapper.createObjectNode();
        requestNode.put("key", "key1");
        requestNode.put("value", "The value");

        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_CONFLICT));

        // Test creating info for unexisting user
        httpPost = new HttpPost(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_INFO_COLLECTION, "unexistinguser"));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NOT_FOUND));

    } finally {

        // Delete user after test passes or fails
        if (savedUser != null) {
            identityService.deleteUser(savedUser.getId());
        }
    }
}

From source file:io.gs2.timer.Gs2TimerClient.java

/**
 * ?????<br>//from   w w  w .  jav  a2 s  .  c  o  m
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public CreateTimerPoolResult createTimerPool(CreateTimerPoolRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("name", request.getName());
    if (request.getDescription() != null)
        body.put("description", request.getDescription());

    HttpPost post = createHttpPost(Gs2Constant.ENDPOINT_HOST + "/timerPool", credential, ENDPOINT,
            CreateTimerPoolRequest.Constant.MODULE, CreateTimerPoolRequest.Constant.FUNCTION, body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    return doRequest(post, CreateTimerPoolResult.class);

}

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

protected void addButtons() {
    // Cancel//from  ww w  . j av a 2 s.c o  m
    Button cancelButton = new Button(i18nManager.getMessage(Messages.BUTTON_CANCEL));
    cancelButton.addStyleName(Reindeer.BUTTON_SMALL);
    cancelButton.addListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            close();
        }
    });

    // Create
    Button createButton = new Button(i18nManager.getMessage(Messages.PROCESS_NEW_POPUP_CREATE_BUTTON));
    createButton.addStyleName(Reindeer.BUTTON_SMALL);
    createButton.addListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {

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

            Model newModelData = repositoryService.newModel();

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

            repositoryService.saveModel(newModelData);

            repositoryService.addModelEditorSource(newModelData.getId(),
                    repositoryService.getModelEditorSource(modelData.getId()));
            repositoryService.addModelEditorSourceExtra(newModelData.getId(),
                    repositoryService.getModelEditorSourceExtra(modelData.getId()));

            close();
            ExplorerApp.get().getViewManager().showEditorProcessDefinitionPage(newModelData.getId());
        }
    });

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

From source file:org.bimserver.servlets.BimBotRunner.java

public BimBotsOutput runBimBot() throws UserException, IOException {
    BimBotContext bimBotContext = new BimBotContext() {
        @Override/*from w ww.jav a 2s . c  o  m*/
        public void updateProgress(String label, int percentage) {
            if (streamingSocketInterface != null) {
                ObjectNode message = objectMapper.createObjectNode();
                message.put("type", "progress");
                message.put("topicId", topicId);
                ObjectNode payload = objectMapper.createObjectNode();
                payload.put("progress", percentage);
                payload.put("label", label);
                message.set("payload", payload);
                streamingSocketInterface.send(message);
            }
        }

        public String getCurrentUser() {
            return authorization.getUsername();
        }

        public String getContextId() {
            return contextId;
        }
    };

    try (DatabaseSession session = bimServer.getDatabase().createSession()) {
        ServiceMap serviceMap = bimServer.getServiceFactory().get(authorization, AccessMethod.INTERNAL);
        ServiceInterface serviceInterface = serviceMap.get(ServiceInterface.class);
        if (bimServer.getServerSettingsCache().getServerSettings().isStoreServiceRuns()) {
            LOGGER.info("Storing intermediate results");
            long start = System.nanoTime();
            // When we store service runs, we can just use the streaming deserializer to stream directly to the database, after that we'll trigger the actual service

            // Create or find project and link user and service to project
            // Checkin stream into project
            // Trigger service

            byte[] data = null;
            if (bimBotsServiceInterface.needsRawInput()) {
                // We need the raw input later on, lets just get it now
                data = ByteStreams.toByteArray(inputStream);
                // Make a clean inputstream that uses the data as the original won't be available after this
                inputStream = new ByteArrayInputStream(data);
            }

            SchemaName schema = SchemaName.valueOf(inputType);
            String projectSchema = getProjectSchema(serviceInterface, schema);

            SProject project = null;
            String uuid = contextId;
            if (uuid != null) {
                project = serviceInterface.getProjectByUuid(uuid);
            } else {
                project = serviceInterface.addProject("tmp-" + new Random().nextInt(), projectSchema);
            }

            SDeserializerPluginConfiguration deserializer = serviceInterface
                    .getSuggestedDeserializerForExtension("ifc", project.getOid());
            if (deserializer == null) {
                throw new BimBotsException("No deserializer found", BimBotDefaultErrorCode.NO_DESERIALIZER);
            }
            Long topicId = serviceInterface.initiateCheckin(project.getOid(), deserializer.getOid());
            ProgressTopic progressTopic = null;
            VirtualEndPoint virtualEndpoint = null;
            try {
                progressTopic = bimServer.getNotificationsManager().getProgressTopic(topicId);
                virtualEndpoint = new VirtualEndPoint() {
                    @Override
                    public NotificationInterface getNotificationInterface() {
                        return new NotificationInterfaceAdaptor() {
                            @Override
                            public void progress(Long topicId, SLongActionState state)
                                    throws UserException, ServerException {
                                bimBotContext.updateProgress(state.getTitle(), state.getProgress());
                            }
                        };
                    }
                };
                progressTopic.register(virtualEndpoint);
            } catch (TopicRegisterException e1) {
                e1.printStackTrace();
            }
            serviceInterface.checkinInitiatedSync(topicId, project.getOid(), "Auto checkin",
                    deserializer.getOid(), -1L, "s", new DataHandler(new InputStreamDataSource(inputStream)),
                    false);
            project = serviceInterface.getProjectByPoid(project.getOid());

            PackageMetaData packageMetaData = bimServer.getMetaDataManager()
                    .getPackageMetaData(project.getSchema());
            BasicIfcModel model = new BasicIfcModel(packageMetaData, null);
            model.setPluginClassLoaderProvider(bimServer.getPluginManager());
            try {
                Revision revision = session.get(project.getLastRevisionId(), OldQuery.getDefault());
                session.getMap(model, new OldQuery(packageMetaData, project.getId(), revision.getId(),
                        revision.getOid(), Deep.NO));
                model.getModelMetaData().setIfcHeader(revision.getLastConcreteRevision().getIfcHeader());
            } catch (BimserverDatabaseException e) {
                e.printStackTrace();
            }

            BimServerBimBotsInput input = new BimServerBimBotsInput(bimServer, authorization.getUoid(),
                    inputType, data, model, false);
            BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, bimBotContext, settings);
            long end = System.nanoTime();

            if (output.getModel() != null) {
                SerializerPlugin plugin = bimServer.getPluginManager()
                        .getSerializerPlugin("org.bimserver.ifc.step.serializer.Ifc2x3tc1StepSerializerPlugin");
                Serializer serializer = plugin.createSerializer(new PluginConfiguration());
                serializer.init(output.getModel(), new ProjectInfo(), true);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                serializer.writeToOutputStream(baos, null);
                output.setData(baos.toByteArray());
                output.setContentType("application/ifc");
            }

            SExtendedData extendedData = new SExtendedData();
            SFile file = new SFile();
            file.setData(output.getData());
            file.setFilename(output.getContentDisposition());
            file.setMime(output.getContentType());
            file.setSize(output.getData().length);
            Long fileId = serviceInterface.uploadFile(file);
            extendedData.setTimeToGenerate((end - start) / 1000000);
            extendedData.setFileId(fileId);
            extendedData.setTitle(output.getTitle());
            SExtendedDataSchema extendedDataSchema = null;
            try {
                extendedDataSchema = serviceInterface.getExtendedDataSchemaByName(output.getSchemaName());
            } catch (UserException e) {
                extendedDataSchema = new SExtendedDataSchema();
                extendedDataSchema.setContentType(output.getContentType());
                extendedDataSchema.setName(output.getSchemaName());
                serviceInterface.addExtendedDataSchema(extendedDataSchema);
            }
            extendedData.setSchemaId(extendedDataSchema.getOid());
            serviceInterface.addExtendedDataToRevision(project.getLastRevisionId(), extendedData);

            output.setContextId(project.getUuid());

            if (progressTopic != null) {
                try {
                    progressTopic.unregister(virtualEndpoint);
                } catch (TopicRegisterException e) {
                    e.printStackTrace();
                }
            }

            return output;
        } else {
            // When we don't store the service runs, there is no other way than to just use the old deserializer and run the service from the EMF model
            LOGGER.info("NOT Storing intermediate results");

            String projectSchema = getProjectSchema(serviceInterface, SchemaName.valueOf(inputType));

            Schema schema = Schema.valueOf(projectSchema.toUpperCase());
            DeserializerPlugin deserializerPlugin = bimServer.getPluginManager().getFirstDeserializer("ifc",
                    schema, true);
            if (deserializerPlugin == null) {
                throw new BimBotsException("No deserializer plugin found",
                        BimBotDefaultErrorCode.NO_DESERIALIZER);
            }

            byte[] data = IOUtils.toByteArray(inputStream);

            Deserializer deserializer = deserializerPlugin.createDeserializer(new PluginConfiguration());
            PackageMetaData packageMetaData = bimServer.getMetaDataManager().getPackageMetaData(schema.name());
            deserializer.init(packageMetaData);
            IfcModelInterface model = deserializer.read(new ByteArrayInputStream(data), inputType, data.length,
                    null);

            BimServerBimBotsInput input = new BimServerBimBotsInput(bimServer, authorization.getUoid(),
                    inputType, data, model, true);
            BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, bimBotContext,
                    new PluginConfiguration(foundService.getSettings()));

            return output;
        }
    } catch (BimBotsException e) {
        ObjectNode errorNode = OBJECT_MAPPER.createObjectNode();
        errorNode.put("code", e.getErrorCode());
        errorNode.put("message", e.getMessage());
        BimBotsOutput bimBotsOutput = new BimBotsOutput("ERROR", errorNode.toString().getBytes(Charsets.UTF_8));
        return bimBotsOutput;
    } catch (Throwable e) {
        LOGGER.error("", e);
        ObjectNode errorNode = OBJECT_MAPPER.createObjectNode();
        errorNode.put("code", 500);

        // TODO should not leak this much info to called, but for now this is useful debugging info
        errorNode.put("message", "Unknown error: " + e.getMessage());
        BimBotsOutput bimBotsOutput = new BimBotsOutput("ERROR", errorNode.toString().getBytes(Charsets.UTF_8));
        return bimBotsOutput;
    }
}

From source file:io.gs2.notification.Gs2NotificationClient.java

/**
 * ?????<br>/*from  ww w.  j a  v a2s . c om*/
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public CreateNotificationResult createNotification(CreateNotificationRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("name", request.getName());
    if (request.getDescription() != null)
        body.put("description", request.getDescription());

    HttpPost post = createHttpPost(Gs2Constant.ENDPOINT_HOST + "/notification", credential, ENDPOINT,
            CreateNotificationRequest.Constant.MODULE, CreateNotificationRequest.Constant.FUNCTION,
            body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    return doRequest(post, CreateNotificationResult.class);

}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

@Override
protected InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {

    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode toBeChangedObject = (ObjectNode) mapper.readTree(toBeChanged);

    for (Map.Entry<String, InputStream> property : properties.entrySet()) {
        final JsonNode propertyNode = mapper.readTree(property.getValue());
        toBeChangedObject.set(property.getKey(), propertyNode);
    }/*from w w  w . j  a  v  a2s .c om*/

    return IOUtils.toInputStream(toBeChangedObject.toString());
}

From source file:org.activiti.rest.service.api.identity.UserResourceTest.java

/**
 * Test updating a single user passing in no fields in the json, user should remain unchanged.
 *///from   ww  w  .j  a  va 2  s.  c o m
public void testUpdateUserNullFields() throws Exception {
    User savedUser = null;
    try {
        User newUser = identityService.newUser("testuser");
        newUser.setFirstName("Fred");
        newUser.setLastName("McDonald");
        newUser.setEmail("no-reply@activiti.org");
        identityService.saveUser(newUser);
        savedUser = newUser;

        ObjectNode taskUpdateRequest = objectMapper.createObjectNode();
        taskUpdateRequest.putNull("firstName");
        taskUpdateRequest.putNull("lastName");
        taskUpdateRequest.putNull("email");
        taskUpdateRequest.putNull("password");

        HttpPut httpPut = new HttpPut(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER, newUser.getId()));
        httpPut.setEntity(new StringEntity(taskUpdateRequest.toString()));
        CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("testuser", responseNode.get("id").textValue());
        assertTrue(responseNode.get("firstName").isNull());
        assertTrue(responseNode.get("lastName").isNull());
        assertTrue(responseNode.get("email").isNull());
        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_USER, newUser.getId())));

        // Check user is updated in activiti
        newUser = identityService.createUserQuery().userId(newUser.getId()).singleResult();
        assertNull(newUser.getLastName());
        assertNull(newUser.getFirstName());
        assertNull(newUser.getEmail());

    } finally {

        // Delete user after test fails
        if (savedUser != null) {
            identityService.deleteUser(savedUser.getId());
        }
    }
}

From source file:io.gs2.realtime.Gs2RealtimeClient.java

/**
 * ?????<br>//ww w . j a v  a  2  s  .  c o  m
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public CreateGatheringPoolResult createGatheringPool(CreateGatheringPoolRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("name", request.getName());
    if (request.getDescription() != null)
        body.put("description", request.getDescription());

    HttpPost post = createHttpPost(Gs2Constant.ENDPOINT_HOST + "/gatheringPool", credential, ENDPOINT,
            CreateGatheringPoolRequest.Constant.MODULE, CreateGatheringPoolRequest.Constant.FUNCTION,
            body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    return doRequest(post, CreateGatheringPoolResult.class);

}