Java Code Examples for io.protostuff.ProtostuffIOUtil#mergeFrom()

The following examples show how to use io.protostuff.ProtostuffIOUtil#mergeFrom() . 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: PolymorphicSerializationTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
public void testOverwrite() throws Exception
{
    Schema<Zoo> schema = RuntimeSchema.getSchema(Zoo.class);

    Zoo zoo = new Zoo();
    zoo.largestAnimal = filledBear();

    // overwriteZoo

    Zoo overwriteZoo = new Zoo();
    overwriteZoo.largestAnimal = filledTiger();

    // ser
    byte[] data = ProtostuffIOUtil.toByteArray(overwriteZoo, schema, buf());
    // deser
    ProtostuffIOUtil.mergeFrom(data, zoo, schema);

    // test that it was overwritten
    assertTrue(zoo.largestAnimal instanceof Tiger);
}
 
Example 2
Source File: BasicSupportService.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private static Optional<ClusterIdentity> getClusterIdentityFromStore(ConfigurationStore store, LegacyKVStoreProvider provider) {
  final ConfigurationEntry entry = store.get(SupportService.CLUSTER_ID);

  if (entry == null) {
    Optional<ClusterIdentity> upgradedClusterIdentity = upgradeToNewSupportStore(provider);
    return upgradedClusterIdentity;
  }

  try {
    ClusterIdentity identity = ClusterIdentity.getSchema().newMessage();
    ProtostuffIOUtil.mergeFrom(entry.getValue().toByteArray(), identity, ClusterIdentity.getSchema());
    return Optional.ofNullable(identity);
  } catch (Exception e) {
    logger.info("failed to get cluster identity", e);
    return Optional.empty();
  }
}
 
Example 3
Source File: SerDeserTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
public void testBar() throws Exception
{
    Schema<Bar> schema = RuntimeSchema.getSchema(Bar.class);

    for (Bar barCompare : new Bar[] { bar, negativeBar })
    {
        Bar dbar = new Bar();

        int expectedSize = ComputedSizeOutput.getSize(barCompare, schema);

        byte[] deferred = toByteArray(barCompare, schema);
        assertTrue(deferred.length == expectedSize);
        ProtostuffIOUtil.mergeFrom(deferred, dbar, schema);
        SerializableObjects.assertEquals(barCompare, dbar);
        // System.err.println(dbar.getSomeInt());
        // System.err.println(dbar.getSomeLong());
        // System.err.println(dbar.getSomeFloat());
        // System.err.println(dbar.getSomeDouble());
        // System.err.println(dbar.getSomeBytes());
        // System.err.println(dbar.getSomeString());
        // System.err.println(dbar.getSomeEnum());
        // System.err.println(dbar.getSomeBoolean());
    }
}
 
Example 4
Source File: CollectionTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
@Test
public void testITask() throws Exception
{
    // Because we mapped ITask to Task, this is ok.
    Schema<ITask> schema = RuntimeSchema.getSchema(ITask.class);

    ITask p = filledTask();

    byte[] data = ProtostuffIOUtil.toByteArray(p, schema,
            LinkedBuffer.allocate(512));

    ITask p2 = new Task();
    ProtostuffIOUtil.mergeFrom(data, p2, schema);
    // System.err.println(p2);

    assertEquals(p, p2);
}
 
Example 5
Source File: CollectionTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleTask() throws Exception
{
    Schema<Task> schema = RuntimeSchema.getSchema(Task.class);

    Task p = filledTask();

    byte[] data = ProtostuffIOUtil.toByteArray(p, schema,
            LinkedBuffer.allocate(512));

    Task p2 = new Task();
    ProtostuffIOUtil.mergeFrom(data, p2, schema);
    // System.err.println(p2);

    assertEquals(p, p2);
}
 
Example 6
Source File: AlwaysUseSunReflectionFactoryOptionTest.java    From protostuff with Apache License 2.0 5 votes vote down vote up
@Test
public void forceUseSunReflectionFactory() throws Exception {
	System.setProperty("protostuff.runtime.always_use_sun_reflection_factory", "true");
	Schema<MyClass> schema = RuntimeSchema.getSchema(MyClass.class);
	ByteArrayOutputStream output = new ByteArrayOutputStream();
	MyClass myClass = new MyClass(); // constructor initializes list with one element
	ProtostuffIOUtil.writeTo(output, myClass, schema, LinkedBuffer.allocate());
	byte[] bytes = output.toByteArray();
	Assert.assertEquals(1, myClass.getList().size());
	MyClass myClassNew = schema.newMessage(); // default constructor should not be used
	ProtostuffIOUtil.mergeFrom(bytes, myClassNew, schema);
	Assert.assertEquals(1, myClassNew.getList().size());
}
 
Example 7
Source File: RedisDAO.java    From jseckill with Apache License 2.0 5 votes vote down vote up
/**
 * 从缓存中获取所有的实时商品数据(包括实时库存量)
 * @return
 */
