Java Code Examples for com.fasterxml.jackson.databind.node.JsonNodeFactory#objectNode()

The following examples show how to use com.fasterxml.jackson.databind.node.JsonNodeFactory#objectNode() . 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: JsonPatchPatchConverter.java    From spring-sync with Apache License 2.0 6 votes vote down vote up
/**
 * Renders a {@link Patch} as a {@link JsonNode}.
 * @param patch the patch
 * @return a {@link JsonNode} containing JSON Patch.
 */
public JsonNode convert(Patch patch) {
	
	List<PatchOperation> operations = patch.getOperations();
	JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
	ArrayNode patchNode = nodeFactory.arrayNode();
	for (PatchOperation operation : operations) {
		ObjectNode opNode = nodeFactory.objectNode();
		opNode.set("op", nodeFactory.textNode(operation.getOp()));
		opNode.set("path", nodeFactory.textNode(operation.getPath()));
		if (operation instanceof FromOperation) {
			FromOperation fromOp = (FromOperation) operation;
			opNode.set("from", nodeFactory.textNode(fromOp.getFrom()));
		}
		Object value = operation.getValue();
		if (value != null) {
			opNode.set("value", MAPPER.valueToTree(value));
		}
		patchNode.add(opNode);
	}
	
	return patchNode;
}
 
Example 2
Source File: SyndEntrySerializer.java    From streams with Apache License 2.0 6 votes vote down vote up
private void serializeSource(ObjectNode root, JsonNodeFactory factory, SyndFeed source) {
  if (source == null) {
    return;
  }
  ObjectNode sourceNode = factory.objectNode();
  serializeString(source.getAuthor(), "author", sourceNode);
  serializeListOfStrings(source.getAuthors(), "authors", sourceNode, factory);
  serializeCategories(sourceNode, factory, source.getCategories());
  serializeString(source.getCopyright(), "copyright", sourceNode);
  serializeListOfStrings(source.getContributors(), "contributors", sourceNode, factory);
  serializeString(source.getDescription(), "description", sourceNode);
  serializeDescription(sourceNode, factory, source.getDescriptionEx());
  // source.getEntries(); wtf?
  serializeString(source.getFeedType(), "feedType", sourceNode);
  serializeImage(sourceNode, factory, source.getImage());
  serializeForeignMarkUp(sourceNode, factory, source.getForeignMarkup());
  serializeString(source.getLanguage(), "language", sourceNode);
  serializeString(source.getLink(), "link", sourceNode);
  serializeListOfStrings(source.getLinks(), "links", sourceNode, factory);
  serializeModules(sourceNode, factory, source.getModules());
  serializeDate(sourceNode, source.getPublishedDate(), "publishedDate");
  serializeString(source.getTitle(), "title", sourceNode);
  serializeString(source.getUri(), "uri", sourceNode);

  root.put("source", sourceNode);
}
 
Example 3
Source File: ApiService_StopTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private EventEntity mockEvent(EventType eventType) throws Exception {
    final JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode node = factory.objectNode();
    node.set("id", factory.textNode(API_ID));

    Map<String, String> properties = new HashMap<String, String>();
    properties.put(Event.EventProperties.API_ID.getValue(), API_ID);
    properties.put(Event.EventProperties.USER.getValue(), USER_NAME);

    Api api = new Api();
    api.setId(API_ID);

    EventEntity event = new EventEntity();
    event.setType(eventType);
    event.setId(UUID.randomUUID().toString());
    event.setPayload(objectMapper.writeValueAsString(api));
    event.setCreatedAt(new Date());
    event.setUpdatedAt(event.getCreatedAt());
    event.setProperties(properties);

    return event;
}
 
Example 4
Source File: ApiService_StartTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private EventEntity mockEvent(EventType eventType) throws Exception {
    final JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode node = factory.objectNode();
    node.set("id", factory.textNode(API_ID));

    Map<String, String> properties = new HashMap<>();
    properties.put(Event.EventProperties.API_ID.getValue(), API_ID);
    properties.put(Event.EventProperties.USER.getValue(), USER_NAME);

    Api api = new Api();
    api.setId(API_ID);

    EventEntity event = new EventEntity();
    event.setType(eventType);
    event.setId(UUID.randomUUID().toString());
    event.setPayload(objectMapper.writeValueAsString(api));
    event.setCreatedAt(new Date());
    event.setUpdatedAt(event.getCreatedAt());
    event.setProperties(properties);

    return event;
}
 
