io.protostuff.Schema Java Examples

The following examples show how to use io.protostuff.Schema. 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: DefaultIdStrategy.java    From protostuff with Apache License 2.0 6 votes vote down vote up
@Override
public Schema<T> getSchema()
{
    Schema<T> schema = this.schema;
    if (schema == null)
    {
        synchronized (this)
        {
            if ((schema = this.schema) == null)
            {
                // create new
                this.schema = schema = strategy.newSchema(typeClass);
            }
        }
    }
    
    return schema;
}
 
Example #2
Source File: SerDeserTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
/**
 * HasHasBar wraps an object without a schema. That object will have to be serialized via the default java
 * serialization and it will be delimited.
 * <p>
 * HasBar wraps a message {@link Bar}.
 */
public void testJavaSerializable() throws Exception
{
    Schema<HasHasBar> schema = RuntimeSchema.getSchema(HasHasBar.class);

    HasHasBar hhbCompare = new HasHasBar("hhb", new HasBar(12345, "hb",
            SerializableObjects.bar));
    HasHasBar dhhb = new HasHasBar();

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

    byte[] deferred = toByteArray(hhbCompare, schema);
    assertTrue(deferred.length == expectedSize);
    ProtostuffIOUtil.mergeFrom(deferred, dhhb, schema);
    assertEquals(hhbCompare, dhhb);
}
 
Example #3
Source File: PolymorphicPojoSchema.java    From protostuff with Apache License 2.0 6 votes vote down vote up
static Object readObjectFrom(Input input, Schema<?> schema, Object owner,
        IdStrategy strategy, int number) throws IOException
{
    final Schema<Object> derivedSchema = strategy.resolvePojoFrom(input,
            number).getSchema();
    
    final Object pojo = derivedSchema.newMessage();
    
    if (input instanceof GraphInput)
    {
        // update the actual reference.
        ((GraphInput) input).updateLast(pojo, owner);
    }
    
    derivedSchema.mergeFrom(input, pojo);
    return pojo;
}
 
Example #4
Source File: PolymorphicMapSchema.java    From protostuff with Apache License 2.0 6 votes vote down vote up
private static void writeCheckedMapTo(Output output, Object value,
        Schema<?> currentSchema, IdStrategy strategy, int id)
        throws IOException
{
    final Object m, keyType, valueType;
    try
    {
        m = fCheckedMap_m.get(value);
        keyType = fCheckedMap_keyType.get(value);
        valueType = fCheckedMap_valueType.get(value);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }

    output.writeObject(id, m, strategy.POLYMORPHIC_MAP_SCHEMA, false);
    output.writeObject(1, keyType, strategy.CLASS_SCHEMA, false);
    output.writeObject(2, valueType, strategy.CLASS_SCHEMA, false);
}
 
Example #5
Source File: PolymorphicPojoCollectionSchema.java    From protostuff with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
static void writeObjectTo(Output output, Object value,
        Schema<?> currentSchema, IdStrategy strategy) throws IOException
{
    final HasSchema<Object> hs = strategy.tryWritePojoIdTo(output, ID_POJO, 
            (Class<Object>)value.getClass(), true);
    
    if (hs == null)
    {
        PolymorphicCollectionSchema.writeObjectTo(output, value, currentSchema, 
                strategy);
        return;
    }
    
    final Schema<Object> schema = hs.getSchema();
    
    if (output instanceof StatefulOutput)
    {
        // update using the derived schema.
        ((StatefulOutput) output).updateLast(schema, currentSchema);
    }
    
    schema.writeTo(output, value);
}
 
Example #6
Source File: DateTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
public void testProtostuff() throws Exception
{
    Schema<Entity> schema = RuntimeSchema.getSchema(Entity.class);
    Entity p = filledEntity();

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

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

    assertEquals(p, p2);

    List<Entity> list = new ArrayList<Entity>();
    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<Entity> parsedList = ProtostuffIOUtil.parseListFrom(in, schema);

    assertEquals(list, parsedList);
}
 
