Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#putNull()

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#putNull() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NullSerializationTest.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
public void testCustomTreeNullsViaProvider() throws Exception
{
    ObjectNode root = MAPPER.createObjectNode();
    root.putNull("a");

    // by default, null is... well, null
    assertEquals("{\"a\":null}", MAPPER.writeValueAsString(root));

    // but then we can customize it
    ObjectMapper m = afterburnerMapperBuilder()
            .addModule(new SimpleModule()
                    .setDefaultNullValueSerializer(new NullSerializer()))
            .serializationContexts(new MyNullSerializerContexts())
            .build();
    assertEquals("{\"a\":\"foobar\"}", m.writeValueAsString(root));
}
 
Example 2
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void addFieldExcludeRoot(String dbName, String fieldName) throws Exception {
	ObjectMapper mapper = new ObjectMapper();

	ObjectNode childNode = mapper.createObjectNode();
	ArrayNode arrNode = mapper.createArrayNode();
	ObjectNode childNodeObject = mapper.createObjectNode();
	childNodeObject.put("field-name", fieldName);
	childNodeObject.put("include-root", false);
	childNodeObject.putNull("included-elements");
	childNodeObject.putNull("excluded-elements");
	childNodeObject.putNull("tokenizer-overrides");
	arrNode.add(childNodeObject);
	childNode.putArray("field").addAll(arrNode);

	setDatabaseProperties(dbName, "field", childNode);
}
 
Example 3
Source File: NodeMergeTest.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
public void testObjectDeepUpdate() throws Exception
{
    ObjectNode base = MAPPER.createObjectNode();
    ObjectNode props = base.putObject("props");
    props.put("base", 123);
    props.put("value", 456);
    ArrayNode a = props.putArray("array");
    a.add(true);
    base.putNull("misc");
    assertSame(base,
            MAPPER.readerForUpdating(base)
            .readValue(aposToQuotes(
                    "{'props':{'value':true, 'extra':25.5, 'array' : [ 3 ]}}")));
    assertEquals(2, base.size());
    ObjectNode resultProps = (ObjectNode) base.get("props");
    assertEquals(4, resultProps.size());
    
    assertEquals(123, resultProps.path("base").asInt());
    assertTrue(resultProps.path("value").asBoolean());
    assertEquals(25.5, resultProps.path("extra").asDouble());
    JsonNode n = resultProps.get("array");
    assertEquals(ArrayNode.class, n.getClass());
    assertEquals(2, n.size());
    assertEquals(3, n.get(1).asInt());
}
 
Example 4
Source File: Pods.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
static ObjectNode createJSONErrorString(String str) {
	ObjectNode outJSON = JSON_OBJECT_MAPPER.createObjectNode();
	outJSON.put("prefix", "Error");
	outJSON.put("message", Boolean.TRUE);
	outJSON.put("tag", "syntax");
	outJSON.put("symbol", "General");
	outJSON.put("text", "<math><mrow><mtext>" + str + "</mtext></mrow></math>");

	ObjectNode resultsJSON = JSON_OBJECT_MAPPER.createObjectNode();
	resultsJSON.putNull("line");
	resultsJSON.putNull("result");

	ArrayNode temp = JSON_OBJECT_MAPPER.createArrayNode();
	temp.add(outJSON);
	resultsJSON.putPOJO("out", temp);

	temp = JSON_OBJECT_MAPPER.createArrayNode();
	temp.add(resultsJSON);
	ObjectNode json = JSON_OBJECT_MAPPER.createObjectNode();
	json.putPOJO("results", temp);
	return json;
}
 
Example 5
Source File: UncachedMessageUtilImpl.java    From Javacord with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> edit(long channelId, long messageId, String content,
                                    boolean updateContent, EmbedBuilder embed, boolean updateEmbed) {
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (updateContent) {
        if (content == null) {
            body.putNull("content");
        } else {
            body.put("content", content);
        }
    }
    if (updateEmbed) {
        if (embed == null) {
            body.putNull("embed");
        } else {
            ((EmbedBuilderDelegateImpl) embed.getDelegate()).toJsonNode(body.putObject("embed"));
        }
    }
    return new RestRequest<Void>(api, RestMethod.PATCH, RestEndpoint.MESSAGE)
            .setUrlParameters(Long.toUnsignedString(channelId), Long.toUnsignedString(messageId))
            .setBody(body)
            .execute(result -> null);
}
 
