Skip to content

Instantly share code, notes, and snippets.

@brikis98
Created May 7, 2012 18:35
Show Gist options
  • Save brikis98/2629518 to your computer and use it in GitHub Desktop.
Save brikis98/2629518 to your computer and use it in GitHub Desktop.
Binding form data to RecordTemplate
{
"doc" : "A form that includes the Greeting resource plus some extra fields",
"type" : "record",
"name" : "GreetingForm",
"include" : [ "Greeting" ],
"fields" :
[
{
"name" : "some-extra-field-1",
"type" : "string",
},
{
"name" : "some-extra-field-2",
"type" : "string",
}
]
}
public class RestliForm<T> extends Form<T extends RecordTemplate> {
private Class<T> clazz;
public RestliForm(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public Form<T> bindFromRequest() {
if (Http.Context.current().request().body() != null && Http.Context.current().request().body().asJson() != null) {
// DataMap dataMap = new JacksonDataCodec().bytesToMap(Http.Context.current().request().body().asJson().toString().getBytes("UTF-8"));
DataMap dataMap = new DataMap(Http.Context.current().request().body());
T record = clazz.newInstance();
record.data().putAll(dataMap);
ValidationErrors errors = DataSchemaValidator.validate(record);
return new Form<T>(null, clazz, dataMap, errors, new Some(record));
}
return null;
}
}
public class RestliFormPlugin {
public static <T extends RecordTemplate> Form<T> form(Class<T> clazz) {
return new RestliForm(clazz);
}
public static <I extends RecordTemplate, O extends RecordTemplate> O toDomainObject(I formObject, Class<O> domainClass) {
O domainObject = domainClass.newInstance();
domainObject.data().putAll(formObject.data());
return domainObject;
}
}
import static RestliFormPlugin.*;
public class Application extends Controller {
public static Result index() {
Form<GreetingsForm> form = form(GreetingsForm.class).bindFromRequest();
if (form.hasErrors()) {
// handle errors...
}
// Convert the form to a domain object and POST it to the greetings rest.li service
Greeting greeting = toDomainObject(form.get(), Greeting.class);
RestliClientJava client = Play.application().plugin(RestliPlugin.class).javaClient();
Promise<Response<Greeting>> promise = client.sendRequest(new GreetingsBuilder().post().input(greeting));
// etc.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment