Example usage for org.springframework.web.servlet.support RequestContextUtils getLocale

List of usage examples for org.springframework.web.servlet.support RequestContextUtils getLocale

Introduction

In this page you can find the example usage for org.springframework.web.servlet.support RequestContextUtils getLocale.

Prototype

public static Locale getLocale(HttpServletRequest request) 

Source Link

Document

Retrieve the current locale from the given request, using the LocaleResolver bound to the request by the DispatcherServlet (if available), falling back to the request's accept-header Locale.

Usage

From source file:org.apereo.portal.layout.dlm.remoting.UpdatePreferencesServlet.java

/**
 * Rename a specified tab.//  ww  w . j a v  a 2  s.co  m
 *
 * @param request
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST, params = "action=renameTab")
public ModelAndView renameTab(HttpServletRequest request, HttpServletResponse response) throws IOException {

    IUserInstance ui = userInstanceManager.getUserInstance(request);
    UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
    IUserLayoutManager ulm = upm.getUserLayoutManager();

    // element ID of the tab to be renamed
    String tabId = request.getParameter("tabId");
    IUserLayoutFolderDescription tab = (IUserLayoutFolderDescription) ulm.getNode(tabId);

    // desired new name
    String tabName = request.getParameter("tabName");

    if (!ulm.canUpdateNode(tab)) {
        logger.warn("Attempting to rename an immutable tab");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return new ModelAndView("jsonView", Collections.singletonMap("error", getMessage("error.element.update",
                "Unable to update element", RequestContextUtils.getLocale(request))));
    }

    /*
     * Update the tab and save the layout
     */
    tab.setName(StringUtils.isBlank(tabName) ? DEFAULT_TAB_NAME : tabName);
    final boolean updated = ulm.updateNode(tab);

    if (updated) {
        try {
            // save the user's layout
            ulm.saveUserLayout();
        } catch (PortalException e) {
            return handlePersistError(request, response, e);
        }

        //TODO why do we have to do this, shouldn't modifying the layout be enough to trigger a full re-render (layout's cache key changes)
        this.stylesheetUserPreferencesService.setLayoutAttribute(request, PreferencesScope.STRUCTURE, tabId,
                "name", tabName);
    }

    Map<String, String> model = Collections.singletonMap("message", "saved new tab name");
    return new ModelAndView("jsonView", model);

}

From source file:org.apereo.portal.layout.dlm.remoting.UpdatePreferencesServlet.java

private ModelAndView handlePersistError(HttpServletRequest request, HttpServletResponse response, Exception e) {
    logger.warn("Error saving layout", e);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return new ModelAndView("jsonView",
            Collections.singletonMap("error", getMessage("error.persisting.attribute.change",
                    "Unable to save attribute changes", RequestContextUtils.getLocale(request))));
}

From source file:org.codehaus.groovy.grails.scaffolding.TemplateGeneratingResponseHandler.java

/**
 * Either delegates to a pre-existing view or renders an in-memory scaffolded view to the response
 *
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @param actionName The name of the action to handle
 * @param model The View model/*from w  w w .  j a v a  2s .  c o  m*/
 * @return A Spring ModelAndView instance
 */
public ModelAndView handleResponse(HttpServletRequest request, HttpServletResponse response, String actionName,
        Map model) {

    if (templateGenerator == null)
        throw new IllegalStateException("Property [templateGenerator] must be set!");
    if (resolver == null)
        throw new IllegalStateException("Property [resolver] must be set!");
    if (scaffoldedClass == null)
        throw new IllegalStateException("Property [scaffoldedClass] must be set!");
    if (grailsApplication == null)
        throw new IllegalStateException("Property [grailsApplication] must be set!");

    GrailsDomainClass domainClass = (GrailsDomainClass) grailsApplication
            .getArtefact(DomainClassArtefactHandler.TYPE, scaffoldedClass.getName());
    GrailsControllerClass controllerClass = grailsApplication.getScaffoldingController(domainClass);
    String uri = controllerClass.getViewByName(actionName);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Scaffolding response for view URI: " + uri);
    }

    try {
        // if the view exists physically then fall back to delegating to the physical view
        View v = resolver.resolveViewName(uri, RequestContextUtils.getLocale(request));
        if (v instanceof AbstractUrlBasedView) {

            uri = ((AbstractUrlBasedView) v).getUrl();
            Resource r = null;
            if (uri.endsWith(GroovyPage.EXTENSION)) {
                GroovyPagesTemplateEngine templateEngine = getTemplateEngine();
                r = templateEngine.getResourceForUri(uri);
            }

            if (r != null && r.exists()) {
                return new ModelAndView(v, model);
            } else {
                return createScaffoldedResponse(uri, model, actionName);
            }
        } else {
            return createScaffoldedResponse(uri, model, actionName);
        }

    } catch (Exception e) {
        throw new ScaffoldingException(
                "Unable to render scaffolded view for uri [" + uri + "]:" + e.getMessage(), e);
    }
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

/**
 * Utility method for creating a GrailsDataBinder instance
 *
 * @param target The target object to bind to
 * @param objectName The name of the object
 * @param request A request instance/*  www .j a v  a  2  s  .  c  om*/
 * @return A GrailsDataBinder instance
 */
public static GrailsDataBinder createBinder(Object target, String objectName, HttpServletRequest request) {
    GrailsDataBinder binder = createBinder(target, objectName);
    final GrailsWebRequest webRequest = GrailsWebRequest.lookup(request);
    initializeFromWebRequest(binder, webRequest);

    Locale locale = RequestContextUtils.getLocale(request);
    registerCustomEditors(webRequest, binder, locale);
    return binder;
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

/**
 * Utility method for creating a GrailsDataBinder instance
 *
 * @param target The target object to bind to
 * @param objectName The name of the object
 * @return A GrailsDataBinder instance/*from ww  w.j  a va  2 s.  c om*/
 */
public static GrailsDataBinder createBinder(Object target, String objectName) {
    GrailsDataBinder binder = new GrailsDataBinder(target, objectName);
    binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    binder.registerCustomEditor(String.class, new StringMultipartFileEditor());
    binder.registerCustomEditor(Currency.class, new CurrencyEditor());
    binder.registerCustomEditor(Locale.class, new LocaleEditor());
    binder.registerCustomEditor(TimeZone.class, new TimeZoneEditor());
    binder.registerCustomEditor(URI.class, new UriEditor());
    //        GenericConversionService conversionService = new GenericConversionService();
    //        conversionService.addConverter(new GenericConverter() {
    //
    //            @Override
    //            public Set<ConvertiblePair> getConvertibleTypes() {
    //                return Collections.singleton(new ConvertiblePair(Map.class, Object.class));
    //            }
    //
    //            @Override
    //            public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
    //                Object obj = BeanUtils.instantiate(targetType.getObjectType());
    //                createBinder(obj, obj.getClass().getName()).bind(new MutablePropertyValues((Map<?, ?>) source));
    //                return obj;
    //            }
    //        });
    //        binder.setConversionService(conversionService);

    final GrailsWebRequest webRequest = GrailsWebRequest.lookup();
    if (webRequest == null) {
        registerCustomEditors(null, binder);
    } else {
        initializeFromWebRequest(binder, webRequest);
        Locale locale = RequestContextUtils.getLocale(webRequest.getCurrentRequest());
        registerCustomEditors(webRequest, binder, locale);
    }

    return binder;
}

From source file:org.displaytag.localization.I18nSpringAdapter.java

/**
 * @see I18nResourceProvider#getResource(String, String, Tag, PageContext)
 *//*from   w ww . j  av  a2  s  . com*/
public String getResource(String resourceKey, String defaultValue, Tag tag, PageContext pageContext) {
    MessageSource messageSource = RequestContextUtils.getWebApplicationContext(pageContext.getRequest());
    if (messageSource == null) {
        log.warn("messageSource not found");
        return null;
    }

    // if resourceKey isn't defined either, use defaultValue
    String key = (resourceKey != null) ? resourceKey : defaultValue;

    String message = null;

    message = messageSource.getMessage(key, null, null,
            RequestContextUtils.getLocale((HttpServletRequest) pageContext.getRequest()));

    // if user explicitely added a titleKey we guess this is an error
    if (message == null && resourceKey != null) {
        log.debug(Messages.getString("Localization.missingkey", resourceKey)); //$NON-NLS-1$
        message = UNDEFINED_KEY + resourceKey + UNDEFINED_KEY;
    }

    return message;

}

From source file:org.encuestame.core.service.AbstractBaseService.java

/**
 * Return the locale inside the {@link HttpServletRequest}.
 * @param request/*w  ww.  ja  v  a2  s.  co  m*/
 * @return
 */
private Locale getLocale(final HttpServletRequest request) {
    return RequestContextUtils.getLocale(request);
}

From source file:org.encuestame.mvc.controller.AbstractBaseOperations.java

/**
 * Get Locale.//from  w w  w.j  av  a  2  s.co m
 * @param request
 * @return
 */
private Locale getLocale(final HttpServletRequest request) {
    if (request == null) {
        return Locale.ENGLISH;
    } else {
        return RequestContextUtils.getLocale(request);
    }
}

From source file:org.gbif.portal.web.content.dataset.HostCountryPicklistHelper.java

/**
 * Gets the ordered map based on the i18n values
 * @see org.gbif.portal.web.content.filter.PicklistHelper#getPicklist(javax.servlet.http.HttpServletRequest)
 */// w ww . j  a v a  2  s .co m
public Map<String, String> getPicklist(HttpServletRequest request, Locale locale) {
    Locale theLocale = null;
    if (request != null)
        theLocale = RequestContextUtils.getLocale(request);
    else
        theLocale = locale;

    List<String> isoCodes = geospatialManager.getHostCountryISOCountryCodes();
    Map<String, String> i18nValue2IsoCode = new TreeMap<String, String>();
    for (String code : isoCodes) {
        if (code != null && !isoCountryCodeToI18NKey.containsKey(code)) {
            logger.warn("Received an unknown country code[" + code + "] - ignoring from map...");
        } else if (code != null && !code.equals("IL") && !code.equals("CN") && !code.equals("TW")) {
            // get the i18n value of it, and use that to key it
            String i18nValue;
            try {
                i18nValue = messageSource.getMessage("country." + code, null, theLocale);
                i18nValue2IsoCode.put(i18nValue, code);
            } catch (NoSuchMessageException e) {
                logger.warn("Received a country code[" + code + "] that has no translation to language["
                        + theLocale + "]- ignoring from map...");
            }
        }
    }
    Map<String, String> orderedIsoCodeToI18NValue = new LinkedHashMap<String, String>();
    for (String i18nValue : i18nValue2IsoCode.keySet()) {
        orderedIsoCodeToI18NValue.put(i18nValue2IsoCode.get(i18nValue), i18nValue);
    }
    return orderedIsoCodeToI18NValue;
}

From source file:org.gbif.portal.web.content.dataset.OccurrenceDateFilterHelper.java

/**
 * @see org.gbif.portal.web.content.filter.FilterHelper#getDefaultDisplayValue(javax.servlet.http.HttpServletRequest)
 *///www.j a  va  2 s  . c om
public String getDefaultDisplayValue(HttpServletRequest request) {
    String defaultValue = getDefaultValue(request);
    Locale locale = RequestContextUtils.getLocale(request);
    return getDisplayValue(defaultValue, locale);
}