Example 6
Source File: UncachedMessageUtilImpl.java    From Javacord with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> edit(long channelId, long messageId, String content,
                                    boolean updateContent, EmbedBuilder embed, boolean updateEmbed) {
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (updateContent) {
        if (content == null) {
            body.putNull("content");
        } else {
            body.put("content", content);
        }
    }
    if (updateEmbed) {
        if (embed == null) {
            body.putNull("embed");
        } else {
            ((EmbedBuilderDelegateImpl) embed.getDelegate()).toJsonNode(body.putObject("embed"));
        }
    }
    return new RestRequest<Void>(api, RestMethod.PATCH, RestEndpoint.MESSAGE)
            .setUrlParameters(Long.toUnsignedString(channelId), Long.toUnsignedString(messageId))
            .setBody(body)
            .execute(result -> null);
}
 
Example 7
Source File: ConversionUtil.java    From native-navigation with MIT License 5 votes vote down vote up
/** Converts a {@link ReadableMap} into an Json {@link ObjectNode} */
static ObjectNode toJsonObject(ReadableMap readableMap) {
  JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
  ObjectNode result = nodeFactory.objectNode();
  ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
  while (iterator.hasNextKey()) {
    String key = iterator.nextKey();
    ReadableType type = readableMap.getType(key);
    switch (type) {
      case Null:
        result.putNull(key);
        break;
      case Boolean:
        result.put(key, readableMap.getBoolean(key));
        break;
      case Number:
        result.put(key, readableMap.getDouble(key));
        break;
      case String:
        result.put(key, readableMap.getString(key));
        break;
      case Map:
        result.set(key, toJsonObject(readableMap.getMap(key)));
        break;
      case Array:
        result.set(key, toJsonArray(readableMap.getArray(key)));
        break;
      default:
        Log.e(TAG, "Could not convert object with key: " + key + ".");
    }
  }
  return result;
}
 
Example 8
Source File: CallActivityJsonConverter.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void addJsonParameters(String propertyName, String valueName, List<IOParameter> parameterList, ObjectNode propertiesNode) {
    ObjectNode parametersNode = objectMapper.createObjectNode();
    ArrayNode itemsNode = objectMapper.createArrayNode();
    for (IOParameter parameter : parameterList) {
        ObjectNode parameterItemNode = objectMapper.createObjectNode();
        if (StringUtils.isNotEmpty(parameter.getSource())) {
            parameterItemNode.put(PROPERTY_IOPARAMETER_SOURCE, parameter.getSource());
        } else {
            parameterItemNode.putNull(PROPERTY_IOPARAMETER_SOURCE);
        }
        if (StringUtils.isNotEmpty(parameter.getTarget())) {
            parameterItemNode.put(PROPERTY_IOPARAMETER_TARGET, parameter.getTarget());
        } else {
            parameterItemNode.putNull(PROPERTY_IOPARAMETER_TARGET);
        }
        if (StringUtils.isNotEmpty(parameter.getSourceExpression())) {
            parameterItemNode.put(PROPERTY_IOPARAMETER_SOURCE_EXPRESSION, parameter.getSourceExpression());
        } else {
            parameterItemNode.putNull(PROPERTY_IOPARAMETER_SOURCE_EXPRESSION);
        }

        itemsNode.add(parameterItemNode);
    }

    parametersNode.set(valueName, itemsNode);
    propertiesNode.set(propertyName, parametersNode);
}
 
Example 9
Source File: CustomEmojiUpdaterDelegateImpl.java    From Javacord with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> update() {
    // Server settings
    boolean patchEmoji = false;
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (name != null) {
        body.put("name", name);
        patchEmoji = true;
    }
    if (updateWhitelist) {
        if (whitelist == null) {
            body.putNull("roles");
        } else {
            ArrayNode jsonRoles = body.putArray("roles");
            whitelist.stream().map(Role::getIdAsString).forEach(jsonRoles::add);
        }
        patchEmoji = true;
    }
    // Only make a REST call, if we really want to update something
    if (patchEmoji) {
        return new RestRequest<Void>(emoji.getApi(), RestMethod.PATCH, RestEndpoint.CUSTOM_EMOJI)
                .setUrlParameters(emoji.getServer().getIdAsString(), emoji.getIdAsString())
                .setBody(body)
                .setAuditLogReason(reason)
                .execute(result -> null);
    }
    return CompletableFuture.completedFuture(null);
}
 