Example 5
Source File: ContextDataJsonAttributeConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
    if (contextData == null) {
        return null;
    }

    try {
        final JsonNodeFactory factory = OBJECT_MAPPER.getNodeFactory();
        final ObjectNode root = factory.objectNode();
        contextData.forEach(new BiConsumer<String, Object>() {
            @Override
            public void accept(final String key, final Object value) {
                // we will cheat here and write the toString of the Object... meh, but ok.
                root.put(key, String.valueOf(value));
            }
        });
        return OBJECT_MAPPER.writeValueAsString(root);
    } catch (final Exception e) {
        throw new PersistenceException("Failed to convert contextData to JSON string.", e);
    }
}
 
Example 6
Source File: SyndEntrySerializer.java    From streams with Apache License 2.0 6 votes vote down vote up
private void serializeDescription(ObjectNode root, JsonNodeFactory factory, SyndContent synd) {
  if (synd == null) {
    return;
  }
  ObjectNode content = factory.objectNode();
  if (synd.getValue() != null) {
    content.put("value", synd.getValue());
  }
  if (synd.getMode() != null) {
    content.put("mode", synd.getMode());
  }
  if (synd.getType() != null) {
    content.put("type", synd.getType());
  }
  root.put("description", content);
}
 
Example 7
Source File: PluginResultHelper.java    From cordova-hot-code-push with MIT License 6 votes vote down vote up
private static PluginResult getResult(String action, JsonNode data, JsonNode error) {
    JsonNodeFactory factory = JsonNodeFactory.instance;

    ObjectNode resultObject = factory.objectNode();
    if (action != null) {
        resultObject.set(JsParams.General.ACTION, factory.textNode(action));
    }

    if (data != null) {
        resultObject.set(JsParams.General.DATA, data);
    }

    if (error != null) {
        resultObject.set(JsParams.General.ERROR, error);
    }

    return new PluginResult(PluginResult.Status.OK, resultObject.toString());
}
 
Example 8
Source File: SyndEntrySerializer.java    From streams with Apache License 2.0 6 votes vote down vote up
private void serializeContents(ObjectNode root, JsonNodeFactory factory, List contents) {
  if (contents == null || contents.size() == 0) {
    return;
  }
  ArrayNode contentsArray = factory.arrayNode();
  for (Object obj : contents) {
    ObjectNode content = factory.objectNode();
    if (obj instanceof com.rometools.rome.feed.rss.Content) {
      com.rometools.rome.feed.rss.Content rssContent = (com.rometools.rome.feed.rss.Content) obj;
      content.put("type", rssContent.getType());
      content.put("value", rssContent.getValue());
    }
    if (obj instanceof com.rometools.rome.feed.atom.Content) {
      com.rometools.rome.feed.atom.Content atomContent = (com.rometools.rome.feed.atom.Content) obj;
      content.put("type", atomContent.getType());
      content.put("value", atomContent.getValue());
      content.put("mode", atomContent.getMode());
      content.put("src", atomContent.getSrc());
    }
    contentsArray.add(content);
  }
  root.put("contents", contentsArray);
}
 
Example 9
Source File: SyndEntrySerializer.java    From streams with Apache License 2.0 6 votes vote down vote up
private ObjectNode deserializeRomeEntry(SyndEntry entry) {
  JsonNodeFactory factory = JsonNodeFactory.instance;
  ObjectNode root = factory.objectNode();

  serializeString(entry.getAuthor(), "author", root);
  serializeListOfStrings(entry.getAuthors(), "authors", root, factory);
  serializeCategories(root, factory, entry.getCategories());
  serializeContents(root, factory, entry.getContents());
  serializeListOfStrings(entry.getContributors(), "contributors", root, factory);
  serializeDescription(root, factory, entry.getDescription());
  serializeEnclosures(root, factory, entry.getEnclosures());
  serializeForeignMarkUp(root, factory, entry.getForeignMarkup());
  serializeString(entry.getLink(), "link", root);
  serializeLinks(root, factory, entry.getLinks());
  serializeModules(root, factory, entry.getModules());
  serializeDate(root, entry.getPublishedDate(), "publishedDate");
  serializeSource(root, factory, entry.getSource());
  serializeString(entry.getTitle(), "title", root);
  serializeDate(root, entry.getUpdatedDate(), "updateDate");
  serializeString(entry.getUri(), "uri", root);

  return root;
}
 
