Java Code Examples for com.fasterxml.jackson.databind.node.JsonNodeFactory

The following are top voted examples for showing how to use com.fasterxml.jackson.databind.node.JsonNodeFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: PropertiesRule.java   View source code 6 votes vote down vote up
/**
 * Applies this schema rule to take the required code generation steps.
 * <p>
 * For each property present within the properties node, this rule will
 * invoke the 'property' rule provided by the given schema mapper.
 *
 * @param nodeName
 *            the name of the node for which properties are being added
 * @param node
 *            the properties node, containing property names and their
 *            definition
 * @param jclass
 *            the Java type which will have the given properties added
 * @return the given jclass
 */
@Override
public JDefinedClass apply(String nodeName, JsonNode node, JDefinedClass jclass, Schema schema) {
    if (node == null) {
        node = JsonNodeFactory.instance.objectNode();
    }

    for (Iterator<String> properties = node.fieldNames(); properties.hasNext(); ) {
        String property = properties.next();

        ruleFactory.getPropertyRule().apply(property, node.get(property), jclass, schema);
    }

    if (ruleFactory.getGenerationConfig().isGenerateBuilders() && !jclass._extends().name().equals("Object")) {
        addOverrideBuilders(jclass, jclass.owner()._getClass(jclass._extends().fullName()));
    }

    ruleFactory.getAnnotator().propertyOrder(jclass, node);

    return jclass;
}
 
Example 2
Project: kafka-0.11.0.0-src-with-comment   File: JsonConverter.java   View source code 6 votes vote down vote up
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
    JsonNode jsonValue;
    try {
        jsonValue = deserializer.deserialize(topic, value);
    } catch (SerializationException e) {
        throw new DataException("Converting byte[] to Kafka Connect data failed due to serialization error: ", e);
    }

    if (enableSchemas && (jsonValue == null || !jsonValue.isObject() || jsonValue.size() != 2 || !jsonValue.has("schema") || !jsonValue.has("payload")))
        throw new DataException("JsonConverter with schemas.enable requires \"schema\" and \"payload\" fields and may not contain additional fields." +
                " If you are trying to deserialize plain JSON data, set schemas.enable=false in your converter configuration.");

    // The deserialized data should either be an envelope object containing the schema and the payload or the schema
    // was stripped during serialization and we need to fill in an all-encompassing schema.
    if (!enableSchemas) {
        ObjectNode envelope = JsonNodeFactory.instance.objectNode();
        envelope.set("schema", null);
        envelope.set("payload", jsonValue);
        jsonValue = envelope;
    }

    return jsonToConnect(jsonValue);
}
 
Example 3
Project: BIMplatform   File: GlbToB3dmConvertor.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	GlbToB3dmConvertor convertor = new GlbToB3dmConvertor();
	JsonNodeFactory factory = new JsonNodeFactory(false);
	try {
		ObjectNode featureTableJsonNode = factory.objectNode();
		featureTableJsonNode.put("BATCH_LENGTH", 0);
		ByteBuffer glbBuffer = convertor.getBufferFromUri("", new File("D:\\tttt.glb").toPath());
		ByteBuffer b3dmBuffer = convertor.glbToB3dm(glbBuffer, featureTableJsonNode);
		OutputStream os = new FileOutputStream(new File("D:\\tttt.b3dm"));
		os.write(b3dmBuffer.array());
		os.flush();
		os.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
	
}
 
Example 4
Project: webmate-sdk-java   File: BrowserSessionRegressionJobInput.java   View source code 6 votes vote down vote up
@Override
public Map<PortName, BrickValue> makeInputValues() {
    JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance;
    ObjectMapper mapper = new ObjectMapper();

    List<JsonNode> compareSessionJson = new ArrayList<>();
    JsonNode sessionNode = mapper.valueToTree(compareSession);
    BrickValue sessionBrickValue = new BrickValue(new BrickDataType("BrowserSessionRef"), sessionNode);
    compareSessionJson.add(mapper.valueToTree(sessionBrickValue));

    return ImmutableMap.of(
            new PortName("referenceSession"), new BrickValue(new BrickDataType("BrowserSessionRef"), jsonNodeFactory.textNode(referenceSession.getValueAsString())),
            new PortName("compareSession"), new BrickValue(new BrickDataType("BrowserSessionRef"), jsonNodeFactory.textNode(compareSession.getValueAsString())),
            new PortName("matchingType"), new BrickValue(new BrickDataType("String"), jsonNodeFactory.textNode("tag")),
            new PortName("enabledynamicelementsfilter"), new BrickValue(new BrickDataType("Boolean"), jsonNodeFactory.booleanNode(true))
    );
}
 