Example 10
Source File: WebhookUpdaterDelegateImpl.java    From Javacord with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Webhook> update() {
    boolean patchWebhook = false;
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (name != null) {
        body.put("name", name);
        patchWebhook = true;
    }
    if (channel != null) {
        body.put("channel_id", channel.getIdAsString());
        patchWebhook = true;
    }
    if (updateAvatar) {
        if (avatar == null) {
            body.putNull("avatar");
        }
        patchWebhook = true;
    }
    if (patchWebhook) {
        if (avatar != null) {
            return avatar.asByteArray(webhook.getApi()).thenAccept(bytes -> {
                String base64Avatar = "data:image/" + avatar.getFileType() + ";base64,"
                        + Base64.getEncoder().encodeToString(bytes);
                body.put("avatar", base64Avatar);
            }).thenCompose(aVoid ->
                    new RestRequest<Webhook>(webhook.getApi(), RestMethod.PATCH, RestEndpoint.WEBHOOK)
                    .setUrlParameters(webhook.getIdAsString())
                    .setBody(body)
                    .setAuditLogReason(reason)
                    .execute(result -> new WebhookImpl(webhook.getApi(), result.getJsonBody())));
        }
        return new RestRequest<Webhook>(webhook.getApi(), RestMethod.PATCH, RestEndpoint.WEBHOOK)
                .setUrlParameters(webhook.getIdAsString())
                .setBody(body)
                .setAuditLogReason(reason)
                .execute(result -> new WebhookImpl(webhook.getApi(), result.getJsonBody()));
    } else {
        return CompletableFuture.completedFuture(webhook);
    }
}
 
Example 11
Source File: NavigateResponseConverter.java    From graphhopper-navigation with Apache License 2.0 5 votes vote down vote up
/**
 * Banner instructions are the turn instructions that are shown to the user in the top bar.
 * <p>
 * Between two instructions we can show multiple banner instructions, you can control when they pop up using distanceAlongGeometry.
 */
private static void putBannerInstructions(InstructionList instructions, double distance, int index, Locale locale, TranslationMap translationMap, ArrayNode bannerInstructions) {
    /*
    A BannerInstruction looks like this
    distanceAlongGeometry: 107,
    primary: {
        text: "Lichtensteinstraße",
        components: [
        {
            text: "Lichtensteinstraße",
            type: "text",
        }
        ],
        type: "turn",
        modifier: "right",
    },
    secondary: null,
     */

    ObjectNode bannerInstruction = bannerInstructions.addObject();

    //Show from the beginning
    bannerInstruction.put("distanceAlongGeometry", distance);

    ObjectNode primary = bannerInstruction.putObject("primary");
    putSingleBannerInstruction(instructions.get(index + 1), locale, translationMap, primary);

    bannerInstruction.putNull("secondary");

    if (instructions.size() > index + 2 && instructions.get(index + 2).getSign() != Instruction.REACHED_VIA) {
        // Sub shows the instruction after the current one
        ObjectNode sub = bannerInstruction.putObject("sub");
        putSingleBannerInstruction(instructions.get(index + 2), locale, translationMap, sub);
    }
}
 
Example 12
Source File: JacksonJsonNode.java    From camunda-spin with Apache License 2.0 5 votes vote down vote up
public SpinJsonNode prop(String name, SpinJsonNode newProperty) {
  ObjectNode node = (ObjectNode) jsonNode;

  if (newProperty != null) {
    node.set(name, (JsonNode) newProperty.unwrap());
  }
  else {
    node.putNull(name);
  }

  return this;
}
 
