users@jersey.java.net

[Jersey] Re: Setting Content-Language Header

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Wed, 25 May 2011 08:50:12 +0200

Hi Charles,

there is a support for your use case in the JAX-RS directly.
You do not need a filter to decide on what language variant
you want to return. The following resource returns either
"English" or "German" text response if the client accepted English
or German language or 406 response back, if the accepted language
differs. I think you can re-use the same pattern.
HTTP Vary header is used in the response to suggest what accept header
values were used to select the right variant.

HTH,

~Jakub


@Path("/language")
public class LanguageResource {

     @Context Request req;

     final static List<Variant> variants =
Variant.mediaTypes(MediaType.TEXT_PLAIN_TYPE).languages(Locale.ENGLISH,
Locale.GERMAN).add().build();

     @GET
     public String getSelectedLanguage() {
         final Variant selectedVariant = req.selectVariant(variants);

         if (selectedVariant != null) {
             return selectedVariant.getLanguage().getDisplayLanguage();
         }

         throw new
WebApplicationException(Response.notAcceptable(variants).build());
     }
}


On 05/24/2011 07:23 PM, charles_overbeck_at_yahoo.com wrote:
> Is there any reason I can't/shouldn't set the HTTP Content-Language
> header in a ContainerResponseFilter? I'm just checking if that sounds
> like a good idea.
>
> I know you can call Response.ok().language()... in the individual
> resource methods, but then in addition to changing every resource
> method to do that, I would also have to change all method signatures to
> return a Response, e.g., from
>
> @GET
> public JAXBElement<InvoiceType> getInvoice()...
>
> to:
>
> @GET
> public Response getInvoice()...
>
> I like the first one better, because it's a more obviously
> self-documenting. So far, I only return a Response for @POST annotated
> methods, where I need to set the HTTP Location header.
>
> So I'm thinking that because I'm going to have the whole service
> localized for a certain set of languages, that I could just figure out
> in a ContainerReponseFilter what language all resource methods will
> return given the Accept-Language header, and set the Content-Language
> header accordingly.
>
> Any thoughts? Has anybody else tackled this in a different way?
>
> Thanks,
>
> Charles
>