Example 5
Project: rskj   File: NetworkStateExporter.java   View source code 6 votes vote down vote up
public boolean exportStatus(String outputFile) {
    Repository frozenRepository = this.repository.getSnapshotTo(this.repository.getRoot());

    File dumpFile = new File(outputFile);

    try(FileWriter fw = new FileWriter(dumpFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw)) {
        JsonNodeFactory jsonFactory = new JsonNodeFactory(false);
        ObjectNode mainNode = jsonFactory.objectNode();
        for (ByteArrayWrapper address : frozenRepository.getAccountsKeys()) {
            if(!address.equals(new ByteArrayWrapper(ZERO_BYTE_ARRAY))) {
                mainNode.set(Hex.toHexString(address.getData()), createAccountNode(mainNode, address.getData(), frozenRepository));
            }
        }
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
        bw.write(writer.writeValueAsString(mainNode));
        return true;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        panicProcessor.panic("dumpstate", e.getMessage());
        return false;
    }
}
 
Example 6
Project: kafka-0.11.0.0-src-with-comment   File: JsonConverterTest.java   View source code 6 votes vote down vote up
@Test
public void mapToJsonNonStringKeys() {
    Schema intIntMap = SchemaBuilder.map(Schema.INT32_SCHEMA, Schema.INT32_SCHEMA).build();
    Map<Integer, Integer> input = new HashMap<>();
    input.put(1, 12);
    input.put(2, 15);
    JsonNode converted = parse(converter.fromConnectData(TOPIC, intIntMap, input));
    validateEnvelope(converted);
    assertEquals(parse("{ \"type\": \"map\", \"keys\": { \"type\" : \"int32\", \"optional\": false }, \"values\": { \"type\" : \"int32\", \"optional\": false }, \"optional\": false }"),
            converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));

    assertTrue(converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME).isArray());
    ArrayNode payload = (ArrayNode) converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME);
    assertEquals(2, payload.size());
    Set<JsonNode> payloadEntries = new HashSet<>();
    for (JsonNode elem : payload)
        payloadEntries.add(elem);
    assertEquals(new HashSet<>(Arrays.asList(JsonNodeFactory.instance.arrayNode().add(1).add(12),
                    JsonNodeFactory.instance.arrayNode().add(2).add(15))),
            payloadEntries
    );
}
 
Example 7
Project: dataplatform-schema-lib   File: JacksonArrayFormatter.java   View source code 6 votes vote down vote up
@Override
public JsonNode write( final Object obj ) throws IOException{
  ArrayNode array = new ArrayNode( JsonNodeFactory.instance );
  if( ! ( obj instanceof List ) ){
    return array;
  }

  List<Object> listObj = (List)obj;
  for( Object childObj : listObj ){
    if( childObj instanceof List ){
      array.add( JacksonContainerToJsonObject.getFromList( (List<Object>)childObj ) );
    }
    else if( childObj instanceof Map ){
      array.add( JacksonContainerToJsonObject.getFromMap( (Map<Object,Object>)childObj ) );
    }
    else{
      array.add( ObjectToJsonNode.get( childObj ) );
    }
  }

  return array;
}
 
Example 8
Project: dataplatform-schema-lib   File: JacksonArrayFormatter.java   View source code 6 votes vote down vote up
@Override
public JsonNode writeParser( final IParser parser ) throws IOException{
  ArrayNode array = new ArrayNode( JsonNodeFactory.instance );
  for( int i = 0 ; i < parser.size() ; i++ ){
    IParser childParser = parser.getParser( i );
    if( childParser.isMap() || childParser.isStruct() ){
      array.add( JacksonParserToJsonObject.getFromObjectParser( childParser ) );
    }
    else if( childParser.isArray() ){
      array.add( JacksonParserToJsonObject.getFromArrayParser( childParser ) );
    }
    else{
      array.add( PrimitiveObjectToJsonNode.get( parser.get( i ) ) );
    }
  }
  return array;
}
 
Example 9
Project: dataplatform-schema-lib   File: JacksonObjectFormatter.java   View source code 6 votes vote down vote up
@Override
public JsonNode write( final Object obj ) throws IOException{
  ObjectNode objectNode = new ObjectNode( JsonNodeFactory.instance );
  if( ! ( obj instanceof Map ) ){
    return objectNode;
  }

  Map<Object,Object> mapObj = (Map<Object,Object>)obj;
  for( Map.Entry<Object,Object> entry : mapObj.entrySet() ){
    String key = entry.getKey().toString();
    Object childObj = entry.getValue();
    if( childObj instanceof List ){
      objectNode.put( key , JacksonContainerToJsonObject.getFromList( (List<Object>)childObj ) );
    }
    else if( childObj instanceof Map ){
      objectNode.put( key , JacksonContainerToJsonObject.getFromMap( (Map<Object,Object>)childObj ) );
    }
    else{
      objectNode.put( key , ObjectToJsonNode.get( childObj ) );
    }
  }

  return objectNode;
}
 
Example 10
Project: dataplatform-schema-lib   File: JacksonObjectFormatter.java   View source code 6 votes vote down vote up
@Override
public JsonNode writeParser( final IParser parser ) throws IOException{
  ObjectNode objectNode = new ObjectNode( JsonNodeFactory.instance );
  for( String key : parser.getAllKey() ){
    IParser childParser = parser.getParser( key );
    if( childParser.isMap() || childParser.isStruct() ){
      objectNode.put( key , JacksonParserToJsonObject.getFromObjectParser( childParser ) );
    }
    else if( childParser.isArray() ){
      objectNode.put( key , JacksonParserToJsonObject.getFromArrayParser( childParser ) );
    }
    else{
      objectNode.put( key , PrimitiveObjectToJsonNode.get( parser.get( key ) ) );
    }
  }
  return objectNode;
}
 
Example 11
Project: exam   File: ReservationController.java   View source code 6 votes vote down vote up
private ArrayNode asJson(List<User> users) {
    ArrayNode array = JsonNodeFactory.instance.arrayNode();
    for (User u : users) {
        String name = String.format("%s %s", u.getFirstName(), u.getLastName());
        if (u.getUserIdentifier() != null) {
            name += String.format(" (%s)", u.getUserIdentifier());
        }
        ObjectNode part = Json.newObject();
        part.put("id", u.getId());
        part.put("firstName", u.getFirstName());
        part.put("lastName", u.getLastName());
        part.put("userIdentifier", u.getUserIdentifier());
        part.put("name", name);
        array.add(part);
    }
    return array;
}
 
Example 12
Project: athena   File: BgpConfig.java   View source code 6 votes vote down vote up
/**
 * Adds BGP speaker to configuration.
 *
 * @param speaker BGP speaker configuration entry
 */
public void addSpeaker(BgpSpeakerConfig speaker) {
    ObjectNode speakerNode = JsonNodeFactory.instance.objectNode();

    speakerNode.put(NAME, speaker.name().get());

    speakerNode.put(VLAN, speaker.vlan().toString());

    speakerNode.put(CONNECT_POINT, speaker.connectPoint().elementId().toString()
            + "/" + speaker.connectPoint().port().toString());

    ArrayNode peersNode = speakerNode.putArray(PEERS);
    for (IpAddress peerAddress: speaker.peers()) {
        peersNode.add(peerAddress.toString());
    }

    ArrayNode speakersArray = bgpSpeakers().isEmpty() ?
            initBgpConfiguration() : (ArrayNode) object.get(SPEAKERS);
    speakersArray.add(speakerNode);
}
 
Example 13
Project: commercetools-sync-java   File: CategorySyncIT.java   View source code 6 votes vote down vote up
@Test
public void syncDrafts_WithValidCustomFieldsChange_ShouldSyncIt() {
    final List<CategoryDraft> newCategoryDrafts = new ArrayList<>();

    final Map<String, JsonNode> customFieldsJsons = new HashMap<>();
    customFieldsJsons.put(BOOLEAN_CUSTOM_FIELD_NAME, JsonNodeFactory.instance.booleanNode(false));
    customFieldsJsons
        .put(LOCALISED_STRING_CUSTOM_FIELD_NAME, JsonNodeFactory.instance.objectNode()
                                                                         .put("de", "rot")
                                                                         .put("en", "red")
                                                                         .put("it", "rosso"));

    final CategoryDraft categoryDraft1 = CategoryDraftBuilder
        .of(LocalizedString.of(Locale.ENGLISH, "Modern Furniture"),
            LocalizedString.of(Locale.ENGLISH, "modern-furniture"))
        .key(oldCategoryKey)
        .custom(CustomFieldsDraft.ofTypeIdAndJson(OLD_CATEGORY_CUSTOM_TYPE_KEY, customFieldsJsons))
        .build();

    newCategoryDrafts.add(categoryDraft1);

    final CategorySyncStatistics syncStatistics = categorySync.sync(newCategoryDrafts).toCompletableFuture().join();

    assertThat(syncStatistics).hasValues(1, 0, 1, 0, 0);
}
 
Example 14
Project: commercetools-sync-java   File: VariantReferenceResolverTest.java   View source code 6 votes vote down vote up
@Test
public void resolveAttributeReference_WithProductReferenceAttribute_ShouldResolveAttribute() {
    when(productService.fetchCachedProductId(anyString()))
        .thenReturn(CompletableFuture.completedFuture(Optional.empty()));

    final ObjectNode attributeValue = JsonNodeFactory.instance.objectNode();
    attributeValue.put("typeId", "product");
    attributeValue.put("id", "nonExistingProductKey");
    final AttributeDraft productReferenceAttribute = AttributeDraft.of("attributeName", attributeValue);

    final AttributeDraft resolvedAttributeDraft =
        referenceResolver.resolveAttributeReference(productReferenceAttribute)
                         .toCompletableFuture().join();
    assertThat(resolvedAttributeDraft).isNotNull();
    assertThat(resolvedAttributeDraft).isSameAs(productReferenceAttribute);
}
 
Example 15
Project: commercetools-sync-java   File: VariantReferenceResolverTest.java   View source code 6 votes vote down vote up
@Test
public void resolveAttributeReference_WithEmptyReferenceSetAttribute_ShouldNotResolveReferences() {
    final ArrayNode referenceSet = JsonNodeFactory.instance.arrayNode();

    final AttributeDraft productReferenceAttribute = AttributeDraft.of("attributeName", referenceSet);

    final AttributeDraft resolvedAttributeDraft =
        referenceResolver.resolveAttributeReference(productReferenceAttribute)
                         .toCompletableFuture().join();
    assertThat(resolvedAttributeDraft).isNotNull();
    assertThat(resolvedAttributeDraft.getValue()).isNotNull();

    final Spliterator<JsonNode> attributeReferencesIterator = resolvedAttributeDraft.getValue().spliterator();
    assertThat(attributeReferencesIterator).isNotNull();
    final Set<JsonNode> resolvedSet = StreamSupport.stream(attributeReferencesIterator, false)
                                                   .collect(Collectors.toSet());
    assertThat(resolvedSet).isEmpty();
}
 
Example 16
Project: commercetools-sync-java   File: VariantReferenceResolverTest.java   View source code 6 votes vote down vote up
@Test
public void resolveAttributeReference_WithProductReferenceSetAttribute_ShouldResolveReferences() {
    final ObjectNode productReferenceWithRandomId = getProductReferenceWithRandomId();
    final AttributeDraft productReferenceSetAttributeDraft =
        getProductReferenceSetAttributeDraft("foo", productReferenceWithRandomId);

    final AttributeDraft resolvedAttributeDraft =
        referenceResolver.resolveAttributeReference(productReferenceSetAttributeDraft)
                         .toCompletableFuture().join();
    assertThat(resolvedAttributeDraft).isNotNull();
    assertThat(resolvedAttributeDraft.getValue()).isNotNull();

    final Spliterator<JsonNode> attributeReferencesIterator = resolvedAttributeDraft.getValue().spliterator();
    assertThat(attributeReferencesIterator).isNotNull();
    final Set<JsonNode> resolvedSet = StreamSupport.stream(attributeReferencesIterator, false)
                                                   .collect(Collectors.toSet());
    assertThat(resolvedSet).isNotEmpty();
    final ObjectNode resolvedReference = JsonNodeFactory.instance.objectNode();
    resolvedReference.put("typeId", "product");
    resolvedReference.put("id", PRODUCT_ID);
    assertThat(resolvedSet).containsExactly(resolvedReference);
}
 
Example 17
Project: webmate-sdk-java   File: BrowserSessionCrossbrowserJobInput.java   View source code 6 votes vote down vote up
@Override
public Map<PortName, BrickValue> makeInputValues() {
    JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance;
    ObjectMapper mapper = new ObjectMapper();

    List<JsonNode> compareSessionJson = new ArrayList<>();
    for (BrowserSessionId compareSession : compareSessions) {
        JsonNode sessionNode = mapper.valueToTree(compareSession);
        BrickValue sessionBrickValue = new BrickValue(new BrickDataType("BrowserSessionRef"), sessionNode);
        compareSessionJson.add(mapper.valueToTree(sessionBrickValue));
    }

    return ImmutableMap.of(
            new PortName("referenceSession"), new BrickValue(new BrickDataType("BrowserSessionRef"), jsonNodeFactory.textNode(referenceSession.toString())),
            new PortName("compareSessions"), new BrickValue(new BrickDataType("List[BrowserSessionRef]"), mapper.valueToTree(compareSessionJson)),
            new PortName("matchingType"), new BrickValue(new BrickDataType("String"), jsonNodeFactory.textNode("tag")),
            new PortName("enabledynamicelementsfilter"), new BrickValue(new BrickDataType("Boolean"), jsonNodeFactory.booleanNode(true))
    );
}
 
Example 18
Project: exam   File: UserController.java   View source code 6 votes vote down vote up
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result getUsersByRole(String role) {

    List<User> users = Ebean.find(User.class)
            .where()
            .eq("roles.name", role)
            .orderBy("lastName")
            .findList();

    ArrayNode array = JsonNodeFactory.instance.arrayNode();
    for (User u : users) {
        ObjectNode part = Json.newObject();
        part.put("id", u.getId());
        part.put("name", String.format("%s %s", u.getFirstName(), u.getLastName()));
        array.add(part);
    }

    return ok(Json.toJson(array));
}
 
Example 19
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void buildNonNullCustomFieldsUpdateActions_WithSameIdsButNullNewCustomFields_ShouldBuildUpdateActions()
    throws BuildUpdateActionException {
    final Reference<Type> categoryTypeReference = Type.referenceOfId("categoryCustomTypeId");

    // Mock old CustomFields
    final CustomFields oldCustomFieldsMock = mock(CustomFields.class);
    final Map<String, JsonNode> oldCustomFieldsJsonMapMock = new HashMap<>();
    oldCustomFieldsJsonMapMock.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));
    when(oldCustomFieldsMock.getType()).thenReturn(categoryTypeReference);
    when(oldCustomFieldsMock.getFieldsJsonMap()).thenReturn(oldCustomFieldsJsonMapMock);

    // Mock new CustomFieldsDraft
    final CustomFieldsDraft newCustomFieldsMock = mock(CustomFieldsDraft.class);
    when(newCustomFieldsMock.getType()).thenReturn(categoryTypeReference);
    when(newCustomFieldsMock.getFields()).thenReturn(null);

    final List<UpdateAction<Category>> updateActions =
        buildNonNullCustomFieldsUpdateActions(oldCustomFieldsMock,
            newCustomFieldsMock, mock(Category.class), CATEGORY_SYNC_OPTIONS);

    assertThat(updateActions).isNotNull();
    assertThat(updateActions).hasSize(1);
    assertThat(updateActions.get(0).getAction()).isEqualTo("setCustomType");
}
 
Example 20
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void buildSetCustomFieldsUpdateActions_WithDifferentCustomFieldValues_ShouldBuildUpdateActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();
    oldCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(false));
    oldCustomFields.put("backgroundColor", JsonNodeFactory.instance.objectNode().put("de", "rot").put("en", "red"));

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));
    newCustomFields.put("backgroundColor", JsonNodeFactory.instance.objectNode().put("de", "rot"));

    final List<UpdateAction<Category>> setCustomFieldsUpdateActions =
        buildSetCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
            CATEGORY_SYNC_OPTIONS);

    assertThat(setCustomFieldsUpdateActions).isNotNull();
    assertThat(setCustomFieldsUpdateActions).isNotEmpty();
    assertThat(setCustomFieldsUpdateActions).hasSize(2);
    final UpdateAction<Category> categoryUpdateAction = setCustomFieldsUpdateActions.get(0);
    assertThat(categoryUpdateAction).isNotNull();
    assertThat(categoryUpdateAction.getAction()).isEqualTo("setCustomField");
}
 
Example 21
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void buildSetCustomFieldsUpdateActions_WithNoNewCustomFieldsInOldCustomFields_ShouldBuildUpdateActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));
    newCustomFields.put("backgroundColor", JsonNodeFactory.instance.objectNode().put("de", "rot"));
    newCustomFields.put("url", JsonNodeFactory.instance.objectNode().put("domain", "domain.com"));
    newCustomFields.put("size", JsonNodeFactory.instance.objectNode().put("cm", 34));

    final List<UpdateAction<Category>> setCustomFieldsUpdateActions =
        buildSetCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
            CATEGORY_SYNC_OPTIONS);

    assertThat(setCustomFieldsUpdateActions).isNotNull();
    assertThat(setCustomFieldsUpdateActions).isNotEmpty();
    assertThat(setCustomFieldsUpdateActions).hasSize(4);
}
 
Example 22
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void buildSetCustomFieldsUpdateActions_WithOldCustomFieldNotInNewFields_ShouldBuildUpdateActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();
    oldCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));
    oldCustomFields.put("backgroundColor", JsonNodeFactory.instance.objectNode().put("de", "rot").put("en", "red"));

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));

    final List<UpdateAction<Category>> setCustomFieldsUpdateActions =
        buildSetCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
            CATEGORY_SYNC_OPTIONS);

    assertThat(setCustomFieldsUpdateActions).isNotNull();
    assertThat(setCustomFieldsUpdateActions).isNotEmpty();
    assertThat(setCustomFieldsUpdateActions).hasSize(1);
}
 
Example 23
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void buildSetCustomFieldsUpdateActions_WithSameCustomFieldValues_ShouldNotBuildUpdateActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();
    oldCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));
    oldCustomFields.put("backgroundColor", JsonNodeFactory.instance.objectNode().put("de", "rot"));

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));
    newCustomFields.put("backgroundColor", JsonNodeFactory.instance.objectNode().put("de", "rot"));

    final List<UpdateAction<Category>> setCustomFieldsUpdateActions =
        buildSetCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
            CATEGORY_SYNC_OPTIONS);

    assertThat(setCustomFieldsUpdateActions).isNotNull();
    assertThat(setCustomFieldsUpdateActions).isEmpty();
}
 
Example 24
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void buildSetCustomFieldsUpdateActions_WithDifferentOrderOfCustomFieldValues_ShouldNotBuildUpdateActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();
    oldCustomFields.put("backgroundColor",
        JsonNodeFactory.instance.objectNode().put("de", "rot").put("es", "rojo"));

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("backgroundColor",
        JsonNodeFactory.instance.objectNode().put("es", "rojo").put("de", "rot"));

    final List<UpdateAction<Category>> setCustomFieldsUpdateActions =
        buildSetCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
            CATEGORY_SYNC_OPTIONS);

    assertThat(setCustomFieldsUpdateActions).isNotNull();
    assertThat(setCustomFieldsUpdateActions).isEmpty();
}
 
Example 25
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void
    buildNewOrModifiedCustomFieldsUpdateActions_WithNewOrModifiedNonHandledResourceFields_ShouldNotBuildActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();
    oldCustomFields.put("backgroundColor", JsonNodeFactory.instance.objectNode().put("de", "rot").put("en", "red"));

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));

    // Cart resource is not handled in GenericUpdateActionUtils#buildTypedUpdateAction
    final Cart cart = mock(Cart.class);
    when(cart.toReference()).thenReturn(Cart.referenceOfId("cartId"));

    final List<UpdateAction<Cart>> customFieldsActions =
        buildNewOrModifiedCustomFieldsUpdateActions(oldCustomFields, newCustomFields, cart, CATEGORY_SYNC_OPTIONS);

    // Custom fields update actions should not be built
    assertThat(customFieldsActions).isNotNull();
    assertThat(customFieldsActions).isEmpty();
}
 
Example 26
Project: commercetools-sync-java   File: CustomUpdateActionUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void buildRemovedCustomFieldsUpdateActions_WithRemovedCustomField_ShouldBuildUpdateActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();
    oldCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));
    oldCustomFields.put("backgroundColor", JsonNodeFactory.instance.objectNode().put("de", "rot").put("en", "red"));

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("invisibleInShop", JsonNodeFactory.instance.booleanNode(true));

    final List<UpdateAction<Category>> customFieldsActions =
        buildRemovedCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
            CATEGORY_SYNC_OPTIONS);

    assertThat(customFieldsActions).isNotNull();
    assertThat(customFieldsActions).isNotEmpty();
    assertThat(customFieldsActions).hasSize(1);
}
 