Example 13
Source File: ProcessDefinitionPropertiesResource.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/process-definition/{processDefinitionId}/properties", method = RequestMethod.GET, produces = "application/json")
public ObjectNode getStartFormProperties(@ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId) {
  StartFormData startFormData = formService.getStartFormData(processDefinitionId);

  ObjectNode responseJSON = objectMapper.createObjectNode();

  ArrayNode propertiesJSON = objectMapper.createArrayNode();

  if (startFormData != null) {

    List<FormProperty> properties = startFormData.getFormProperties();

    for (FormProperty property : properties) {
      ObjectNode propertyJSON = objectMapper.createObjectNode();
      propertyJSON.put("id", property.getId());
      propertyJSON.put("name", property.getName());

      if (property.getValue() != null) {
        propertyJSON.put("value", property.getValue());
      } else {
        propertyJSON.putNull("value");
      }

      if (property.getType() != null) {
        propertyJSON.put("type", property.getType().getName());

        if (property.getType() instanceof EnumFormType) {
          @SuppressWarnings("unchecked")
          Map<String, String> valuesMap = (Map<String, String>) property.getType().getInformation("values");
          if (valuesMap != null) {
            ArrayNode valuesArray = objectMapper.createArrayNode();
            propertyJSON.put("enumValues", valuesArray);

            for (String key : valuesMap.keySet()) {
              ObjectNode valueJSON = objectMapper.createObjectNode();
              valueJSON.put("id", key);
              valueJSON.put("name", valuesMap.get(key));
              valuesArray.add(valueJSON);
            }
          }
        }

      } else {
        propertyJSON.put("type", "String");
      }

      propertyJSON.put("required", property.isRequired());
      propertyJSON.put("readable", property.isReadable());
      propertyJSON.put("writable", property.isWritable());

      propertiesJSON.add(propertyJSON);
    }
  }

  responseJSON.put("data", propertiesJSON);
  return responseJSON;
}
 
Example 14
Source File: BaseBpmnJsonConverter.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
protected void addFormProperties(List<FormProperty> formProperties, ObjectNode propertiesNode) {
  if (CollectionUtils.isEmpty(formProperties))
    return;

  ObjectNode formPropertiesNode = objectMapper.createObjectNode();
  ArrayNode propertiesArrayNode = objectMapper.createArrayNode();
  for (FormProperty property : formProperties) {
    ObjectNode propertyItemNode = objectMapper.createObjectNode();
    propertyItemNode.put(PROPERTY_FORM_ID, property.getId());
    propertyItemNode.put(PROPERTY_FORM_NAME, property.getName());
    propertyItemNode.put(PROPERTY_FORM_TYPE, property.getType());
    if (StringUtils.isNotEmpty(property.getExpression())) {
      propertyItemNode.put(PROPERTY_FORM_EXPRESSION, property.getExpression());
    } else {
      propertyItemNode.putNull(PROPERTY_FORM_EXPRESSION);
    }
    if (StringUtils.isNotEmpty(property.getVariable())) {
      propertyItemNode.put(PROPERTY_FORM_VARIABLE, property.getVariable());
    } else {
      propertyItemNode.putNull(PROPERTY_FORM_VARIABLE);
    }
    if (StringUtils.isNotEmpty(property.getDatePattern())) {
      propertyItemNode.put(PROPERTY_FORM_DATE_PATTERN, property.getDatePattern());
    }
    if (CollectionUtils.isNotEmpty(property.getFormValues())) {
      ArrayNode valuesNode = objectMapper.createArrayNode();
      for (FormValue formValue : property.getFormValues()) {
        ObjectNode valueNode = objectMapper.createObjectNode();
        valueNode.put(PROPERTY_FORM_ENUM_VALUES_NAME, formValue.getName());
        valueNode.put(PROPERTY_FORM_ENUM_VALUES_ID, formValue.getId());
        valuesNode.add(valueNode);
      }
      propertyItemNode.set(PROPERTY_FORM_ENUM_VALUES, valuesNode);
    }
    propertyItemNode.put(PROPERTY_FORM_REQUIRED, property.isRequired());
    propertyItemNode.put(PROPERTY_FORM_READABLE, property.isReadable());
    propertyItemNode.put(PROPERTY_FORM_WRITABLE, property.isWriteable());

    propertiesArrayNode.add(propertyItemNode);
  }

  formPropertiesNode.set("formProperties", propertiesArrayNode);
  propertiesNode.set(PROPERTY_FORM_PROPERTIES, formPropertiesNode);
}
 
Example 15
Source File: UserResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Test updating a single user passing in no fields in the json, user should remain unchanged.
 */
