Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //========================================================================
  //Copyright 2007-2009 David Yu dyuproject@gmail.com
  //------------------------------------------------------------------------
  //Licensed under the Apache License, Version 2.0 (the "License");
  //you may not use this file except in compliance with the License.
  //You may obtain a copy of the License at 
  //http://www.apache.org/licenses/LICENSE-2.0
  //Unless required by applicable law or agreed to in writing, software
  //distributed under the License is distributed on an "AS IS" BASIS,
 //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 //See the License for the specific language governing permissions and
 //limitations under the License.
 //========================================================================
 
 package io.protostuff;
 
 import java.io.Reader;
 import java.io.Writer;
 import java.util.List;
 
Utility for the JSON serialization/deserialization of messages and objects tied to a schema.

Author(s):
David Yu
Created:
Nov 20, 2009
 
 public final class JsonIOUtil
 {
 
     private JsonIOUtil()
     {
     }

    
A custom factory simply to expose certain fields.
 
     public static final class Factory extends JsonFactory
     {

        
Needed by jackson's internal utf8 strema parser.
 
         public BytesToNameCanonicalizer getRootByteSymbols()
         {
             return ;
         }

        
Returns the parser feature flags.
 
         public int getParserFeatures()
         {
             return ;
         }

        
Returns the generator feature flags.
 
         public int getGeneratorFeatures()
         {
             return ;
         }
 
     }

    
The default json factory for creating json parsers and generators.
 
     public static final Factory DEFAULT_JSON_FACTORY = new Factory();
 
     static
     {
         // disable auto-close to have same behavior as protostuff-core utility io methods
     }

    
Creates a json pipe from a byte array.
 
     public static Pipe newPipe(byte[] databoolean numericthrows IOException
     {
         return newPipe(data, 0, data.lengthnumeric);
     }

    
Creates a json pipe from a byte array.
    public static Pipe newPipe(byte[] dataint offsetint lengthboolean numeric)
            throws IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                datafalse);
        final JsonParser parser = newJsonParser(nulldataoffsetoffset + lengthfalse,
                context);
        return newPipe(parsernumeric);
    }

    
Creates a json pipe from an java.io.InputStream.
    public static Pipe newPipe(InputStream inboolean numericthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                infalse);
        final JsonParser parser = newJsonParser(incontext.allocReadIOBuffer(), 0, 0,
                truecontext);
        return newPipe(parsernumeric);
    }

    
