当前位置: 首页>>代码示例>>Java>>正文


Java Codec类代码示例

本文整理汇总了Java中org.bson.codecs.Codec的典型用法代码示例。如果您正苦于以下问题:Java Codec类的具体用法?Java Codec怎么用?Java Codec使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Codec类属于org.bson.codecs包,在下文中一共展示了Codec类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testResilience

import org.bson.codecs.Codec; //导入依赖的package包/类
/**
 * Testing if List<String> can be decoded into a
 */
@Test
public void testResilience() {

    Codec<EncodingPojo> encodingPojoCodec = codecRegistry.get(EncodingPojo.class);
    Codec<DecodingPojo> decodingPojoCodec = codecRegistry.get(DecodingPojo.class);

    EncodingPojo encodingPojo = new EncodingPojo();
    encodingPojo.someList = new ArrayList<>();
    encodingPojo.someList.add("string1");
    encodingPojo.someList.add("string2");
    encodingPojo.someList.add("string3");


    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true));
    encodingPojoCodec.encode(writer, encodingPojo, EncoderContext.builder().build());
    System.out.println(stringWriter.toString());

    DecodingPojo decodingPojo = decodingPojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build());
    Assert.assertNotNull(decodingPojo.someList);
    assertThat(decodingPojo.someList, instanceOf(ListOfStrings.class));
}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:26,代码来源:ListTypeCodecTest.java

示例2: registryFor

import org.bson.codecs.Codec; //导入依赖的package包/类
/**
 * "Smart" registry just for this particular {@code type}. It is typically composed with existing
 * registries using {@link org.bson.codecs.configuration.CodecRegistries#fromRegistries(CodecRegistry...)} method.
 */
public static <T> CodecRegistry registryFor(final Class<T> type, final TypeAdapter<T> adapter) {
  return new CodecRegistry() {
    @SuppressWarnings("unchecked")
    @Override
    public <X> Codec<X> get(Class<X> clazz) {
      // TODO is this a safe assumption with polymorphism (in repositories) ?
      if (type.isAssignableFrom(clazz)) {
        return (Codec<X>) codecFor(type, adapter);
      } else {
        // let other registries decide
        throw new CodecConfigurationException(String.format("Type %s not supported by this registry", type.getName()));
      }
    }
  };
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:20,代码来源:BsonEncoding.java

示例3: get

import org.bson.codecs.Codec; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
	if (clazz == BigDecimal.class) {
		return (Codec<T>) bigDecimalCodec;
	}
	if (clazz == BigInteger.class) {
		return (Codec<T>) bigIntegerCodec;
	}
	if (clazz == InetAddress.class || clazz == Inet4Address.class || clazz == Inet6Address.class) {
		return (Codec<T>) inetAddressCodec;
	}
	if (clazz.isArray()) {
		return (Codec<T>) arrayCodec;
	}
	return null;
}
 
开发者ID:berkesa,项目名称:datatree-adapters,代码行数:18,代码来源:JsonBson.java

示例4: get

import org.bson.codecs.Codec; //导入依赖的package包/类
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    // if clazz has type parameters, we warn the user that generic class definitions are problematic
    Codec<T> codec = pojoContext.get(clazz, registry);
    if (codec instanceof TypeCodec) {
        if (clazz != null && clazz.getTypeParameters().length > 0) {
            LOGGER.warn("Generic classes will only be encoded/decoded with their upper bounds! " +
                    "We could prohibit handling of the pojo codec for those generic classes, " +
                    "but then user would loose flexibility when subclassing such classes. Class: " + clazz.toGenericString());
        }
        TypeCodec typeCodec = (TypeCodec) codec;
        // generate dynamic proxy to add CollectibleCodec functionality
        if (typeCodec.isCollectible()) {
            LOGGER.debug("Enhancing {} to be collectible codec.", typeCodec);
            Class[] proxyInterfaces = new Class[]{CollectibleCodec.class};
            CollectibleCodec collectibleCodec = (CollectibleCodec) Proxy.newProxyInstance(
                    PojoCodecProvider.class.getClassLoader(),
                    proxyInterfaces,
                    new CollectibleCodecDelegator(typeCodec));

            return collectibleCodec;
        }
    }
    return codec;
}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:26,代码来源:PojoCodecProvider.java

示例5: getCodec

import org.bson.codecs.Codec; //导入依赖的package包/类
/**
 * Calculates and returns a codec for the given type, null otherwise
 *
 * @param type              type for which a codec is requested
 * @param typeCodecRegistry codec registry that can handle any type including parameterizd types, generic arrays, etc
 * @param <T>               the value type
 * @return the codec responsible for the given type or null
 */
