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.citrix.cpbm.portal.fragment.controllers.AbstractRegistrationController.java

/**
 * SignUp of Step 1/*from  w  w  w . jav  a  2 s.  c om*/
 * 
 * @param model
 * @param request
 * @return String
 */
@RequestMapping(value = "/account_type", method = RequestMethod.GET)
public String signupStep1(ModelMap model, final HttpServletRequest request) {
    logger.debug("###Entering in account types selection(model) method @GET");
    IPtoCountry iPtoCountry = super.getGeoIpToCountry(request);
    if (iPtoCountry.isBlackListed()) {
        logger.debug("Error in validation because of blacklisted country " + "Country Code :"
                + iPtoCountry.getCountryCode());
        throw new IPtoCountryException(
                messageSource.getMessage("message.country.notsupported.error", null, request.getLocale()));
    }
    model.addAttribute("page", Page.HOME);
    model.addAttribute(Page.HOME.getLevel1().name(), "on");
    model.addAttribute("title", "page.order_now");

    UserRegistration registration = createDefaultRegistration();
    List<AccountType> accountTypes = registrationService.getSelfRegistrationAccountTypes();
    if (accountTypes != null && accountTypes.size() > 0) {
        registration.setSelfRegistrationAccountTypes(accountTypes);
    } else {
        model.addAttribute("signupwarningmessage",
                messageSource.getMessage("ui.signup.warning.message", null, request.getLocale()));
    }

    Channel channel = channelService.getDefaultServiceProviderChannel();
    registration.getTenant().setSourceChannel(channel);
    TelephoneVerificationService telephoneVerificationService = (TelephoneVerificationService) connectorManagementService
            .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION);
    boolean isEnabled = telephoneVerificationService != null && telephoneVerificationService.isEnabled();
    registration.setPhoneVerificationEnabled(isEnabled);
    model.addAttribute("registration", registration);
    model.addAttribute("tenant", registration.getTenant());
    model.addAttribute("channelParam", channel.getParam());

    String homeUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_home_url);
    String cloudmktgUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_marketing_url);
    if (homeUrl != null) {
        model.addAttribute("homeUrl", homeUrl);
    }
    if (cloudmktgUrl != null) {
        model.addAttribute("cloudmktgUrl", cloudmktgUrl);
    }
    logger.debug("###Exiting register(model) method @GET");

    return "register.account_type";
}

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

@Transactional
@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Usuario usuario,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam Boolean enviaCorreo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*from w w w. j  a  va  2  s  .co m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    }

    String password = null;
    try {
        log.debug("Evaluando roles {}", request.getParameterValues("roles"));
        String[] roles = request.getParameterValues("roles");
        if (roles == null || roles.length == 0) {
            log.debug("Asignando ROLE_USER por defecto");
            roles = new String[] { "ROLE_USER" };
        }
        Long almacenId = (Long) request.getSession().getAttribute("almacenId");
        password = KeyGenerators.string().generateKey();
        usuario.setPassword(password);
        usuario = usuarioDao.crea(usuario, almacenId, roles);

        if (enviaCorreo) {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(usuario.getCorreo());
            helper.setSubject(messageSource.getMessage("envia.correo.password.titulo.message", new String[] {},
                    request.getLocale()));
            helper.setText(messageSource.getMessage("envia.correo.password.contenido.message",
                    new String[] { usuario.getNombre(), usuario.getUsername(), password }, request.getLocale()),
                    true);
            mailSender.send(message);
        }

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al usuario", e);
        errors.rejectValue("username", "campo.duplicado.message", new String[] { "username" }, null);
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    } catch (MessagingException e) {
        log.error("No se pudo enviar la contrasena por correo", e);

        redirectAttributes.addFlashAttribute("message", "usuario.creado.sin.correo.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername(), password });

        return "redirect:/admin/usuario/ver/" + usuario.getId();
    }

    redirectAttributes.addFlashAttribute("message", "usuario.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername() });

    return "redirect:/admin/usuario/ver/" + usuario.getId();
}

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

public Map removeAmp(HttpServletRequest request) {
    Map<String, Object> map = new HashMap<String, Object>();

    //TODO ?AMP  ??AMP?

    final List<Map<String, String>> ampListMapF = getListMapByJsonArrayString(
            request.getParameter("agentAmpInfo"));
    boolean flag = false;
    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");

        jdbcTemplate.execute(/*w ww.  j ava 2s  .  com*/
                String.format("delete from TD_AVMON_AMP_POLICY where agent_id='%s' and amp_inst_id='%s'",
                        agentId, ampInstId));
        jdbcTemplate.execute(
                String.format("delete from TD_AVMON_AMP_VM_HOST where agent_id='%s' and amp_inst_id='%s'",
                        agentId, ampInstId));
        jdbcTemplate.execute(
                String.format("delete from TD_AVMON_AMP_ILO_HOST where agent_id='%s' and amp_inst_id='%s'",
                        agentId, ampInstId));
        jdbcTemplate.execute(
                String.format("delete from TD_AVMON_AMP_INST_ATTR where agent_id='%s' and amp_inst_id='%s'",
                        agentId, ampInstId));
        jdbcTemplate.execute(String.format(
                "delete from TD_AVMON_AMP_INST where agent_id='%s' and amp_inst_id='%s'", agentId, ampInstId));

        map.put("errorMsg", bundle.getString("uninstallSuccess"));

    }

    //updateNormalAMPStatus(ampListMapF,ConfigConstant.AMP_STATUS_DISABLED);
    if (flag) {
        map.put("success", true);
    } else {
        map.put("success", false);
    }
    return map;
}

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

/**
 * Return the new suggest submit object/*from  w  ww .j a  va 2  s .  c o m*/
 *
 * @param request
 *            The HTTP request
 * @param nMode
 *            The current mode.
 * @param plugin
 *            The Plugin
 * @param suggest
 *            the suggest
 * @param nIdCategory
 *            the id of the category
 * @param nIdType
 *            the id of the type
 * @param user
 *            the lutece user
 * @return the new suggest submit object
 * @throws SiteMessageException
 *             SiteMessageException
 */
private SuggestSubmit doInsertSuggestSubmit(HttpServletRequest request, int nMode, Plugin plugin,
        Suggest suggest, int nIdCategory, int nIdType, LuteceUser user) throws SiteMessageException {
    Locale locale = request.getLocale();
    List<Response> listResponse = new ArrayList<Response>();

    if (suggest.isActiveCaptcha() && PluginService.isPluginEnable(JCAPTCHA_PLUGIN)) {
        CaptchaSecurityService captchaSecurityService = new CaptchaSecurityService();

        if (!captchaSecurityService.validate(request)) {
            SiteMessageService.setMessage(request, MESSAGE_CAPTCHA_ERROR, SiteMessage.TYPE_STOP);
        }
    }

    SuggestSubmit suggestSubmit = new SuggestSubmit();
    suggestSubmit.setSuggest(suggest);
    suggestSubmit.setResponses(listResponse);

    FormError formError = SuggestUtils.getAllResponsesData(request, suggestSubmit, plugin, locale);

    if (formError != null) {
        if (formError.isMandatoryError()) {
            Object[] tabRequiredFields = { formError.getTitleQuestion() };
            SiteMessageService.setMessage(request, MESSAGE_MANDATORY_QUESTION, tabRequiredFields,
                    SiteMessage.TYPE_STOP);
        } else {
            Object[] tabFormError = { formError.getTitleQuestion(), formError.getErrorMessage() };
            SiteMessageService.setMessage(request, MESSAGE_FORM_ERROR, tabFormError, SiteMessage.TYPE_STOP);
        }
    }

    // perform suggest submit
    if (nIdCategory != SuggestUtils.CONSTANT_ID_NULL) {
        Category category = CategoryHome.findByPrimaryKey(nIdCategory, plugin);
        suggestSubmit.setCategory(category);
    }

    if (nIdType != SuggestUtils.CONSTANT_ID_NULL) {
        SuggestSubmitType type = SuggestSubmitTypeHome.findByPrimaryKey(nIdType, plugin);
        suggestSubmit.setSuggestSubmitType(type);
    }

    if (user != null) {
        suggestSubmit.setLuteceUserKey(user.getName());
        //insert SuggestSubmitInfi=ormation if not exists
        SuggestUserInfoService.getService().updateSuggestUserInfoByLuteceUser(user, plugin);
    }

    try {
        _suggestSubmitService.create(suggestSubmit, plugin, locale);
    } catch (Exception ex) {
        // something very wrong happened... a database check might be needed
        AppLogService.error(ex.getMessage() + " for SuggestSubmit " + suggestSubmit.getIdSuggestSubmit(), ex);
        // revert
        // we clear the DB form the given formsubmit (FormSubmitHome also
        // removes the reponses)
        _suggestSubmitService.remove(suggestSubmit.getIdSuggestSubmit(), plugin);
        // throw a message to the user
        SiteMessageService.setMessage(request, MESSAGE_MESSAGE_SUBMIT_SAVE_ERROR, SiteMessage.TYPE_ERROR);
    }

    return suggestSubmit;
}

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

/**
 * The modification form of an attribute
 *
 * @param request The Http Request//from  ww  w .  j  av a  2s  .c om
 * @return The XPage
 */
@View(VIEW_MODIFY_ATTRIBUTE)
public XPage getModifyAttribute(HttpServletRequest request) {
    Map<String, Object> model = getModel();
    int nIdBusinessClass = Integer.parseInt(request.getParameter(PARAM_BUSINESS_CLASS_ID));
    int nIdAttribute = Integer.parseInt(request.getParameter(PARAM_ATTRIBUTE_ID));

    if ((_attribute == null) || (_attribute.getId() != nIdAttribute)) {
        _attribute = ModelService.getAttribute(_nPluginId, nIdBusinessClass, nIdAttribute);
    }

    model.put(MARK_PLUGIN_ID, _nPluginId);
    model.put(MARK_BUSINESS_CLASS_ID, nIdBusinessClass);
    model.put(MARK_ATTRIBUTE_TYPE_COMBO, ModelService.getAttributeTypes());
    model.put(MARK_ATTRIBUTE, _attribute);

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

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

/**
 * For the Signup./* w  ww . j av  a  2  s  . c  o  m*/
 * 
 * @param registration
 * @param result
 * @param map
 * @param channelParam
 * @param promoCode
 * @param channelCode
 * @param sessionStatus
 * @param request
 * @return String
 * @throws IPtoCountryException
 */
@RequestMapping(value = "/signup", method = RequestMethod.GET)
public String signup(final ModelMap map,
        @RequestParam(value = "promocode", required = false) final String promoCode,
        @RequestParam(value = "channelcode", required = false) final String channelCode,
        @RequestParam(value = "accountTypeId", required = true) String accountTypeId,
        SessionStatus sessionStatus, HttpServletRequest request) throws IPtoCountryException {
    logger.debug("###Entering in signup(model) method @GET");

    AccountType accountType = registrationService.getAccountTypeById(accountTypeId);

    List<AccountType> accountTypes = registrationService.getSelfRegistrationAccountTypes();
    if (accountTypes == null || accountTypes.size() == 0 || !(accountTypes.contains(accountType))) {
        map.addAttribute("signupwarningmessage",
                messageSource.getMessage("ui.signup.warning.message", null, request.getLocale()));
    }

    UserRegistration registration = createDefaultRegistration();
    Channel channel = channelService.getDefaultServiceProviderChannel();
    registration.getTenant().setSourceChannel(channel);
    registration.setAccountTypeId(accountTypeId);
    TelephoneVerificationService telephoneVerificationService = (TelephoneVerificationService) connectorManagementService
            .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION);
    boolean isEnabled = telephoneVerificationService != null && telephoneVerificationService.isEnabled();
    registration.setPhoneVerificationEnabled(isEnabled);

    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));

    return showSignup(registration, map, channel.getParam(), request, accountType, promoCode, channelCode);
}

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

/**
 * Gets the modify business class page/*  w  ww.  j a v  a 2 s  .  co m*/
 *
 * @param request The HTTP request
 * @return The page
 */
