Search in sources :

Example 26 with IPortletEntity

use of org.apereo.portal.portlet.om.IPortletEntity in project uPortal by Jasig.

the class PortalEventFactoryImpl method createPortletExecutionEventBuilder.

protected PortletExecutionEvent.PortletExecutionEventBuilder createPortletExecutionEventBuilder(PortalEvent.PortalEventBuilder portalEventBuilder, IPortletWindowId portletWindowId, long executionTimeNano, boolean renderRequest) {
    final HttpServletRequest portalRequest = portalEventBuilder.getPortalRequest();
    //Get the portlet's fname
    final IPortletWindow portletWindow = this.portletWindowRegistry.getPortletWindow(portalRequest, portletWindowId);
    final IPortletEntity portletEntity = portletWindow.getPortletEntity();
    final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition();
    final String fname = portletDefinition.getFName();
    //Get the parameters used for the portlet execution
    final Map<String, List<String>> parameters = getParameters(portalRequest, portletWindowId, renderRequest);
    //Get the state & mode used for this request
    final WindowState windowState = portletWindow.getWindowState();
    final PortletMode portletMode = portletWindow.getPortletMode();
    return new PortletExecutionEvent.PortletExecutionEventBuilder(portalEventBuilder, portletWindowId, fname, executionTimeNano, parameters, windowState, portletMode);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) WindowState(javax.portlet.WindowState) IPortletEntity(org.apereo.portal.portlet.om.IPortletEntity) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) IPortletWindow(org.apereo.portal.portlet.om.IPortletWindow) PortletMode(javax.portlet.PortletMode) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition)

Example 27 with IPortletEntity

use of org.apereo.portal.portlet.om.IPortletEntity 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<IPortletEntity>(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<String>(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);
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) IPortletPreference(org.apereo.portal.portlet.om.IPortletPreference) AuthorizationException(org.apereo.portal.AuthorizationException) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) IPerson(org.apereo.portal.security.IPerson) IPortletEntity(org.apereo.portal.portlet.om.IPortletEntity) Iterator(java.util.Iterator) PortletPreferenceImpl(org.apereo.portal.portlet.dao.jpa.PortletPreferenceImpl) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition) Namespace(org.dom4j.Namespace) PersonImpl(org.apereo.portal.security.provider.PersonImpl) DocumentSource(org.dom4j.io.DocumentSource) IUserProfile(org.apereo.portal.IUserProfile) BrokenSecurityContext(org.apereo.portal.security.provider.BrokenSecurityContext) Transactional(org.springframework.transaction.annotation.Transactional)

Example 28 with IPortletEntity

use of org.apereo.portal.portlet.om.IPortletEntity in project uPortal by Jasig.

the class RDBMDistributedLayoutStore method getPortletEntity.

private IPortletEntity getPortletEntity(String fName, String layoutNodeId, int userId) {
    //Try getting the entity
    final IPortletEntity portletEntity = this.portletEntityDao.getPortletEntity(layoutNodeId, userId);
    if (portletEntity != null) {
        return portletEntity;
    }
    //Load the portlet definition
    final IPortletDefinition portletDefinition;
    try {
        portletDefinition = this.portletDefinitionRegistry.getPortletDefinitionByFname(fName);
    } catch (Exception e) {
        throw new DataRetrievalFailureException("Failed to retrieve ChannelDefinition for fName='" + fName + "'", e);
    }
    //The channel definition for the fName MUST exist for this class to function
    if (portletDefinition == null) {
        throw new EmptyResultDataAccessException("No ChannelDefinition exists for fName='" + fName + "'", 1);
    }
    //create the portlet entity
    final IPortletDefinitionId portletDefinitionId = portletDefinition.getPortletDefinitionId();
    return this.portletEntityDao.createPortletEntity(portletDefinitionId, layoutNodeId, userId);
}
Also used : IPortletDefinitionId(org.apereo.portal.portlet.om.IPortletDefinitionId) IPortletEntity(org.apereo.portal.portlet.om.IPortletEntity) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) PortalException(org.apereo.portal.PortalException) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) SQLException(java.sql.SQLException) AuthorizationException(org.apereo.portal.AuthorizationException) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition)

Example 29 with IPortletEntity

use of org.apereo.portal.portlet.om.IPortletEntity in project uPortal by Jasig.

the class RDBMDistributedLayoutStore method exportLayout.

@Override
public org.dom4j.Element exportLayout(IPerson person, IUserProfile profile) {
    org.dom4j.Element layout = getExportLayoutDom(person, profile);
    final int userId = person.getID();
    final String userName = person.getUserName();
    final Set<IPortletEntity> portletEntities = this.portletEntityDao.getPortletEntitiesForUser(userId);
    org.dom4j.Element preferencesElement = null;
    for (final Iterator<IPortletEntity> entityItr = portletEntities.iterator(); entityItr.hasNext(); ) {
        final IPortletEntity portletEntity = entityItr.next();
        final List<IPortletPreference> preferencesList = portletEntity.getPortletPreferences();
        //Only bother with entities that have preferences
        if (!preferencesList.isEmpty()) {
            final String layoutNodeId = portletEntity.getLayoutNodeId();
            final Pathref dlmPathref = nodeReferenceFactory.getPathrefFromNoderef(userName, layoutNodeId, layout);
            if (dlmPathref == null) {
                logger.warn("{} in user {}'s layout has no corresponding layout or portlet information and will be ignored", portletEntity, userName);
                continue;
            }
            for (final IPortletPreference portletPreference : preferencesList) {
                if (preferencesElement == null) {
                    if (layout == null) {
                        final org.dom4j.Document layoutDoc = new org.dom4j.DocumentFactory().createDocument();
                        layout = layoutDoc.addElement("layout");
                        layout.addNamespace("dlm", Constants.NS_URI);
                    }
                    preferencesElement = layout.addElement("preferences");
                }
                final org.dom4j.Element preferenceEntry = preferencesElement.addElement("entry");
                preferenceEntry.addAttribute("entity", dlmPathref.toString());
                preferenceEntry.addAttribute("channel", dlmPathref.getPortletFname());
                preferenceEntry.addAttribute("name", portletPreference.getName());
                for (final String value : portletPreference.getValues()) {
                    final org.dom4j.Element valueElement = preferenceEntry.addElement("value");
                    if (value != null) {
                        valueElement.setText(value);
                    }
                }
            }
        }
    }
    if (layout != null) {
        layout.addAttribute("script", "classpath://org/jasig/portal/io/import-layout_v3-2.crn");
        layout.addAttribute("username", userName);
    }
    return layout;
}
Also used : IPortletPreference(org.apereo.portal.portlet.om.IPortletPreference) IPortletEntity(org.apereo.portal.portlet.om.IPortletEntity)

Example 30 with IPortletEntity

use of org.apereo.portal.portlet.om.IPortletEntity in project uPortal by Jasig.

the class PortletEntityRegistryImpl method storePortletEntity.

/* (non-Javadoc)
     * @see org.apereo.portal.portlet.registry.IPortletEntityRegistry#storePortletEntity(org.apereo.portal.portlet.om.IPortletEntity)
     */
@Override
public void storePortletEntity(HttpServletRequest request, final IPortletEntity portletEntity) {
    Validate.notNull(portletEntity, "portletEntity can not be null");
    final IUserInstance userInstance = this.userInstanceManager.getUserInstance(request);
    final IPerson person = userInstance.getPerson();
    if (person.isGuest()) {
        //Never persist things for the guest user, just rely on in-memory storage
        return;
    }
    final IPortletEntityId wrapperPortletEntityId = portletEntity.getPortletEntityId();
    final Lock portletEntityLock = this.getPortletEntityLock(request, wrapperPortletEntityId);
    portletEntityLock.lock();
    try {
        final boolean shouldBePersisted = this.shouldBePersisted(portletEntity);
        if (portletEntity instanceof PersistentPortletEntityWrapper) {
            //Unwrap the persistent entity
            final IPortletEntity persistentEntity = ((PersistentPortletEntityWrapper) portletEntity).getPersistentEntity();
            //Already persistent entity that still has prefs
            if (shouldBePersisted) {
                try {
                    this.portletEntityDao.updatePortletEntity(persistentEntity);
                } catch (HibernateOptimisticLockingFailureException e) {
                    //Check if this exception is from the entity being deleted from under us.
                    final boolean exists = this.portletEntityDao.portletEntityExists(persistentEntity.getPortletEntityId());
                    if (!exists) {
                        this.logger.warn("The persistent portlet has already been deleted: " + persistentEntity + ". The passed entity should be persistent so a new persistent entity will be created");
                        this.deletePortletEntity(request, portletEntity, true);
                        this.createPersistentEntity(persistentEntity, wrapperPortletEntityId);
                    } else {
                        throw e;
                    }
                }
            } else //Already persistent entity that should not be, DELETE!
            {
                //Capture identifiers needed to recreate the entity as session persistent
                final IPortletDefinitionId portletDefinitionId = portletEntity.getPortletDefinitionId();
                final String layoutNodeId = portletEntity.getLayoutNodeId();
                final int userId = portletEntity.getUserId();
                //Delete the persistent entity
                this.deletePortletEntity(request, portletEntity, false);
                //Create a new entity and stick it in the cache
                this.getOrCreatePortletEntity(request, portletDefinitionId, layoutNodeId, userId);
            }
        } else if (portletEntity instanceof SessionPortletEntityImpl) {
            //There are preferences on the interim entity, create an store it
            if (shouldBePersisted) {
                //Remove the session scoped entity from the request and session caches
                this.deletePortletEntity(request, portletEntity, false);
                final IPortletEntity persistentEntity = createPersistentEntity(portletEntity, wrapperPortletEntityId);
                if (this.logger.isTraceEnabled()) {
                    this.logger.trace("Session scoped entity " + wrapperPortletEntityId + " should now be persistent. Deleted it from session cache and created persistent portlet entity " + persistentEntity.getPortletEntityId());
                }
            } else //Session scoped entity that is still session scoped,
            {
                //Look for a persistent entity and delete it
                final String channelSubscribeId = portletEntity.getLayoutNodeId();
                final int userId = portletEntity.getUserId();
                IPortletEntity existingPersistentEntity = this.portletEntityDao.getPortletEntity(channelSubscribeId, userId);
                if (existingPersistentEntity != null) {
                    final IPortletEntityId consistentPortletEntityId = this.createConsistentPortletEntityId(existingPersistentEntity);
                    existingPersistentEntity = new PersistentPortletEntityWrapper(existingPersistentEntity, consistentPortletEntityId);
                    this.logger.warn("A persistent portlet entity already exists: " + existingPersistentEntity + ". The passed entity has no preferences so the persistent version will be deleted");
                    this.deletePortletEntity(request, existingPersistentEntity, false);
                    //Add to request cache
                    final PortletEntityCache<IPortletEntity> portletEntityMap = this.getPortletEntityMap(request);
                    portletEntityMap.storeIfAbsentEntity(portletEntity);
                    //Add to session cache
                    final PortletEntityCache<PortletEntityData> portletEntityDataMap = this.getPortletEntityDataMap(request);
                    portletEntityDataMap.storeIfAbsentEntity(((SessionPortletEntityImpl) portletEntity).getPortletEntityData());
                }
            }
        } else {
            throw new IllegalArgumentException("Invalid portlet entity implementation passed: " + portletEntity.getClass());
        }
    } finally {
        portletEntityLock.unlock();
    }
}
Also used : HibernateOptimisticLockingFailureException(org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) IUserInstance(org.apereo.portal.user.IUserInstance) IPortletDefinitionId(org.apereo.portal.portlet.om.IPortletDefinitionId) IPerson(org.apereo.portal.security.IPerson) IPortletEntity(org.apereo.portal.portlet.om.IPortletEntity) IPortletEntityId(org.apereo.portal.portlet.om.IPortletEntityId)

Aggregations

IPortletEntity (org.apereo.portal.portlet.om.IPortletEntity)63 IPortletWindow (org.apereo.portal.portlet.om.IPortletWindow)32 IPortletEntityId (org.apereo.portal.portlet.om.IPortletEntityId)25 IPortletDefinition (org.apereo.portal.portlet.om.IPortletDefinition)24 IPortletDefinitionId (org.apereo.portal.portlet.om.IPortletDefinitionId)19 IUserInstance (org.apereo.portal.user.IUserInstance)12 Test (org.junit.Test)11 IPortletPreference (org.apereo.portal.portlet.om.IPortletPreference)10 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 List (java.util.List)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 PortletPreferenceImpl (org.apereo.portal.portlet.dao.jpa.PortletPreferenceImpl)9 IPortletWindowId (org.apereo.portal.portlet.om.IPortletWindowId)9 BasePortalJpaDaoTest (org.apereo.portal.test.BasePortalJpaDaoTest)9 IPerson (org.apereo.portal.security.IPerson)7 PortletApplicationDefinition (org.apache.pluto.container.om.portlet.PortletApplicationDefinition)5 IUserPreferencesManager (org.apereo.portal.IUserPreferencesManager)5 IUserLayoutManager (org.apereo.portal.layout.IUserLayoutManager)5 ArrayList (java.util.ArrayList)4 Callable (java.util.concurrent.Callable)4