use of org.apereo.portal.layout.IUserLayoutManager in project uPortal by Jasig.
the class UpdatePreferencesServlet method removeByFName.
/**
* Remove the first element with the provided fname from the layout.
*
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param fname fname of the portlet to remove from the layout
* @return json response
* @throws IOException if the person cannot be retrieved
*/
@RequestMapping(method = RequestMethod.POST, params = "action=removeByFName")
public ModelAndView removeByFName(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fname") String fname) throws IOException {
IUserInstance ui = userInstanceManager.getUserInstance(request);
UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
IUserLayoutManager ulm = upm.getUserLayoutManager();
try {
String elementId = ulm.getUserLayout().findNodeId(new PortletSubscribeIdResolver(fname));
if (elementId != null) {
// 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.setStatus(HttpServletResponse.SC_FORBIDDEN);
return new ModelAndView("jsonView", Collections.singletonMap("error", getMessage("error.element.update", "Unable to update element", RequestContextUtils.getLocale(request))));
}
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return null;
}
ulm.saveUserLayout();
return new ModelAndView("jsonView", Collections.emptyMap());
} catch (PortalException e) {
return handlePersistError(request, response, e);
}
}
use of org.apereo.portal.layout.IUserLayoutManager in project uPortal by Jasig.
the class UpdatePreferencesServlet method addTab.
/**
* Add a new tab to the layout. The new tab will be appended to the end of the list and named
* with the BLANK_TAB_NAME variable.
*
* @param request
* @throws IOException
*/
@RequestMapping(method = RequestMethod.POST, params = "action=addTab")
public ModelAndView addTab(HttpServletRequest request, HttpServletResponse response, @RequestParam("widths[]") String[] widths) throws IOException {
IUserInstance ui = userInstanceManager.getUserInstance(request);
IPerson person = getPerson(ui, response);
UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
IUserLayoutManager ulm = upm.getUserLayoutManager();
// Verify that the user has permission to add this tab
final IAuthorizationPrincipal authPrincipal = this.getUserPrincipal(person.getUserName());
if (!authPrincipal.hasPermission(IPermission.PORTAL_SYSTEM, IPermission.ADD_TAB_ACTIVITY, IPermission.ALL_TARGET)) {
logger.warn("Attempt to add a tab through the REST API by unauthorized user '" + person.getUserName() + "'");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return new ModelAndView("jsonView", Collections.singletonMap("error", "Add tab disabled"));
}
// construct a brand new tab
String id = "tbd";
String tabName = request.getParameter("tabName");
if (StringUtils.isBlank(tabName))
tabName = DEFAULT_TAB_NAME;
IUserLayoutFolderDescription newTab = new UserLayoutFolderDescription();
newTab.setName(tabName);
newTab.setId(id);
newTab.setFolderType(IUserLayoutFolderDescription.REGULAR_TYPE);
newTab.setHidden(false);
newTab.setUnremovable(false);
newTab.setImmutable(false);
// add the tab to the layout
ulm.addNode(newTab, ulm.getRootFolderId(), null);
try {
// save the user's layout
ulm.saveUserLayout();
} catch (PortalException e) {
return handlePersistError(request, response, e);
}
// get the id of the newly added tab
String tabId = newTab.getId();
for (String width : widths) {
// create new column element
IUserLayoutFolderDescription newColumn = new UserLayoutFolderDescription();
newColumn.setName("Column");
newColumn.setId("tbd");
newColumn.setFolderType(IUserLayoutFolderDescription.REGULAR_TYPE);
newColumn.setHidden(false);
newColumn.setUnremovable(false);
newColumn.setImmutable(false);
// add the column to our layout
ulm.addNode(newColumn, tabId, null);
this.stylesheetUserPreferencesService.setLayoutAttribute(request, PreferencesScope.STRUCTURE, newColumn.getId(), CLASSIC_COLUMNS_WIDTH_USER_PREFERENCE_NAME, width + "%");
try {
// This sets the column attribute in memory but doesn't persist it. Comment says
// saves changes "prior to persisting"
Element folder = ulm.getUserLayoutDOM().getElementById(newColumn.getId());
UserPrefsHandler.setUserPreference(folder, CLASSIC_COLUMNS_WIDTH_USER_PREFERENCE_NAME, person);
} catch (Exception e) {
logger.error("Error saving new column widths", e);
}
}
// this new tab; use the currently active tabGroup.
if (request.getParameter(TAB_GROUP_PARAMETER) != null) {
String tabGroup = request.getParameter(TAB_GROUP_PARAMETER).trim();
if (logger.isDebugEnabled()) {
logger.debug(TAB_GROUP_PARAMETER + "=" + tabGroup);
}
if (!TAB_GROUP_DEFAULT.equals(tabGroup) && tabGroup.length() != 0) {
// Persists SSUP values to the database
this.stylesheetUserPreferencesService.setLayoutAttribute(request, PreferencesScope.STRUCTURE, tabId, TAB_GROUP_PARAMETER, tabGroup);
}
}
try {
// save the user's layout
ulm.saveUserLayout();
} catch (PortalException e) {
return handlePersistError(request, response, e);
}
return new ModelAndView("jsonView", Collections.singletonMap("tabId", tabId));
}
use of org.apereo.portal.layout.IUserLayoutManager in project uPortal by Jasig.
the class UpdatePreferencesServlet method updateAttributes.
/**
* Update the attributes for the node. Unrecognized attributes will log a warning, but are
* otherwise ignored.
*
* @param request
* @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);
}
}
use of org.apereo.portal.layout.IUserLayoutManager in project uPortal by Jasig.
the class FavoritesController method initializeView.
/**
* Handles all Favorites portlet VIEW mode renders. Populates model with user's favorites and
* selects a view to display those favorites.
*
* <p>View selection:
*
* <p>Returns "jsp/Favorites/view" in the normal case where the user has at least one favorited
* portlet or favorited collection.
*
* <p>Returns "jsp/Favorites/view_zero" in the edge case where the user has zero favorited
* portlets AND zero favorited collections.
*
* <p>Model: marketPlaceFname --> String functional name of Marketplace portlet, or null if not
* available. collections --> List of favorited collections (IUserLayoutNodeDescription s)
* favorites --> List of favorited individual portlets (IUserLayoutNodeDescription s)
*
* @param model . Spring model. This method adds three model attributes.
* @return jsp/Favorites/view[_zero]
*/
@RenderMapping
public String initializeView(PortletRequest req, Model model) {
final IUserInstance ui = userInstanceManager.getUserInstance(portalRequestUtils.getCurrentPortalRequest());
final UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
final IUserLayoutManager ulm = upm.getUserLayoutManager();
final IUserLayout userLayout = ulm.getUserLayout();
// TODO: the portlet could predicate including a non-null marketplace portlet fname
// on the accessing user having permission to render the portlet referenced by that fname
// so that portlet would gracefully degrade when configured with bad marketplace portlet
// fname
// and also gracefully degrade when the accessing user doesn't have permission to access an
// otherwise
// viable configured marketplace. This complexity may not be worth it. Anyway it is not
// yet implemented.
model.addAttribute("marketplaceFname", this.marketplaceFName);
final List<IUserLayoutNodeDescription> collections = FavoritesUtils.getFavoriteCollections(userLayout);
model.addAttribute("collections", collections);
final List<IUserLayoutNodeDescription> rawFavorites = FavoritesUtils.getFavoritePortlets(userLayout);
/*
* Filter the collection by SUBSCRIBE permission.
*
* NOTE: In the "regular" (non-Favorites) layout, this permissions check is handled by
* the rendering engine. It will refuse to spawn a worker for a portlet to which you
* cannot SUBSCRIBE.
*/
final String username = req.getRemoteUser() != null ? req.getRemoteUser() : // First item is the default
PersonFactory.getGuestUsernames().get(0);
final IAuthorizationPrincipal principal = authorizationService.newPrincipal(username, IPerson.class);
final List<IUserLayoutNodeDescription> favorites = new ArrayList<>();
for (IUserLayoutNodeDescription nodeDescription : rawFavorites) {
if (nodeDescription instanceof IUserLayoutChannelDescription) {
final IUserLayoutChannelDescription channelDescription = (IUserLayoutChannelDescription) nodeDescription;
if (principal.canRender(channelDescription.getChannelPublishId())) {
favorites.add(nodeDescription);
}
}
}
model.addAttribute("favorites", favorites);
// default to the regular old view
String viewName = "jsp/Favorites/view";
if (collections.isEmpty() && favorites.isEmpty()) {
// special edge case of zero favorites, switch to special view
viewName = "jsp/Favorites/view_zero";
}
logger.debug("Favorites Portlet VIEW mode render populated model [{}] for render by view {}.", model, viewName);
return viewName;
}
use of org.apereo.portal.layout.IUserLayoutManager in project uPortal by Jasig.
the class FavoritesEditController method unFavoriteNode.
/**
* Un-favorite a favorite node (portlet or collection) identified by node ID. Routed by the
* action=delete parameter. If no favorites remain after un-favoriting, switches portlet mode to
* VIEW.
*
* <p>Sets render parameters: successMessageCode: message code of success message if applicable
* errorMessageCode: message code of error message if applicable nameOfFavoriteActedUpon:
* user-facing name of favorite acted upon. action: will be set to "list" to facilitate not
* repeatedly attempting delete.
*
* <p>Exactly one of [successMessageCode|errorMessageCode] render parameters will be set.
* nameOfFavoriteActedUpon and action will always be set.
*
* @param nodeId identifier of target node
* @param response ActionResponse onto which render parameters will, mode may, be set
*/
@ActionMapping(params = { "action=delete" })
public void unFavoriteNode(@RequestParam("nodeId") String nodeId, ActionResponse response) {
try {
// ferret out the layout manager
HttpServletRequest servletRequest = this.portalRequestUtils.getCurrentPortalRequest();
IUserInstance userInstance = this.userInstanceManager.getUserInstance(servletRequest);
IUserPreferencesManager preferencesManager = userInstance.getPreferencesManager();
IUserLayoutManager layoutManager = preferencesManager.getUserLayoutManager();
IUserLayoutNodeDescription nodeDescription = layoutManager.getNode(nodeId);
String userFacingNodeName = nodeDescription.getName();
response.setRenderParameter("nameOfFavoriteActedUpon", userFacingNodeName);
if (nodeDescription.isDeleteAllowed()) {
boolean nodeSuccessfullyDeleted = layoutManager.deleteNode(nodeId);
if (nodeSuccessfullyDeleted) {
layoutManager.saveUserLayout();
response.setRenderParameter("successMessageCode", "favorites.unfavorite.success.parameterized");
IUserLayout updatedLayout = layoutManager.getUserLayout();
// if removed last favorite, return to VIEW mode
if (!FavoritesUtils.hasAnyFavorites(updatedLayout)) {
response.setPortletMode(PortletMode.VIEW);
}
logger.debug("Successfully unfavorited [{}]", nodeDescription);
} else {
logger.error("Failed to delete node [{}] on unfavorite request, but this should have succeeded?", nodeDescription);
response.setRenderParameter("errorMessageCode", "favorites.unfavorite.fail.parameterized");
}
} else {
logger.warn("Attempt to unfavorite [{}] failed because user lacks permission to delete that layout node.", nodeDescription);
response.setRenderParameter("errorMessageCode", "favorites.unfavorite.fail.lack.permission.parameterized");
}
} catch (Exception e) {
// TODO: this log message is kind of useless without the username to put the node in
// context
logger.error("Something went wrong unfavoriting nodeId [{}].", nodeId);
// may have failed to load node description, so fall back on describing by id
final String fallbackUserFacingNodeName = "node with id " + nodeId;
response.setRenderParameter("errorMessageCode", "favorites.unfavorite.fail.parameterized");
response.setRenderParameter("nameOfFavoriteActedUpon", fallbackUserFacingNodeName);
}
response.setRenderParameter("action", "list");
}
Aggregations