Skip to content

Instantly share code, notes, and snippets.

@julienrf
Last active August 29, 2015 14:00
Show Gist options
  • Save julienrf/11248653 to your computer and use it in GitHub Desktop.
Save julienrf/11248653 to your computer and use it in GitHub Desktop.
Content negotiation in Java with Play framework
package controllers;
import play.mvc.Controller;
import play.libs.Json;
import static controllers.Render.*;
import static play.mvc.Http.MimeTypes;
public class Application extends Controller {
public static Result index() {
return render(
version(MimeTypes.JSON, () -> ok(Json.toJson("Hello, World!"))),
version(MimeTypes.HTML, () -> ok(views.html.index.render()))
);
}
}
package controllers;
import play.api.http.MediaRange;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.function.Supplier;
public class Render extends Controller {
public static Result render(Version... versions) {
List<MediaRange> acceptedTypes = request().acceptedTypes();
if (acceptedTypes.isEmpty() && versions.length > 0) {
return versions[0].resultThunk.get();
}
for (MediaRange mediaRange : acceptedTypes) {
for (Version version : versions) {
if (mediaRange.accepts(version.mimeType)) {
return version.resultThunk.get();
}
}
}
return status(NOT_ACCEPTABLE);
}
public static class Version {
public final String mimeType;
public final Supplier<Result> resultThunk;
public Version(String mimeType, Supplier<Result> resultThunk) {
this.mimeType = mimeType;
this.resultThunk = resultThunk;
}
}
public static Version version(String mimeType, Supplier<Result> resultThunk) {
return new Version(mimeType, resultThunk);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment