use of org.apereo.portal.portlet.om.IPortletDefinition in project uPortal by Jasig.
the class RDBMDistributedLayoutStore method importLayout.
@Override
@SuppressWarnings("unchecked")
@Transactional
public void importLayout(org.dom4j.Element layout) {
if (layout.getNamespaceForPrefix("dlm") == null) {
layout.add(new Namespace("dlm", Constants.NS_URI));
}
// Remove comments from the DOM they break import
final List<org.dom4j.Node> comments = layout.selectNodes("//comment()");
for (final org.dom4j.Node comment : comments) {
comment.detach();
}
// Get a ref to the prefs element and then remove it from the layout
final org.dom4j.Node preferencesElement = layout.selectSingleNode("preferences");
if (preferencesElement != null) {
preferencesElement.getParent().remove(preferencesElement);
}
final String ownerUsername = layout.valueOf("@username");
// Get a ref to the profile element and then remove it from the layout
final org.dom4j.Node profileElement = layout.selectSingleNode("profile");
if (profileElement != null) {
profileElement.getParent().remove(profileElement);
final org.dom4j.Document profileDocument = new org.dom4j.DocumentFactory().createDocument();
profileDocument.setRootElement((org.dom4j.Element) profileElement);
profileDocument.setName(ownerUsername + ".profile");
final DocumentSource profileSource = new DocumentSource(profileElement);
this.portalDataHandlerService.importData(profileSource);
}
final IPerson person = new PersonImpl();
person.setUserName(ownerUsername);
int ownerId;
try {
// Can't just pass true for create here, if the user actually exists the create flag
// also updates the user data
ownerId = this.userIdentityStore.getPortalUID(person);
} catch (final AuthorizationException t) {
if (this.errorOnMissingUser) {
throw new RuntimeException("Unrecognized user " + person.getUserName() + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.", t);
}
// Create the missing user
ownerId = this.userIdentityStore.getPortalUID(person, true);
}
if (ownerId == -1) {
throw new RuntimeException("Unrecognized user " + person.getUserName() + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.");
}
person.setID(ownerId);
IUserProfile profile = null;
try {
person.setSecurityContext(new BrokenSecurityContext());
profile = this.getUserProfileByFname(person, "default");
} catch (final Throwable t) {
throw new RuntimeException("Failed to load profile for " + person.getUserName() + "; This user must have a profile for import to continue.", t);
}
// (6) Add database Ids & (5) Add dlm:plfID ...
int nextId = 1;
for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("folder | dlm:* | channel").iterator(); it.hasNext(); ) {
nextId = this.addIdAttributesIfNecessary(it.next(), nextId);
}
// Now update UP_USER...
this.jdbcOperations.update("UPDATE up_user SET next_struct_id = ? WHERE user_id = ?", nextId, person.getID());
// (4) Convert external DLM pathrefs to internal form (noderefs)...
for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//@dlm:origin").iterator(); itr.hasNext(); ) {
final org.dom4j.Attribute a = itr.next();
final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null, true, layout);
if (dlmNoderef != null) {
// Change the value only if we have a valid pathref...
a.setValue(dlmNoderef.toString());
// For dlm:origin only, also use the noderef as the ID attribute...
a.getParent().addAttribute("ID", dlmNoderef.toString());
} else {
// At least insure the value is between 1 and 35 characters
a.setValue(BAD_PATHREF_MESSAGE);
}
}
for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//@dlm:target").iterator(); itr.hasNext(); ) {
final org.dom4j.Attribute a = itr.next();
final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null, true, layout);
// Put in the correct value, or at least insure the value is between 1 and 35 characters
a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
}
for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//dlm:*/@name").iterator(); names.hasNext(); ) {
final org.dom4j.Attribute a = names.next();
final String value = a.getValue().trim();
if (!VALID_PATHREF_PATTERN.matcher(value).matches()) {
/* Don't send it to getDlmNoderef if we know in advance it's not
* going to work; saves annoying/misleading log messages and
* possibly some processing. NOTE this is _only_ a problem with
* the name attribute of some dlm:* elements, which seems to go
* unused intentionally in some circumstances
*/
continue;
}
final org.dom4j.Attribute fname = a.getParent().attribute("fname");
Noderef dlmNoderef = null;
if (fname != null) {
dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, fname.getValue(), false, layout);
// Remove the fname attribute now that we're done w/ it...
fname.getParent().remove(fname);
} else {
dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, null, true, layout);
}
// Put in the correct value, or at least insure the value is between 1 and 35 characters
a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
}
// (3) Restore chanID attributes on <channel> elements...
for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("//channel").iterator(); it.hasNext(); ) {
final org.dom4j.Element c = it.next();
final String fname = c.valueOf("@fname");
final IPortletDefinition cd = this.portletDefinitionRegistry.getPortletDefinitionByFname(fname);
if (cd == null) {
final String msg = "No portlet with fname=" + fname + " exists referenced by node " + c.valueOf("@ID") + " from layout for " + ownerUsername;
if (errorOnMissingPortlet) {
throw new IllegalArgumentException(msg);
} else {
logger.warn(msg);
// Remove the bad channel node
c.getParent().remove(c);
}
} else {
c.addAttribute("chanID", String.valueOf(cd.getPortletDefinitionId().getStringId()));
}
}
// (2) Restore locale info...
// (This step doesn't appear to be needed for imports)
// (1) Process structure & theme attributes...
Document layoutDom = null;
try {
final int structureStylesheetId = profile.getStructureStylesheetId();
this.loadStylesheetUserPreferencesAttributes(person, profile, layout, structureStylesheetId, "structure");
final int themeStylesheetId = profile.getThemeStylesheetId();
this.loadStylesheetUserPreferencesAttributes(person, profile, layout, themeStylesheetId, "theme");
// From this point forward we need the user's PLF set as DLM expects it...
for (final Iterator<org.dom4j.Text> it = (Iterator<org.dom4j.Text>) layout.selectNodes("descendant::text()").iterator(); it.hasNext(); ) {
// How many years have we used Java & XML, and this still isn't easy?
final org.dom4j.Text txt = it.next();
if (txt.getText().trim().length() == 0) {
txt.getParent().remove(txt);
}
}
final org.dom4j.Element copy = layout.createCopy();
final org.dom4j.Document doc = this.fac.createDocument(copy);
doc.normalize();
layoutDom = this.writer.get().write(doc);
person.setAttribute(Constants.PLF, layoutDom);
} catch (final Throwable t) {
throw new RuntimeException("Unable to set UserPreferences for user: " + person.getUserName(), t);
}
// Finally store the layout...
try {
this.setUserLayout(person, profile, layoutDom, true, true);
} catch (final Throwable t) {
final String msg = "Unable to persist layout for user: " + ownerUsername;
throw new RuntimeException(msg, t);
}
if (preferencesElement != null) {
final int ownerUserId = this.userIdentityStore.getPortalUserId(ownerUsername);
// TODO this assumes a single layout, when multi-layout support exists portlet entities
// will need to be re-worked to allow for a layout id to be associated with the entity
// track which entities from the user's pre-existing set are touched (all non-touched
// entities will be removed)
final Set<IPortletEntity> oldPortletEntities = new LinkedHashSet<>(this.portletEntityDao.getPortletEntitiesForUser(ownerUserId));
final List<org.dom4j.Element> entries = preferencesElement.selectNodes("entry");
for (final org.dom4j.Element entry : entries) {
final String dlmPathRef = entry.attributeValue("entity");
final String fname = entry.attributeValue("channel");
final String prefName = entry.attributeValue("name");
final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(person.getUserName(), dlmPathRef, fname, false, layout);
if (dlmNoderef != null && fname != null) {
final IPortletEntity portletEntity = this.getPortletEntity(fname, dlmNoderef.toString(), ownerUserId);
oldPortletEntities.remove(portletEntity);
final List<IPortletPreference> portletPreferences = portletEntity.getPortletPreferences();
final List<org.dom4j.Element> valueElements = entry.selectNodes("value");
final List<String> values = new ArrayList<>(valueElements.size());
for (final org.dom4j.Element valueElement : valueElements) {
values.add(valueElement.getText());
}
portletPreferences.add(new PortletPreferenceImpl(prefName, false, values.toArray(new String[values.size()])));
this.portletEntityDao.updatePortletEntity(portletEntity);
}
}
// Delete all portlet preferences for entities that were not imported
for (final IPortletEntity portletEntity : oldPortletEntities) {
portletEntity.setPortletPreferences(null);
if (portletEntityRegistry.shouldBePersisted(portletEntity)) {
this.portletEntityDao.updatePortletEntity(portletEntity);
} else {
this.portletEntityDao.deletePortletEntity(portletEntity);
}
}
}
}
use of org.apereo.portal.portlet.om.IPortletDefinition in project uPortal by Jasig.
the class MarketplacePortletDefinition method initRelatedPortlets.
/**
* Initialize related portlets. This must be called lazily so that MarketplacePortletDefinitions
* instantiated as related portlets off of a MarketplacePortletDefinition do not always
* instantiate their related MarketplacePortletDefinitions, ad infinitem.
*/
private void initRelatedPortlets() {
final Set<MarketplacePortletDefinition> allRelatedPortlets = new HashSet<>();
for (PortletCategory parentCategory : this.portletCategoryRegistry.getParentCategories(this)) {
final Set<IPortletDefinition> portletsInCategory = this.portletCategoryRegistry.getAllChildPortlets(parentCategory);
for (IPortletDefinition portletDefinition : portletsInCategory) {
allRelatedPortlets.add(new MarketplacePortletDefinition(portletDefinition, this.marketplaceService, this.portletCategoryRegistry));
}
}
allRelatedPortlets.remove(this);
this.relatedPortlets = allRelatedPortlets;
}
use of org.apereo.portal.portlet.om.IPortletDefinition in project uPortal by Jasig.
the class PortletMarketplaceController method entryView.
@RenderMapping(params = "action=view")
public String entryView(RenderRequest renderRequest, RenderResponse renderResponse, WebRequest webRequest, PortletRequest portletRequest, Model model) {
IPortletDefinition result = this.portletDefinitionRegistry.getPortletDefinitionByFname(portletRequest.getParameter("fName"));
if (result == null) {
this.setUpInitialView(webRequest, portletRequest, model, null);
return "jsp/Marketplace/portlet/view";
}
final HttpServletRequest servletRequest = this.portalRequestUtils.getPortletHttpRequest(portletRequest);
final IPerson user = personManager.getPerson(servletRequest);
final IAuthorizationPrincipal principal = AuthorizationPrincipalHelper.principalFromUser(user);
if (!this.marketplaceService.mayBrowsePortlet(principal, result)) {
// TODO: provide an error experience
// currently at least blocks rendering the entry for the portlet the user is not
// authorized to see.
this.setUpInitialView(webRequest, portletRequest, model, null);
return "jsp/Marketplace/portlet/view";
}
MarketplacePortletDefinition mpDefinition = marketplaceService.getOrCreateMarketplacePortletDefinition(result);
IMarketplaceRating tempRatingImpl = marketplaceRatingDAO.getRating(portletRequest.getRemoteUser(), portletDefinitionDao.getPortletDefinitionByFname(result.getFName()));
final MarketplaceEntry marketplaceEntry = new MarketplaceEntry(mpDefinition, user);
model.addAttribute("marketplaceRating", tempRatingImpl);
model.addAttribute("reviewMaxLength", IMarketplaceRating.REVIEW_MAX_LENGTH);
model.addAttribute("marketplaceEntry", marketplaceEntry);
model.addAttribute("shortURL", mpDefinition.getShortURL());
// User allowed to favorite this portlet?
final String targetString = PermissionHelper.permissionTargetIdForPortletDefinition(mpDefinition);
final boolean canFavorite = principal.hasPermission(IPermission.PORTAL_SYSTEM, IPermission.PORTLET_FAVORITE_ACTIVITY, targetString);
model.addAttribute("canFavorite", canFavorite);
// Reviews feature enabled?
final PortletPreferences prefs = renderRequest.getPreferences();
final String enableReviewsPreferenceValue = prefs.getValue(ENABLE_REVIEWS_PREFERENCE, ENABLE_REVIEWS_DEFAULT);
model.addAttribute("enableReviews", Boolean.valueOf(enableReviewsPreferenceValue));
return "jsp/Marketplace/portlet/entry";
}
use of org.apereo.portal.portlet.om.IPortletDefinition in project uPortal by Jasig.
the class PortletAdministrationHelper method savePortletRegistration.
/**
* Persist a new or edited PortletDefinition from a form, replacing existing values.
*
* @param publisher {@code IPerson} that requires permission to save this definition
* @param form form data to persist
* @return new {@code PortletDefinitionForm} for this portlet ID
*/
public PortletDefinitionForm savePortletRegistration(IPerson publisher, PortletDefinitionForm form) throws Exception {
logger.trace("In savePortletRegistration() - for: {}", form.getPortletName());
// is made when the user enters the lifecycle-selection step in the wizard.)
if (!hasLifecyclePermission(publisher, form.getLifecycleState(), form.getCategories())) {
logger.warn("User '" + publisher.getUserName() + "' attempted to save the following portlet without the selected MANAGE permission: " + form);
throw new SecurityException("Not Authorized");
}
if (!form.isNew()) {
// User must have the previous lifecycle permission
// in AT LEAST ONE previous category as well
IPortletDefinition def = this.portletDefinitionRegistry.getPortletDefinition(form.getId());
Set<PortletCategory> categories = portletCategoryRegistry.getParentCategories(def);
SortedSet<JsonEntityBean> categoryBeans = new TreeSet<>();
for (PortletCategory cat : categories) {
categoryBeans.add(new JsonEntityBean(cat));
}
if (!hasLifecyclePermission(publisher, def.getLifecycleState(), categoryBeans)) {
logger.warn("User '" + publisher.getUserName() + "' attempted to save the following portlet without the previous MANAGE permission: " + form);
throw new SecurityException("Not Authorized");
}
}
if (form.isNew() || portletDefinitionRegistry.getPortletDefinition(form.getId()).getType().getId() != form.getTypeId()) {
// User must have access to the selected CPD if s/he selected it in this interaction
final int selectedTypeId = form.getTypeId();
final PortletPublishingDefinition cpd = portletPublishingDefinitionDao.getChannelPublishingDefinition(selectedTypeId);
final Map<IPortletType, PortletPublishingDefinition> allowableCpds = this.getAllowableChannelPublishingDefinitions(publisher);
if (!allowableCpds.containsValue(cpd)) {
logger.warn("User '" + publisher.getUserName() + "' attempted to administer the following portlet without the selected " + IPermission.PORTLET_MANAGER_SELECT_PORTLET_TYPE + " permission: " + form);
throw new SecurityException("Not Authorized");
}
}
// create the principal array from the form's principal list -- only principals with
// permissions
final Set<IGroupMember> subscribePrincipalSet = new HashSet<>(form.getPrincipals().size());
final Set<IGroupMember> browsePrincipalSet = new HashSet<>(form.getPrincipals().size());
final Set<IGroupMember> configurePrincipalSet = new HashSet<>(form.getPrincipals().size());
for (JsonEntityBean bean : form.getPrincipals()) {
final String subscribePerm = bean.getTypeAndIdHash() + "_" + IPermission.PORTLET_SUBSCRIBER_ACTIVITY;
final String browsePerm = bean.getTypeAndIdHash() + "_" + IPermission.PORTLET_BROWSE_ACTIVITY;
final String configurePerm = bean.getTypeAndIdHash() + "_" + IPermission.PORTLET_MODE_CONFIG;
final EntityEnum entityEnum = bean.getEntityType();
final IGroupMember principal = entityEnum.isGroup() ? (GroupService.findGroup(bean.getId())) : (GroupService.getGroupMember(bean.getId(), entityEnum.getClazz()));
if (form.getPermissions().contains(subscribePerm)) {
logger.info("In savePortletRegistration() - Found a subscribePerm for principal: {}", principal);
subscribePrincipalSet.add(principal);
}
if (form.getPermissions().contains(browsePerm)) {
logger.info("In savePortletRegistration() - Found a browsePerm for principal: {}", principal);
browsePrincipalSet.add(principal);
}
if (form.getPermissions().contains(configurePerm)) {
logger.info("In savePortletRegistration() - Found a configurePerm for principal: {}", principal);
configurePrincipalSet.add(principal);
}
}
// create the category list from the form's category bean list
List<PortletCategory> categories = new ArrayList<>();
for (JsonEntityBean category : form.getCategories()) {
String id = category.getId();
String iCatID = id.startsWith("cat") ? id.substring(3) : id;
categories.add(portletCategoryRegistry.getPortletCategory(iCatID));
}
final IPortletType portletType = portletTypeRegistry.getPortletType(form.getTypeId());
if (portletType == null) {
throw new IllegalArgumentException("No IPortletType exists for ID " + form.getTypeId());
}
IPortletDefinition portletDef;
if (form.getId() == null) {
portletDef = new PortletDefinitionImpl(portletType, form.getFname(), form.getName(), form.getTitle(), form.getApplicationId(), form.getPortletName(), form.isFramework());
} else {
portletDef = portletDefinitionRegistry.getPortletDefinition(form.getId());
portletDef.setType(portletType);
portletDef.setFName(form.getFname());
portletDef.setName(form.getName());
portletDef.setTitle(form.getTitle());
portletDef.getPortletDescriptorKey().setWebAppName(form.getApplicationId());
portletDef.getPortletDescriptorKey().setPortletName(form.getPortletName());
portletDef.getPortletDescriptorKey().setFrameworkPortlet(form.isFramework());
}
portletDef.setDescription(form.getDescription());
portletDef.setTimeout(form.getTimeout());
// portletDef reflect the state of the form, in case any have changed.
for (String key : form.getParameters().keySet()) {
String value = form.getParameters().get(key).getValue();
if (!StringUtils.isBlank(value)) {
portletDef.addParameter(key, value);
}
}
portletDef.addParameter(IPortletDefinition.EDITABLE_PARAM, Boolean.toString(form.isEditable()));
portletDef.addParameter(IPortletDefinition.CONFIGURABLE_PARAM, Boolean.toString(form.isConfigurable()));
portletDef.addParameter(IPortletDefinition.HAS_HELP_PARAM, Boolean.toString(form.isHasHelp()));
portletDef.addParameter(IPortletDefinition.HAS_ABOUT_PARAM, Boolean.toString(form.isHasAbout()));
// Now add portlet preferences
List<IPortletPreference> preferenceList = new ArrayList<>();
for (String key : form.getPortletPreferences().keySet()) {
List<String> prefValues = form.getPortletPreferences().get(key).getValue();
if (prefValues != null && prefValues.size() > 0) {
String[] values = prefValues.toArray(new String[prefValues.size()]);
BooleanAttribute readOnly = form.getPortletPreferenceReadOnly().get(key);
preferenceList.add(new PortletPreferenceImpl(key, readOnly.getValue(), values));
}
}
portletDef.setPortletPreferences(preferenceList);
// Lastly update the PortletDefinition's lifecycle state & lifecycle-related metadata
updateLifecycleState(form, portletDef, publisher);
// The final parameter of IGroupMembers is used to set the initial SUBSCRIBE permission set
portletPublishingService.savePortletDefinition(portletDef, publisher, categories, new ArrayList<>(subscribePrincipalSet));
// updatePermissions(portletDef, subscribePrincipalSet,
// IPermission.PORTLET_SUBSCRIBER_ACTIVITY);
updatePermissions(portletDef, browsePrincipalSet, IPermission.PORTAL_SUBSCRIBE, IPermission.PORTLET_BROWSE_ACTIVITY);
updatePermissions(portletDef, configurePrincipalSet, IPermission.PORTAL_PUBLISH, IPermission.PORTLET_MODE_CONFIG);
return this.createPortletDefinitionForm(publisher, portletDef.getPortletDefinitionId().getStringId());
}
use of org.apereo.portal.portlet.om.IPortletDefinition in project uPortal by Jasig.
the class PortletAdministrationHelper method removePortletRegistration.
/**
* Delete the portlet with the given portlet ID.
*
* @param person the person removing the portlet
* @param form
*/
public void removePortletRegistration(IPerson person, PortletDefinitionForm form) {
// (They're hierarchical.)
if (!hasLifecyclePermission(person, form.getLifecycleState(), form.getCategories())) {
logger.warn("User '" + person.getUserName() + "' attempted to remove portlet '" + form.getFname() + "' without the proper MANAGE permission");
throw new SecurityException("Not Authorized");
}
IPortletDefinition def = portletDefinitionRegistry.getPortletDefinition(form.getId());
/*
* It's very important to remove portlets via the portletPublishingService
* because that API cleans up details like category memberships and permissions.
*/
portletPublishingService.removePortletDefinition(def, person);
}
Aggregations