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:no.abmu.organisationregister.webflow.VerifyAddressInfoFormAction.java

protected Object createFormObject(RequestContext context) {

    WebFlowVariables flowVariables = (WebFlowVariables) context.getFlowScope().get("flowVariables");
    if (logger.isDebugEnabled()) {
        logger.debug(flowVariables);/*w w w  .  j av a  2  s  .  c om*/
    }

    Long id = flowVariables.getWorkingSchemaOrganisationUnitId();
    Assert.assertNotNull("id", id);
    OrganisationUnit orgUnit = organisationUnitService.get(id);

    ServletExternalContext servletContext = (ServletExternalContext) context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) servletContext.getNativeRequest();
    Locale locale = RequestContextUtils.getLocale(request);

    // Hack to prevent error when edding nynorsk (Only using bokml).
    // TODO fix error on nynorsk in database.
    locale = LocaleTypeNameConst.DEFAULT;

    AddressStatus addressStatus = new AddressStatus(orgUnit, locale);

    return addressStatus;
}

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

/**
 * Remove an element from the layout.//  w w  w  .  j  a va2 s.c o  m
 *
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST, params = "action=removeElement")
public ModelAndView removeElement(HttpServletRequest request, HttpServletResponse response) throws IOException {

    IUserInstance ui = userInstanceManager.getUserInstance(request);
    IPerson per = getPerson(ui, response);

    UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
    IUserLayoutManager ulm = upm.getUserLayoutManager();

    try {

        // if the element ID starts with the fragment prefix and is a folder,
        // attempt first to treat it as a pulled fragment subscription
        String elementId = request.getParameter("elementID");
        if (elementId != null && elementId.startsWith(Constants.FRAGMENT_ID_USER_PREFIX) && ulm
                .getNode(elementId) instanceof org.apereo.portal.layout.node.UserLayoutFolderDescription) {

            removeSubscription(per, elementId, ulm);

        } else {
            // Delete the requested element node.  This code is the same for
            // all node types, so we can just have a generic action.
            if (!ulm.deleteNode(elementId)) {
                logger.info(
                        "Failed to remove element ID {} from layout root folder ID {}, delete node returned false",
                        elementId, ulm.getRootFolderId());
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return new ModelAndView("jsonView",
                        Collections.singletonMap("error", getMessage("error.element.update",
                                "Unable to update element", RequestContextUtils.getLocale(request))));
            }
        }

        ulm.saveUserLayout();

        return new ModelAndView("jsonView", Collections.EMPTY_MAP);

    } catch (PortalException e) {
        return handlePersistError(request, response, e);
    }
}

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

/**
 * Moves the portlet either before nextNodeId or after previousNodeId as appropriate.
 *
 * @param request HttpRequest/*  ww  w  . java 2  s.com*/
 * @param response HttpResponse
 * @param sourceId nodeId to move
 * @param previousNodeId if nextNodeId is not blank, moves portlet to end of list previousNodeId is in
 * @param nextNodeId nodeId to insert sourceId before.
 * @return
 */
@RequestMapping(method = RequestMethod.POST, params = "action=movePortletAjax")
public ModelAndView movePortletAjax(HttpServletRequest request, HttpServletResponse response,
        @RequestParam String sourceId, @RequestParam String previousNodeId, @RequestParam String nextNodeId) {
    final Locale locale = RequestContextUtils.getLocale(request);
    boolean success = false;
    if (StringUtils.isNotBlank(nextNodeId)) {
        success = moveElementInternal(request, sourceId, nextNodeId, "insertBefore");
    } else {
        success = moveElementInternal(request, sourceId, previousNodeId, "appendAfter");
    }
    if (success) {
        return new ModelAndView("jsonView", Collections.singletonMap("response",
                getMessage("success.move.element", "Element moved successfully", locale)));
    } else {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return new ModelAndView("jsonView", Collections.singletonMap("response",
                getMessage("error.move.element", "Error moving element.", locale)));
    }
}

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

