Java 类com.fasterxml.jackson.databind.node.JsonNodeFactory 实例源码

项目:GitHub    文件:PropertiesRule.java   
/**
 * 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;
}
项目:kafka-0.11.0.0-src-with-comment    文件:JsonConverter.java   
@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);
}
项目:BIMplatform    文件:GlbToB3dmConvertor.java   
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();
    }

}
项目:webmate-sdk-java    文件:BrowserSessionRegressionJobInput.java   
@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))
    );
}
项目:rskj    文件:NetworkStateExporter.java   
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;
    }
}
项目:kafka-0.11.0.0-src-with-comment    文件:JsonConverterTest.java   
@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
    );
}
项目:dataplatform-schema-lib    文件:JacksonArrayFormatter.java   
@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;
}
项目:dataplatform-schema-lib    文件:JacksonArrayFormatter.java   
@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;
}
项目:dataplatform-schema-lib    文件:JacksonObjectFormatter.java   
@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;
}
项目:dataplatform-schema-lib    文件:JacksonObjectFormatter.java   
@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;
}
项目:exam    文件:ReservationController.java   
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;
}
项目:athena    文件:BgpConfig.java   
/**
 * 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);
}
项目:commercetools-sync-java    文件:CategorySyncIT.java   
@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);
}
项目:commercetools-sync-java    文件:VariantReferenceResolverTest.java   
@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);
}
项目:commercetools-sync-java    文件:VariantReferenceResolverTest.java   
@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();
}
项目:commercetools-sync-java    文件:VariantReferenceResolverTest.java   
@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);
}
项目:webmate-sdk-java    文件:BrowserSessionCrossbrowserJobInput.java   
@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))
    );
}
项目:exam    文件:UserController.java   
@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));
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@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");
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@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");
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@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);
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@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);
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@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();
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@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();
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@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();
}
项目:commercetools-sync-java    文件:CustomUpdateActionUtilsTest.java   
@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);
}
项目:athena    文件:OpticalPortConfigTest.java   
@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();
    }
}
项目:localcloud_fe    文件:PluginResultHelper.java   
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;
}
项目:localcloud_fe    文件:PluginResultHelper.java   
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;
}
项目:localcloud_fe    文件:PluginResultHelper.java   
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());
}
项目:kafka-0.11.0.0-src-with-comment    文件:JsonConverterTest.java   
@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));
}
项目:flink-stream-processing-refarch    文件:WatermarkEvent.java   
public WatermarkEvent(long timestamp)  {
  super(
      new ObjectNode(JsonNodeFactory.instance)
          .put("watermark", new DateTime(timestamp).toString())
          .put(TYPE_FIELD, "watermark")
          .toString()
  );
}
项目:centraldogma    文件:HttpApiUtil.java   
/**
 * 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);
    }
}
项目:athena    文件:BasicDeviceConfigTest.java   
@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);
}
项目:syndesis    文件:ExtractConnectorDescriptorsMojo.java   
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);
    }
}
项目:syndesis    文件:ExtractConnectorDescriptorsMojo.java   
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);
    }
}
项目:syndesis    文件:ErrorMapTest.java   
@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("!");
}
项目:bigchaindb-java-driver    文件:UnsignedCreateTransactionImplTest.java   
@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());
}
项目:bigchaindb-java-driver    文件:BigchainDBTest.java   
@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));
}
项目:java-microservice    文件:TodoServiceStatisticsController.java   
@GetMapping
public ObjectNode get() {
    LongSummaryStatistics statistics = monitor.getStatistics();
    return JsonNodeFactory.instance.objectNode().
            put("average-duration", statistics.getAverage()).
            put("invocation-count", statistics.getCount()).
            put("min-duration", statistics.getMin()).
            put("max-duration", statistics.getMax());
}