@Test
public void testUpdateUserNullFields() throws Exception {
    User savedUser = null;
    try {
        User newUser = identityService.newUser("testuser");
        newUser.setFirstName("Fred");
        newUser.setLastName("McDonald");
        newUser.setDisplayName("Fred McDonald");
        newUser.setEmail("[email protected]");
        identityService.saveUser(newUser);
        savedUser = newUser;

        ObjectNode taskUpdateRequest = objectMapper.createObjectNode();
        taskUpdateRequest.putNull("firstName");
        taskUpdateRequest.putNull("lastName");
        taskUpdateRequest.putNull("displayName");
        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);
        assertThat(responseNode).isNotNull();
        assertThatJson(responseNode)
                .when(Option.IGNORING_EXTRA_FIELDS)
                .isEqualTo("{"
                        + "id: 'testuser',"
                        + "firstName: null,"
                        + "lastName: null,"
                        + "displayName: null,"
                        + "email: null,"
                        + "url: '" + SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER, newUser.getId()) + "'"
                        + "}");

        // Check user is updated in Flowable
        newUser = identityService.createUserQuery().userId(newUser.getId()).singleResult();
        assertThat(newUser.getLastName()).isNull();
        assertThat(newUser.getFirstName()).isNull();
        assertThat(newUser.getDisplayName()).isNull();
        assertThat(newUser.getEmail()).isNull();

    } finally {

        // Delete user after test fails
        if (savedUser != null) {
            identityService.deleteUser(savedUser.getId());
        }
    }
}
 
Example 16
Source File: JSONDocumentTest.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testJsonPathPatch() throws IOException {
  String docId = "/test/testWrite1.json";
  ObjectMapper mapper = new ObjectMapper();
  ObjectNode sourceNode = makeContent(mapper);
  sourceNode.put("numberKey3" , 31);
  String content = mapper.writeValueAsString(sourceNode);
  JSONDocumentManager docMgr = Common.client.newJSONDocumentManager();
  docMgr.write(docId, new StringHandle().with(content));

  DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder().pathLanguage(
    PathLanguage.JSONPATH);

  patchBldr
    .replaceValue("$.stringKey", Cardinality.ONE, "replaced value");

  patchBldr.replaceApply("$.numberKey", patchBldr.call().add(2));

  ObjectNode fragmentNode = mapper.createObjectNode();
  fragmentNode.put("replacedChildKey", "replaced object value");
  String fragment = mapper.writeValueAsString(fragmentNode);
  patchBldr.replaceFragment("$.objectKey.childObjectKey", fragment);

  fragmentNode = mapper.createObjectNode();
  fragmentNode.put("insertedKey", 9);
  fragment = mapper.writeValueAsString(fragmentNode);
  patchBldr.insertFragment("$.[\"arrayKey\"]", Position.BEFORE, fragment);

  //patchBldr.delete("$.arrayKey.[*][?(@.string=\"3\")]");

  fragmentNode = mapper.createObjectNode();
  fragmentNode.put("appendedKey", "appended item");
  fragment = mapper.writeValueAsString(fragmentNode);
  patchBldr.insertFragment("$.[\"arrayKey\"]", Position.LAST_CHILD,
    Cardinality.ZERO_OR_ONE, fragment);
  patchBldr.replaceValue("$.booleanKey", true);
  patchBldr.replaceValue("$.numberKey2", 2);
  patchBldr.replaceValue("$.nullKey", null);
  patchBldr.library("http://marklogic.com/java-unit-test/my-lib",
    "/ext/my-lib.xqy");
  patchBldr.replaceApply("$.numberKey3",
    patchBldr.call().applyLibraryValues("getMin", 18, 21));

  DocumentPatchHandle patchHandle = patchBldr.pathLanguage(
    PathLanguage.JSONPATH).build();

  logger.debug("Patch1:" + patchHandle.toString());
  docMgr.patch(docId, patchHandle);

  ObjectNode expectedNode = mapper.createObjectNode();
  expectedNode.put("stringKey", "replaced value");
  expectedNode.put("numberKey", 9);
  ObjectNode replacedChildNode = mapper.createObjectNode();
  replacedChildNode.put("replacedChildKey", "replaced object value");
  ObjectNode childNode = mapper.createObjectNode();
  childNode.set("childObjectKey", replacedChildNode);
  expectedNode.set("objectKey", childNode);
  expectedNode.put("insertedKey", 9);
  ArrayNode childArray = mapper.createArrayNode();
  childArray.add("item value");
  childArray.add(3);
  childNode = mapper.createObjectNode();
  childNode.put("itemObjectKey", "item object value");
  childArray.add(childNode);
  childNode = mapper.createObjectNode();
  childNode.put("appendedKey", "appended item");
  childArray.add(childNode);
  expectedNode.set("arrayKey", childArray);
  expectedNode.put("booleanKey", true);
  expectedNode.put("numberKey2", 2);
  expectedNode.putNull("nullKey");
  expectedNode.put("numberKey3" , 18);

  String docText = docMgr.read(docId, new StringHandle()).get();
  assertNotNull("Read null string for patched JSON content", docText);

  logger.debug("Before1:" + content);
  logger.debug("After1:"+docText);
  logger.debug("Expected1:" + mapper.writeValueAsString(expectedNode));

  JsonNode readNode = mapper.readTree(docText);
  assertTrue("Patched JSON document without expected result",
    expectedNode.equals(readNode));

}
 
Example 17
Source File: StoreSubmittedFormCmd.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public SubmittedForm execute(CommandContext commandContext) {
  
  if (formDefinition == null || formDefinition.getId() == null) {
    throw new ActivitiFormException("Invalid form definition provided");
  }
  
  ObjectMapper objectMapper = commandContext.getFormEngineConfiguration().getObjectMapper();
  ObjectNode submittedFormValuesJson = objectMapper.createObjectNode();
  
  ObjectNode valuesNode = submittedFormValuesJson.putObject("values");
  
  // Loop over all form fields and see if a value was provided
  Map<String, FormField> fieldMap = formDefinition.allFieldsAsMap();
  for (String fieldId : fieldMap.keySet()) {
    FormField formField = fieldMap.get(fieldId);

    if (FormFieldTypes.EXPRESSION.equals(formField.getType()) || FormFieldTypes.CONTAINER.equals(formField.getType())) {
      continue;
    }

    if (variables.containsKey(fieldId)) {
      Object variableValue = variables.get(fieldId);
      if (variableValue == null) {
        valuesNode.putNull(fieldId);
      } else if (variableValue instanceof Long) {
        valuesNode.put(fieldId, (Long) variables.get(fieldId));
        
      } else if (variableValue instanceof Double) {
        valuesNode.put(fieldId, (Double) variables.get(fieldId));
      
      } else if (variableValue instanceof LocalDate) {
        valuesNode.put(fieldId, ((LocalDate) variableValue).toString());
      
      } else {
        valuesNode.put(fieldId, variableValue.toString());
      }
    }
  }

  // Handle outcome
  String outcomeVariable = null;
  if (formDefinition.getOutcomeVariableName() != null) {
    outcomeVariable = formDefinition.getOutcomeVariableName();
  } else {
    outcomeVariable = "form_" + formDefinition.getKey() + "_outcome";
  }
    
  if (variables.containsKey(outcomeVariable) && variables.get(outcomeVariable) != null) {
    submittedFormValuesJson.put("activiti_form_outcome", variables.get(outcomeVariable).toString());
  }
  
  SubmittedFormEntityManager submittedFormEntityManager = commandContext.getSubmittedFormEntityManager();
  SubmittedFormEntity submittedFormEntity = submittedFormEntityManager.create();
  submittedFormEntity.setFormId(formDefinition.getId());
  submittedFormEntity.setTaskId(taskId);
  submittedFormEntity.setProcessInstanceId(processInstanceId);
  submittedFormEntity.setSubmittedDate(new Date());
  try {
    submittedFormEntity.setFormValueBytes(objectMapper.writeValueAsBytes(submittedFormValuesJson));
  } catch (Exception e) {
    throw new ActivitiFormException("Error setting form values JSON", e);
  }
  
  submittedFormEntityManager.insert(submittedFormEntity);
  
  return submittedFormEntity;
}
 
Example 18
Source File: BaseBpmnJsonConverter.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected void addFormProperties(List<FormProperty> formProperties, ObjectNode propertiesNode) {
    if (CollectionUtils.isEmpty(formProperties))
        return;

    ObjectNode formPropertiesNode = objectMapper.createObjectNode();
    ArrayNode propertiesArrayNode = objectMapper.createArrayNode();
    for (FormProperty property : formProperties) {
        ObjectNode propertyItemNode = objectMapper.createObjectNode();
        propertyItemNode.put(PROPERTY_FORM_ID, property.getId());
        propertyItemNode.put(PROPERTY_FORM_NAME, property.getName());
        propertyItemNode.put(PROPERTY_FORM_TYPE, property.getType());
        if (StringUtils.isNotEmpty(property.getExpression())) {
            propertyItemNode.put(PROPERTY_FORM_EXPRESSION, property.getExpression());
        } else {
            propertyItemNode.putNull(PROPERTY_FORM_EXPRESSION);
        }
        if (StringUtils.isNotEmpty(property.getVariable())) {
            propertyItemNode.put(PROPERTY_FORM_VARIABLE, property.getVariable());
        } else {
            propertyItemNode.putNull(PROPERTY_FORM_VARIABLE);
        }
        if (StringUtils.isNotEmpty(property.getDefaultExpression())) {
            propertyItemNode.put(PROPERTY_FORM_DEFAULT, property.getDefaultExpression());
        } else {
            propertyItemNode.putNull(PROPERTY_FORM_DEFAULT);
        }
        if (StringUtils.isNotEmpty(property.getDatePattern())) {
            propertyItemNode.put(PROPERTY_FORM_DATE_PATTERN, property.getDatePattern());
        }
        if (CollectionUtils.isNotEmpty(property.getFormValues())) {
            ArrayNode valuesNode = objectMapper.createArrayNode();
            for (FormValue formValue : property.getFormValues()) {
                ObjectNode valueNode = objectMapper.createObjectNode();
                valueNode.put(PROPERTY_FORM_ENUM_VALUES_NAME, formValue.getName());
                valueNode.put(PROPERTY_FORM_ENUM_VALUES_ID, formValue.getId());
                valuesNode.add(valueNode);
            }
            propertyItemNode.set(PROPERTY_FORM_ENUM_VALUES, valuesNode);
        }
        propertyItemNode.put(PROPERTY_FORM_REQUIRED, property.isRequired());
        propertyItemNode.put(PROPERTY_FORM_READABLE, property.isReadable());
        propertyItemNode.put(PROPERTY_FORM_WRITABLE, property.isWriteable());

        propertiesArrayNode.add(propertyItemNode);
    }

    formPropertiesNode.set("formProperties", propertiesArrayNode);
    propertiesNode.set(PROPERTY_FORM_PROPERTIES, formPropertiesNode);
}
 
Example 19
Source File: JSONDocumentTest.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testXPathPatch() throws IOException {
  String docId = "/test/testWrite1.json";
  ObjectMapper mapper = new ObjectMapper();
  ObjectNode sourceNode = makeContent(mapper);
  sourceNode.put("numberKey3", 31);
  String content = mapper.writeValueAsString(sourceNode);

  JSONDocumentManager docMgr = Common.client.newJSONDocumentManager();
  docMgr.write(docId, new StringHandle().with(content));

  DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();

  patchBldr.replaceValue("/stringKey", Cardinality.ONE, "replaced value");

  patchBldr.replaceApply("/numberKey", patchBldr.call().add(2));

  ObjectNode fragmentNode = mapper.createObjectNode();
  fragmentNode.put("replacedChildKey", "replaced object value");
  String fragment = mapper.writeValueAsString(fragmentNode);
  patchBldr.replaceFragment("/objectKey/childObjectKey", fragment);

  fragmentNode = mapper.createObjectNode();
  fragmentNode.put("insertedKey", 9);
  fragment = mapper.writeValueAsString(fragmentNode);
  patchBldr.insertFragment("/array-node('arrayKey')", Position.BEFORE,
    fragment);
  patchBldr.replaceValue("/booleanKey", true);
  patchBldr.replaceValue("/numberKey2", 2);
  patchBldr.replaceValue("/nullKey", null);
  patchBldr.library("http://marklogic.com/java-unit-test/my-lib",
    "/ext/my-lib.xqy");
  patchBldr.replaceApply("/numberKey3",
    patchBldr.call().applyLibraryValues("getMin", 18, 21));
  //patchBldr.replaceApply("/node()/arrayKey/node()[string(.) eq '3']",
  //		patchBldr.call().add(2));

  fragmentNode = mapper.createObjectNode();
  fragmentNode.put("appendedKey", "appended item");
  fragment = mapper.writeValueAsString(fragmentNode);
  patchBldr.insertFragment("/array-node('arrayKey')",
    Position.LAST_CHILD, Cardinality.ZERO_OR_ONE, fragment);

  DocumentPatchHandle patchHandle = patchBldr.build();

  logger.debug("Sending patch 3:" + patchBldr.build().toString());
  docMgr.patch(docId, patchHandle);

  ObjectNode expectedNode = mapper.createObjectNode();
  expectedNode.put("stringKey", "replaced value");
  expectedNode.put("numberKey",  9);
  ObjectNode replacedChildNode = mapper.createObjectNode();
  replacedChildNode.put("replacedChildKey", "replaced object value");
  ObjectNode childNode = mapper.createObjectNode();
  childNode.set("childObjectKey", replacedChildNode);
  expectedNode.set("objectKey", childNode);
  expectedNode.put("insertedKey", 9);
  ArrayNode childArray = mapper.createArrayNode();
  childArray.add("item value");
  childArray.add(3);
  childNode = mapper.createObjectNode();
  childNode.put("itemObjectKey", "item object value");
  childArray.add(childNode);
  childNode = mapper.createObjectNode();
  childNode.put("appendedKey", "appended item");
  childArray.add(childNode);
  expectedNode.set("arrayKey", childArray);
  expectedNode.put("booleanKey", true);
  expectedNode.put("numberKey2", 2);
  expectedNode.putNull("nullKey");
  expectedNode.put("numberKey3", 18);

  String docText = docMgr.read(docId, new StringHandle()).get();

  assertNotNull("Read null string for patched JSON content", docText);
  JsonNode readNode = mapper.readTree(docText);

  logger.debug("Before3:" + content);
  logger.debug("After3:"+docText);
  logger.debug("Expected3:" + mapper.writeValueAsString(expectedNode));

  assertTrue("Patched JSON document without expected result",
    expectedNode.equals(readNode));

  docMgr.delete(docId);
}
 