/**
 * Move an element to another location on the tab.
 *
 * Used by Respondr UI when moving portlets around in content area. Will be made more generic
 * to support ngPortal UI which supports arbitrary nesting of folders.  When that code is
 * merged in, the behavior of this method will need to change slightly (make sure movePortlet
 * behavior doesn't change though). Current behavior:<ul>
 *   <li>If destination is a tab either adds to end of 1st column or if no columns, creates one and adds it. AFAIK
 *       this was not actually used by the UI.</li>
 *   <li>If target is a column (2 down from root), portlet always added to end of column. Used by UI to drop
 *       portlet into empty column (UI did insertBefore with elementId=columnId)</li>
 *   <li>If method=insertBefore does insert before elementId (always a portlet in 4.2).</li>
 *   <li>If method=appendAfter does append at end of parent(elementId), result of which is a column.
 *       Used by UI to add to end of column (elementId is last portlet in column).</li>
 * </ul>/*w ww  .j a  va 2s .c  om*/
 *
 * @param request
 * @param response
 * @param sourceId id of the element to move
 * @param method insertBefore or appendAfter
 * @param destinationId Id of element. If a tab, sourceID added to end of a folder/column in the tab.
 *         If a folder, sourceID added to the end of the folder. Otherwise sourceID added before
 *         elementID.
 * @throws IOException
 * @throws PortalException
 */
@RequestMapping(method = RequestMethod.POST, params = "action=moveElement")
public ModelAndView moveElement(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "sourceID") String sourceId, @RequestParam String method,
        @RequestParam(value = "elementID") String destinationId) throws IOException, PortalException {
    final Locale locale = RequestContextUtils.getLocale(request);

    if (moveElementInternal(request, sourceId, destinationId, method)) {
        return new ModelAndView("jsonView", Collections.singletonMap("response",
                getMessage("success.move.element", "Element moved successfully", locale)));
    } else {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return new ModelAndView("jsonView", Collections.singletonMap("response",
                getMessage("error.move.element", "Error moving element", locale)));
    }
}

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

/**
 * Move a tab left or right./*  www.  j a v a2s.  co  m*/
 *
 * @param sourceId node ID of tab to move
 * @param method insertBefore or appendAfter. If appendAfter, tab is added as last tab (parent of destinationId).
 * @param destinationId insertBefore: node ID of tab to move sourceId before. insertAfter: node ID of another tab
 * @param request
 * @param response
 * @throws PortalException
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST, params = "action=moveTab")
public ModelAndView moveTab(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "sourceID") String sourceId, @RequestParam String method,
        @RequestParam(value = "elementID") String destinationId) throws IOException {

    IUserInstance ui = userInstanceManager.getUserInstance(request);

    UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
    IUserLayoutManager ulm = upm.getUserLayoutManager();
    final Locale locale = RequestContextUtils.getLocale(request);

    // If we're moving this element before another one, we need
    // to know what the target is. If there's no target, just
    // assume we're moving it to the very end of the list.
    String siblingId = null;
    if ("insertBefore".equals(method))
        siblingId = destinationId;

    try {
        // move the node as requested and save the layout
        if (!ulm.moveNode(sourceId, ulm.getParentId(destinationId), siblingId)) {
            logger.warn("Failed to move tab in user layout. moveNode returned false");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return new ModelAndView("jsonView",
                    Collections.singletonMap("response",
                            getMessage("error.move.tab",
                                    "There was an issue moving the tab, please refresh the page and try again.",
                                    locale)));
        }
        ulm.saveUserLayout();
    } catch (PortalException e) {
        return handlePersistError(request, response, e);
    }

    return new ModelAndView("jsonView", Collections.singletonMap("response",
            getMessage("success.move.tab", "Tab moved successfully", locale)));
}

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

@RequestMapping(method = RequestMethod.POST, params = "action=addFavorite")
public ModelAndView addFavorite(@RequestParam String channelId, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    final IUserInstance ui = userInstanceManager.getUserInstance(request);
    final IPerson person = getPerson(ui, response);
    final IPortletDefinition pdef = portletDefinitionRegistry.getPortletDefinition(channelId);
    final Locale locale = RequestContextUtils.getLocale(request);

    final IAuthorizationPrincipal authPrincipal = this.getUserPrincipal(person.getUserName());
    final String targetString = PermissionHelper.permissionTargetIdForPortletDefinition(pdef);
    if (!authPrincipal.hasPermission(IPermission.PORTAL_SYSTEM, IPermission.PORTLET_FAVORITE_ACTIVITY,
            targetString)) {/*from www . j a v  a 2 s. c  o m*/
        logger.warn("Unauthorized attempt to favorite portlet '{}' through the REST API by user '{}'",
                pdef.getFName(), person.getUserName());
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return new ModelAndView("jsonView", Collections.singletonMap("response",
                getMessage("error.favorite.not.permitted", "Favorite not permitted", locale)));
    }

    final UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
    final IUserLayoutManager ulm = upm.getUserLayoutManager();

    final IUserLayoutChannelDescription channel = new UserLayoutChannelDescription(pdef);

    //get favorite tab
    final String favoriteTabNodeId = FavoritesUtils.getFavoriteTabNodeId(ulm.getUserLayout());

    if (favoriteTabNodeId != null) {
        //add portlet to favorite tab
        final IUserLayoutNodeDescription node = addNodeToTab(ulm, channel, favoriteTabNodeId);

        if (node == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return new ModelAndView("jsonView", Collections.singletonMap("response",
                    getMessage("error.add.portlet.in.tab", "Can''t add a new favorite", locale)));
        }

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

        //document success for notifications
        final Map<String, String> model = new HashMap<String, String>();
        final String channelTitle = channel.getTitle();
        model.put("response", getMessage("favorites.added.favorite", channelTitle,
                "Added " + channelTitle + " as a favorite.", locale));
        model.put("newNodeId", node.getId());
        return new ModelAndView("jsonView", model);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("jsonView", Collections.singletonMap("response",
                getMessage("error.finding.favorite.tab", "Can''t find favorite tab", locale)));
    }
}

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

/**
 * This method removes the channelId specified from favorites. Note that even if you pass in the layout channel id, it will always remove from the favorites.
 * @param channelId The long channel ID that is used to determine which fname to remove from favorites
 * @param request/*from  w ww .ja  va 2  s .  c o m*/
 * @param response
 * @return returns a mav object with a response attribute for noty
 * @throws IOException if it has problem reading the layout file.
 */
@RequestMapping(method = RequestMethod.POST, params = "action=removeFavorite")
public ModelAndView removeFavorite(@RequestParam String channelId, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    UserPreferencesManager upm = (UserPreferencesManager) userInstanceManager.getUserInstance(request)
            .getPreferencesManager();
    IUserLayoutManager ulm = upm.getUserLayoutManager();
    final Locale locale = RequestContextUtils.getLocale(request);
    IPortletDefinition portletDefinition = portletDefinitionRegistry.getPortletDefinition(channelId);

    if (portletDefinition != null && StringUtils.isNotBlank(portletDefinition.getFName())) {
        String functionalName = portletDefinition.getFName();
        List<IUserLayoutNodeDescription> favoritePortlets = FavoritesUtils
                .getFavoritePortlets(ulm.getUserLayout());

        //search for the favorite to delete
        EqualPredicate nameEqlPredicate = new EqualPredicate(functionalName);
        Object result = CollectionUtils.find(favoritePortlets,
                new BeanPredicate("functionalName", nameEqlPredicate));

        if (result != null && result instanceof UserLayoutChannelDescription) {
            UserLayoutChannelDescription channelDescription = (UserLayoutChannelDescription) result;
            try {
                if (!ulm.deleteNode(channelDescription.getChannelSubscribeId())) {
                    logger.warn("Error deleting the node" + channelId + "from favorites for user "
                            + (upm.getPerson() == null ? "unknown" : upm.getPerson().getID()));
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    return new ModelAndView("jsonView", Collections.singletonMap("response",
                            getMessage("error.remove.favorite", "Can''t remove favorite", locale)));
                }
                // save the user's layout
                ulm.saveUserLayout();
            } catch (PortalException e) {
                return handlePersistError(request, response, e);
            }

            //document success for notifications
            Map<String, String> model = new HashMap<String, String>();
            model.put("response",
                    getMessage("success.remove.portlet", "Removed from Favorites successfully", locale));
            return new ModelAndView("jsonView", model);
        }
    }
    // save the user's layout
    ulm.saveUserLayout();
    return new ModelAndView("jsonView", Collections.singletonMap("response",
            getMessage("error.finding.favorite", "Can''t find favorite", locale)));
}

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

/**
 * Add a new channel.//  w  ww.j  a  v  a2s.  c  o  m
 *
 * @param request
 * @param response
 * @throws IOException
 * @throws PortalException
 */
@RequestMapping(method = RequestMethod.POST, params = "action=addPortlet")
public ModelAndView addPortlet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, PortalException {

    IUserInstance ui = userInstanceManager.getUserInstance(request);
    UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
    IUserLayoutManager ulm = upm.getUserLayoutManager();
    final Locale locale = RequestContextUtils.getLocale(request);

    // gather the parameters we need to move a channel
    String destinationId = request.getParameter("elementID");
    String sourceId = request.getParameter("channelID");
    String method = request.getParameter("position");
    String fname = request.getParameter("fname");

    if (destinationId == null) {
        String tabName = request.getParameter("tabName");
        if (tabName != null) {
            destinationId = getTabIdFromName(ulm.getUserLayout(), tabName);
        }
    }

    IPortletDefinition definition = null;
    if (sourceId != null)
        definition = portletDefinitionRegistry.getPortletDefinition(sourceId);
    else if (fname != null)
        definition = portletDefinitionRegistry.getPortletDefinitionByFname(fname);
    else {
        logger.error("SourceId or fname invalid when adding a portlet");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("jsonView", Collections.singletonMap("error", "SourceId or fname invalid"));
    }

    IUserLayoutChannelDescription channel = new UserLayoutChannelDescription(definition);

    IUserLayoutNodeDescription node = null;
    if (isTab(ulm, destinationId)) {
        node = addNodeToTab(ulm, channel, destinationId);

    } else {
        boolean isInsert = method != null && method.equals("insertBefore");

        //If neither an insert or type folder - Can't "insert into" non-folder
        if (!(isInsert || isFolder(ulm, destinationId))) {
            logger.error("Cannot insert into portlet element");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return new ModelAndView("jsonView",
                    Collections.singletonMap("error", "Cannot insert into portlet element"));
        }

        String siblingId = isInsert ? destinationId : null;
        String target = isInsert ? ulm.getParentId(destinationId) : destinationId;

        // move the channel into the column
        node = ulm.addNode(channel, target, siblingId);
    }

    if (node == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return new ModelAndView("jsonView", Collections.singletonMap("error",
                getMessage("error.add.element", "Unable to add element", locale)));
    }

    String nodeId = node.getId();

    try {
        // save the user's layout
        ulm.saveUserLayout();
        if (addedWindowState != null) {
            IPortletWindow portletWindow = this.portletWindowRegistry
                    .getOrCreateDefaultPortletWindowByFname(request, channel.getFunctionalName());
            portletWindow.setWindowState(addedWindowState);
            this.portletWindowRegistry.storePortletWindow(request, portletWindow);
        }
    } catch (PortalException e) {
        return handlePersistError(request, response, e);
    }

    Map<String, String> model = new HashMap<String, String>();
    model.put("response", getMessage("success.add.portlet", "Added a new channel", locale));
    model.put("newNodeId", nodeId);
    return new ModelAndView("jsonView", model);

}

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