public synchronized <T> Codec<T> getCodec(Type type, TypeCodecRegistry typeCodecRegistry) {
    Codec codec = codecMap.get(type);
    if (codec != null) {
        return codec;
    }

    // we register within codecMap as LazyCodec for recursion detection
    LazyCodec lazyCodec = new LazyCodec(type, typeCodecRegistry);
    codecMap.put(type, lazyCodec);

    // calculate the codec for given type
    codec = calculateCodec(type, typeCodecRegistry);
    if (codec == null) {
        codecMap.remove(type);
    } else {
        codecMap.put(type, codec);
    }

    return codec;
}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:29,代码来源:PojoContext.java

示例6: reorderingDocumentTest

import org.bson.codecs.Codec; //导入依赖的package包/类
@Test
public void reorderingDocumentTest() {
    Document document = new Document();
    document.stringProperty = "a nice string";
    document.datProperty = new Date();

    MongoCollection<Document> documentMongoCollection = mongoClient.getDatabase("test").getCollection("documents").withDocumentClass(Document.class);

    documentMongoCollection.insertOne(document);

    Document readDocument = documentMongoCollection.find(Filters.eq("_id", document.getMeta().getId())).first();

    Assert.assertEquals(document, readDocument);

    Codec<Document> documentCodec = codecRegistry.get(Document.class);
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true));
    documentCodec.encode(writer, document, EncoderContext.builder().build());
    LOGGER.info("The encoded json looks like: {}", stringWriter);

}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:22,代码来源:CodecResolverTest.java

示例7: basicTest

import org.bson.codecs.Codec; //导入依赖的package包/类
@Test
public void basicTest() {
    BasePojo basePojo = new BasePojo();
    basePojo.aString = STRING;

    Codec<BasePojo> primitivePojoCodec = codecRegistry.get(BasePojo.class);

    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true));
    primitivePojoCodec.encode(writer, basePojo, EncoderContext.builder().build());
    LOGGER.info("The encoded json looks like: {}", stringWriter);

    BasePojo readBasePojo = primitivePojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build());
    // assert that the modified version was actually written to the database
    Assert.assertEquals(basePojo, readBasePojo);
    Assert.assertEquals(MODIFIED_STRING, readBasePojo.aString);
}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:18,代码来源:PreSaveHookTest.java

示例8: testEnums

import org.bson.codecs.Codec; //导入依赖的package包/类
@Test
public void testEnums() {
    Codec<Pojo> pojoCodec = codecRegistry.get(Pojo.class);

    LovelyDisplayable lovelyDisplayable = LovelyDisplayable.builder().identityProperty("foo").build();

    Pojo pojo = Pojo.builder()
            .simpleEnumProperty(EnumA.TYPE1)
            .displayable(Arrays.asList(EnumB.TYPE1, EnumA.TYPE1, EnumA.TYPE3, lovelyDisplayable))
            .build();

    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true));
    pojoCodec.encode(writer, pojo, EncoderContext.builder().build());
    System.out.println(stringWriter.toString());

    Pojo decodedPojo = pojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build());

    MatcherAssert.assertThat(decodedPojo.getDisplayable(),
            IsIterableContainingInOrder.contains(EnumB.TYPE1, EnumA.TYPE1, EnumA.TYPE3, lovelyDisplayable));

}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:23,代码来源:TestEnums.java

示例9: toBson

import org.bson.codecs.Codec; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public <T> BsonValue toBson(Object value, Class<T> clazz) {
	if(value == null) {
		return new BsonNull();
	}
	if(value instanceof BsonValue) {
		return (BsonValue) value;
	}
	final Codec<T> codec = registry.get(clazz);
	final String key = "value";
	final BsonDocument document = new BsonDocument();
	final BsonWriter writer = new BsonDocumentWriter(document);
	writer.writeStartDocument();
	writer.writeName(key);
	codec.encode(writer, (T) value, EncoderContext.builder().build());
	writer.writeEndDocument();
	return document.get(key);
}
 
开发者ID:JPDSousa,项目名称:mongo-obj-framework,代码行数:19,代码来源:SmofParser.java

示例10: get

import org.bson.codecs.Codec; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
    // Optimistic get to avoid using dynamic memory
    Codec<?> ret = codecs.get(clazz);
    if (ret != null) {
        return (Codec<T>) ret;
    }
    if (clazz.isEnum()) {
        return (Codec<T>) codecs.computeIfAbsent(clazz, c -> new EnumCodec<>((Class<? extends Enum>) c));
    }
    if (clazz.isArray()) {
        Class<?> componentType = clazz.getComponentType();
        Codec componentCodec = get(componentType, registry);
        if (componentCodec != null) {
            return (Codec<T>) codecs.computeIfAbsent(clazz, c -> new ArrayCodec(clazz, componentCodec));
        }
    }
    return registry.get(clazz);
}
 
