Example usage for javax.servlet ServletRequest getLocale

List of usage examples for javax.servlet ServletRequest getLocale

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getLocale.

Prototype

public Locale getLocale();

Source Link

Document

Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.

Usage

From source file:com.github.mrstampy.gameboot.web.locale.WebLocale.java

/**
 * Sets the locale.//from  w  w w  .j a va2s.  c om
 *
 * @param request
 *          the request
 * @param key
 *          the key
 */
public void setLocale(ServletRequest request, SystemIdKey key) {
    Locale locale = request.getLocale();

    if (locale == null)
        return;

    log.debug("Setting locale {} for {}", locale, key);

    registry.put(key, locale);
}

From source file:de.uni_koeln.spinfo.maalr.webapp.i18n.InternationalUrlFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    //long start = System.nanoTime();
    HttpServletRequest h = (HttpServletRequest) request;
    String uri = h.getRequestURI();
    String path = h.getContextPath();
    Locale userLocale = request.getLocale();
    h.getSession().setAttribute("lang", userLocale.getLanguage());
    String url = uri.substring(path.length());
    /*/*from   w w w .  jav  a2 s  .co  m*/
     * Idee: die URL in ihre Bestandteile zerlegen und die einzelnen Teile
     * in einem Keyword-Tree matchen. Auf jeder Stufe wird dabei die eigentliche
     * URL um ein neues Element ergnzt.
     * 
     * Funktioniert auf diese Weise gut fr statische URLs, aufbau eines Baums
     * fr URLs mit fest definierten Klassen (z.B. bersetzungsrichtung) ist ebenfalls mglich.
     * 
     * Funktioniert aber nicht fr dynamische Bestandteile - da muss eine Wildcard
     * rein.
     * 
     * :wrterbuch:deutsch-rumantsch:nase.html oder .json oder .xml
     * 
     * Baum:
     * wrterbuch -> dictionary
     *      deutsch-rumantsch -> tudesg->rumantsch
     *         * -> *
     *            ending
     * 
     * Filter-Funktionalitt:
     * 
     * a) Prfen, ob die URL schon in die Zielsprache bersetzt wurde. Falls ja:
     * doFilter() aufrufen, sonst bersetzen (andernfalls Endlos-Schleife).
     * 
     * b) die gewhlte Sprache irgendwo in der Session hinterlegen, damit der
     * Rest des Programms (GUI) entsprechend der URL auch die richtigen Elemente
     * darstellt.
     * 
     * c) Hilfsklasse notwendig, die URLs entsprechend der Sprache generiert,
     * z.B. fr dictionary (s.o.), aber auch fr "translate", einschlielich der
     * Durchblttern-Funktion. HTTP-GET sollte auch bersetzt werden (also Parameter-Namen),
     * POST nicht.
     * 
     * d) Die Generierung des Baums darf lange dauern, die Abfrage muss aber
     * schnell sein - also z.B. Pattern.compile() beim Aufbau des Baums, nicht
     * beim Abfragen. 
     *  
     */
    if ("/hilfe.html".equals(url) || "/help.html".equals(url)) {
        // change url and forward
        RequestDispatcher dispatcher = request.getRequestDispatcher("/agid.html");
        //   long end = System.nanoTime();
        dispatcher.forward(request, response);
    } else {
        //   long end = System.nanoTime();
        chain.doFilter(request, response);
    }
}

From source file:com.headissue.pigeon.PigeonContainer.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    long dtStart = System.currentTimeMillis();
    HttpServletRequest httpReq = (HttpServletRequest) req;
    if (log.isTraceEnabled()) {
        LogUtils.trace(log, "%s '%s'", httpReq.getMethod(), httpReq.getRequestURI());
        Enumeration<String> en = httpReq.getHeaderNames();
        while (en.hasMoreElements()) {
            String name = en.nextElement();
            String value = httpReq.getHeader(name);
            LogUtils.trace(log, "request header '%s=%s'", name, value);
        }/*from   www . j  ava 2 s.  c o m*/
        LogUtils.trace(log, "locale=%s", req.getLocale());
    }
    super.service(req, res);
    // how long?
    LogUtils.debug(log, "%s '%s' in msecs %s", httpReq.getMethod(), httpReq.getRequestURI(),
            System.currentTimeMillis() - dtStart);
}

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;/*w  w w.  j a  v a 2 s.co  m*/
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

/** The method to obtain the correct Site from the request.
 * It only returns a site with a locale supported by that site.
 ** @param servletRequest/*w  w  w . ja v a2  s.  c om*/
 * @return the site instance. or null if no such skin has been deployed.
 */
public static Site getSite(final ServletRequest servletRequest) {
    // find the current site. Since we are behind a ajp13 connection request.getServerName() won't work!
    // httpd.conf needs:
    //      1) "JkEnvVar SERVER_NAME" inside the virtual host directive.
    //      2) "UseCanonicalName Off" to assign ServerName from client's request.
    final String vhost = getServerName(servletRequest);

    // Tweak the port if SERVER_PORT has been explicitly set. (We may have gone through Apache or Cisco LB).
    final String correctedVhost = Site.SERVER_PORT > 0 && vhost.indexOf(':') > 0
            ? vhost.substring(0, vhost.indexOf(':') + 1) + Site.SERVER_PORT
            : vhost;

    LOG.trace(DEBUG_REQUESTED_VHOST + correctedVhost);

    // Construct the site object off the browser's locale, even if it won't finally be used.
    final Locale locale = servletRequest.getLocale();

    final Site result;
    try {
        result = Site.valueOf(SITE_CONTEXT, correctedVhost, locale);

        final SiteConfiguration.Context siteConfCxt = UrlResourceLoader.newSiteConfigurationContext(result);
        final SiteConfiguration siteConf = SiteConfiguration.instanceOf(siteConfCxt);
        servletRequest.setAttribute(SiteConfiguration.NAME_KEY, siteConf);

        if (LOG.isTraceEnabled()) { // MessageFormat.format(..) is expensive
            LOG.trace(MessageFormat.format(LOCALE_DETAILS, locale.getLanguage(), locale.getCountry(),
                    locale.getVariant()));
        }

        // Check if the browser's locale is supported by this skin. Use it if so.
        if (siteConf.isSiteLocaleSupported(locale)) {
            return result;
        }

        // Use the skin's default locale. For some reason that fails use JVM's default.
        final String[] prefLocale = null != siteConf.getProperty(SiteConfiguration.SITE_LOCALE_DEFAULT)
                ? siteConf.getProperty(SiteConfiguration.SITE_LOCALE_DEFAULT).split("_")
                : new String[] { Locale.getDefault().toString() };

        switch (prefLocale.length) {

        case 3:
            LOG.trace(result + INFO_USING_DEFAULT_LOCALE + prefLocale[0] + '_' + prefLocale[1] + '_'
                    + prefLocale[2]);
            return Site.valueOf(SITE_CONTEXT, correctedVhost,
                    new Locale(prefLocale[0], prefLocale[1], prefLocale[2]));

        case 2:
            LOG.trace(result + INFO_USING_DEFAULT_LOCALE + prefLocale[0] + '_' + prefLocale[1]);
            return Site.valueOf(SITE_CONTEXT, correctedVhost, new Locale(prefLocale[0], prefLocale[1]));

        case 1:
        default:
            LOG.trace(result + INFO_USING_DEFAULT_LOCALE + prefLocale[0]);
            return Site.valueOf(SITE_CONTEXT, correctedVhost, new Locale(prefLocale[0]));

        }
    } catch (IllegalArgumentException iae) {
        return null;
    }
}

From source file:org.apache.pluto.driver.tags.PortletModeDropDownTag.java

