Example usage for javax.servlet.http HttpServletRequest getLocale

List of usage examples for javax.servlet.http HttpServletRequest getLocale

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest 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.edgenius.core.webapp.filter.LocaleFilter.java

public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    //       if(log.isDebugEnabled()){
    //          log.debug("Request URL: " + request.getRequestURI());
    //       }/*  w w  w  . j a  va 2s . c o m*/

    //charset encoding
    if (!StringUtils.isEmpty(this.encoding))
        request.setCharacterEncoding(encoding);
    else
        request.setCharacterEncoding(Constants.UTF8);

    String direction = null;
    Locale preferredLocale = null;
    TimeZone timezone = null;
    HttpSession session = request.getSession(false);
    if (getUserService() != null) { //for Install mode, it will return null
        User user = getUserService().getUserByName(request.getRemoteUser());
        if (user != null && !user.isAnonymous()) {
            //locale
            UserSetting set = user.getSetting();
            String userLang = set.getLocaleLanguage();
            String userCountry = set.getLocaleCountry();
            if (userLang != null && userCountry != null) {
                preferredLocale = new Locale(userLang, userCountry);
            }
            //text direction in HTML 
            direction = set.getDirection();
            //timezone
            if (set.getTimeZone() != null)
                timezone = TimeZone.getTimeZone(set.getTimeZone());
        }
    }
    if (preferredLocale == null) {
        if (Global.DetectLocaleFromRequest) {
            Locale locale = request.getLocale();
            if (locale != null) {
                preferredLocale = locale;
            }
        }
        if (preferredLocale == null) {
            preferredLocale = Global.getDefaultLocale();
        }
    }

    if (direction == null) {
        direction = Global.DefaultDirection;
    }

    if (timezone == null) {
        if (session != null) {
            //try to get timezone from HttpSession, which will be intial set in SecurityControllerImpl.checkLogin() method
            timezone = (TimeZone) session.getAttribute(Constants.TIMEZONE);
        }
        if (timezone == null)
            timezone = TimeZone.getTimeZone(Global.DefaultTimeZone);
    }

    //set locale for STURTS and JSTL
    // set the time zone - must be set for dates to display the time zone
    if (session != null) {
        Config.set(session, Config.FMT_LOCALE, preferredLocale);
        session.setAttribute(Constants.DIRECTION, direction);
        Config.set(session, Config.FMT_TIME_ZONE, timezone);
    }

    //replace request by LocaleRequestWrapper
    if (!(request instanceof LocaleRequestWrapper)) {
        request = new LocaleRequestWrapper(request, preferredLocale);
        LocaleContextConfHolder.setLocale(preferredLocale);
    }

    if (chain != null) {
        request.setAttribute(PREFERRED_LOCALE, preferredLocale.toString());
        chain.doFilter(request, response);
    }
    // Reset thread-bound LocaleContext.
    LocaleContextConfHolder.setLocaleContext(null);
}

From source file:fr.paris.lutece.plugins.pluginwizard.web.PluginWizardApp.java

/**
 * The creation screen of a plugin application
 *
 * @param request The Http Request//from   w  w w  .j  a va 2 s .c  o  m
 * @return The XPage
 */
@View(VIEW_CREATE_APPLICATION)
public XPage getCreateApplication(HttpServletRequest request) {
    PluginModel pm = ModelService.getPluginModel(_nPluginId);
    _application = (_application != null) ? _application : new Application();

    Map<String, Object> model = getPluginModel();
    model.put(MARK_APPLICATION, _application);
    model.put(MARK_PLUGIN_APPLICATIONS, pm.getApplications());
    model.put(MARK_BUSINESS_CLASSES_COMBO, ModelService.getComboBusinessClasses(_nPluginId));

    return getXPage(TEMPLATE_CREATE_PLUGIN_APPLICATION, request.getLocale(), model);
}

From source file:fr.paris.lutece.portal.web.search.SearchApp.java

/**
 * Returns search results//from   w ww.  j ava  2s.  c o m
 *
 * @param request The HTTP request.
 * @param nMode The current mode.
 * @param plugin The plugin
 * @return The HTML code of the page.
 * @throws SiteMessageException If an error occurs
 */
@Override
public XPage getPage(HttpServletRequest request, int nMode, Plugin plugin) throws SiteMessageException {
    XPage page = new XPage();
    String strQuery = request.getParameter(PARAMETER_QUERY);
    String strTagFilter = request.getParameter(PARAMETER_TAG_FILTER);

    String strEncoding = AppPropertiesService.getProperty(PROPERTY_ENCODE_URI_ENCODING, DEFAULT_URI_ENCODING);

    if (StringUtils.equalsIgnoreCase(CONSTANT_HTTP_METHOD_GET, request.getMethod())
            && !StringUtils.equalsIgnoreCase(strEncoding, CONSTANT_ENCODING_UTF8)) {
        try {
            if (StringUtils.isNotBlank(strQuery)) {
                strQuery = new String(strQuery.getBytes(strEncoding), CONSTANT_ENCODING_UTF8);
            }

            if (StringUtils.isNotBlank(strTagFilter)) {
                strTagFilter = new String(strTagFilter.getBytes(strEncoding), CONSTANT_ENCODING_UTF8);
            }
        } catch (UnsupportedEncodingException e) {
            AppLogService.error(e.getMessage(), e);
        }
    }

    if (StringUtils.isNotEmpty(strTagFilter)) {
        strQuery = strTagFilter;
    }

    boolean bEncodeUri = Boolean.parseBoolean(
            AppPropertiesService.getProperty(PROPERTY_ENCODE_URI, Boolean.toString(DEFAULT_ENCODE_URI)));

    String strSearchPageUrl = AppPropertiesService.getProperty(PROPERTY_SEARCH_PAGE_URL);
    String strError = "";
    Locale locale = request.getLocale();

    // Check XSS characters
    if ((strQuery != null) && (SecurityUtil.containsXssCharacters(request, strQuery))) {
        strError = I18nService.getLocalizedString(MESSAGE_INVALID_SEARCH_TERMS, locale);
        strQuery = "";
    }

    String strNbItemPerPage = request.getParameter(PARAMETER_NB_ITEMS_PER_PAGE);
    String strDefaultNbItemPerPage = AppPropertiesService.getProperty(PROPERTY_RESULTS_PER_PAGE,
            DEFAULT_RESULTS_PER_PAGE);
    strNbItemPerPage = (strNbItemPerPage != null) ? strNbItemPerPage : strDefaultNbItemPerPage;

    int nNbItemsPerPage = Integer.parseInt(strNbItemPerPage);
    String strCurrentPageIndex = request.getParameter(PARAMETER_PAGE_INDEX);
    strCurrentPageIndex = (strCurrentPageIndex != null) ? strCurrentPageIndex : DEFAULT_PAGE_INDEX;

    SearchEngine engine = (SearchEngine) SpringContextService.getBean(BEAN_SEARCH_ENGINE);
    List<SearchResult> listResults = engine.getSearchResults(strQuery, request);

    // The page should not be added to the cache

    // Notify results infos to QueryEventListeners 
    notifyQueryListeners(strQuery, listResults.size(), request);

    UrlItem url = new UrlItem(strSearchPageUrl);
    String strQueryForPaginator = strQuery;

    if (bEncodeUri) {
        strQueryForPaginator = encodeUrl(request, strQuery);
    }

    if (StringUtils.isNotBlank(strTagFilter)) {
        strQuery = "";
    }

    url.addParameter(PARAMETER_QUERY, strQueryForPaginator);
    url.addParameter(PARAMETER_NB_ITEMS_PER_PAGE, nNbItemsPerPage);

    Paginator<SearchResult> paginator = new Paginator<SearchResult>(listResults, nNbItemsPerPage, url.getUrl(),
            PARAMETER_PAGE_INDEX, strCurrentPageIndex);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(MARK_RESULTS_LIST, paginator.getPageItems());
    model.put(MARK_QUERY, strQuery);
    model.put(MARK_PAGINATOR, paginator);
    model.put(MARK_NB_ITEMS_PER_PAGE, strNbItemPerPage);
    model.put(MARK_ERROR, strError);

    ISponsoredLinksSearchService sponsoredLinksService = new SponsoredLinksSearchService();

    if (sponsoredLinksService.isAvailable()) {
        model.put(MARK_SPONSOREDLINKS_SET, sponsoredLinksService.getHtmlCode(strQuery, locale));
    }

    model.put(MARK_LIST_TYPE_AND_LINK, SearchService.getSearchTypesAndLinks());
    model.putAll(SearchParameterHome.findAll());

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_RESULTS, locale, model);

    page.setPathLabel(I18nService.getLocalizedString(PROPERTY_PATH_LABEL, locale));
    page.setTitle(I18nService.getLocalizedString(PROPERTY_PAGE_TITLE, locale));
    page.setContent(template.getHtml());

    return page;
}

From source file:fr.paris.lutece.plugins.workflow.modules.mappings.web.CodeMappingJspBean.java

/**
 * Get modify a code mapping/*  ww  w.java  2s . com*/
 * @param request the HTTP request
 * @return the HTML code
 */