@View(VIEW_MODIFY_BUSINESS_CLASS)
public XPage getModifyBusinessClass(HttpServletRequest request) {
    int nBusinessClassId = Integer.parseInt(request.getParameter(PARAM_BUSINESS_CLASS_ID));
    String strRefresh = request.getParameter(PARAM_REFRESH);

    if ((_businessClass == null) || (_businessClass.getId() != nBusinessClassId) || (strRefresh != null)) {
        _businessClass = ModelService.getFormBusinessClass(_nPluginId, nBusinessClassId);
    }

    _attribute = null;

    Map<String, Object> model = getPluginModel();
    model.put(MARK_BUSINESS_CLASS, _businessClass);
    model.put(MARK_ATTRIBUTES_LIST,
            ModelService.getBusinessClass(_nPluginId, nBusinessClassId).getAttributes());

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

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

/**
 * ?+????AMP???/* w  w  w  .  jav  a  2s  .c  o m*/
 * // modify by mark start
//???AMP?  --??
// modify by mark end
 * @param request ?--muzh
 * @return
 */
public Map pushAgentAmpScript(HttpServletRequest request) {
    Map<String, Object> map = new HashMap<String, Object>();
    //???AMPList
    final List<Map<String, String>> ampListMapF = getListMapByJsonArrayString(
            request.getParameter("agentAmpInfo"));
    StringBuffer buff = new StringBuffer();
    String msg = "";
    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.deployAmpPackage(agentId, ampInstId);
        buff.append(ampInstId);
        if (result.startsWith("00")) {
            // modify by mark start
            //???AMP?  --??
            String updateAmpStatusSql = String.format(
                    "UPDATE TD_AVMON_AMP_INST SET STATUS = 1,LAST_AMP_UPDATE_TIME = sysdate WHERE AMP_INST_ID ='%s' AND AMP_ID ='%s' AND AGENT_ID ='%s'",
                    ampInstId, ampId, agentId);
            // modify by mark start
            jdbcTemplate.update(updateAmpStatusSql);
            buff.append(bundle.getString("scriptIssuedSuccess"));
        } else {
            buff.append(bundle.getString("scriptIssuedFail"));
        }
        buff.append("<br/>");
        map.put("msg", buff.toString());
    }
    //        if(pushFlag){
    //            flag  = updateNormalAMPStatus(ampListMapF,ConfigConstant.AMP_STATUS_DISABLED);
    //        }

    map.put("success", true);
    return map;
}

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

@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST)
@ResponseBody/*from  w  ww.j  a  va2 s.  co m*/
public String editChannelLogo(@ModelAttribute("channelLogoForm") ChannelLogoForm form, BindingResult result,
        HttpServletRequest request, ModelMap map) {
    logger.debug("### editChannelLogo 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("")) {
        Channel channel = channelService.getChannelById(form.getChannel().getId().toString());
        ChannelLogoFormValidator validator = new ChannelLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            JsonObject error = new JsonObject();
            setPage(map, Page.CHANNELS);
            error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                    null, request.getLocale()));
            return error.toString();
        } else {
            String channelsDir = "channels";
            File file = new File(FilenameUtils.concat(rootImageDir, channelsDir));
            if (!file.exists()) {
                file.mkdir();
            }
            String channelsAbsoluteDir = FilenameUtils.concat(rootImageDir, channelsDir);
            String relativeImageDir = FilenameUtils.concat(channelsDir, channel.getId().toString());
            File file1 = new File(FilenameUtils.concat(channelsAbsoluteDir, channel.getId().toString()));
            if (!file1.exists()) {
                file1.mkdir();
            }

            MultipartFile logoFile = form.getLogo();
            try {
                if (!logoFile.getOriginalFilename().trim().equals("")) {
                    String logoFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir,
                            logoFile);
                    channel.setImagePath(logoFileRelativePath);
                }
                channelService.updateChannel(channel);
            } catch (IOException e) {
                logger.debug("###IO Exception in writing custom image file");
            }
        }
        String response = null;
        try {
            response = JSONUtils
                    .toJSONString(channelService.getChannelById(form.getChannel().getId().toString()));
        } 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");
        }
        logger.debug("### editChannelLogo method ending (Success)...(POST)");
        return response;
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        setPage(map, Page.CHANNELS);
        JsonObject error = new JsonObject();
        error.addProperty("errormessage",
                messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
        logger.debug("### editChannelLogo method ending (No Image Logo Dir Defined)...(POST)");
        return error.toString();
    }
}