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.haulmont.restapi.ldap.LdapAuthController.java

@RequestMapping(value = "/v2/ldap/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
        @RequestParam Map<String, String> parameters, HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!ldapConfig.getLdapEnabled()) {
        log.debug("LDAP authentication is disabled. Property cuba.rest.ldap.enabled is false");

        throw new InvalidGrantException("LDAP is not supported");
    }// www. j  a  v a  2 s . c o  m

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
    if (!"password".equals(grantType)) {
        throw new InvalidGrantException("grant type not supported for ldap/token endpoint");
    }

    String username = parameters.get("username");

    if (restApiConfig.getStandardAuthenticationUsers().contains(username)) {
        log.info("User {} is not allowed to use external login in REST API", username);
        throw new BadCredentialsException("Bad credentials");
    }

    String ipAddress = request.getRemoteAddr();

    String password = parameters.get("password");

    OAuth2AccessTokenResult tokenResult = authenticate(username, password, request.getLocale(), ipAddress,
            parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}

From source file:fr.paris.lutece.plugins.extend.modules.follow.web.component.FollowResourceExtenderComponent.java

/**
 * {@inheritDoc}//from ww w .  j ava2 s . co  m
 */
@SuppressWarnings("deprecation")
@Override
public String getPageAddOn(String strIdExtendableResource, String strExtendableResourceType,
        String strParameters, HttpServletRequest request) {
    LuteceUser user = SecurityService.getInstance().getRegisteredUser(request);

    Follow follow = _followService.findByResource(strIdExtendableResource, strExtendableResourceType);
    String strTemplateContent = DatabaseTemplateService.getTemplateFromKey(FollowConstants.MARK_EXTEND_FOLLOW);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(FollowConstants.MARK_FOLLOW, follow);
    model.put(FollowConstants.MARK_ID_EXTENDABLE_RESOURCE, strIdExtendableResource);
    model.put(FollowConstants.MARK_EXTENDABLE_RESOURCE_TYPE, strExtendableResourceType);
    model.put(FollowConstants.MARK_SHOW, fetchShowParameter(strParameters));

    if (user != null) {
        model.put(FollowConstants.MARK_CAN_FOLLOW, true);
        model.put(FollowConstants.MARK_FOLLOW_CLOSED, false);
        model.put(FollowConstants.MARK_CAN_DELETE_FOLLOW,
                isFollower(user, strIdExtendableResource, strExtendableResourceType));
    } else {
        model.put(FollowConstants.MARK_CAN_FOLLOW, false);
        model.put(FollowConstants.MARK_FOLLOW_CLOSED, true);
    }

    model.put(FollowConstants.MARK_FOLLOW_HTML_CONTENT, AppTemplateService
            .getTemplateFromStringFtl(strTemplateContent, request.getLocale(), model).getHtml());

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

    return template.getHtml();
}

From source file:fr.paris.lutece.plugins.mylutece.authentication.MultiLuteceAuthentication.java

/**
 *
 * {@inheritDoc}/*w w w.  j a v a  2  s.  c  o m*/
 */
public LuteceUser login(String strUserName, String strUserPassword, HttpServletRequest request)
        throws LoginException, LoginRedirectException {
    LuteceUser luteceUser = null;
    String strAuthProvider = request.getParameter(PARAMETER_AUTH_PROVIDER);

    if (strAuthProvider != null) {
        LuteceAuthentication myLuteceAuthentication = _mapAuthentications.get(strAuthProvider);

        if (myLuteceAuthentication != null) {
            if (AppLogService.isDebugEnabled()) {
                AppLogService.debug(
                        "Using " + myLuteceAuthentication.getAuthServiceName() + " for user " + strUserName);
            }

            luteceUser = myLuteceAuthentication.login(strUserName, strUserPassword, request);
        } else {
            AppLogService.error("Authentication null for key " + strAuthProvider);
            throw new LoginException(I18nService.getLocalizedString(PROPERTY_MESSAGE_NO_AUTHENTICATION_SELECTED,
                    request.getLocale()));
        }
    } else {
        throw new LoginException(I18nService.getLocalizedString(PROPERTY_MESSAGE_NO_AUTHENTICATION_SELECTED,
                request.getLocale()));
    }

    return luteceUser;
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

public static Locale getLocale(HttpServletRequest request, HttpSession session, Object appDefaultLocale) {
    // check session first, should override all if anything set there
    Object localeObject = session != null ? session.getAttribute("locale") : null;

    // next see if the userLogin has a value
    if (localeObject == null) {
        Map<?, ?> userLogin = (Map<?, ?>) session.getAttribute("userLogin");
        if (userLogin == null) {
            userLogin = (Map<?, ?>) session.getAttribute("autoUserLogin");
        }//from  w  ww.ja  va  2  s  .  co m

        if (userLogin != null) {
            localeObject = userLogin.get("lastLocale");
        }
    }

    // no user locale? before global default try appDefaultLocale if specified
    if (localeObject == null && UtilValidate.isNotEmpty(appDefaultLocale)) {
        localeObject = appDefaultLocale;
    }

    // finally request (w/ a fall back to default)
    if (localeObject == null) {
        localeObject = request != null ? request.getLocale() : null;
    }

    return UtilMisc.ensureLocale(localeObject);
}

From source file:com.googlecode.psiprobe.controllers.DecoratorController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {//from   w  w w .j  a va 2 s.  co m
        request.setAttribute("hostname", InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        request.setAttribute("hostname", "unknown");
    }

    Properties version = (Properties) getApplicationContext().getBean("version");
    request.setAttribute("version", version.getProperty("probe.version"));

    Object uptimeStart = getServletContext().getAttribute(UptimeListener.START_TIME_KEY);
    if (uptimeStart != null && uptimeStart instanceof Long) {
        long l = ((Long) uptimeStart).longValue();
        long uptime = System.currentTimeMillis() - l;
        long uptime_days = uptime / (1000 * 60 * 60 * 24);

        uptime = uptime % (1000 * 60 * 60 * 24);
        long uptime_hours = uptime / (1000 * 60 * 60);

        uptime = uptime % (1000 * 60 * 60);
        long uptime_mins = uptime / (1000 * 60);

        request.setAttribute("uptime_days", new Long(uptime_days));
        request.setAttribute("uptime_hours", new Long(uptime_hours));
        request.setAttribute("uptime_mins", new Long(uptime_mins));
    }

    //
    // Work out the language of the interface by matching resource files that we have
    // to the request locale.
    //
    List fileNames = getMessageFileNamesForLocale(request.getLocale());
    String lang = "en";
    for (Iterator it = fileNames.iterator(); it.hasNext();) {
        String f = (String) it.next();
        if (getServletContext().getResource(f + ".properties") != null) {
            lang = f.substring(messagesBasename.length() + 1);
            break;
        }
    }

    request.setAttribute("lang", lang);

    return super.handleRequestInternal(request, response);
}

From source file:com.manydesigns.portofino.stripes.AuthenticationRequiredResolution.java

public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (request.getParameter("__portofino_quiet_auth_failure") != null) {
        return;/*  ww  w .j  av  a2  s . c  o m*/
    }
    ServletContext servletContext = request.getServletContext();
    Configuration configuration = (Configuration) servletContext
            .getAttribute(BaseModule.PORTOFINO_CONFIGURATION);
    String loginPage = configuration.getString(PortofinoProperties.LOGIN_PAGE);
    if (response.getContentType() == null || response.getContentType().contains("text/html")) {
        ElementsActionBeanContext context = new ElementsActionBeanContext();
        context.setRequest(request);
        String originalPath = context.getActionPath();
        UrlBuilder urlBuilder = new UrlBuilder(Locale.getDefault(), originalPath, false);
        Map<?, ?> parameters = request.getParameterMap();
        urlBuilder.addParameters(parameters);
        String returnUrl = urlBuilder.toString();
        logger.info("Anonymous user not allowed to see {}. Redirecting to login.", originalPath);
        RedirectResolution redirectResolution = new RedirectResolution(loginPage, true);
        redirectResolution.addParameter("returnUrl", returnUrl);
        redirectResolution.execute(request, response);
    } else {
        logger.debug("AJAX call while user disconnected");
        UrlBuilder loginUrlBuilder = new UrlBuilder(request.getLocale(), loginPage, false);
        response.setHeader(LOGIN_PAGE_HEADER, loginUrlBuilder.toString());
        new ErrorResolution(STATUS, errorMessage).execute(request, response);
    }
}

From source file:fr.paris.lutece.plugins.sponsoredlinks.web.SponsoredLinksJspBean.java

/**
 * Returns the Manage Sponsoredlinks page
 * @param request The HTTP request/* w w  w . j  av a 2  s.c  om*/
 * @return The HTML page
 */
public String getManageSponsoredLinks(HttpServletRequest request) {
    setPageTitleProperty(EMPTY_STRING);

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

    boolean bPermissionAdvancedParameter = RBACService.isAuthorized(SponsoredLinkTemplate.RESOURCE_TYPE,
            RBAC.WILDCARD_RESOURCES_ID,
            SponsoredLinksTemplateResourceIdService.PERMISSION_MANAGE_ADVANCED_PARAMETERS, getUser());

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

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

    return getAdminPage(template.getHtml());
}

From source file:fr.paris.lutece.plugins.workflow.modules.notifycrm.web.NotifyCRMTaskComponent.java

/**
 * {@inheritDoc}//from  w  w w. j  av a  2 s  .c  om
 */
@Override
public String getDisplayConfigForm(HttpServletRequest request, Locale locale, ITask task) {
    String strDefaultSenderName = AppPropertiesService
            .getProperty(NotifyCRMConstants.PROPERTY_DEFAULT_SENDER_NAME);
    Plugin pluginWorkflow = PluginService.getPlugin(WorkflowPlugin.PLUGIN_NAME);
    Map<String, Object> model = new HashMap<String, Object>();

    model.put(NotifyCRMConstants.MARK_CONFIG, _taskNotifyCRMConfigService.findByPrimaryKey(task.getId()));
    model.put(NotifyCRMConstants.MARK_DEFAULT_SENDER_NAME, strDefaultSenderName);
    model.put(NotifyCRMConstants.MARK_LIST_ENTRIES_ID_DEMAND,
            _notifyCRMService.getListEntriesIdDemand(task.getId(), locale));
    model.put(NotifyCRMConstants.MARK_LIST_ENTRIES_USER_GUID,
            _notifyCRMService.getListEntriesUserGuid(task.getId(), locale));
    model.put(NotifyCRMConstants.MARK_LIST_ENTRIES_CRM_WEB_APP_CODE,
            _notifyCRMService.getListEntriesCrmWebAppCode(task.getId(), locale));

    model.put(NotifyCRMConstants.MARK_LIST_DIRECTORIES, _notifyCRMService.getListDirectories());
    model.put(NotifyCRMConstants.MARK_LIST_ENTRIES_FREEMARKER,
            _notifyCRMService.getListEntriesFreemarker(task.getId()));
    model.put(NotifyCRMConstants.MARK_WEBAPP_URL, AppPathService.getBaseUrl(request));
    model.put(NotifyCRMConstants.MARK_LOCALE, request.getLocale());
    model.put(NotifyCRMConstants.MARK_IS_USER_ATTRIBUTE_WS_ACTIVE, _userAttributesManager.isEnabled());
    model.put(NotifyCRMConstants.MARK_PLUGIN_WORKFLOW, pluginWorkflow);
    model.put(NotifyCRMConstants.MARK_LOCALE, locale);
    model.put(NotifyCRMConstants.MARK_TASKS_LIST, _notifyCRMService.getListBelowTasks(task, locale));
    model.put(NotifyCRMConstants.MARK_DEFAULT_CRM_WEBAPP_BASE_URL,
            AppPropertiesService.getProperty(NotifyCRMConstants.PROPERTY_CRMCLIENT_REST_WEBAPP_URL));

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

    return template.getHtml();
}

From source file:fr.paris.lutece.plugins.workflow.modules.editrecord.service.EditRecordService.java

/**
 * {@inheritDoc}//www  .  j  a v a2 s  .co  m
 */
@Override
public boolean doEditRecordData(HttpServletRequest request, EditRecord editRecord) throws SiteMessageException {
    Plugin pluginDirectory = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);

    Record record = getRecordFromIdHistory(editRecord.getIdHistory());

    if (record != null) {
        String strUploadAction = DirectoryAsynchronousUploadHandler.getHandler().getUploadAction(request);
        List<IEntry> listEntriesToEdit = getListEntriesToEdit(request, editRecord.getListEditRecordValues());
        List<RecordField> listRecordFields = getListRecordFieldsToNotEdit(request, record.getIdRecord(),
                editRecord.getListEditRecordValues());

        for (IEntry entry : listEntriesToEdit) {
            try {
                DirectoryUtils.getDirectoryRecordFieldData(record, request, entry.getIdEntry(), true,
                        listRecordFields, pluginDirectory, request.getLocale());
            } catch (DirectoryErrorException error) {
                // Case if the user does not upload a file, then throw the error message
                if (StringUtils.isBlank(strUploadAction)) {
                    if (error.isMandatoryError()) {
                        Object[] tabRequiredFields = { error.getTitleField() };
                        SiteMessageService.setMessage(request, EditRecordConstants.MESSAGE_MANDATORY_FIELD,
                                tabRequiredFields, SiteMessage.TYPE_STOP);
                    } else {
                        Object[] tabRequiredFields = { error.getTitleField(), error.getErrorMessage() };
                        SiteMessageService.setMessage(request, EditRecordConstants.MESSAGE_DIRECTORY_ERROR,
                                tabRequiredFields, SiteMessage.TYPE_STOP);
                    }
                }
            }
        }

        record.setListRecordField(listRecordFields);

        // Special case for upload fields : if no action is specified, a submit
        // button associated with an upload might have been pressed :
        if (StringUtils.isNotBlank(strUploadAction)) {
            Map<String, List<RecordField>> mapListRecordFields = DirectoryUtils
                    .buildMapIdEntryListRecordField(record);

            // Upload the file
            try {
                DirectoryAsynchronousUploadHandler.getHandler().doUploadAction(request, strUploadAction,
                        mapListRecordFields, record, pluginDirectory);
            } catch (DirectoryErrorException error) {
                if (error.isMandatoryError()) {
                    Object[] tabRequiredFields = { error.getTitleField() };
                    SiteMessageService.setMessage(request, EditRecordConstants.MESSAGE_MANDATORY_FIELD,
                            tabRequiredFields, SiteMessage.TYPE_STOP);
                } else {
                    Object[] tabRequiredFields = { error.getTitleField(), error.getErrorMessage() };
                    SiteMessageService.setMessage(request, EditRecordConstants.MESSAGE_DIRECTORY_ERROR,
                            tabRequiredFields, SiteMessage.TYPE_STOP);
                }
            }

            // Put the map <idEntry, RecordFields> in the session
            request.getSession().setAttribute(
                    EditRecordConstants.SESSION_EDIT_RECORD_LIST_SUBMITTED_RECORD_FIELDS, mapListRecordFields);

            return false;
        }

        RecordHome.updateWidthRecordField(record, pluginDirectory);

        return true;
    }

    setSiteMessage(request, EditRecordConstants.MESSAGE_APP_ERROR, SiteMessage.TYPE_STOP,
            request.getParameter(EditRecordConstants.PARAMETER_URL_RETURN));

    return false;
}

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

/**
 * The screen for management of portlets associated to the generated plugin
 *
 * @param request The Http Request//ww  w .  j a v  a  2 s  . c  o m
 * @return The XPage
 */
@View(VIEW_MANAGE_PORTLETS)
public XPage getManagePortlets(HttpServletRequest request) {
    Map<String, Object> model = getModel();
    model.put(MARK_PLUGIN_ID, Integer.toString(_nPluginId));
    model.put(MARK_PLUGIN_PORTLETS, ModelService.getPluginModel(_nPluginId).getPortlets());

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