/**
 * Add a new folder to the layout.//from w  w  w.  ja va2s  .  c o  m
 *
 * @param request
 * @param response
 * @param targetId - id of the folder node to add the new folder to. By default, the folder will be inserted after other
 *                   existing items in the node unless a siblingId is provided.
 * @param siblingId - if set, insert new folder prior to the node with this id, otherwise simple insert at the end of the list.
 * @param attributes - if included, parse the JSON name-value pairs in the body as the attributes of the folder. These
 *                     will override the defaults.
 * e.g. :
 * {
 *      "structureAttributes" : {"display" : "row", "other" : "another" },
 *      "attributes" : {"hidden": "true", "type" : "header-top" }
 * }
 */
@RequestMapping(method = RequestMethod.POST, params = "action=addFolder")
public ModelAndView addFolder(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("targetId") String targetId,
        @RequestParam(value = "siblingId", required = false) String siblingId,
        @RequestParam(value = "display", required = false) String display,
        @RequestBody(required = false) Map<String, Map<String, String>> attributes) {
    IUserLayoutManager ulm = userInstanceManager.getUserInstance(request).getPreferencesManager()
            .getUserLayoutManager();
    final Locale locale = RequestContextUtils.getLocale(request);

    if (!ulm.getNode(targetId).isAddChildAllowed()) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return new ModelAndView("jsonView", Collections.singletonMap("error",
                getMessage("error.add.element", "Unable to add element", locale)));
    }

    UserLayoutFolderDescription newFolder = new UserLayoutFolderDescription();
    newFolder.setHidden(false);
    newFolder.setImmutable(false);
    newFolder.setAddChildAllowed(true);
    newFolder.setFolderType(IUserLayoutFolderDescription.REGULAR_TYPE);

    // Update the attributes based on the supplied JSON (optional request body name-value pairs)
    if (attributes != null && !attributes.isEmpty()) {
        setObjectAttributes(newFolder, request, attributes);
    }

    ulm.addNode(newFolder, targetId, siblingId);

    try {
        ulm.saveUserLayout();
    } catch (PortalException e) {
        return handlePersistError(request, response, e);
    }

    Map<String, Object> model = new HashMap<>();
    model.put("response", getMessage("success.add.folder", "Added a new folder", locale));
    model.put("folderId", newFolder.getId());
    model.put("immutable", newFolder.isImmutable());
    return new ModelAndView("jsonView", model);
}

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

/**
 * Update the attributes for the node. Unrecognized attributes will log a warning, but are otherwise ignored.
 *
 * @param request/*from www. j a  v a  2s .co m*/
 * @param response
 * @param targetId - the id of the node whose attributes will be updated.
 * @param attributes - parse the JSON name-value pairs in the body as the attributes of the folder.
 * e.g. :
 * {
 *      "structureAttributes" : {"display" : "row", "other" : "another" },
 *      "attributes" : {"hidden": "true", "type" : "header-top" }
 * }
 */
@RequestMapping(method = RequestMethod.POST, params = "action=updateAttributes")
public ModelAndView updateAttributes(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("targetId") String targetId, @RequestBody Map<String, Map<String, String>> attributes) {
    IUserLayoutManager ulm = userInstanceManager.getUserInstance(request).getPreferencesManager()
            .getUserLayoutManager();

    if (!ulm.getNode(targetId).isEditAllowed()) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return new ModelAndView("jsonView", Collections.singletonMap("error", getMessage("error.element.update",
                "Unable to update element", RequestContextUtils.getLocale(request))));
    }

    // Update the attributes based on the supplied JSON (request body name-value pairs)
    IUserLayoutNodeDescription node = ulm.getNode(targetId);
    if (node == null) {
        logger.warn("[updateAttributes()] Unable to locate node with id: " + targetId);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("jsonView",
                Collections.singletonMap("error", "Unable to locate node with id: " + targetId));
    } else {
        setObjectAttributes(node, request, attributes);

        final Locale locale = RequestContextUtils.getLocale(request);
        try {
            ulm.saveUserLayout();
        } catch (PortalException e) {
            return handlePersistError(request, response, e);
        }

        Map<String, String> model = Collections.singletonMap("success",
                getMessage("success.element.update", "Updated element attributes", locale));
        return new ModelAndView("jsonView", model);
    }
}