Java Reference
In-Depth Information
That's a lot of code to say that the getSomething() JAX-RS method supports XML, JSON,
English, Spanish, deflated, and GZIP encodings. You're almost better off not using the se-
lectVariant() API and doing the selection manually. Luckily, JAX-RS offers the
javax.ws.rs.core.Variant.VariantListBuilder class to make writing these complex
selections easier:
public
public static
static abstract
abstract class
class VariantListBuilder
VariantListBuilder {
public
public static
static VariantListBuilder newInstance () {...}
public
public abstract
abstract VariantListBuilder mediaTypes ( MediaType ... mediaTypes );
public
public abstract
abstract VariantListBuilder languages ( Locale ... languages );
public
public abstract
abstract VariantListBuilder encodings ( String ... encodings );
public
public abstract
abstract List < Variant > build ();
public
public abstract
abstract VariantListBuilder add ();
}
The VariantListBuilder class allows you to add a series of media types, languages, and
encodings to it. It will then automatically create a list of variants that contains every possible
combination of these objects. Let's rewrite our previous example using a Vari-
antListBuilder :
@Path ( "/myservice" )
public
public class
class MyService
MyService {
@GET
Response getSomething ( @Context Request request ) {
Variant . VariantListBuilder vb = Variant . VariantListBuilder . newInstance ();
vb . mediaTypes ( MediaType . APPLICATION_XML_TYPE ,
MediaType . APPLICATION_JSON_TYPE )
. languages ( new
new Locale ( "es" ))
. encodings ( "deflate" , "gzip" ). add ();
new Locale ( "en" ), new
List < Variant > variants = vb . build ();
// Pick the variant
Variant v = request . selectVariant ( variants );
Object entity = ...; // get the object you want to return
ResponseBuilder builder = Response . ok ( entity );
Search WWH ::




Custom Search