public String getModifyCodeMapping(HttpServletRequest request) {
    setPageTitleProperty(PROPERTY_CREATE_MAPPING_PAGE_TITLE);

    String strIdCode = request.getParameter(PARAMETER_ID_CODE);

    if (StringUtils.isNotBlank(strIdCode) && StringUtils.isNumeric(strIdCode)) {
        int nIdCode = Integer.parseInt(strIdCode);
        ICodeMapping codeMapping = _codeMappingService.getCodeMapping(nIdCode);

        if (codeMapping != null) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put(MARK_CODE_MAPPING, codeMapping);
            model.put(MARK_LOCALE, getLocale());

            IMappingTypeComponent mappingTypeComponent = _codeMappingFactory
                    .getMappingTypeComponent(codeMapping.getMappingType().getKey());

            if (mappingTypeComponent != null) {
                model.put(MARK_REFERENCE_CODE_FORM,
                        mappingTypeComponent.getModifyCodeMappingHtml(codeMapping, request, getLocale()));
            } else {
                AppLogService.error("CodeMappingJspBean - MappingTypeComponent is null for key '"
                        + codeMapping.getMappingType().getKey() + "'");

                String strErrorMessage = I18nService.getLocalizedString(
                        MESSAGE_ERROR_MAPPING_TYPE_COMPONENT_NOT_FOUND, request.getLocale());

                return getError(request, strErrorMessage);
            }

            HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_MODIFY_CODE_MAPPING, getLocale(),
                    model);

            return getAdminPage(template.getHtml());
        }

        AppLogService.debug("CodeMappingJspBean - CodeMapping is null for id code '" + strIdCode + "'");

        String strErrorMessage = I18nService.getLocalizedString(MESSAGE_ERROR_CODE_MAPPING_NOT_FOUND,
                request.getLocale());

        return getError(request, strErrorMessage);
    }

    String strErrorMessage = I18nService.getLocalizedString(Messages.MANDATORY_FIELDS, request.getLocale());

    return getError(request, strErrorMessage);
}

From source file:be.iminds.aiolos.ui.ComponentServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final PlatformManager platformManager = platformTracker.getService();
    final String action = (String) request.getParameter("action");
    Activator.logger.log(LogService.LOG_DEBUG, "post request (" + action + ")");

    Future<?> task = null;//from   w w w .j  a  v a 2 s  . c o  m
    if (action != null)
        if (action.equals("scale")) {
            final String componentId = request.getParameter("component");
            final String version = request.getParameter("version");
            final int scaleCount = Integer.parseInt(request.getParameter("scaleCount"));
            final boolean forceNew = (request.getParameter("forceNew") != null);
            task = executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        platformManager.scaleComponent(componentId, version, scaleCount, forceNew);
                        Activator.logger.log(LogService.LOG_INFO, "Scaled component " + componentId);
                    } catch (Exception e) {
                        Activator.logger.log(LogService.LOG_ERROR,
                                "Error scaling component " + componentId + ": " + e.getLocalizedMessage(), e);
                    }
                }
            });
        }

    try {
        if (task != null) {
            task.get(); // result not important just wait.
        }
        renderJSON(response, request.getLocale());
    } catch (InterruptedException e) {
        Activator.logger.log(LogService.LOG_ERROR, "Action interrupted: " + action, e);
        super.doPost(request, response);
    } catch (ExecutionException e) {
        Activator.logger.log(LogService.LOG_ERROR, "Action failed to execute: " + action, e);
        super.doPost(request, response);
    }
}

From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java

public void testGetFormPreviewOK() throws Exception {
    final Renderer renderer = EasyMock.createMock(Renderer.class);
    final Translator translator = EasyMock.createMock(Translator.class);
    final ServletContext context = EasyMock.createMock(ServletContext.class);
    final HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    RESTFormService restService = emulateRESTFormService(translator, null, renderer, null);
    restService.setFormService(new MockFormDefinitionService());

    FormRepresentation form = createMockForm("myForm", "key1", "key2");
    FormPreviewDTO dto = createFormPreviewDTO(form);

    URL url = new URL("http://www.redhat.com");
    EasyMock.expect(translator.translateForm(EasyMock.eq(form))).andReturn(url).once();
    String htmlResult = "<html><body><div>Hello</div></body></html>";
    @SuppressWarnings("unchecked")
    Map<String, Object> anyObject = EasyMock.anyObject(Map.class);
    EasyMock.expect(renderer.render(EasyMock.anyObject(URL.class), anyObject)).andReturn(htmlResult);
    EasyMock.expect(context.getContextPath()).andReturn("/").anyTimes();
    EasyMock.expect(request.getLocale()).andReturn(Locale.getDefault()).once();

    EasyMock.replay(renderer, translator, context, request);
    Response resp = restService.getFormPreview(dto, "lang", context, request);
    EasyMock.verify(renderer, translator, context, request);

    assertNotNull("resp shouldn't be null", resp);
    assertStatus(resp.getStatus(), Status.OK);
    assertNotNull("resp.entity shouldn't be null", resp.getEntity());
    Object entity = resp.getEntity();
    assertNotNull("resp.metadata shouldn't be null", resp.getMetadata());
    Object contentType = resp.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE);
    assertNotNull("contentType shouldn't be null", contentType);
    assertEquals("contentType should be application/xml but is" + contentType, contentType,
            MediaType.TEXT_PLAIN);//from w ww.j a  v  a  2s . c o  m
    String html = entity.toString();
    assertTrue("html should contain data", html.length() > 0);
}