/**
 * Obtains decoration name for a portlet managed mode from the portlet's resource bundle
 * as defined in PLT.8.4 of the JSR-286 spec using the key 
 * javax.portlet.app.custom-portlet-mode.<custom mode>.decoration-name where
 * custom mode is the name of the custom mode as defined in portlet.xml
 * (//portlet-app/custom-portlet-mode/portlet-mode element). If the decoration
 * name is not found in the resource bundle, this method returns the uppercased
 * mode name./*  w  w  w  .  j  a v a  2s  .co  m*/
 * 
 * @param driverConfig the driver config object found in the session.
 * @param mode the portlet managed custom mode that will be searched for decoration name
 * in the resource bundle.
 * @return the decoration name for a portlet managed mode in the resource bundle
 * using the key javax.portlet.app.custom-portlet-mode.<custom mode>.decoration-name 
 * where custom mode is the name of the custom mode as defined in portlet.xml
 * (//portlet-app/custom-portlet-mode/portlet-mode element). If the decoration
 * name is not found in the resource bundle, the uppercased
 * mode name is returned.
 */
private String getCustomModeDecorationName(DriverConfiguration driverConfig, PortletMode mode) {
    //decoration name is mode name by default
    String decorationName = mode.toString().toUpperCase();
    ResourceBundle bundle;
    StringBuffer res;
    try {
        PortletConfig config = driverConfig.getPortletConfig(evaluatedPortletId);
        ServletRequest request = pageContext.getRequest();
        Locale defaultLocale = request.getLocale();
        bundle = config.getResourceBundle(defaultLocale);
        res = new StringBuffer();
        res.append("javax.portlet.app.custom-portlet-mode.");
        res.append(mode.toString());
        res.append(".decoration-name");
        decorationName = bundle.getString(res.toString());
    } catch (Exception e) {
        LOG.debug("Problem finding decoration-name for custom mode: " + mode.toString());
    }
    return decorationName;
}

From source file:org.infoscoop.web.I18NFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    BufferHttpServletResponseWrapper bufResponse = new BufferHttpServletResponseWrapper(
            (HttpServletResponse) response);
    chain.doFilter(request, bufResponse);
    bufResponse.flushBuffer();//from www.j av a 2 s .  c om
    String body = bufResponse.getStringContent();

    try {
        body = I18NUtil.resolve(type, body, request.getLocale());
    } catch (Exception e) {
        log.error("database error occurred. ", e);
    }

    if (bufResponse.getLocale() != null)
        response.setLocale(bufResponse.getLocale());
    response.setContentLength(body.getBytes("utf-8").length);

    Writer out = null;
    try {
        out = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        out.write(body);
        out.flush();
    } finally {
        if (out != null)
            out.close();
    }
}

From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param result The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *///from   w  ww.ja v a2 s  .co m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (filterConfig == null)
        return;

    // Render the generic servlet request properties
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis())));
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");
    Enumeration locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        if (first)
            first = false;
        else
            writer.print(", ");
        writer.print(locale.toString());
    }
    writer.println();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        writer.print("         parameter=" + name + "=");
        String values[] = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0)
                writer.print(", ");
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        writer.println("---------------------------------------------");
        HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());
        Cookie cookies[] = hrequest.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }
        names = hrequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());
    }
    writer.println("=============================================");

    // Log the resulting string
    writer.flush();
    filterConfig.getServletContext().log(sw.getBuffer().toString());
    log.info(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(request, response);

}

From source file:org.uberfire.server.locale.GWTLocaleHeaderFilter.java

private Locale getLocale(final ServletRequest request) {
    Locale locale = request.getLocale();
    final String paramLocale = request.getParameter("locale");
    if (paramLocale == null || paramLocale.isEmpty()) {
        return locale;
    }/*w  w  w.j  av  a2s .co m*/
    try {
        locale = LocaleUtils.toLocale(paramLocale);
    } catch (Exception e) {
        //Swallow. Locale is initially set to ServletRequest locale
    }
    return locale;
}

From source file:org.yes.cart.web.filter.RequestLocaleResolverFilter.java

/**
 * {@inheritDoc}/*from  ww w.ja v  a 2  s . co m*/
 */
public ServletRequest doBefore(final ServletRequest servletRequest, final ServletResponse servletResponse)
        throws IOException, ServletException {

    final ShoppingCart cart = ApplicationDirector.getShoppingCart();

    if (cart != null && StringUtils.isBlank(cart.getCurrentLocale())) {

        final String currentLang;
        final String lang = servletRequest.getLocale().getLanguage();

        final List<String> supported = languageService
                .getSupportedLanguages(cart.getShoppingContext().getShopCode());
        if (supported.contains(lang)) {

            currentLang = lang;

        } else {

            currentLang = supported.get(0);

        }

        cartCommandFactory.execute(cart, new HashMap<String, Object>() {
            {
                put(ShoppingCartCommand.CMD_CHANGELOCALE, currentLang);
            }
        });

    }

    return servletRequest;
}