Skip to content

Instantly share code, notes, and snippets.

@ghusta
Last active March 17, 2016 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghusta/6835a0b05533beec7866 to your computer and use it in GitHub Desktop.
Save ghusta/6835a0b05533beec7866 to your computer and use it in GitHub Desktop.
RestEasy Interceptor (JAX-RS).Extract current locale from HTTP Request Header : 'Accept-Languages'.
package com...rest.support.interceptors;
import java.util.List;
import java.util.Locale;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.ext.Provider;
import org.jboss.resteasy.annotations.interception.Precedence;
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
/**
* Extract current locale from HTTP Request Header : 'Accept-Languages'.
*/
@Provider
@Precedence("CUSTOM-REQUEST-HEADERS")
@ServerInterceptor
public class AcceptLanguagesRequestInterceptor
implements PreProcessInterceptor
{
@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException
{
HttpHeaders httpHeaders = request.getHttpHeaders();
List<Locale> acceptableLanguages = httpHeaders.getAcceptableLanguages();
Locale defLocale = (acceptableLanguages.isEmpty() ? Locale.getDefault() : acceptableLanguages.get(0));
// TODO: store it in ThreadLocal...
System.out.println("Locale found = " + defLocale.toString());
return null;
}
}
import java.util.Locale;
/**
** A {@link ThreadLocal} to store the Locale to be used in the message interpolator.
*/
public class LocaleThreadLocal
{
public static final ThreadLocal<Locale> THREAD_LOCAL = new ThreadLocal<Locale>();
public static Locale get()
{
return (THREAD_LOCAL.get() == null) ? Locale.getDefault() : THREAD_LOCAL.get();
}
public static void set(Locale locale)
{
THREAD_LOCAL.set(locale);
}
public static void unset()
{
THREAD_LOCAL.remove();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment