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:mx.edu.um.mateo.general.web.EmpresaController.java

@SuppressWarnings("unchecked")
@RequestMapping/*from  w ww  .  j  a  v  a2  s .c  om*/
public String lista(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(required = false) String filtro, @RequestParam(required = false) Long pagina,
        @RequestParam(required = false) String tipo, @RequestParam(required = false) String correo,
        @RequestParam(required = false) String order, @RequestParam(required = false) String sort,
        Model modelo) {
    log.debug("Mostrando lista de empresas");
    Map<String, Object> params = this.convierteParams(request.getParameterMap());
    Long organizacionId = (Long) request.getSession().getAttribute("organizacionId");
    params.put("organizacion", organizacionId);

    if (StringUtils.isNotBlank(tipo)) {
        params.put("reporte", true);
        params = empresaDao.lista(params);
        try {
            generaReporte(tipo, (List<Empresa>) params.get("empresas"), response, "empresas", Constantes.ORG,
                    organizacionId);
            return null;
        } catch (ReporteException e) {
            log.error("No se pudo generar el reporte", e);
        }
    }

    if (StringUtils.isNotBlank(correo)) {
        params.put("reporte", true);
        params = empresaDao.lista(params);

        params.remove("reporte");
        try {
            enviaCorreo(correo, (List<Empresa>) params.get("empresas"), request, "empresas", Constantes.ORG,
                    organizacionId);
            modelo.addAttribute("message", "lista.enviada.message");
            modelo.addAttribute("messageAttrs",
                    new String[] { messageSource.getMessage("empresa.lista.label", null, request.getLocale()),
                            ambiente.obtieneUsuario().getUsername() });
        } catch (ReporteException e) {
            log.error("No se pudo enviar el reporte por correo", e);
        }
    }
    params = empresaDao.lista(params);
    modelo.addAttribute("empresas", params.get("empresas"));

    this.pagina(params, modelo, "empresas", pagina);

    return "admin/empresa/lista";
}

From source file:fr.paris.lutece.plugins.calendar.web.CalendarApp.java

/**
 * Return unregistered form if unregistered user wants to acces application
 * management form//from  w  ww  .  j  a  v  a  2 s .c o  m
 * @param request {@link HttpServletRequest}
 * @param plugin {@link Plugin}
 * @return the html
 * @throws SiteMessageException message if error
 */
private XPage getAddEventPage(HttpServletRequest request, Plugin plugin) throws SiteMessageException {
    XPage page = null;
    String strCalendarId = request.getParameter(Constants.PARAMETER_CALENDAR_ID);
    if (StringUtils.isNotBlank(strCalendarId) && StringUtils.isNumeric(strCalendarId)) {
        page = new XPage();

        Map<String, Object> model = new HashMap<String, Object>();

        model.put(Constants.MARK_CALENDAR_ID, strCalendarId);
        model.put(Constants.MARK_LOCALE, request.getLocale().getLanguage());

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

        page.setContent(template.getHtml());
        page.setTitle(I18nService.getLocalizedString(Constants.PROPERTY_PAGE_TITLE_CREATE_EVENT,
                request.getLocale()));
        page.setPathLabel(I18nService.getLocalizedString(Constants.PROPERTY_PAGE_TITLE_CREATE_EVENT,
                request.getLocale()));
    }

    return page;

}

From source file:fr.paris.lutece.plugins.directory.web.DirectoryApp.java

/**
 * Returns the html code of the search page
 *
 * @param request// w  w  w. j  a  v  a 2s. com
 *            the http request
 * @param plugin
 *            the plugin
 * @return the html page
 * @throws SiteMessageException
 *             a exception that triggers a site message
 */
public String getSearchPage(HttpServletRequest request, Plugin plugin) throws SiteMessageException {
    String strQuery = request.getParameter(PARAMETER_QUERY);

    HashMap<String, Object> model = new HashMap<String, Object>();

    if (StringUtils.isNotBlank(strQuery)) {
        Date dateBegin = null;
        Date dateEnd = null;

        String strOperator = request.getParameter(PARAMETER_OPERATOR);
        String strDateBegin = request.getParameter(PARAMETER_DATE_BEGIN);
        String strDateEnd = request.getParameter(PARAMETER_DATE_END);

        // Mandatory fields
        if (StringUtils.isBlank(strOperator)) {
            Object[] tabRequiredFields = { PARAMETER_OPERATOR };
            SiteMessageService.setMessage(request, MESSAGE_DIRECTORY_ERROR_MANDATORY_FIELD, tabRequiredFields,
                    SiteMessage.TYPE_STOP);
        }

        // Safety checks
        if (StringUtils.isNotBlank(strDateBegin)) {
            dateBegin = DateUtil.formatDate(strDateBegin, request.getLocale());

            if (dateBegin == null) {
                SiteMessageService.setMessage(request, MESSAGE_SEARCH_DATE_VALIDITY, SiteMessage.TYPE_STOP);
            }
        }

        if (StringUtils.isNotBlank(strDateEnd)) {
            dateEnd = DateUtil.formatDate(strDateEnd, request.getLocale());

            if (dateEnd == null) {
                SiteMessageService.setMessage(request, MESSAGE_SEARCH_DATE_VALIDITY, SiteMessage.TYPE_STOP);
            }
        }

        if (!strOperator.equalsIgnoreCase(OPERATOR_AND) && !strOperator.equalsIgnoreCase(OPERATOR_OR)) {
            SiteMessageService.setMessage(request, MESSAGE_SEARCH_OPERATOR_VALIDITY, SiteMessage.TYPE_STOP);
        }

        // Check XSS characters
        if (SecurityUtil.containsXssCharacters(request, strQuery)) {
            SiteMessageService.setMessage(request, MESSAGE_INVALID_SEARCH_TERMS, SiteMessage.TYPE_STOP);
        }

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

        model.put(MARK_RESULT_LIST, listResults);

        // re-populate search parameters
        model.put(MARK_QUERY, strQuery);
        model.put(MARK_OPERATOR, strOperator);
        model.put(MARK_DATE_BEGIN, strDateBegin);
        model.put(MARK_DATE_END, strDateEnd);
    }

    // Display the list of all Directory
    DirectoryFilter filter = new DirectoryFilter();
    filter.setIsDisabled(DirectoryFilter.FILTER_TRUE);

    List<Directory> listDirectory = DirectoryHome.getDirectoryList(filter, plugin);
    List<Directory> listDirectoryAuthorized;

    if (SecurityService.isAuthenticationEnable()) {
        listDirectoryAuthorized = new ArrayList<Directory>();

        for (Directory directory : listDirectory) {
            if ((directory.getRoleKey() == null) || directory.getRoleKey().equals(Directory.ROLE_NONE)
                    || SecurityService.getInstance().isUserInRole(request, directory.getRoleKey())) {
                listDirectoryAuthorized.add(directory);
            }
        }
    } else {
        listDirectoryAuthorized = listDirectory;
    }

    model.put(MARK_DIRECTORY_LIST, listDirectoryAuthorized);

    model.put(MARK_LOCALE, request.getLocale());

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

    return template.getHtml();
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractProductsController.java

@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST)
@ResponseBody//from w  ww  .  j ava  2  s. c o  m
public String editProductLogo(@ModelAttribute("productLogoForm") ProductLogoForm form, BindingResult result,
        HttpServletRequest request, ModelMap map) {
    logger.debug("### edit product logo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");
        JsonObject error = new JsonObject();
        error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                new Object[] { fileSize }, request.getLocale()));
        return error.toString();
    }

    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        Product product = form.getProduct();
        ProductLogoFormValidator validator = new ProductLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            setPage(map, Page.PRODUCTS);
            JsonObject error = new JsonObject();
            error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                    null, request.getLocale()));
            return error.toString();
        } else {
            try {
                product = productService.editProductLogo(product, form.getLogo());
            } catch (FileUploadException e) {
                logger.debug("###IO Exception in writing custom image file", e);
                result.rejectValue("logo", "error.uploading.file");
                JsonObject error = new JsonObject();
                error.addProperty("errormessage", messageSource
                        .getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
                return error.toString();
            }
        }
        String response = null;
        try {
            response = JSONUtils.toJSONString(product);
        } catch (JsonGenerationException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (JsonMappingException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (IOException e) {
            logger.debug("###IO Exception in writing custom image file");
        }
        return response;
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        setPage(map, Page.PRODUCTS);
        JsonObject error = new JsonObject();
        error.addProperty("errormessage",
                messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
        return error.toString();
    }
}

From source file:it.cilea.osd.jdyna.web.controller.FormAnagraficaController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws Exception {
    AnagraficaObjectAreaDTO anagraficaObjectDTO = (AnagraficaObjectAreaDTO) object;

    String exitPage = "redirect:details.htm?id=" + anagraficaObjectDTO.getObjectId() + "&areaId="
            + anagraficaObjectDTO.getTabId();

    if (request.getParameter("cancel") != null) {
        return new ModelAndView(exitPage);
    }/*w  ww.j  av  a 2  s.  c o  m*/

    EO myObject = applicationService.get(clazzAnagraficaObject, anagraficaObjectDTO.getObjectId());

    List<H> propertyHolders = applicationService.findPropertyHolderInTab(clazzTab,
            anagraficaObjectDTO.getTabId());

    List<IContainable> tipProprietaInArea = new LinkedList<IContainable>();

    for (IPropertyHolder<Containable> iph : propertyHolders) {
        tipProprietaInArea = applicationService.<H, T>findContainableInPropertyHolder(clazzBox, iph.getId());
    }

    List<TP> realTPS = new LinkedList<TP>();
    for (IContainable c : tipProprietaInArea) {
        realTPS.add((TP) applicationService.findContainableByDecorable(
                clazzTipologiaProprieta.newInstance().getDecoratorClass(), c.getId()));
    }

    AnagraficaUtils.reverseDTO(anagraficaObjectDTO, myObject, realTPS);

    myObject.pulisciAnagrafica();
    applicationService.saveOrUpdate(clazzAnagraficaObject, myObject);
    T area = applicationService.get(clazzTab, anagraficaObjectDTO.getTabId());
    final String areaTitle = area.getTitle();
    saveMessage(request,
            getText("action.opera.anagrafica.edited", new Object[] { areaTitle }, request.getLocale()));

    return new ModelAndView(exitPage);
}

From source file:fr.paris.lutece.plugins.mylutece.modules.openam.authentication.OpenamAuthentication.java

/**
 * This methods checks the login info in the base repository
 * //from   www.j a v  a 2 s  .  c o  m
 * @param strUserName
 *            The username
 * @param strUserPassword
 *            The password
 * @param request
 *            The HTTP request
 * @return A LuteceUser object corresponding to the login
 * @throws LoginException
 *             The LoginException
 */
@Override
public LuteceUser login(String strUserName, String strUserPassword, HttpServletRequest request)
        throws LoginException, LoginRedirectException {
    LuteceUser user;

    if (SecurityService.getInstance().getRegisteredUser(request) == null) {
        try {
            user = OpenamService.getInstance().doLogin(request, strUserName, strUserPassword, this);
        } catch (OpenamAuthenticationAgentException e) {
            String strUrlErrorLoginAgent = AppPropertiesService.getProperty(PROPERTY_URL_ERROR_LOGIN_AGENT);
            String strBackUrlErrorAgent = AppPropertiesService.getProperty(PROPERTY_BACK_URL_ERROR_AGENT);

            if (StringUtils.isEmpty(strUrlErrorLoginAgent)) {
                try {
                    SiteMessageService.setMessage(request, PROPERTY_MESSAGE_ERROR_LOGIN_AGENT, null, " ", null,
                            "", SiteMessage.TYPE_STOP, null, strBackUrlErrorAgent);
                } catch (SiteMessageException lme) {
                    strUrlErrorLoginAgent = AppPathService.getSiteMessageUrl(request);
                }
            }

            if ((strUrlErrorLoginAgent == null) || (!strUrlErrorLoginAgent.startsWith(CONSTANT_HTTP)
                    && !strUrlErrorLoginAgent.startsWith(CONSTANT_HTTPS))) {
                strUrlErrorLoginAgent = AppPathService.getBaseUrl(request) + strUrlErrorLoginAgent;
            }

            LoginRedirectException ex = new LoginRedirectException(strUrlErrorLoginAgent);
            throw ex;
        }

        if (user == null) {
            throw new FailedLoginException(
                    I18nService.getLocalizedString(PROPERTY_MESSAGE_FAILED_LOGIN, request.getLocale()));
        }

        // add Openam LuteceUser session
        OpenamLuteceUserSessionService.getInstance().addLuteceUserSession(user.getName(),
                request.getSession(true).getId());
    } else {
        user = SecurityService.getInstance().getRegisteredUser(request);
    }

    return user;
}

From source file:com.hp.avmon.kpigetconfig.service.KpigetconfigAgentManageService.java

public Map pushAgentAmpSchedule(HttpServletRequest request) {
    Map<String, Object> map = new HashMap<String, Object>();
    //???AMPList/*from  www  .  j a  va2s  . c o m*/
    final List<Map<String, String>> ampListMapF = getListMapByJsonArrayString(
            request.getParameter("agentAmpInfo"));
    StringBuffer buff = new StringBuffer();
    Locale locale = request.getLocale();
    ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);

    for (Map<String, String> ampMap : ampListMapF) {
        String ampInstId = ampMap.get("ampInstId");
        String agentId = ampMap.get("agentId");
        String ampId = ampMap.get("ampId");

        String result = avmonServer.deployAmpSchedule(agentId, ampInstId);
        buff.append(ampInstId);
        if (result.startsWith("00")) {
            String updateAmpStatusSql = String.format(
                    "UPDATE TD_AVMON_AMP_INST SET STATUS = 1,LAST_SCHEDULE_UPDATE_TIME = SYSDATE WHERE AMP_INST_ID ='%s' AND AMP_ID ='%s' AND AGENT_ID ='%s'",
                    ampInstId, ampId, agentId);
            jdbcTemplate.update(updateAmpStatusSql);
            buff.append(bundle.getString("dispatchIssuedSuccess"));
        } else {
            buff.append(bundle.getString("dispatchIssuedFail"));
        }

        buff.append("<br/>");
        map.put("msg", buff.toString());
    }
    map.put("success", true);
    return map;
}

From source file:org.dspace.app.webui.cris.controller.ImportFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    Context dspaceContext = UIUtil.obtainContext(request);

    ImportDTO object = (ImportDTO) command;
    MultipartFile fileDTO = object.getFile();

    // read folder from configuration and make dir
    String path = ConfigurationManager.getProperty(CrisConstants.CFG_MODULE, "researcherpage.file.import.path");
    File dir = new File(path);
    dir.mkdir();//from   w w  w  .  j av  a 2 s.c  om
    try {
        if (object.getModeXSD() != null) {
            response.setContentType("application/xml;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=rp.xsd");
            String nameXSD = "xsd-download-webuirequest.xsd";
            File filexsd = new File(dir, nameXSD);
            filexsd.createNewFile();
            ImportExportUtils.generateXSD(response.getWriter(), dir,
                    applicationService.findAllContainables(RPPropertiesDefinition.class), filexsd, null);
            response.getWriter().flush();
            response.getWriter().close();
            return null;
        } else {
            if (fileDTO != null && !fileDTO.getOriginalFilename().isEmpty()) {
                Boolean defaultStatus = ConfigurationManager.getBooleanProperty(CrisConstants.CFG_MODULE,
                        "researcherpage.file.import.rpdefaultstatus");
                if (AuthorizeManager.isAdmin(dspaceContext)) {
                    dspaceContext.turnOffAuthorisationSystem();
                }
                ImportExportUtils.importResearchersXML(fileDTO.getInputStream(), dir, applicationService,
                        dspaceContext, defaultStatus);
                saveMessage(request, getText("action.import.with.success", request.getLocale()));
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        saveMessage(request, getText("action.import.with.noSuccess", e.getMessage(), request.getLocale()));
    }

    return new ModelAndView(getSuccessView());

}

From source file:fr.paris.lutece.plugins.suggest.web.SuggestApp.java

/**
 * Return the html form for creating suggest submit
 *
 * @param request/*from w  ww .ja v a2s  .com*/
 *            The HTTP request
 * @param nMode
 *            The current mode.
 * @param plugin
 *            The Plugin
 * @param suggest
 *            the suggest
 * @param nIdDefaultCategory the id of the default category
 * @return the html form
 * @throws SiteMessageException
 *             SiteMessageException
 */
private String getHtmlForm(HttpServletRequest request, int nMode, Plugin plugin, Suggest suggest,
        int nIdDefaultCategory) throws SiteMessageException {
    Map<String, Object> model = SuggestUtils.getModelHtmlForm(suggest, plugin, request.getLocale(),
            nIdDefaultCategory, false);

    // get form Recap
    model.put(MARK_DISABLE_NEW_SUGGEST_SUBMIT, suggest.isDisableNewSuggestSubmit());

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

    return template.getHtml();
}

From source file:mx.edu.um.mateo.general.web.UsuarioController.java

@SuppressWarnings("unchecked")
@RequestMapping// w w  w  .  ja  v a 2s  .  c o  m
public String lista(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(required = false) String filtro, @RequestParam(required = false) Long pagina,
        @RequestParam(required = false) String tipo, @RequestParam(required = false) String correo,
        @RequestParam(required = false) String order, @RequestParam(required = false) String sort,
        Model modelo) {
    log.debug("Mostrando lista de usuarios");
    Map<String, Object> params = this.convierteParams(request.getParameterMap());
    Long empresaId = (Long) request.getSession().getAttribute("empresaId");
    params.put("empresa", empresaId);

    if (StringUtils.isNotBlank(tipo)) {
        params.put("reporte", true);
        params = usuarioDao.lista(params);
        try {
            generaReporte(tipo, (List<Usuario>) params.get("usuarios"), response, "usuarios", Constantes.EMP,
                    empresaId);
            return null;
        } catch (ReporteException e) {
            log.error("No se pudo generar el reporte", e);
        }
    }

    if (StringUtils.isNotBlank(correo)) {
        params.put("reporte", true);
        params = usuarioDao.lista(params);

        params.remove("reporte");
        try {
            enviaCorreo(correo, (List<Usuario>) params.get("usuarios"), request, "usuarios", Constantes.EMP,
                    empresaId);
            modelo.addAttribute("message", "lista.enviada.message");
            modelo.addAttribute("messageAttrs",
                    new String[] { messageSource.getMessage("usuario.lista.label", null, request.getLocale()),
                            ambiente.obtieneUsuario().getUsername() });
        } catch (ReporteException e) {
            log.error("No se pudo enviar el reporte por correo", e);
        }
    }
    params = usuarioDao.lista(params);
    modelo.addAttribute("usuarios", params.get("usuarios"));

    this.pagina(params, modelo, "usuarios", pagina);

    return "admin/usuario/lista";
}