Example 20
Source File: JsonNodeELResolver.java    From activiti6-boot2 with Apache License 2.0 3 votes vote down vote up
/**
 * If the base object is a map, attempts to set the value associated with the given key, as
 * specified by the property argument. If the base is a Map, the propertyResolved property of
 * the ELContext object must be set to true by this resolver, before returning. If this property
 * is not true after this method is called, the caller can safely assume no value was set. If
 * this resolver was constructed in read-only mode, this method will always throw
 * PropertyNotWritableException. If a Map was created using
 * java.util.Collections.unmodifiableMap(Map), this method must throw
 * PropertyNotWritableException. Unfortunately, there is no Collections API method to detect
 * this. However, an implementation can create a prototype unmodifiable Map and query its
 * runtime type to see if it matches the runtime type of the base object as a workaround.
 * 
 * @param context
 *            The context of this evaluation.
 * @param base
 *            The map to analyze. Only bases of type Map are handled by this resolver.
 * @param property
 *            The key to return the acceptable type for. Ignored by this resolver.
 * @param value
 *            The value to be associated with the specified key.
 * @throws ClassCastException
 *             if the class of the specified key or value prevents it from being stored in this
 *             map.
 * @throws NullPointerException
 *             if context is null, or if this map does not permit null keys or values, and the
 *             specified key or value is null.
 * @throws IllegalArgumentException
 *             if some aspect of this key or value prevents it from being stored in this map.
 * @throws PropertyNotWritableException
 *             if this resolver was constructed in read-only mode, or if the put operation is
 *             not supported by the underlying map.
 * @throws ELException
 *             if an exception was thrown while performing the property or variable resolution.
 *             The thrown exception must be included as the cause property of this exception, if
 *             available.
 */
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
  if (context == null) {
    throw new NullPointerException("context is null");
  }
  if (base instanceof ObjectNode) {
    if (readOnly) {
      throw new PropertyNotWritableException("resolver is read-only");
    }
    ObjectNode node = (ObjectNode) base;
    if (value instanceof BigDecimal) {
      node.put(property.toString(), (BigDecimal) value);
      
    } else if (value instanceof Boolean) {
      node.put(property.toString(), (Boolean) value);
      
    } else if (value instanceof Long) {
      node.put(property.toString(), (Long) value);
      
    } else if (value instanceof Double) {
      node.put(property.toString(), (Double) value);
    
    } else if (value != null) {
      node.put(property.toString(), value.toString());
    
    } else {
      node.putNull(property.toString());
    }
    context.setPropertyResolved(true);
  }
}