public List<Seckill> getAllGoods() {
    List<Seckill> result = new ArrayList<>();
    Jedis jedis = jedisPool.getResource();
    Set<String> idSet = jedis.smembers(RedisKey.SECKILL_ID_SET);
    if (idSet != null || idSet.size() > 0) {
        for (String seckillId : idSet) {
            String goodsKey = RedisKeyPrefix.SECKILL_GOODS + seckillId;
            byte[] bytes = jedis.get(goodsKey.getBytes());
            if (bytes != null) {
                Seckill seckill = schema.newMessage();
                ProtostuffIOUtil.mergeFrom(bytes, seckill, schema);

                try {
                    // goodsKey获取到的库存量是初始值,并不是当前值,所有需要从RedisKeyPrefix.SECKILL_INVENTORY+seckillID
                    // 获取到的库存,再设置到结果中去
                    String inventoryStr = jedis.get(RedisKeyPrefix.SECKILL_INVENTORY + seckillId);
                    if (!StringUtils.isEmpty(inventoryStr)) {
                        seckill.setInventory(Integer.valueOf(inventoryStr));
                    }
                } catch (NumberFormatException ex) {
                    logger.error(ex.getMessage(), ex);
                }
                result.add(seckill);
            }
        }
    }
    jedis.close();
    return result;
}
 
Example 8
Source File: ProtostuffSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(AbstractByteBuf data, Class clazz, Map<String, String> context) throws SofaRpcException {
    if (clazz == null) {
        throw buildDeserializeError("class is null!");
    } else {
        Schema schema = RuntimeSchema.getSchema(clazz);
        Object fooParsed = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data.array(), fooParsed, schema);
        return fooParsed;
    }
}
 
Example 9
Source File: ProtobufRuntimeObjectSchemaTest.java    From protostuff with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> void roundTrip(T message, Schema<T> schema,
        Pipe.Schema<T> pipeSchema) throws Exception
{
    byte[] protobuf = ProtobufIOUtil.toByteArray(message, schema, buf());

    ByteArrayInputStream protobufStream = new ByteArrayInputStream(protobuf);

    byte[] protostuff = ProtostuffIOUtil.toByteArray(
            ProtobufIOUtil.newPipe(protobuf, 0, protobuf.length),
            pipeSchema, buf());

    byte[] protostuffFromStream = ProtostuffIOUtil.toByteArray(
            ProtobufIOUtil.newPipe(protobufStream), pipeSchema, buf());

    assertTrue(Arrays.equals(protostuff, protostuffFromStream));

    T parsedMessage = schema.newMessage();
    ProtostuffIOUtil.mergeFrom(protostuff, parsedMessage, schema);
    SerializableObjects.assertEquals(message, parsedMessage);

    ByteArrayInputStream protostuffStream = new ByteArrayInputStream(
            protostuff);

    byte[] protobufRoundTrip = ProtobufIOUtil.toByteArray(
            ProtostuffIOUtil.newPipe(protostuff, 0, protostuff.length),
            pipeSchema, buf());

    byte[] protobufRoundTripFromStream = ProtobufIOUtil.toByteArray(
            ProtostuffIOUtil.newPipe(protostuffStream), pipeSchema, buf());

    assertTrue(Arrays.equals(protobufRoundTrip, protobufRoundTripFromStream));

    assertTrue(Arrays.equals(protobufRoundTrip, protobuf));
}
 
Example 10
Source File: PurchaseInfoDeSerializer.java    From ChengFeng1.5 with MIT License 5 votes vote down vote up
@Override
public PurchaseInfoDto deserialize(String topic, byte[] data) {
    if(data==null) {
        return null;
    }

    Schema<PurchaseInfoDto> schema = RuntimeSchema.getSchema(PurchaseInfoDto.class);
    PurchaseInfoDto purchaseInfoDto=new PurchaseInfoDto();
    ProtostuffIOUtil.mergeFrom(data, purchaseInfoDto, schema);
    return purchaseInfoDto;
}
 
Example 11
Source File: ProtobufUtils.java    From spring-boot-starter-grpc with MIT License 5 votes vote down vote up
/**
 * 反序列化方法,将字节数组反序列化为对象(字节数组 ---> 对象)
 */
public static <T> T deserialize(byte[] data, Class<T> clazz) {
    RuntimeSchema<T> schema = RuntimeSchema.createFrom(clazz);
    T message = schema.newMessage();
    ProtostuffIOUtil.mergeFrom(data, message, schema);
    return message;
}
 