开发者ID:egopulse,项目名称:java-code-gen,代码行数:21,代码来源:ExtraCodecProvider.java

示例11: buildCodecRegistries

import org.bson.codecs.Codec; //导入依赖的package包/类
private CodecRegistry buildCodecRegistries() {
	Codec<Document> defaultDocumentCodec = MongoClient.getDefaultCodecRegistry().get(Document.class);
	
	CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
		MongoClient.getDefaultCodecRegistry(),
		CodecRegistries.fromCodecs(
			new BibleCodec(defaultDocumentCodec),
			new BookCodec(defaultDocumentCodec),
			new ChapterCodec(defaultDocumentCodec),
			new VerseCodec(defaultDocumentCodec),
			new UserCodec(defaultDocumentCodec)
		)
	);
	
	return codecRegistry;
}
 
开发者ID:aureliano,项目名称:verbum-domini,代码行数:17,代码来源:PersistenceManagerImpl.java

示例12: encode

import org.bson.codecs.Codec; //导入依赖的package包/类
/**
 * To be used if and only if it belongs to {@link java.util} package
 * @param writer
 * @param coll
 * @param encoderContext
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void encode(BsonWriter writer, Collection<?> coll, EncoderContext encoderContext) {
	writer.writeStartArray();
	Iterator<?> iterator = coll.iterator();
	while(iterator.hasNext()) {
		Object next = iterator.next();
		if (next == null) {
			writer.writeNull();
		} else {
			Codec codec = registry.get(next.getClass());
			encoderContext.encodeWithChildContext(codec, writer, next);
		}
	}
	writer.writeEndArray();
}
 
开发者ID:guicamest,项目名称:bsoneer,代码行数:22,代码来源:BaseBsoneerCodec.java

示例13: encode

import org.bson.codecs.Codec; //导入依赖的package包/类
@Override
public void encode(BsonWriter writer, List value, EncoderContext encoderContext) {
	if (value != null && !value.isEmpty()) {
		writer.writeStartArray();
		for (Object a : value) {
			if (a != null) {
				Codec codec = this.codecRegistry.get(a.getClass());
				encoderContext.encodeWithChildContext(codec, writer, a);
			}
			else {
				writer.writeNull();
			}
		}
		writer.writeEndArray();
	}
	else {
		writer.writeNull();
	}
}
 
开发者ID:ralscha,项目名称:eds-starter6-mongodb,代码行数:20,代码来源:ListCodec.java

示例14: writeReadCompare

import org.bson.codecs.Codec; //导入依赖的package包/类
@SuppressWarnings("resource")
protected <T> void writeReadCompare(T source, Codec<T> codec) {
	BasicOutputBuffer bsonOutput = new BasicOutputBuffer();
	BsonBinaryWriter writer = new BsonBinaryWriter(bsonOutput);
	writer.writeStartDocument();
	writer.writeName("name");
	codec.encode(writer, source, EncoderContext.builder().build());
	writer.writeEndDocument();
	writer.close();

	BsonBinaryReader reader = new BsonBinaryReader(
			ByteBuffer.wrap(bsonOutput.toByteArray()));
	reader.readStartDocument();
	assertThat(reader.readName()).isEqualTo("name");
	T readNow = codec.decode(reader, DecoderContext.builder().build());

	assertThat(readNow).isEqualTo(source);
}
 
开发者ID:ralscha,项目名称:bsoncodec,代码行数:19,代码来源:AbstractTest.java

示例15: testCodec

import org.bson.codecs.Codec; //导入依赖的package包/类
@Test
public void testCodec() throws IOException {
    Codec<DefaultDomain> codec = DefaultDomainCodec.INSTANCE;
    DefaultDomain domain = new DefaultDomain();
    domain.addPlayer(UUID.randomUUID());
    domain.addGroup("test_group");

    DefaultDomain other;
    try (StringWriter sw = new StringWriter()) {
        codec.encode(new JsonWriter(sw), domain, EncoderContext.builder().build());
        other = codec.decode(new JsonReader(sw.toString()), DecoderContext.builder().build());
    }

    Assert.assertEquals(domain.getPlayers(), other.getPlayers());
    Assert.assertEquals(domain.getUniqueIds(), other.getUniqueIds());
    Assert.assertEquals(domain.getGroups(), other.getGroups());
}
 
开发者ID:maxikg,项目名称:mongowg,代码行数:18,代码来源:DefaultDomainCodecTest.java


注:本文中的org.bson.codecs.Codec类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。