From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java

public void testGetFormPreviewRendererProblem() throws Exception {
    final Renderer renderer = EasyMock.createMock(Renderer.class);
    final Translator translator = EasyMock.createMock(Translator.class);
    final ServletContext context = EasyMock.createMock(ServletContext.class);
    final HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    RESTFormService restService = emulateRESTFormService(translator, null, renderer, null);
    restService.setFormService(new MockFormDefinitionService());

    FormRepresentation form = createMockForm("myForm", "key1", "key2");
    FormPreviewDTO dto = createFormPreviewDTO(form);

    EasyMock.expect(translator.translateForm(EasyMock.eq(form))).andReturn(new URL("http://www.redhat.com"))
            .once();// w  w w .j ava 2 s  .c o  m
    RendererException exception = new RendererException("Something going wrong");
    @SuppressWarnings("unchecked")
    Map<String, Object> anyObject = EasyMock.anyObject(Map.class);
    EasyMock.expect(renderer.render(EasyMock.anyObject(URL.class), anyObject)).andThrow(exception).once();
    EasyMock.expect(context.getContextPath()).andReturn("/").anyTimes();
    EasyMock.expect(request.getLocale()).andReturn(Locale.getDefault()).once();

    EasyMock.replay(renderer, translator, context, request);
    Response resp = restService.getFormPreview(dto, "lang", context, request);
    EasyMock.verify(renderer, translator, context, request);

    assertNotNull("resp shouldn't be null", resp);
    assertStatus(resp.getStatus(), Status.INTERNAL_SERVER_ERROR);
}

From source file:mx.edu.um.mateo.colportor.web.PedidoColportorController.java

@RequestMapping("/finalizar/{id}")
public String finalizar(HttpServletRequest request, @PathVariable Long id, Model modelo) {
    log.debug("Finalizando pedidoColportor {}", id);
    PedidoColportor pedidoColportor = pedidoColportorDao.obtiene(id);

    Map<String, Object> params = new HashMap<>();
    params.put("pedido", id);
    params = pedidoColportorItemDao.lista(params);

    //Guardar los VO en params
    List<PedidoColportorVO> voList = new ArrayList<>();
    PedidoColportorVO vo = null;/*  ww  w  .j a  v  a  2  s  .  c o m*/
    for (PedidoColportorItem pci : (List<PedidoColportorItem>) params
            .get(Constantes.PEDIDO_COLPORTOR_ITEM_LIST)) {
        vo = new PedidoColportorVO();
        vo.setNumPedido(pedidoColportor.getNumPedido());
        vo.setFormaPago(pedidoColportor.getFormaPago());
        vo.setFechaPedido(pedidoColportor.getFechaPedido());
        vo.setFechaEntrega(pedidoColportor.getFechaEntrega());
        vo.setColportor(pedidoColportor.getColportor());
        vo.setItem(pci);
        voList.add(vo);
    }

    Usuario usuario = ambiente.obtieneUsuario();

    try {
        log.debug("enviaCorreo");
        enviaCorreo("PDF", voList, request, "pedidoColportor", Constantes.EMP, usuario.getEmpresa().getId());
        modelo.addAttribute("message", "lista.enviado.message");
        modelo.addAttribute("messageAttrs",
                new String[] {
                        messageSource.getMessage("pedidoColportor.lista.label", null, request.getLocale()),
                        ambiente.obtieneUsuario().getUsername() });
    } catch (ReporteException e) {
        log.error("No se pudo enviar el reporte por correo", e);
    }

    return "redirect:" + Constantes.PEDIDO_COLPORTOR_PATH;
}

From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeText.java

/**
 * {@inheritDoc}// w  ww  . j av  a 2  s .com
 */
@Override
public GenericAttributeError getResponseData(Entry entry, HttpServletRequest request,
        List<Response> listResponse, Locale locale) {
    String strValueEntry = request.getParameter(PREFIX_ATTRIBUTE + entry.getIdEntry()).trim();
    boolean bConfirmField = entry.isConfirmField();
    String strValueEntryConfirmField = null;

    if (bConfirmField) {
        strValueEntryConfirmField = request
                .getParameter(PREFIX_ATTRIBUTE + entry.getIdEntry() + SUFFIX_CONFIRM_FIELD).trim();
    }

    List<RegularExpression> listRegularExpression = entry.getFields().get(0).getRegularExpressionList();
    Response response = new Response();
    response.setEntry(entry);

    if (strValueEntry != null) {
        response.setResponseValue(strValueEntry);

        if (StringUtils.isNotBlank(response.getResponseValue())) {
            response.setToStringValueResponse(getResponseValueForRecap(entry, request, response, locale));
        } else {
            response.setToStringValueResponse(StringUtils.EMPTY);
        }

        listResponse.add(response);

        // Checks if the entry value contains XSS characters
        if (StringUtil.containsXssCharacters(strValueEntry)) {
            GenericAttributeError error = new GenericAttributeError();
            error.setMandatoryError(false);
            error.setTitleQuestion(entry.getTitle());
            error.setErrorMessage(I18nService.getLocalizedString(MESSAGE_XSS_FIELD, request.getLocale()));

            return error;
        }

        if (entry.isMandatory()) {
            if (StringUtils.isBlank(strValueEntry)) {
                if (StringUtils.isNotEmpty(entry.getErrorMessage())) {
                    GenericAttributeError error = new GenericAttributeError();
                    error.setMandatoryError(true);
                    error.setErrorMessage(entry.getErrorMessage());

                    return error;
                }

                return new MandatoryError(entry, locale);
            }
        }

        if ((!strValueEntry.equals(StringUtils.EMPTY)) && (listRegularExpression != null)
                && (listRegularExpression.size() != 0)
                && RegularExpressionService.getInstance().isAvailable()) {
            for (RegularExpression regularExpression : listRegularExpression) {
                if (!RegularExpressionService.getInstance().isMatches(strValueEntry, regularExpression)) {
                    GenericAttributeError error = new GenericAttributeError();
                    error.setMandatoryError(false);
                    error.setTitleQuestion(entry.getTitle());
                    error.setErrorMessage(regularExpression.getErrorMessage());

                    return error;
                }
            }
        }

        if (bConfirmField
                && ((strValueEntryConfirmField == null) || !strValueEntry.equals(strValueEntryConfirmField))) {
            GenericAttributeError error = new GenericAttributeError();
            error.setMandatoryError(false);
            error.setTitleQuestion(entry.getConfirmFieldTitle());
            error.setErrorMessage(I18nService.getLocalizedString(MESSAGE_CONFIRM_FIELD,
                    new String[] { entry.getTitle() }, request.getLocale()));

            return error;
        }
    }

    return null;
}

From source file:com.wabacus.system.ReportRequest.java

public ReportRequest(HttpServletRequest request, int _showtype) {
    this.locallanguage = request.getLocale().getLanguage();
    if (this.locallanguage == null || this.locallanguage.trim().toLowerCase().equals("en")) {
        this.locallanguage = "";
    } else {/* w w w  . j  a v  a  2 s . c  o  m*/
        this.locallanguage = this.locallanguage.trim().toLowerCase();
    }
    Enumeration enume = request.getAttributeNames();
    while (enume.hasMoreElements()) {
        String name = (String) enume.nextElement();
        Object value = request.getAttribute(name);
        if (value != null) {
            if (this.attributes.containsKey(name)) {
                log.warn("request attribute????" + name + "?");
            }
            this.attributes.put(name, value);
        }
    }

    Enumeration enumer = request.getParameterNames();
    while (enumer.hasMoreElements()) {
        String name = (String) enumer.nextElement();
        if (name != null && !name.trim().equals("")) {
            if (this.attributes.containsKey(name)) {
                log.warn("request????" + name + "?");
            }
            String[] values = request.getParameterValues(name);
            if (values == null) {
                this.attributes.put(name, null);
            } else if (values.length == 1) {
                this.attributes.put(name, values[0]);
            } else {
                this.attributes.put(name, values);
            }

        }
    }
    this.showtype = _showtype;
    this.request = request;
    request.setAttribute("WX_REPORTREQUEST", this);
    this.actiontype = Tools.getRequestValue(request, "ACTIONTYPE", Consts.SHOWREPORT_ACTION);
}