Package ratpack.core.parse
Class ParserSupport<O>
- java.lang.Object
-
- ratpack.core.parse.ParserSupport<O>
-
- Type Parameters:
O
- the type of option object this parser accepts
- All Implemented Interfaces:
Parser<O>
- Direct Known Subclasses:
NoOptParserSupport
public abstract class ParserSupport<O> extends Object implements Parser<O>
A convenience superclass forParser
implementations.Specializations only need to implement the
Parser.parse(Context, TypedData, Parse)
method.import ratpack.exec.Promise; import ratpack.core.handling.Handler; import ratpack.core.handling.Context; import ratpack.core.http.TypedData; import ratpack.core.parse.Parse; import ratpack.core.parse.ParserSupport; import ratpack.core.parse.ParseException; import ratpack.func.Types; import java.io.UnsupportedEncodingException; import ratpack.test.handling.HandlingResult; import ratpack.test.handling.RequestFixture; import static org.junit.jupiter.api.Assertions.assertEquals; public class Example { // The parse options public static class StringParseOpts { private int maxLength; public StringParseOpts(int maxLength) { this.maxLength = maxLength; } public int getMaxLength() { return maxLength; } } // A parser for this type public static class MaxLengthStringParser extends ParserSupport<StringParseOpts> { public <T> T parse(Context context, TypedData body, Parse<T, StringParseOpts> parse) throws UnsupportedEncodingException { if (!parse.getType().getRawType().equals(String.class)) { return null; } String rawString = body.getText(); StringParseOpts opts = parse.getOpts().orElse(new StringParseOpts(rawString.length())); if (rawString.length() < opts.getMaxLength()) { return Types.cast(rawString); } else { return Types.cast(rawString.substring(0, opts.getMaxLength())); } } } public static class ToUpperCaseHandler implements Handler { public void handle(Context context) throws Exception { context.parse(String.class, new StringParseOpts(5)).then(string -> context.render(string)); } } // unit test public static void main(String[] args) throws Exception { HandlingResult result = RequestFixture.handle(new ToUpperCaseHandler(), fixture -> fixture .body("123456", "text/plain") .registry(registry -> registry.add(new MaxLengthStringParser())) ); assertEquals("12345", result.rendered(String.class)); } }
- See Also:
NoOptParserSupport
-
-
Constructor Summary
Constructors Modifier Constructor Description protected
ParserSupport()
Constructor.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description Class<O>
getOptsType()
The type of option object that this parser accepts.
-
-
-
Method Detail
-
getOptsType
public final Class<O> getOptsType()
The type of option object that this parser accepts.- Specified by:
getOptsType
in interfaceParser<O>
- Returns:
- the type of option object that this parser accepts
- See Also:
ParserSupport
-
-