Creates a json pipe from a java.io.Reader.
    public static Pipe newPipe(Reader readerboolean numericthrows IOException
    {
        return newPipe(.createJsonParser(reader), numeric);
    }

    
Creates a json pipe from a com.fasterxml.jackson.core.JsonParser.
    public static Pipe newPipe(final JsonParser parserboolean numericthrows IOException
    {
        final JsonInput jsonInput = new JsonInput(parsernumeric);
        return new Pipe()
        {
            @Override
            protected Input begin(Pipe.Schema<?> pipeSchemathrows IOException
            {
                if (parser.nextToken() != .)
                {
                    throw new JsonInputException("Expected token: { but was " +
                            parser.getCurrentToken() + " on message " +
                            pipeSchema.wrappedSchema.messageFullName());
                }
                return jsonInput;
            }
            @Override
            protected void end(Pipe.Schema<?> pipeSchemaInput input,
                    boolean cleanupOnlythrows IOException
            {
                if (cleanupOnly)
                {
                    parser.close();
                    return;
                }
                assert input == jsonInput;
                final JsonToken token = parser.getCurrentToken();
                parser.close();
                if (token != .)
                {
                    throw new JsonInputException("Expected token: } but was " +
                            token + " on message " +
                            pipeSchema.wrappedSchema.messageFullName());
                }
            }
        };
    }

    
Creates a com.fasterxml.jackson.core.json.UTF8StreamJsonParser from the inputstream with the supplied buf inBuffer to use.
    public static UTF8StreamJsonParser newJsonParser(InputStream inbyte[] buf,
            int offsetint limitthrows IOException
    {
        return newJsonParser(inbufoffsetlimitfalse,
                new IOContext(._getBufferRecycler(), in,
                        false));
    }

    
Creates a com.fasterxml.jackson.core.json.UTF8StreamJsonParser from the inputstream with the supplied buf inBuffer to use.
    static UTF8StreamJsonParser newJsonParser(InputStream inbyte[] buf,
            int offsetint limitboolean bufferRecyclableIOContext context)
            throws IOException
    {
        return new UTF8StreamJsonParser (context,
                .getParserFeatures(), in,
                .getCodec(),
                .getRootByteSymbols().makeChild(truetrue),
                bufoffsetlimitbufferRecyclable);
    }

    
Creates a com.fasterxml.jackson.core.json.UTF8JsonGenerator for the outputstream with the supplied buf outBuffer to use.
    public static UTF8JsonGenerator newJsonGenerator(OutputStream outbyte[] buf)
    {
        return newJsonGenerator(outbuf, 0, falsenew IOContext(
                ._getBufferRecycler(), outfalse));
    }

    
Creates a com.fasterxml.jackson.core.json.UTF8JsonGenerator for the outputstream with the supplied buf outBuffer to use.
    static UTF8JsonGenerator newJsonGenerator(OutputStream outbyte[] bufint offset,
            boolean bufferRecyclableIOContext context)
    {
        context.setEncoding(.);
        return new UTF8JsonGenerator(context,
                .getGeneratorFeatures(),
                .getCodec(),
                out,
                buf,
                offset,
                bufferRecyclable);
    }

    
Merges the message with the byte array using the given schema.
    public static <T> void mergeFrom(byte[] data, T messageSchema<T> schema,
            boolean numericthrows IOException
    {
        mergeFrom(data, 0, data.lengthmessageschemanumeric);
    }

    
Merges the message with the byte array using the given schema.
    public static <T> void mergeFrom(byte[] dataint offsetint length, T message,
            Schema<T> schemaboolean numericthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                datafalse);
        final JsonParser parser = newJsonParser(nulldataoffsetoffset + lengthfalse,
                context);
        /*
         * final JsonParser parser = DEFAULT_JSON_FACTORY.createJsonParser(data, offset, length);
         */
        try
        {
            mergeFrom(parsermessageschemanumeric);
        }
        finally
        {
            parser.close();
        }
    }

    
Merges the message from the java.io.InputStream using the given schema.
    public static <T> void mergeFrom(InputStream in, T messageSchema<T> schema,
            boolean numericthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                infalse);
        final JsonParser parser = newJsonParser(incontext.allocReadIOBuffer(), 0, 0,
                truecontext);
        // final JsonParser parser = DEFAULT_JSON_FACTORY.createJsonParser(in);
        try
        {
            mergeFrom(parsermessageschemanumeric);
        }
        finally
        {
            parser.close();
        }
    }

    
Merges the message from the java.io.InputStream using the given schema.

The io.protostuff.LinkedBuffer's internal byte array will be used when reading the message.

    public static <T> void mergeFrom(InputStream in, T messageSchema<T> schema,
            boolean numericLinkedBuffer bufferthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                infalse);
        final JsonParser parser = newJsonParser(inbuffer.buffer, 0, 0, falsecontext);
        try
        {
            mergeFrom(parsermessageschemanumeric);
        }
        finally
        {
            parser.close();
        }
    }

    
Merges the message from the java.io.Reader using the given schema.
    public static <T> void mergeFrom(Reader reader, T messageSchema<T> schema,
            boolean numericthrows IOException
    {
        final JsonParser parser = .createJsonParser(reader);
        try
        {
            mergeFrom(parsermessageschemanumeric);
        }
        finally
        {
            parser.close();
        }
    }

    
Merges the message from the JsonParser using the given schema.
    public static <T> void mergeFrom(JsonParser parser, T messageSchema<T> schema,
            boolean numericthrows IOException
    {
        if (parser.nextToken() != .)
        {
            throw new JsonInputException("Expected token: { but was " +
                    parser.getCurrentToken() + " on message " +
                    schema.messageFullName());
        }
        schema.mergeFrom(new JsonInput(parsernumeric), message);
        if (parser.getCurrentToken() != .)
        {
            throw new JsonInputException("Expected token: } but was " +
                    parser.getCurrentToken() + " on message " +
                    schema.messageFullName());
        }
    }

    
Serializes the message into a byte array using the given schema.
    public static <T> byte[] toByteArray(T messageSchema<T> schemaboolean numeric)
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try
        {
            writeTo(baosmessageschemanumeric);
        }
        catch (IOException e)
        {
            throw new RuntimeException("Serializing to a byte array threw an IOException " +
                    "(should never happen)."e);
        }
        return baos.toByteArray();
    }

    
Serializes the message into a byte array using the given schema.

The io.protostuff.LinkedBuffer's internal byte array will be used as the primary buffer when writing the message.

    public static <T> byte[] toByteArray(T messageSchema<T> schemaboolean numeric,
            LinkedBuffer buffer)
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try
        {
            writeTo(baosmessageschemanumericbuffer);
        }
        catch (IOException e)
        {
            throw new RuntimeException("Serializing to a byte array threw an IOException " +
                    "(should never happen)."e);
        }
        return baos.toByteArray();
    }

    
Serializes the message into an java.io.OutputStream using the given schema.
    public static <T> void writeTo(OutputStream out, T messageSchema<T> schema,
            boolean numericthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                outfalse);
        final JsonGenerator generator = newJsonGenerator(out,
                context.allocWriteEncodingBuffer(), 0, truecontext);
        /*
         * final JsonGenerator generator = DEFAULT_JSON_FACTORY.createJsonGenerator(out, JsonEncoding.UTF8);
         */
        try
        {
            writeTo(generatormessageschemanumeric);
        }
        finally
        {
            generator.close();
        }
    }

    
Serializes the message into an java.io.OutputStream using the given schema.

The io.protostuff.LinkedBuffer's internal byte array will be used as the primary buffer when writing the message.

    public static <T> void writeTo(OutputStream out, T messageSchema<T> schema,
            boolean numericLinkedBuffer bufferthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                outfalse);
        final JsonGenerator generator = newJsonGenerator(outbuffer.buffer, 0, false,
                context);
        try
        {
            writeTo(generatormessageschemanumeric);
        }
        finally
        {
            generator.close();
        }
    }

    
Serializes the message into a java.io.Writer using the given schema.
    public static <T> void writeTo(Writer writer, T messageSchema<T> schema,
            boolean numericthrows IOException
    {
        final JsonGenerator generator = .createJsonGenerator(writer);
        try
        {
            writeTo(generatormessageschemanumeric);
        }
        finally
        {
            generator.close();
        }
    }

    
Serializes the message into a JsonGenerator using the given schema.
    public static <T> void writeTo(JsonGenerator generator, T messageSchema<T> schema,
            boolean numericthrows IOException
    {
        generator.writeStartObject();
        final JsonOutput output = new JsonOutput(generatornumericschema);
        schema.writeTo(outputmessage);
        if (output.isLastRepeated())
            generator.writeEndArray();
        generator.writeEndObject();
    }

    
Serializes the messages into the stream using the given schema.
    public static <T> void writeListTo(OutputStream outList<T> messages,
            Schema<T> schemaboolean numericthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                outfalse);
        final JsonGenerator generator = newJsonGenerator(out,
                context.allocWriteEncodingBuffer(), 0, truecontext);
        /*
         * final JsonGenerator generator = DEFAULT_JSON_FACTORY.createJsonGenerator(out, JsonEncoding.UTF8);
         */
        try
        {
            writeListTo(generatormessagesschemanumeric);
        }
        finally
        {
            generator.close();
        }
    }

    
Serializes the messages into the stream using the given schema.

The io.protostuff.LinkedBuffer's internal byte array will be used as the primary buffer when writing the message.

    public static <T> void writeListTo(OutputStream outList<T> messages,
            Schema<T> schemaboolean numericLinkedBuffer bufferthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                outfalse);
        final JsonGenerator generator = newJsonGenerator(outbuffer.buffer, 0, false,
                context);
        try
        {
            writeListTo(generatormessagesschemanumeric);
        }
        finally
        {
            generator.close();
        }
    }

    
Serializes the messages into the writer using the given schema.
    public static <T> void writeListTo(Writer writerList<T> messagesSchema<T> schema,
            boolean numericthrows IOException
    {
        final JsonGenerator generator = .createJsonGenerator(writer);
        try
        {
            writeListTo(generatormessagesschemanumeric);
        }
        finally
        {
            generator.close();
        }
    }

    
Serializes the messages into the generator using the given schema.
    public static <T> void writeListTo(JsonGenerator generatorList<T> messages,
            Schema<T> schemaboolean numericthrows IOException
    {
        generator.writeStartArray();
        if (messages.isEmpty())
        {
            generator.writeEndArray();
            return;
        }
        final JsonOutput output = new JsonOutput(generatornumericschema);
        for (T m : messages)
        {
            generator.writeStartObject();
            schema.writeTo(outputm);
            if (output.isLastRepeated())
                generator.writeEndArray();
            generator.writeEndObject();
            output.reset();
        }
        generator.writeEndArray();
    }

    
Parses the messages from the stream using the given schema.
    public static <T> List<T> parseListFrom(InputStream inSchema<T> schema,
            boolean numericthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                infalse);
        final JsonParser parser = newJsonParser(incontext.allocReadIOBuffer(), 0, 0,
                truecontext);
        // final JsonParser parser = DEFAULT_JSON_FACTORY.createJsonParser(in);
        try
        {
            return parseListFrom(parserschemanumeric);
        }
        finally
        {
            parser.close();
        }
    }

    
Parses the messages from the stream using the given schema.

The io.protostuff.LinkedBuffer's internal byte array will be used when reading the message.

    public static <T> List<T> parseListFrom(InputStream inSchema<T> schema,
            boolean numericLinkedBuffer bufferthrows IOException
    {
        final IOContext context = new IOContext(._getBufferRecycler(),
                infalse);
        final JsonParser parser = newJsonParser(inbuffer.buffer, 0, 0, falsecontext);
        try
        {
            return parseListFrom(parserschemanumeric);
        }
        finally
        {
            parser.close();
        }
    }

    
Parses the messages from the reader using the given schema.
    public static <T> List<T> parseListFrom(Reader readerSchema<T> schema,
            boolean numericthrows IOException
    {
        final JsonParser parser = .createJsonParser(reader);
        try
        {
            return parseListFrom(parserschemanumeric);
        }
        finally
        {
            parser.close();
        }
    }

    
Parses the messages from the parser using the given schema.
    public static <T> List<T> parseListFrom(JsonParser parserSchema<T> schema,
            boolean numericthrows IOException
    {
        if (parser.nextToken() != .)
        {
            throw new JsonInputException("Expected token: [ but was " +
                    parser.getCurrentToken() + " on message: " +
                    schema.messageFullName());
        }
        final JsonInput input = new JsonInput(parsernumeric);
        final List<T> list = new ArrayList<>();
        for (JsonToken t = parser.nextToken(); t != .t = parser.nextToken())
        {
            if (t != .)
            {
                throw new JsonInputException("Expected token: { but was " +
                        parser.getCurrentToken() + " on message " +
                        schema.messageFullName());
            }
            final T message = schema.newMessage();
            schema.mergeFrom(inputmessage);
            if (parser.getCurrentToken() != .)
            {
                throw new JsonInputException("Expected token: } but was " +
                        parser.getCurrentToken() + " on message " +
                        schema.messageFullName());
            }
            list.add(message);
            input.reset();
        }
        return list;
    }
New to GrepCode? Check out our FAQ X