Example 10
Source File: AbstractProducerCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
protected void afterProducer(Exchange exchange) throws IOException {
    Message in = exchange.getIn();

    JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode statusNode = factory.objectNode();

    int response = 400;
    String info = "No Information";
    HttpStatusCode code = in.getBody(HttpStatusCode.class);
    if (code != null) {
        response = code.getStatusCode();
        info = code.getInfo();
    }

    statusNode.put("Response", response);
    statusNode.put("Information", info);

    String json = OBJECT_MAPPER.writeValueAsString(statusNode);
    in.setBody(json);
}
 
Example 11
Source File: MapRestServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void setData(ObjectNode mainNode, ArrayNode arrayNode)
    throws AxelorException, JSONException {

  mainNode.put("status", 0);
  mainNode.set("data", arrayNode);
  Optional<Address> optionalAddress = Beans.get(UserService.class).getUserActiveCompanyAddress();

  if (optionalAddress.isPresent()) {
    Optional<Pair<BigDecimal, BigDecimal>> latLong =
        Beans.get(AddressService.class).getOrUpdateLatLong(optionalAddress.get());

    if (latLong.isPresent()) {
      JsonNodeFactory factory = JsonNodeFactory.instance;
      ObjectNode objectNode = factory.objectNode();
      objectNode.put("lat", latLong.get().getLeft());
      objectNode.put("lng", latLong.get().getRight());
      mainNode.set("company", objectNode);
    }
  }
}
 
Example 12
Source File: ContentConfig.java    From cordova-hot-code-push with MIT License 5 votes vote down vote up
private JsonNode generateJson() {
    JsonNodeFactory nodeFactory = JsonNodeFactory.instance;

    ObjectNode node = nodeFactory.objectNode();
    node.set(JsonKeys.CONTENT_URL, nodeFactory.textNode(contentUrl));
    node.set(JsonKeys.MINIMUM_NATIVE_VERSION, nodeFactory.numberNode(minimumNativeVersion));
    node.set(JsonKeys.VERSION, nodeFactory.textNode(releaseVersion));
    node.set(JsonKeys.UPDATE, nodeFactory.textNode(updateTime.toString()));

    return node;
}
 
Example 13
Source File: JsonDiff.java    From zjsonpatch with Apache License 2.0 5 votes vote down vote up
private static ObjectNode getJsonNode(JsonNodeFactory FACTORY, Diff diff, EnumSet<DiffFlags> flags) {
    ObjectNode jsonNode = FACTORY.objectNode();
    jsonNode.put(Constants.OP, diff.getOperation().rfcName());

    switch (diff.getOperation()) {
        case MOVE:
        case COPY:
            jsonNode.put(Constants.FROM, diff.getPath().toString());    // required {from} only in case of Move Operation
            jsonNode.put(Constants.PATH, diff.getToPath().toString());  // destination Path
            break;

        case REMOVE:
            jsonNode.put(Constants.PATH, diff.getPath().toString());
            if (!flags.contains(DiffFlags.OMIT_VALUE_ON_REMOVE))
                jsonNode.set(Constants.VALUE, diff.getValue());
            break;

        case REPLACE:
            if (flags.contains(DiffFlags.ADD_ORIGINAL_VALUE_ON_REPLACE)) {
                jsonNode.set(Constants.FROM_VALUE, diff.getSrcValue());
            }
        case ADD:
        case TEST:
            jsonNode.put(Constants.PATH, diff.getPath().toString());
            jsonNode.set(Constants.VALUE, diff.getValue());
            break;

        default:
            // Safety net
            throw new IllegalArgumentException("Unknown operation specified:" + diff.getOperation());
    }

    return jsonNode;
}
 
Example 14
Source File: ResolverCacheTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private Pair<JsonNode, JsonNode> constructJsonTree(String... properties) {
    JsonNodeFactory factory = new JsonNodeFactory(true);
    final ObjectNode parent = factory.objectNode();
    ObjectNode current = parent;

    for (String property : properties) {
        current = current.putObject(property);
    }

    current.put("key", "value");

    return Pair.of((JsonNode) parent, (JsonNode) current);
}
 
Example 15
Source File: PluginInternalPreferences.java    From cordova-hot-code-push with MIT License 5 votes vote down vote up
/**
 * Convert object into JSON string
 *
 * @return JSON string
 */
@Override
public String toString() {
    JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    ObjectNode object = nodeFactory.objectNode();
    object.set(APPLICATION_BUILD_VERSION, nodeFactory.numberNode(appBuildVersion));
    object.set(WWW_FOLDER_INSTALLED_FLAG, nodeFactory.booleanNode(wwwFolderInstalled));
    object.set(CURRENT_RELEASE_VERSION_NAME, nodeFactory.textNode(currentReleaseVersionName));
    object.set(PREVIOUS_RELEASE_VERSION_NAME, nodeFactory.textNode(previousReleaseVersionName));
    object.set(READY_FOR_INSTALLATION_RELEASE_VERSION_NAME, nodeFactory.textNode(readyForInstallationReleaseVersionName));

    return object.toString();
}
 
Example 16
Source File: ContentManifest.java    From cordova-hot-code-push with MIT License 5 votes vote down vote up
private String generateJson() {
    final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    ArrayNode filesListNode = nodeFactory.arrayNode();
    for (ManifestFile fileEntry : files) {
        ObjectNode fileNode = nodeFactory.objectNode();
        fileNode.set(JsonKeys.FILE_PATH, nodeFactory.textNode(fileEntry.name));
        fileNode.set(JsonKeys.FILE_HASH, nodeFactory.textNode(fileEntry.hash));
        filesListNode.add(fileNode);
    }

    return filesListNode.toString();
}
 
Example 17
Source File: PluginResultHelper.java    From cordova-hot-code-push with MIT License 5 votes vote down vote up
private static JsonNode createErrorNode(int errorCode, String errorDescription) {
    JsonNodeFactory factory = JsonNodeFactory.instance;

    ObjectNode errorData = factory.objectNode();
    errorData.set(JsParams.Error.CODE, factory.numberNode(errorCode));
    errorData.set(JsParams.Error.DESCRIPTION, factory.textNode(errorDescription));

    return errorData;
}
 
Example 18
Source File: MultiPointToSinglePointIntentCodecTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the multi point to single point intent decoding with JSON codec.
 *
 * @throws IOException if JSON processing fails
 */
@Test
public void decodeMultiPointToSinglePointIntent() throws IOException {

    final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    ObjectNode json = nodeFactory.objectNode();
    json.put("type", "MultiPointToSinglePointIntent");
    json.put("id", "0x0");
    json.put("appId", "foo");
    json.put("priority", 100);
    ArrayNode ingress = nodeFactory.arrayNode();
    ObjectNode ingressPoint = nodeFactory.objectNode();
    ingressPoint.put("port", "3");
    ingressPoint.put("device", "333");
    ingress.add(ingressPoint);
    ObjectNode ingressPoint2 = nodeFactory.objectNode();
    ingressPoint2.put("port", "1");
    ingressPoint2.put("device", "111");
    ingress.add(ingressPoint2);
    json.set("ingressPoint", ingress);
    ObjectNode egressPoint = nodeFactory.objectNode();
    egressPoint.put("port", "2");
    egressPoint.put("device", "222");
    json.set("egressPoint", egressPoint);
    assertThat(json, notNullValue());

    JsonCodec<MultiPointToSinglePointIntent> intentCodec = context.codec(MultiPointToSinglePointIntent.class);
    assertThat(intentCodec, notNullValue());

    final MultiPointToSinglePointIntent intent = intentCodec.decode(json, context);

    assertThat(intent.toString(), notNullValue());
    assertThat(intent, instanceOf(MultiPointToSinglePointIntent.class));
    assertThat(intent.priority(), is(100));
    assertThat(intent.ingressPoints().toString(), is("[333/3, 111/1]"));
    assertThat(intent.egressPoint().toString(), is("222/2"));

}
 
Example 19
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 20
Source File: ErrorMapTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTryToLookupInJson() {
    final JsonNodeFactory factory = JsonNodeFactory.instance;
    final ObjectNode obj = factory.objectNode();
    obj.set("a", factory.arrayNode().add("b").add("c"));
    obj.set("x", factory.objectNode().set("y", factory.objectNode().put("z", "!")));

    assertThat(ErrorMap.tryLookingUp(obj, "a")).contains("b");
    assertThat(ErrorMap.tryLookingUp(obj, "a", "b")).isEmpty();
    assertThat(ErrorMap.tryLookingUp(obj, "x", "y")).contains("{\"z\":\"!\"}");
    assertThat(ErrorMap.tryLookingUp(obj, "x", "y", "z")).contains("!");
}