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:fr.paris.lutece.plugins.calendar.service.AgendaSubscriberService.java

/**
 * Notify the subscription/* w w w  .  j  a  va2 s  .  c o  m*/
 * @param agenda The agenda
 * @param request HttpServletRequest
 * @param plugin The plugin
 * @throws SiteMessageException site message exception
 */
public void doNotificationSubscription(AgendaResource agenda, HttpServletRequest request, Plugin plugin)
        throws SiteMessageException {
    String strEmail = request.getParameter(Constants.PARAMETER_EMAIL);

    CalendarNotification calendarNotification = new CalendarNotification();
    //Generate key
    UUID key = java.util.UUID.randomUUID();
    calendarNotification.setKey(key.toString());
    calendarNotification.setEmail(strEmail);
    calendarNotification.setIdAgenda(Integer.parseInt(agenda.getId()));
    Calendar calendar = GregorianCalendar.getInstance();
    if (agenda.isNotify()) {
        calendar.add(Calendar.DAY_OF_MONTH, agenda.getPeriodValidity());
    } else {
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    calendarNotification.setDateExpiry(new Timestamp(calendar.getTimeInMillis()));
    CalendarNotificationHome.create(calendarNotification, plugin);
    if (agenda.isNotify()) {
        String strSenderName = AppPropertiesService.getProperty(PROPERTY_SENDER_NAME);
        String strSenderEmail = AppPropertiesService.getProperty(PROPERTY_SENDER_EMAIL);
        String strObject = I18nService.getLocalizedString(PROPERTY_SUBSCRIBE_HTML_OBJECT, request.getLocale());

        String strBaseUrl = AppPathService.getBaseUrl(request) + URL_JSP_SUBSCRIPTION_NOTIFICATION;
        UrlItem url = new UrlItem(strBaseUrl);
        url.addParameter(Constants.MARK_KEY, key.toString());

        String strlink = I18nService.getLocalizedString(PROPERTY_SUBSCRIBE_HTML_LINK, request.getLocale());
        String strMessage = I18nService.getLocalizedString(PROPERTY_SUBSCRIBE_HTML_MESSAGE,
                request.getLocale());
        String linkHtml = HTML_LINK_OPEN_1 + url.getUrl() + HTML_LINK_OPEN_2 + strlink + HTML_LINK_CLOSE;

        HashMap<String, String> emailModel = new HashMap<String, String>();
        emailModel.put(MARK_MESSAGE, strMessage);
        emailModel.put(MARK_LINK, linkHtml);

        HtmlTemplate templateAgenda = AppTemplateService.getTemplate(TEMPLATE_NOTIFY_SUBSCRIPTION_MAIL,
                request.getLocale(), emailModel);
        String strEmailCode = templateAgenda.getHtml();

        MailService.sendMailHtml(strEmail, strSenderName, strSenderEmail, strObject, strEmailCode);
        emailModel.clear();

        SiteMessageService.setMessage(request, PROPERTY_SUBSCRIPTION_MAIL_SEND_ALERT_MESSAGE,
                PROPERTY_SUBSCRIPTION_MAIL_SEND_TITLE_MESSAGE, SiteMessage.TYPE_INFO);
    } else {
        ServletConfig config = LocalVariables.getConfig();
        HttpServletResponse response = LocalVariables.getResponse();
        try {
            String strAdresse = URL_JSP_SUBSCRIPTION_REDIRECTION + Constants.INTERROGATION_MARK
                    + Constants.MARK_KEY + Constants.EQUAL + key;
            response.sendRedirect(strAdresse);
        } catch (Exception e) {
            SiteMessageService.setMessage(request, PROPERTY_REDIRECTION_TITLE_MESSAGE,
                    PROPERTY_REDIRECTION_ALERT_MESSAGE, SiteMessage.TYPE_INFO);
        }
        LocalVariables.setLocal(config, request, response);
    }
}

From source file:fr.paris.lutece.plugins.extend.modules.comment.web.component.CommentResourceExtenderComponent.java

/**
 * {@inheritDoc}/*from www  .  j a  va2 s  . c om*/
 */
@Override
public String getPageAddOn(String strIdExtendableResource, String strExtendableResourceType,
        String strParameters, HttpServletRequest request) {
    CommentExtenderConfig config = _configService.find(getResourceExtender().getKey(), strIdExtendableResource,
            strExtendableResourceType);
    int nNbComments = 1;
    boolean bAuthorizedsubComments = true;
    boolean bUseBBCodeEditor = false;
    String strAdminBadge = StringUtils.EMPTY;
    if (config != null) {
        nNbComments = config.getNbComments();
        bAuthorizedsubComments = config.getAuthorizeSubComments();
        bUseBBCodeEditor = config.getUseBBCodeEditor();
        strAdminBadge = config.getAdminBadge();
    }

    List<Comment> listComments = _commentService.findLastComments(strIdExtendableResource,
            strExtendableResourceType, nNbComments, true, true, bAuthorizedsubComments);
    Map<String, Object> model = new HashMap<String, Object>();
    model.put(CommentConstants.MARK_LIST_COMMENTS, listComments);
    model.put(CommentConstants.MARK_ID_EXTENDABLE_RESOURCE, strIdExtendableResource);
    model.put(CommentConstants.MARK_EXTENDABLE_RESOURCE_TYPE, strExtendableResourceType);
    model.put(CommentConstants.MARK_USE_BBCODE, bUseBBCodeEditor);
    model.put(CommentConstants.MARK_ADMIN_BADGE, strAdminBadge);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_COMMENT, request.getLocale(), model);
    String strContent = template.getHtml();

    ContentPostProcessor postProcessor = getExtendPostProcessor();
    if (postProcessor != null) {
        strContent = postProcessor.process(request, strContent);
    }

    return strContent;
}

From source file:fr.paris.lutece.plugins.calendar.service.AgendaSubscriberService.java

/**
 * Send the calendar to a friend/*from   w  w  w .  j ava  2s.c  o m*/
 * @param request the http request
 * @return The next URL to redirect to
 * @throws SiteMessageException To display an error
 */
public String sendFriendMail(HttpServletRequest request) throws SiteMessageException {
    //Form parameters
    String strFriendEmail = request.getParameter(Constants.PARAMETER_SENDER_FRIEND_EMAIL);
    String strSenderFirstName = request.getParameter(Constants.PARAMETER_SENDER_FIRST_NAME);
    String strSenderLastName = request.getParameter(Constants.PARAMETER_SENDER_LAST_NAME);
    String strSenderEmail = request.getParameter(Constants.PARAMETER_SENDER_EMAIL);
    String strSenderMessage = request.getParameter(Constants.PARAMETER_SENDER_MESSAGE);

    // Mandatory field
    if (StringUtils.isNotBlank(strFriendEmail) && StringUtils.isNotBlank(strSenderFirstName)
            && StringUtils.isNotBlank(strSenderLastName) && StringUtils.isNotBlank(strSenderEmail)
            && StringUtils.isNotBlank(strSenderMessage)) {
        if (StringUtil.checkEmail(strFriendEmail)) {
            if (StringUtil.checkEmail(strSenderEmail)) {
                String strSenderName = strSenderFirstName + Constants.SPACE + strSenderLastName;

                //Properties
                String strObject = I18nService.getLocalizedString(PROPERTY_EMAIL_FRIEND_OBJECT,
                        request.getLocale());
                String strBaseUrl = AppPathService.getBaseUrl(request);

                HashMap<String, Object> emailModel = new HashMap<String, Object>();
                emailModel.put(MARK_SENDER_MESSAGE, strSenderMessage);
                emailModel.put(MARK_BASE_URL, strBaseUrl);

                HtmlTemplate templateAgenda = AppTemplateService.getTemplate(TEMPLATE_SEND_NOTIFICATION_MAIL,
                        request.getLocale(), emailModel);

                String strNewsLetterCode = templateAgenda.getHtml();

                MailService.sendMailHtml(strFriendEmail, strSenderName, strSenderEmail, strObject,
                        strNewsLetterCode);
            } else {
                Object[] args = { strSenderEmail };
                SiteMessageService.setMessage(request, PROPERTY_INVALID_MAIL_ERROR_MESSAGE, args,
                        PROPERTY_INVALID_MAIL_TITLE_MESSAGE, SiteMessage.TYPE_STOP);
            }
        } else {
            Object[] args = { strFriendEmail };
            SiteMessageService.setMessage(request, PROPERTY_INVALID_MAIL_ERROR_MESSAGE, args,
                    PROPERTY_INVALID_MAIL_TITLE_MESSAGE, SiteMessage.TYPE_STOP);
        }
    } else {
        SiteMessageService.setMessage(request, Messages.MANDATORY_FIELDS, Messages.MANDATORY_FIELDS,
                SiteMessage.TYPE_STOP);
    }

    return URL_JSP_RETURN_SEND_FRIEND_MAIL;
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@ModelAttribute
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
protected User showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // If not an administrator, make sure user is not trying to add or edit another user
    if (!request.isUserInRole(Constants.ADMIN_ROLE) && !isFormSubmission(request)) {
        if (isAdd(request) || request.getParameter("id") != null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '"
                    + request.getParameter("id") + "'");

            throw new AccessDeniedException("You do not have permission to modify other users.");
        }//from w  ww. j a  v  a2 s . c  om
    }

    if (!isFormSubmission(request)) {
        String userId = request.getParameter("id");

        // if user logged in with remember me, display a warning that they can't change passwords
        log.debug("checking for remember me login...");

        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() != null) {
            Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                request.getSession().setAttribute("cookieLogin", "true");

                // add warning message
                saveMessage(request, getText("userProfile.cookieLogin", request.getLocale()));
            }
        }

        User user;
        if (userId == null && !isAdd(request)) {
            user = getUserManager().getUserByUsername(request.getRemoteUser());
        } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) {
            user = getUserManager().getUser(userId);
        } else {
            user = new User();
            user.addRole(new Role(Constants.USER_ROLE));
        }

        user.setConfirmPassword(user.getPassword());

        return user;
    } else {
        // populate user object from database, so all fields don't need to be hidden fields in form
        return getUserManager().getUser(request.getParameter("id"));
    }
}

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

/**
 * Get the XPage for getting the rss//from   ww w.j a va2  s  .  com
 * @param request {@link HttpServletRequest}
 * @param plugin {@link Plugin}
 * @return the html
 */
private XPage getRssPage(HttpServletRequest request, Plugin plugin) {
    Collection<Category> categoryList = _categoryService.getCategories(plugin);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(Constants.MARK_LOCALE, request.getLocale());
    model.put(Constants.MARK_CALENDARS_LIST, getListAgenda(request, plugin));
    model.put(Constants.MARK_CATEGORY_LIST, getReferenceListCategory(categoryList));
    model.put(Constants.MARK_CATEGORY_DEFAULT_LIST, StringUtils.EMPTY);

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

    XPage page = new XPage();
    page.setContent(template.getHtml());
    page.setTitle(I18nService.getLocalizedString(Constants.PROPERTY_PAGE_RSS_TITLE, request.getLocale()));
    page.setPathLabel(I18nService.getLocalizedString(Constants.PROPERTY_PAGE_RSS_TITLE, request.getLocale()));

    return page;
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.PurchaseJspBean.java

/**
 * Send booking notification./*from   w  ww.j  a  v a2  s  .c  om*/
 *
 * @param request The Http request
 * @return the html code message
 */
public String doNotifyPurchase(HttpServletRequest request) {
    String strPurchaseId = request.getParameter(PARAMETER_PURCHASE_ID);

    Integer nIdPurchase;

    try {
        nIdPurchase = Integer.parseInt(strPurchaseId);
    } catch (NumberFormatException e) {
        LOGGER.debug(e);

        return AdminMessageService.getMessageUrl(request, StockConstants.MESSAGE_ERROR_OCCUR,
                AdminMessage.TYPE_STOP);
    }

    ReservationDTO purchase = _servicePurchase.findById(nIdPurchase);

    //Generate mail content
    Map<String, Object> model = new HashMap<String, Object>();
    model.put(MARK_PURCHASE, purchase);
    model.put(MARK_BASE_URL, AppPathService.getBaseUrl(request));

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

    // Create mail object
    NotificationDTO notificationDTO = new NotificationDTO();
    notificationDTO.setRecipientsTo(purchase.getEmailAgent());

    String[] args = new String[] { purchase.getOffer().getName(), };
    notificationDTO.setSubject(
            I18nService.getLocalizedString(MESSAGE_NOTIFICATION_BOOKING_SUBJECT, args, request.getLocale()));
    notificationDTO.setMessage(template.getHtml());

    // Send it
    _serviceNotification.send(notificationDTO);

    return doGoBack(request);
}

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

/**
 * The creation form of the admin _feature
 *
 * @param request The Http Request/*from  w ww .j av  a2s.c  o  m*/
 * @return The html code of the admin _feature
 */
@View(VIEW_CREATE_ADMIN_FEATURE)
public XPage getCreateAdminFeature(HttpServletRequest request) {
    PluginModel pm = ModelService.getPluginModel(_nPluginId);
    _feature = (_feature != null) ? _feature : new Feature();

    Map<String, Object> model = getPluginModel();
    model.put(MARK_ADMIN_FEATURES, pm.getFeatures());
    model.put(MARK_FEATURE, _feature);
    model.put(MARK_BUSINESS_CLASSES_COMBO, ModelService.getComboBusinessClasses(_nPluginId));

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

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

/**
 * The creation form of the attribute associated to a business class
 *
 * @param request The Http Request//  www.  ja va  2  s.c o  m
 * @return The XPage
 */
@View(VIEW_CREATE_ATTRIBUTE)
public XPage getCreateAttribute(HttpServletRequest request) {
    String strBusinessClassId = request.getParameter(PARAM_BUSINESS_CLASS_ID);

    if (_attribute == null) {
        _attribute = new Attribute();
    }

    Map<String, Object> model = getModel();
    model.put(MARK_BUSINESS_CLASS_ID, strBusinessClassId);
    model.put(MARK_ATTRIBUTE_TYPE_COMBO, ModelService.getAttributeTypes());
    model.put(MARK_ATTRIBUTE, _attribute);

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

From source file:fr.paris.lutece.plugins.mylutece.modules.database.authentication.BaseAuthentication.java

/**
 * This methods checks the login info in the database
 *
 * @param strUserName The username/*ww  w .j av a 2s.c om*/
 * @param strUserPassword The password
 * @param request The HttpServletRequest
 * @return A LuteceUser object corresponding to the login
 * @throws LoginException The LoginException
 */
@Override
public LuteceUser login(String strUserName, String strUserPassword, HttpServletRequest request)
        throws LoginException {
    DatabaseService databaseService = DatabaseService.getService();

    Plugin pluginMyLutece = PluginService.getPlugin(MyLutecePlugin.PLUGIN_NAME);
    Plugin plugin = PluginService.getPlugin(DatabasePlugin.PLUGIN_NAME);

    // Creating a record of connections log
    ConnectionLog connectionLog = new ConnectionLog();
    connectionLog.setIpAddress(SecurityUtil.getRealIp(request));
    connectionLog.setDateLogin(new java.sql.Timestamp(new java.util.Date().getTime()));

    // Test the number of errors during an interval of minutes
    int nMaxFailed = DatabaseUserParameterHome.getIntegerSecurityParameter(PROPERTY_MAX_ACCESS_FAILED, plugin);
    int nMaxFailedCaptcha = 0;
    int nIntervalMinutes = DatabaseUserParameterHome.getIntegerSecurityParameter(PROPERTY_INTERVAL_MINUTES,
            plugin);
    boolean bEnableCaptcha = false;

    if (PluginService.isPluginEnable(PLUGIN_JCAPTCHA)) {
        nMaxFailedCaptcha = DatabaseUserParameterHome
                .getIntegerSecurityParameter(PROPERTY_ACCESS_FAILED_CAPTCHA, plugin);
    }

    Locale locale = request.getLocale();

    if (((nMaxFailed > 0) || (nMaxFailedCaptcha > 0)) && (nIntervalMinutes > 0)) {
        int nNbFailed = ConnectionLogHome.getLoginErrors(connectionLog, nIntervalMinutes, pluginMyLutece);

        if ((nMaxFailedCaptcha > 0) && (nNbFailed >= nMaxFailedCaptcha)) {
            bEnableCaptcha = true;
        }

        if ((nMaxFailed > 0) && (nNbFailed >= nMaxFailed)) {
            if (nNbFailed == nMaxFailed) {
                ReferenceItem item = DatabaseUserParameterHome.findByKey(PARAMETER_ENABLE_UNBLOCK_IP, plugin);

                if ((item != null) && item.isChecked()) {
                    sendUnlockLinkToUser(strUserName, nIntervalMinutes, request, plugin);
                }
            }

            Object[] args = { Integer.toString(nIntervalMinutes) };
            String strMessage = I18nService.getLocalizedString(PROPERTY_TOO_MANY_FAILURES, args, locale);

            if (bEnableCaptcha) {
                throw new FailedLoginCaptchaException(strMessage, bEnableCaptcha);
            } else {
                throw new FailedLoginException(strMessage);
            }
        }
    }

    BaseUser user = DatabaseHome.findLuteceUserByLogin(strUserName, plugin, this);

    // Unable to find the user
    if ((user == null) || !databaseService.isUserActive(strUserName, plugin)) {
        AppLogService.info("Unable to find user in the database : " + strUserName);

        if (bEnableCaptcha) {
            throw new FailedLoginCaptchaException(
                    I18nService.getLocalizedString(PROPERTY_MESSAGE_USER_NOT_FOUND_DATABASE, locale),
                    bEnableCaptcha);
        } else {
            throw new FailedLoginException(
                    I18nService.getLocalizedString(PROPERTY_MESSAGE_USER_NOT_FOUND_DATABASE, locale));
        }
    }

    // Check password
    if (!databaseService.checkPassword(strUserName, strUserPassword, plugin)) {
        AppLogService.info("User login : Incorrect login or password" + strUserName);

        if (bEnableCaptcha) {
            throw new FailedLoginCaptchaException(
                    I18nService.getLocalizedString(PROPERTY_MESSAGE_USER_NOT_FOUND_DATABASE, locale),
                    bEnableCaptcha);
        } else {
            throw new FailedLoginException(
                    I18nService.getLocalizedString(PROPERTY_MESSAGE_USER_NOT_FOUND_DATABASE, locale));
        }
    }

    // Get roles
    List<String> arrayRoles = DatabaseHome.findUserRolesFromLogin(strUserName, plugin);

    if (!arrayRoles.isEmpty()) {
        user.setRoles(arrayRoles);
    }

    // Get groups
    List<String> arrayGroups = DatabaseHome.findUserGroupsFromLogin(strUserName, plugin);

    if (!arrayGroups.isEmpty()) {
        user.setGroups(arrayGroups);
    }

    // We update the status of the user if his password has become obsolete
    Timestamp passwordMaxValidDate = DatabaseHome.findPasswordMaxValideDateFromLogin(strUserName, plugin);

    if ((passwordMaxValidDate != null) && (passwordMaxValidDate.getTime() < new java.util.Date().getTime())) {
        DatabaseHome.updateResetPasswordFromLogin(strUserName, Boolean.TRUE, plugin);
    }

    int nUserId = DatabaseHome.findUserIdFromLogin(strUserName, plugin);
    databaseService.updateUserExpirationDate(nUserId, plugin);

    return user;
}