Class NoOptParserSupport

  • All Implemented Interfaces:
    Parser<Void>

    public abstract class NoOptParserSupport
    extends ParserSupport<Void>
    A convenience base for parsers that don't require options.

    The following is an example of an implementation that parses to an Integer.

    
     import com.google.common.reflect.TypeToken;
     import ratpack.exec.Promise;
     import ratpack.core.handling.Context;
     import ratpack.core.handling.Handler;
     import ratpack.core.http.TypedData;
     import ratpack.core.parse.NoOptParserSupport;
     import ratpack.test.handling.HandlingResult;
     import ratpack.test.handling.RequestFixture;
     import ratpack.func.Types;
    
     import static org.junit.jupiter.api.Assertions.assertEquals;
    
     public class Example {
       public static class IntParser extends NoOptParserSupport {
         public <T> T parse(Context context, TypedData body, TypeToken<T> type) {
           if (type.getRawType().equals(Integer.class)) {
             return Types.cast(Integer.valueOf(body.getText()));
           } else {
             return null;
           }
         }
       }
    
       public static class ExampleHandler implements Handler {
         public void handle(Context context) throws Exception {
           context.parse(Integer.class).then(integer -> context.render(integer.toString()));
         }
       }
    
       // unit test
       public static void main(String[] args) throws Exception {
         HandlingResult result = RequestFixture.handle(new ExampleHandler(),
           fixture -> fixture
               .body("10", "text/plain")
               .registry(registry -> registry.add(new IntParser()))
         );
    
         assertEquals("10", result.rendered(String.class));
       }
     }
     
    • Constructor Detail

      • NoOptParserSupport

        public NoOptParserSupport()
    • Method Detail

      • parse

        protected abstract <T> T parse​(Context context,
                                       TypedData requestBody,
                                       com.google.common.reflect.TypeToken<T> type)
                                throws Exception
        The parser implementation.
        Type Parameters:
        T - the type of object to construct from the request body
        Parameters:
        context - The context to deserialize
        requestBody - The request body to deserialize
        type - the type of object to construct from the request body
        Returns:
        an instance of T if this parser can construct this type, otherwise null
        Throws:
        Exception - any exception thrown while parsing