Example #7
Source File: AbstractRuntimeMapTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
public void testSingleGenericTypeMap() throws Exception
{
    DefaultIdStrategy strategy = new DefaultIdStrategy();
    strategy.registerMap(CustomMapFactory.IntObjectMap);
    
    Schema<TestBean> schema = RuntimeSchema.getSchema(TestBean.class, strategy);
    Pipe.Schema<TestBean> pipeSchema = ((RuntimeSchema<TestBean>) schema)
            .getPipeSchema();
    
    TestBean p = new TestBean();
    p.map.put(1, Short.valueOf((short) 25));
    p.concreteMap.put(2, Short.valueOf((short) 50));
    
    byte[] data = toByteArray(p, schema);

    TestBean pFromByteArray = schema.newMessage();
    mergeFrom(data, 0, data.length, pFromByteArray, schema);
    assertEquals(p, pFromByteArray);

    TestBean pFromStream = schema.newMessage();
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    mergeFrom(in, pFromStream, schema);
    assertEquals(p, pFromByteArray);

    roundTrip(p, schema, pipeSchema);
}
 
Example #8
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 #9
Source File: ArraySchema.java    From protostuff with Apache License 2.0 6 votes vote down vote up
static void transferObject(Pipe.Schema<Object> pipeSchema, Pipe pipe,
        Input input, Output output, IdStrategy strategy) throws IOException
{
    final int number = input.readFieldNumber(pipeSchema.wrappedSchema);
    switch (number)
    {
        case ID_ARRAY:
            ObjectSchema.transferArray(pipe, input, output, number, pipeSchema,
                    false, strategy);
            return;

        case ID_ARRAY_MAPPED:
            ObjectSchema.transferArray(pipe, input, output, number, pipeSchema,
                    true, strategy);
            return;

        default:
            throw new ProtostuffException("Corrupt input.");
    }
}
 
Example #10
Source File: DefaultIdStrategy.java    From protostuff with Apache License 2.0 6 votes vote down vote up
@Override
public Pipe.Schema<T> getPipeSchema()
{
    Pipe.Schema<T> pipeSchema = this.pipeSchema;
    if (pipeSchema == null)
    {
        synchronized (this)
        {
            if ((pipeSchema = this.pipeSchema) == null)
            {
                this.pipeSchema = pipeSchema = RuntimeSchema
                        .resolvePipeSchema(getSchema(), typeClass, true);
            }
        }
    }
    
    return pipeSchema;
}
 
Example #11
Source File: ExplicitIdStrategy.java    From protostuff with Apache License 2.0 6 votes vote down vote up
/**
 * Pojo ids start at 1.
 */
@Override
public <T> Registry registerPojo(Schema<T> schema, Pipe.Schema<T> pipeSchema,
        int id)
{
    if (id >= strategy.pojos.size())
        grow(strategy.pojos, id + 1);
    else if (strategy.pojos.get(id) != null)
    {
        throw new IllegalArgumentException("Duplicate id registration: " + id +
                " (" + schema.typeClass().getName() + ")");
    }

    if (strategy.pojoMapping.containsKey(schema.typeClass()))
        throw new IllegalArgumentException("Duplicate registration for: " + schema.typeClass());

    Registered<T> wrapper = new Registered<T>(id, schema, pipeSchema, strategy);
    strategy.pojos.set(id, wrapper);

    strategy.pojoMapping.put(schema.typeClass(), wrapper);

    return this;
}
 
Example #12
Source File: IncrementalIdStrategy.java    From protostuff with Apache License 2.0 6 votes vote down vote up
@Override
public Pipe.Schema<T> getPipeSchema()
{
    Pipe.Schema<T> pipeSchema = this.pipeSchema;
    if (pipeSchema == null)
    {
        synchronized (this)
        {
            if ((pipeSchema = this.pipeSchema) == null)
            {
                this.pipeSchema = pipeSchema = RuntimeSchema.resolvePipeSchema(
                        getSchema(), typeClass, true);
            }
        }
    }
    return pipeSchema;
}
 
Example #13
Source File: ProtoStuffSerializer.java    From bitchat with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public byte[] serialize(Object object) {
    LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    byte[] bytes = null;
    try {
        Class clazz = object.getClass();
        Schema schema = getSchema(clazz);
        bytes = ProtostuffIOUtil.toByteArray(object, schema, buffer);
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    } finally {
        buffer.clear();
    }
    return bytes;
}
 
Example #14
Source File: EnumSetAndMapTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
static void doBean(IdStrategy strategy)
{
    Bean bean = fill(new Bean());

    verify(bean);

    Schema<Bean> schema = RuntimeSchema.getSchema(Bean.class, strategy);
    // print(schema);
    byte[] bytes = ProtostuffIOUtil.toByteArray(bean, schema,
            LinkedBuffer.allocate(256));

    Bean deBean = new Bean();
    ProtostuffIOUtil.mergeFrom(bytes, deBean, schema);

    verify(deBean);
}
 
Example #15
Source File: DubboProtostuffWriter.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@Override
public void writeObject(final Object obj) throws IOException {
    byte[] bytes;
    byte[] classNameBytes;
    Schema mySchema;
    try {
        if (obj == null || Wrapper.needWrapper(obj)) {
            mySchema = getSchema(Wrapper.class);
            classNameBytes = Wrapper.CLASS_NAMES;
            bytes = GraphIOUtil.toByteArray(new Wrapper(obj), mySchema, buffer);
        } else {
            Class<?> objClass = obj.getClass();
            mySchema = objClass == schema.typeClass() ? schema : getSchema(objClass);
            classNameBytes = objClass.getName().getBytes();
            bytes = GraphIOUtil.toByteArray(obj, mySchema, buffer);
        }
    } finally {
        buffer.clear();
    }
    dos.writeInt(classNameBytes.length);
    dos.writeInt(bytes.length);
    dos.write(classNameBytes);
    dos.write(bytes);
}
 
Example #16
Source File: AbstractRuntimeMapTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
public void testInlineKPojoV() throws Exception
{
    Schema<HasMapInlineKPojoV> schema = RuntimeSchema
            .getSchema(HasMapInlineKPojoV.class);
    Pipe.Schema<HasMapInlineKPojoV> pipeSchema = ((RuntimeSchema<HasMapInlineKPojoV>) schema).getPipeSchema();

    HasMapInlineKPojoV p = new HasMapInlineKPojoV().fill();

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

    HasMapInlineKPojoV pFromByteArray = new HasMapInlineKPojoV();
    mergeFrom(data, 0, data.length, pFromByteArray, schema);
    assertEquals(p, pFromByteArray);

    HasMapInlineKPojoV pFromStream = new HasMapInlineKPojoV();
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    mergeFrom(in, pFromStream, schema);
    assertEquals(p, pFromByteArray);

    roundTrip(p, schema, pipeSchema);
}
 
Example #17
Source File: ProtostuffSerializer.java    From turbo-rpc with Apache License 2.0 6 votes vote down vote up
public Request readRequest(ByteBuf byteBuf) throws IOException {
	int requestId = byteBuf.readInt();
	int serviceId = ByteBufUtils.readVarInt(byteBuf);
	Tracer tracer = TRACER_SERIALIZER.read(byteBuf);

	Schema<MethodParam> schema = schema(serviceId);
	MethodParam methodParam = null;

	if (EmptyMethodParam.class.equals(schema.typeClass())) {
		methodParam = EmptyMethodParam.empty();
	} else {
		ByteBufInput input = getOrUpdate(INPUT_ATTACHMENT_INDEX, INPUT_SUPPLIER);
		input.setByteBuf(byteBuf, true);

		methodParam = schema.newMessage();
		schema.mergeFrom(input, methodParam);
	}

	Request request = RecycleRequest.newInstance(requestId, serviceId, tracer, methodParam);

	return request;
}
 
Example #18
Source File: AbstractRuntimeObjectSchemaTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
public void testPojoWithClassFields() throws Exception
{
    Schema<PojoWithClassFields> schema = RuntimeSchema
            .getSchema(PojoWithClassFields.class);
    Pipe.Schema<PojoWithClassFields> pipeSchema = ((RuntimeSchema<PojoWithClassFields>) schema).getPipeSchema();

    PojoWithClassFields p = new PojoWithClassFields().fill();

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

    PojoWithClassFields pFromByteArray = new PojoWithClassFields();
    mergeFrom(data, 0, data.length, pFromByteArray, schema);
    assertEquals(p, pFromByteArray);

    PojoWithClassFields pFromStream = new PojoWithClassFields();
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    mergeFrom(in, pFromStream, schema);
    assertEquals(p, pFromStream);

    roundTrip(p, schema, pipeSchema);
}
 
Example #19
Source File: PolymorphicMapSchema.java    From protostuff with Apache License 2.0 6 votes vote down vote up
private static void writeUnmodifiableMapTo(Output output, Object value,
        Schema<?> currentSchema, IdStrategy strategy, int id)
        throws IOException
{
    final Object m;
    try
    {
        m = fUnmodifiableMap_m.get(value);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }

    output.writeObject(id, m, strategy.POLYMORPHIC_MAP_SCHEMA, false);
}
 
Example #20
Source File: AbstractRuntimeMapTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
public void testEnumKPolymorphicV() throws Exception
{
    Schema<HasMapEnumKPolymorphicV> schema = RuntimeSchema
            .getSchema(HasMapEnumKPolymorphicV.class);
    Pipe.Schema<HasMapEnumKPolymorphicV> pipeSchema = ((RuntimeSchema<HasMapEnumKPolymorphicV>) schema)
            .getPipeSchema();

    HasMapEnumKPolymorphicV p = new HasMapEnumKPolymorphicV().fill();

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

    HasMapEnumKPolymorphicV pFromByteArray = new HasMapEnumKPolymorphicV();
    mergeFrom(data, 0, data.length, pFromByteArray, schema);
    assertEquals(p, pFromByteArray);

    HasMapEnumKPolymorphicV pFromStream = new HasMapEnumKPolymorphicV();
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    mergeFrom(in, pFromStream, schema);
    assertEquals(p, pFromByteArray);

    roundTrip(p, schema, pipeSchema);
}
 
Example #21
Source File: AbstractRuntimeObjectSchemaTest.java    From protostuff with Apache License 2.0 6 votes vote down vote up
public void testPojoWithCustomArrayListAndHashMapAndHashMap()
        throws Exception
{
    Schema<PojoWithCustomArrayListAndHashMap> schema = RuntimeSchema
            .getSchema(PojoWithCustomArrayListAndHashMap.class);
    Pipe.Schema<PojoWithCustomArrayListAndHashMap> pipeSchema = ((RuntimeSchema<PojoWithCustomArrayListAndHashMap>) schema)
            .getPipeSchema();

    PojoWithCustomArrayListAndHashMap p = new PojoWithCustomArrayListAndHashMap()
            .fill();

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

    PojoWithCustomArrayListAndHashMap pFromByteArray = new PojoWithCustomArrayListAndHashMap();
    mergeFrom(data, 0, data.length, pFromByteArray, schema);
    assertEquals(p, pFromByteArray);

    PojoWithCustomArrayListAndHashMap pFromStream = new PojoWithCustomArrayListAndHashMap();
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    mergeFrom(in, pFromStream, schema);
    assertEquals(p, pFromStream);

    roundTrip(p, schema, pipeSchema);
}
 
Example #22
Source File: FileFormat.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@JsonIgnore
@SuppressWarnings({ "rawtypes", "unchecked" })
public FileConfig asFileConfig() {
  buffer.clear();
  FileConfig fc = new FileConfig();
  fc.setType(getFileType());
  fc.setName(name);
  fc.setOwner(owner);
  fc.setCtime(ctime);
  fc.setType(getFileType());
  fc.setTag(getVersion());
  fc.setLocation(location);
  byte[] bytes = ProtobufIOUtil.toByteArray(this, (Schema) getPrivateSchema(), buffer);
  fc.setExtendedConfig(ByteString.copyFrom(bytes));
  fc.setFullPathList(fullPath);
  return fc;
}
 
Example #23
Source File: SchemaCache.java    From voyage with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Schema<T> getSchema(Class<T> clazz) {
	String className = clazz.getName();
	Schema<T> schema = (Schema<T>) SCHEMA_CACHE.get(className);
	if (null != schema) {
		return schema;
	}
	synchronized (SCHEMA_CACHE) {
		if (null == SCHEMA_CACHE.get(className)) {
			schema = RuntimeSchema.getSchema(clazz);
			SCHEMA_CACHE.put(className, schema);
			return schema;
		} else {
			return (Schema<T>) SCHEMA_CACHE.get(className);
		}
	}
}
 
Example #24
Source File: MathObjectsTest.java    From protostuff with Apache License 2.0 5 votes vote down vote up
public void testProtostuff() throws Exception
{
    Schema<Payment> schema = RuntimeSchema.getSchema(Payment.class);
    Payment p = filledPayment();

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

    Payment p2 = new Payment();
    ProtostuffIOUtil.mergeFrom(data, 0, data.length, p2, schema);
    /*
     * System.err.println(p2.getId()); System.err.println(p2.getBd()); System.err.println(p2.getBi());
     * System.err.println(p2.getBdList()); System.err.println(p2.getBiList());
     */

    assertEquals(p, p2);

    List<Payment> list = new ArrayList<Payment>();
    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<Payment> parsedList = ProtostuffIOUtil.parseListFrom(in, schema);

    assertEquals(list, parsedList);
}
 