Example 27
Project: athena   File: OpticalPortConfigTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() {
    try {
        JsonNode tree = new ObjectMapper().readTree(DEMOTREE);
        Iterator<JsonNode> pitr = tree.get(FIELD).elements();
        while (pitr.hasNext()) {
            // initialize a config entity, add to lists
            JsonNode jn = pitr.next();
            OpticalPortConfig opc = new OpticalPortConfig();
            ObjectNode node = JsonNodeFactory.instance.objectNode();
            opc.init(CPT, KEY, node, mapper, delegate);

            testNodes.add(jn);
            opcl.add(opc);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 28
Project: localcloud_fe   File: PluginResultHelper.java   View source code 6 votes vote down vote up
private static JsonNode createDataNode(Map<String, Object> data) {
    JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode dataNode = factory.objectNode();

    Set<Map.Entry<String, Object>> dataSet = data.entrySet();
    for (Map.Entry<String, Object> entry : dataSet) {
        Object value = entry.getValue();
        if (value == null) {
            continue;
        }

        dataNode.set(entry.getKey(), factory.textNode(value.toString()));
    }

    return dataNode;
}
 
Example 29
Project: localcloud_fe   File: PluginResultHelper.java   View source code 6 votes vote down vote up
private static JsonNode createDataNode(Map<String, Object> data) {
    JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode dataNode = factory.objectNode();

    Set<Map.Entry<String, Object>> dataSet = data.entrySet();
    for (Map.Entry<String, Object> entry : dataSet) {
        Object value = entry.getValue();
        if (value == null) {
            continue;
        }

        dataNode.set(entry.getKey(), factory.textNode(value.toString()));
    }

    return dataNode;
}
 
Example 30
Project: localcloud_fe   File: PluginResultHelper.java   View source code 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 31
Project: localcloud_fe   File: ContentManifest.java   View source code 6 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 32
Project: kafka-0.11.0.0-src-with-comment   File: JsonConverterTest.java   View source code 5 votes vote down vote up
@Test
public void nullSchemaAndMapToJson() {
    // This still needs to do conversion of data, null schema means "anything goes". Make sure we mix and match
    // types to verify conversion still works.
    Map<String, Object> input = new HashMap<>();
    input.put("key1", 12);
    input.put("key2", "string");
    input.put("key3", true);
    JsonNode converted = parse(converter.fromConnectData(TOPIC, null, input));
    validateEnvelopeNullSchema(converted);
    assertTrue(converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME).isNull());
    assertEquals(JsonNodeFactory.instance.objectNode().put("key1", 12).put("key2", "string").put("key3", true),
            converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
}
 
Example 33
Project: flink-stream-processing-refarch   File: WatermarkEvent.java   View source code 5 votes vote down vote up
public WatermarkEvent(long timestamp)  {
  super(
      new ObjectNode(JsonNodeFactory.instance)
          .put("watermark", new DateTime(timestamp).toString())
          .put(TYPE_FIELD, "watermark")
          .toString()
  );
}
 
Example 34
Project: centraldogma   File: HttpApiUtil.java   View source code 5 votes vote down vote up
/**
 * Returns a newly created {@link HttpResponse} with the specified {@link HttpStatus} and {@code message}.
 */
static HttpResponse newResponseWithErrorMessage(HttpStatus status, String message) {
    // TODO(minwoox) refine the error message
    final ObjectNode content = JsonNodeFactory.instance.objectNode().put("message", message);
    try {
        return HttpResponse.of(status, MediaType.JSON_UTF_8, Jackson.writeValueAsBytes(content));
    } catch (JsonProcessingException e) {
        // should not reach here
        throw new Error(e);
    }
}
 
Example 35
Project: athena   File: BasicDeviceConfigTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() {
    SW_BDC.init(DeviceId.deviceId(NAME1), NAME1, JsonNodeFactory.instance.objectNode(), mapper, delegate);
    SW_BDC.type(SWITCH).manufacturer(MANUFACTURER).hwVersion(HW_VERSION)
            .swVersion(SW_VERSION).serial(SERIAL).managementAddress(MANAGEMENT_ADDRESS).driver(DRIVER)
            .deviceKeyId(DEVICE_KEY_ID);
}
 
Example 36
Project: syndesis   File: ExtractConnectorDescriptorsMojo.java   View source code 5 votes vote down vote up
private void addConnectorMeta(ObjectNode root, ClassLoader classLoader) {
    ObjectNode node = new ObjectNode(JsonNodeFactory.instance);
    addOptionalNode(classLoader, node, "meta", "camel-connector.json");
    addOptionalSchemaAsString(classLoader, node, "schema", "camel-connector-schema.json");
    if (node.size() > 0) {
        root.set("connector", node);
    }
}
 
Example 37
Project: syndesis   File: ExtractConnectorDescriptorsMojo.java   View source code 5 votes vote down vote up
private void addComponentMeta(ObjectNode root, ClassLoader classLoader) {
    // is there any custom Camel components in this library?
    ObjectNode component = new ObjectNode(JsonNodeFactory.instance);

    ObjectNode componentMeta = getComponentMeta(classLoader);
    if (componentMeta != null) {
        component.set("meta", componentMeta);
    }
    addOptionalSchemaAsString(classLoader, component, "schema", "camel-component-schema.json");

    if (component.size() > 0) {
        root.set("component", component);
    }
}
 
Example 38
Project: syndesis   File: ErrorMapTest.java   View source code 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("!");
}
 
Example 39
Project: bigchaindb-java-driver   File: UnsignedCreateTransactionImplTest.java   View source code 5 votes vote down vote up
@Test
public void sign() throws Exception {
    final ObjectNode metaData = JsonNodeFactory.instance.objectNode();
    metaData.set("bogosity", JsonNodeFactory.instance.numberNode(42));
    transaction.withCondition(Collections.singletonList(keyPair.getPublic()), 1)
            .withMetadata(metaData);
    SignedBigchaindbTransaction signedBigchaindbTransaction = transaction.sign(Collections.singletonList(keyPair));
    assertNotNull(signedBigchaindbTransaction);
    assertTrue(signedBigchaindbTransaction instanceof SignedBigchaindbTransactionImpl);
    assertTrue(signedBigchaindbTransaction.asJsonObject().isObject());
}
 
Example 40
Project: bigchaindb-java-driver   File: BigchainDBTest.java   View source code 5 votes vote down vote up
@Test
public void createAssetTransaction1() throws Exception {
    final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER);
    final ObjectNode json = objectMapper.createObjectNode();
    json.set("foo", JsonNodeFactory.instance.textNode("bar"));
    final UnsignedCreateTransaction transaction = bigchainDB.createAssetTransaction(json);
    assertNotNull(transaction);
    assertEquals(json, getAssetData(transaction));
}