public abstract class NoOptParserSupport extends ParserSupport<NullParseOpts>
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.handling.Context;
import ratpack.handling.Handler;
import ratpack.http.TypedData;
import ratpack.parse.NoOptParserSupport;
import ratpack.test.handling.HandlingResult;
import ratpack.test.handling.RequestFixture;
import ratpack.util.Types;
import static org.junit.Assert.assertEquals;
public class Example {
public static class IntParser extends NoOptParserSupport {
public IntParser() {
super("text/plain");
}
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));
}
}
Modifier | Constructor and Description |
---|---|
protected |
NoOptParserSupport(String contentType)
Constructor.
|
Modifier and Type | Method and Description |
---|---|
<T> T |
parse(Context context,
TypedData requestBody,
Parse<T,NullParseOpts> parse)
Delegates to
parse(ratpack.handling.Context, ratpack.http.TypedData, TypeToken) , discarding the opts object of the given parse . |
protected abstract <T> T |
parse(Context context,
TypedData requestBody,
TypeToken<T> type)
The parser implementation.
|
getContentType, getOptsType
protected NoOptParserSupport(String contentType)
contentType
- the type of request this parser can handlepublic final <T> T parse(Context context, TypedData requestBody, Parse<T,NullParseOpts> parse) throws Exception
parse(ratpack.handling.Context, ratpack.http.TypedData, TypeToken)
, discarding the opts object of the given parse
.T
- the type of object to construct from the request bodycontext
- The context to deserializerequestBody
- The request body to deserializeparse
- The description of how to parse the request bodyparse(ratpack.handling.Context, ratpack.http.TypedData, TypeToken)
Exception
- any exception thrown by parse(ratpack.handling.Context, ratpack.http.TypedData, TypeToken)
protected abstract <T> T parse(Context context, TypedData requestBody, TypeToken<T> type) throws Exception
T
- the type of object to construct from the request bodycontext
- The context to deserializerequestBody
- The request body to deserializetype
- the type of object to construct from the request bodyT
if this parser can construct this type, otherwise null
Exception
- any exception thrown while parsing