Example #25
Source File: ProtobufSerializer.java    From voyage with Apache License 2.0 5 votes vote down vote up
protected <T> void parseObject(InputStream in, T template, Schema<T> schema) {
	try {
		ProtobufIOUtil.mergeFrom(in, template, schema);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #26
Source File: MessageCrypto.java    From jeesupport with MIT License 5 votes vote down vote up
/**
 * S2C
 * 将对象序列化为byte[]
 *
 * @param _obj 序列化对象
 * @return 序列化后的byte[]值
 */
public static < T > byte[] serializer ( T _obj ) {
	@SuppressWarnings( "unchecked" )
	Class< T > cls = ( Class< T > ) _obj.getClass();
	LinkedBuffer buf = LinkedBuffer.allocate( LinkedBuffer.DEFAULT_BUFFER_SIZE );
	try {
		Schema< T > schema = _get_schema( cls );
		return ProtostuffIOUtil.toByteArray( _obj , schema , buf );
	} catch ( Exception e ) {
		throw new IllegalStateException( e.getMessage() , e );
	} finally {
		buf.clear();
	}
}
 
Example #27
Source File: PolymorphicMapSchema.java    From protostuff with Apache License 2.0 5 votes vote down vote up
private static Object readUnmodifiableMapFrom(Input input,
        Schema<?> schema, Object owner, IdStrategy strategy, boolean graph,
        Object map, boolean sm) throws IOException
{
    if (graph)
    {
        // update the actual reference.
        ((GraphInput) input).updateLast(map, owner);
    }

    final Wrapper wrapper = new Wrapper();
    Object m = input.mergeObject(wrapper, strategy.POLYMORPHIC_MAP_SCHEMA);
    if (!graph || !((GraphInput) input).isCurrentMessageReference())
        m = wrapper.value;
    try
    {
        fUnmodifiableMap_m.set(map, m);

        if (sm)
            fUnmodifiableSortedMap_sm.set(map, m);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }

    return map;
}
 
Example #28
Source File: ProtoStuffSerializer.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T readObject(final byte[] bytes, final int offset, final int length, final Class<T> clazz) {
    final Schema<T> schema = RuntimeSchema.getSchema(clazz);
    final T msg = schema.newMessage();

    final Input input = Inputs.getInput(bytes, offset, length);
    try {
        schema.mergeFrom(input, msg);
        Inputs.checkLastTagWas(input, 0);
    } catch (final IOException e) {
        ThrowUtil.throwException(e);
    }

    return msg;
}
 
Example #29
Source File: ArraySchema.java    From protostuff with Apache License 2.0 5 votes vote down vote up
static void writeObjectTo(Output output, Object value,
        Schema<?> currentSchema, IdStrategy strategy) throws IOException
{
    final Class<?> clazz = value.getClass();
    int dimensions = 1;
    Class<?> componentType = clazz.getComponentType();
    while (componentType.isArray())
    {
        dimensions++;
        componentType = componentType.getComponentType();
    }

    strategy.writeArrayIdTo(output, componentType);
    // write the length of the array
    output.writeUInt32(ID_ARRAY_LEN, ((Object[])value).length, false);
    // write the dimensions of the array
    output.writeUInt32(ID_ARRAY_DIMENSION, dimensions, false);

    if (output instanceof StatefulOutput)
    {
        // update using the derived schema.
        ((StatefulOutput) output).updateLast(strategy.ARRAY_SCHEMA,
                currentSchema);
    }

    strategy.ARRAY_SCHEMA.writeTo(output, value);
}
 
Example #30
Source File: FastIdStrategy.java    From turbo-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public Pipe.Schema<T> getPipeSchema() {
	HasSchema<T> wrapper = this.wrapper;
	if (wrapper == null) {
		synchronized (this) {
			if ((wrapper = this.wrapper) == null) {
				this.wrapper = wrapper = strategy.getSchemaWrapper(typeClass, true);
			}
		}
	}

	return wrapper.getPipeSchema();
}