Example 12
Source File: ProtoStuffSerializer.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T deserialize(byte[] bytes, Class<T> clazz) {
    T object = null;
    try {
        object = objenesis.newInstance(clazz);
        Schema<T> schema = getSchema(clazz);
        ProtostuffIOUtil.mergeFrom(bytes, object, schema);
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    return object;
}
 
Example 13
Source File: ProtostuffRowDeserializationSchema.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@Override
public Row deserialize(byte[] bytes) throws IOException {
    try {
        if(schema == null){
            this.schema = RuntimeSchema.getSchema(clazz);
        }
        Object obj = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(bytes, obj, schema);
        // convert to row
        return ConvertRowUtil.convertToRow(obj, ((RowTypeInfo)typeInfo).getFieldNames());
    } catch (Exception e) {
       throw e;
    }
}
 
Example 14
Source File: MessageCrypto.java    From jeesupport with MIT License 5 votes vote down vote up
/**
 * C2S
 * 反序列化byte[]为对象
 *
 * @param _byts 序列化后的byte[]值
 * @param _cls 反序列化后的对象
 * @return 返回的对象
 */
public static < T > T deserializer( byte[] _byts , Class< T > _cls ) {
	try {
		T obj = _cls.newInstance();
		ProtostuffIOUtil.mergeFrom( _byts , obj , _get_schema( _cls ) );
		return obj;
	} catch ( Exception e ) {
		throw new IllegalStateException( e.getMessage() , e );
	}
}
 
Example 15
Source File: EnumSetAndMapTest.java    From protostuff with Apache License 2.0 5 votes vote down vote up
public void testPojoWithEnumSet() throws Exception
{
    Schema<PojoWithEnumSet> schema = RuntimeSchema
            .getSchema(PojoWithEnumSet.class);
    PojoWithEnumSet p = new PojoWithEnumSet().fill();

    byte[] data = ProtostuffIOUtil.toByteArray(p, schema, buf());

    PojoWithEnumSet p2 = new PojoWithEnumSet();
    ProtostuffIOUtil.mergeFrom(data, 0, data.length, p2, schema);

    assertEquals(p, p2);

    List<PojoWithEnumSet> list = new ArrayList<PojoWithEnumSet>();
    list.add(p);
    list.add(p2);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ProtostuffIOUtil.writeListTo(out, list, schema, buf());
    byte[] listData = out.toByteArray();

    ByteArrayInputStream in = new ByteArrayInputStream(listData);
    List<PojoWithEnumSet> parsedList = ProtostuffIOUtil.parseListFrom(in,
            schema);

    assertEquals(list, parsedList);
}
 
Example 16
Source File: ProtostuffRuntimeObjectSchemaTest.java    From protostuff with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> void roundTrip(T message, Schema<T> schema,
        Pipe.Schema<T> pipeSchema) throws Exception
{
    byte[] protobuf = ProtobufIOUtil.toByteArray(message, schema, buf());

    ByteArrayInputStream protobufStream = new ByteArrayInputStream(protobuf);

    byte[] protostuff = ProtostuffIOUtil.toByteArray(
            ProtobufIOUtil.newPipe(protobuf, 0, protobuf.length),
            pipeSchema, buf());

    byte[] protostuffFromStream = ProtostuffIOUtil.toByteArray(
            ProtobufIOUtil.newPipe(protobufStream), pipeSchema, buf());

    assertTrue(Arrays.equals(protostuff, protostuffFromStream));

    T parsedMessage = schema.newMessage();
    ProtostuffIOUtil.mergeFrom(protostuff, parsedMessage, schema);
    SerializableObjects.assertEquals(message, parsedMessage);

    ByteArrayInputStream protostuffStream = new ByteArrayInputStream(
            protostuff);

    byte[] protobufRoundTrip = ProtobufIOUtil.toByteArray(
            ProtostuffIOUtil.newPipe(protostuff, 0, protostuff.length),
            pipeSchema, buf());

    byte[] protobufRoundTripFromStream = ProtobufIOUtil.toByteArray(
            ProtostuffIOUtil.newPipe(protostuffStream), pipeSchema, buf());

    assertTrue(Arrays.equals(protobufRoundTrip, protobufRoundTripFromStream));

    assertTrue(Arrays.equals(protobufRoundTrip, protobuf));
}
 
Example 17
Source File: ProtostuffNullArrayElementTest.java    From protostuff with Apache License 2.0 4 votes vote down vote up
@Override
protected <T> void mergeFrom(InputStream in, T message, Schema<T> schema)
        throws IOException
{
    ProtostuffIOUtil.mergeFrom(in, message, schema);
}
 
Example 18
Source File: ProtostuffRuntimeCollectionSchemaTest.java    From protostuff with Apache License 2.0 4 votes vote down vote up
@Override
protected <T> void mergeFrom(byte[] data, int offset, int length,
        T message, Schema<T> schema) throws IOException
{
    ProtostuffIOUtil.mergeFrom(data, offset, length, message, schema);
}
 
Example 19
Source File: ProtostuffUtils.java    From dog with GNU Lesser General Public License v3.0 3 votes vote down vote up
@Override
public TccContext byteArrayToObject(byte[] bytes) {

    TccContext obj = schema.newMessage();

    ProtostuffIOUtil.mergeFrom(bytes, obj, schema);

    return obj;

}
 
Example 20
Source File: MessageSerializer.java    From protect with MIT License 2 votes vote down vote up
/**
 * Deserializes a previously serialized byte array into a payload
 * 
 * @param input
 * @return
 */
public static Payload deserializePayload(byte[] serializedPayload) {
	final Payload parsedPayload = PAYLOAD_SCHEMA.newMessage();
	ProtostuffIOUtil.mergeFrom(serializedPayload, parsedPayload, PAYLOAD_SCHEMA);
	return parsedPayload;
}