Search in sources :

Example 26 with IEntityGroup

use of org.apereo.portal.groups.IEntityGroup in project uPortal by Jasig.

the class PortletDefinitionImporterExporter method savePortletDefinition.

/**
     * Save a portlet definition.
     *
     * @param definition the portlet definition
     * @param publisher the person publishing the portlet
     * @param categories the list of categories for the portlet
     * @param permissionMap a map of permission name -> list of groups who are granted that
     *     permission (Note: for now, only grant is supported and only for the FRAMEWORK_OWNER perm
     *     manager)
     */
private IPortletDefinition savePortletDefinition(IPortletDefinition definition, IPerson publisher, List<PortletCategory> categories, Map<ExternalPermissionDefinition, Set<IGroupMember>> permissionMap) {
    boolean newChannel = (definition.getPortletDefinitionId() == null);
    // save the channel
    definition = portletDefinitionDao.savePortletDefinition(definition);
    definition = portletDefinitionDao.getPortletDefinitionByFname(definition.getFName());
    final String defId = definition.getPortletDefinitionId().getStringId();
    final IEntity portletDefEntity = GroupService.getEntity(defId, IPortletDefinition.class);
    //The groups service needs to deal with concurrent modification better.
    synchronized (this.groupUpdateLock) {
        // Delete existing category memberships for this channel
        if (!newChannel) {
            for (IEntityGroup group : portletDefEntity.getAncestorGroups()) {
                group.removeChild(portletDefEntity);
                group.update();
            }
        }
        // For each category ID, add channel to category
        for (PortletCategory category : categories) {
            final IEntityGroup categoryGroup = GroupService.findGroup(category.getId());
            categoryGroup.addChild(portletDefEntity);
            categoryGroup.updateMembers();
        }
        // Set groups
        final AuthorizationService authService = AuthorizationService.instance();
        final String target = PermissionHelper.permissionTargetIdForPortletDefinition(definition);
        // Loop over the affected permission managers...
        Map<String, Collection<ExternalPermissionDefinition>> permissionsBySystem = getPermissionsBySystem(permissionMap.keySet());
        for (String system : permissionsBySystem.keySet()) {
            Collection<ExternalPermissionDefinition> systemPerms = permissionsBySystem.get(system);
            // get the permission manager for this system...
            final IUpdatingPermissionManager upm = authService.newUpdatingPermissionManager(system);
            final List<IPermission> permissions = new ArrayList<>();
            // add activity grants for each permission..
            for (ExternalPermissionDefinition permissionDef : systemPerms) {
                Set<IGroupMember> members = permissionMap.get(permissionDef);
                for (final IGroupMember member : members) {
                    final IAuthorizationPrincipal authPrincipal = authService.newPrincipal(member);
                    final IPermission permEntity = upm.newPermission(authPrincipal);
                    permEntity.setType(IPermission.PERMISSION_TYPE_GRANT);
                    permEntity.setActivity(permissionDef.getActivity());
                    permEntity.setTarget(target);
                    permissions.add(permEntity);
                }
            }
            // If modifying the channel, remove the existing permissions before adding the new ones
            if (!newChannel) {
                for (ExternalPermissionDefinition permissionName : permissionMap.keySet()) {
                    IPermission[] oldPermissions = upm.getPermissions(permissionName.getActivity(), target);
                    upm.removePermissions(oldPermissions);
                }
            }
            upm.addPermissions(permissions.toArray(new IPermission[permissions.size()]));
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Portlet " + defId + " has been " + (newChannel ? "published" : "modified") + ".");
    }
    return definition;
}
Also used : IEntity(org.apereo.portal.groups.IEntity) ArrayList(java.util.ArrayList) IEntityGroup(org.apereo.portal.groups.IEntityGroup) IGroupMember(org.apereo.portal.groups.IGroupMember) AuthorizationService(org.apereo.portal.services.AuthorizationService) IPermission(org.apereo.portal.security.IPermission) IAuthorizationPrincipal(org.apereo.portal.security.IAuthorizationPrincipal) Collection(java.util.Collection) ExternalPermissionDefinition(org.apereo.portal.io.xml.portlettype.ExternalPermissionDefinition) PortletCategory(org.apereo.portal.portlet.om.PortletCategory) IUpdatingPermissionManager(org.apereo.portal.security.IUpdatingPermissionManager)

Example 27 with IEntityGroup

use of org.apereo.portal.groups.IEntityGroup in project uPortal by Jasig.

the class PortletDefinitionImporterExporter method removePortletDefinition.

@Transactional
@Override
public void removePortletDefinition(IPortletDefinition portletDefinition, IPerson person) {
    IPortletDefinition portletDef = portletDefinitionDao.getPortletDefinition(portletDefinition.getPortletDefinitionId());
    // Delete existing category memberships for this portlet
    String portletDefinitionId = portletDefinition.getPortletDefinitionId().getStringId();
    IEntity channelDefEntity = GroupService.getEntity(portletDefinitionId, IPortletDefinition.class);
    for (IEntityGroup group : channelDefEntity.getAncestorGroups()) {
        group.removeChild(channelDefEntity);
        group.update();
    }
    // Delete permissions records that refer to this portlet
    AuthorizationService authService = AuthorizationService.instance();
    String target = PermissionHelper.permissionTargetIdForPortletDefinition(portletDefinition);
    IUpdatingPermissionManager upm = authService.newUpdatingPermissionManager(IPermission.PORTAL_SUBSCRIBE);
    IPermission[] oldPermissions = upm.getPermissionsForTarget(target);
    upm.removePermissions(oldPermissions);
    // Delete any ratings (incl. reviews) associated with the portlet
    marketplaceRatingDao.clearRatingsForPortlet(portletDef);
    //Delete the portlet itself.
    portletDefinitionDao.deletePortletDefinition(portletDef);
}
Also used : IEntityGroup(org.apereo.portal.groups.IEntityGroup) IEntity(org.apereo.portal.groups.IEntity) AuthorizationService(org.apereo.portal.services.AuthorizationService) IPermission(org.apereo.portal.security.IPermission) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition) IUpdatingPermissionManager(org.apereo.portal.security.IUpdatingPermissionManager) Transactional(org.springframework.transaction.annotation.Transactional)

Example 28 with IEntityGroup

use of org.apereo.portal.groups.IEntityGroup in project uPortal by Jasig.

the class PortletDefinitionImporterExporter method convert.

protected ExternalPortletDefinition convert(IPortletDefinition def) {
    ExternalPortletDefinition rep = new ExternalPortletDefinition();
    rep.setFname(def.getFName());
    rep.setDesc(def.getDescription());
    rep.setName(def.getName());
    rep.setTimeout(BigInteger.valueOf(def.getTimeout()));
    rep.setActionTimeout(convertToBigInteger(def.getActionTimeout()));
    rep.setEventTimeout(convertToBigInteger(def.getEventTimeout()));
    rep.setRenderTimeout(convertToBigInteger(def.getRenderTimeout()));
    rep.setResourceTimeout(convertToBigInteger(def.getResourceTimeout()));
    rep.setTitle(def.getTitle());
    rep.setType(def.getType().getName());
    if (def.getLifecycleState().isEqualToOrAfter(PortletLifecycleState.APPROVED)) {
        Lifecycle lifecycle = new Lifecycle();
        LifecycleEntry approved = new LifecycleEntry();
        approved.setUser(getUsernameForUserId(def.getApproverId()));
        approved.setValue(getCalendar(def.getApprovalDate()));
        lifecycle.setApproved(approved);
        if (def.getLifecycleState().isEqualToOrAfter(PortletLifecycleState.PUBLISHED)) {
            LifecycleEntry published = new LifecycleEntry();
            published.setUser(getUsernameForUserId(def.getPublisherId()));
            published.setValue(getCalendar(def.getPublishDate()));
            lifecycle.setPublished(published);
        }
        /* An EXPIRED record in the lifecycle history requires two things:
             *   - Current lifecycle state >= EXPIRED
             *   - An expiration date
             */
        if (def.getLifecycleState().isEqualToOrAfter(PortletLifecycleState.EXPIRED) && def.getExpirationDate() != null) {
            LifecycleEntry expired = new LifecycleEntry();
            expired.setUser(getUsernameForUserId(def.getExpirerId()));
            expired.setValue(getCalendar(def.getExpirationDate()));
            lifecycle.setExpiration(expired);
        }
        // Maintenance mode is handled via a portlet publishing parameter and not a lifecycle
        rep.setLifecycle(lifecycle);
    }
    final org.apereo.portal.xml.PortletDescriptor portletDescriptor = new org.apereo.portal.xml.PortletDescriptor();
    final IPortletDescriptorKey portletDescriptorKey = def.getPortletDescriptorKey();
    if (portletDescriptorKey.isFrameworkPortlet()) {
        portletDescriptor.setIsFramework(true);
    } else {
        portletDescriptor.setWebAppName(portletDescriptorKey.getWebAppName());
    }
    portletDescriptor.setPortletName(portletDescriptorKey.getPortletName());
    rep.setPortletDescriptor(portletDescriptor);
    final List<ExternalPortletParameter> parameterList = rep.getParameters();
    for (IPortletDefinitionParameter param : def.getParameters()) {
        final ExternalPortletParameter externalPortletParameter = new ExternalPortletParameter();
        externalPortletParameter.setName(param.getName());
        externalPortletParameter.setDescription(param.getDescription());
        externalPortletParameter.setValue(param.getValue());
        parameterList.add(externalPortletParameter);
    }
    Collections.sort(parameterList, ExternalPortletParameterNameComparator.INSTANCE);
    final List<ExternalPortletPreference> portletPreferenceList = rep.getPortletPreferences();
    for (IPortletPreference pref : def.getPortletPreferences()) {
        final ExternalPortletPreference externalPortletPreference = new ExternalPortletPreference();
        externalPortletPreference.setName(pref.getName());
        externalPortletPreference.setReadOnly(pref.isReadOnly());
        final List<String> value = externalPortletPreference.getValues();
        value.addAll(Arrays.asList(pref.getValues()));
        //no sorting of preference values, order is specified by the portlet
        portletPreferenceList.add(externalPortletPreference);
    }
    Collections.sort(portletPreferenceList, ExternalPortletPreferenceNameComparator.INSTANCE);
    final List<String> categoryList = rep.getCategories();
    final IGroupMember gm = GroupService.getGroupMember(def.getPortletDefinitionId().getStringId(), IPortletDefinition.class);
    @SuppressWarnings("unchecked") final Iterator<IEntityGroup> categories = GroupService.getCompositeGroupService().findParentGroups(gm);
    while (categories.hasNext()) {
        IEntityGroup category = categories.next();
        categoryList.add(category.getName());
    }
    Collections.sort(categoryList);
    // handle the SUBSCRIBER_ACTIVITY perm separately...
    final List<String> groupList = rep.getGroups();
    final List<String> userList = rep.getUsers();
    exportPermission(def, ExternalPermissionDefinition.SUBSCRIBE, groupList, userList);
    // handle other supported perms (currently just BROWSE)
    ExternalPermissions externalPermissions = new ExternalPermissions();
    for (ExternalPermissionDefinition perm : ExternalPermissionDefinition.values()) {
        if (!perm.getExportForPortletDef()) {
            continue;
        }
        ExternalPermissionMemberList members = new ExternalPermissionMemberList();
        members.setSystem(perm.getSystem());
        members.setActivity(perm.getActivity());
        List<String> groups = members.getGroups();
        boolean found = exportPermission(def, perm, groups, null);
        if (found) {
            externalPermissions.getPermissions().add(members);
        }
    }
    if (!externalPermissions.getPermissions().isEmpty()) {
        rep.setPermissions(externalPermissions);
    }
    return rep;
}
Also used : IPortletPreference(org.apereo.portal.portlet.om.IPortletPreference) IPortletDescriptorKey(org.apereo.portal.portlet.om.IPortletDescriptorKey) PortletDescriptor(org.apereo.portal.xml.PortletDescriptor) IPortletDefinitionParameter(org.apereo.portal.portlet.om.IPortletDefinitionParameter) ExternalPermissionDefinition(org.apereo.portal.io.xml.portlettype.ExternalPermissionDefinition) PortletDescriptor(org.apereo.portal.xml.PortletDescriptor) IEntityGroup(org.apereo.portal.groups.IEntityGroup) IGroupMember(org.apereo.portal.groups.IGroupMember)

Example 29 with IEntityGroup

use of org.apereo.portal.groups.IEntityGroup in project uPortal by Jasig.

the class GroupMembershipEvaluator method isApplicable.

@Override
public boolean isApplicable(IPerson p) {
    if (groupKey == null || p == null)
        return false;
    IEntityGroup group = getGroup(groupKey);
    // the lower-level methods.
    if (group == null) {
        throw new RuntimeException("Error in evaluation. Group key " + groupKey + " for group name " + groupName + " did not find a group.");
    }
    EntityIdentifier ei = p.getEntityIdentifier();
    try {
        IGroupMember groupMember = GroupService.getGroupMember(ei);
        boolean isMember = false;
        if (evaluatorMode == MEMBER_OF_MODE) {
            isMember = groupMember.isMemberOf(group);
        } else {
            isMember = groupMember.isDeepMemberOf(group);
        }
        return isMember;
    } catch (Exception e) {
        throw new RuntimeException("Unable to determine if user '" + p.getFullName() + "' is in group '" + groupName + "'", e);
    }
}
Also used : IEntityGroup(org.apereo.portal.groups.IEntityGroup) IGroupMember(org.apereo.portal.groups.IGroupMember) EntityIdentifier(org.apereo.portal.EntityIdentifier) GroupsException(org.apereo.portal.groups.GroupsException)

Example 30 with IEntityGroup

use of org.apereo.portal.groups.IEntityGroup in project uPortal by Jasig.

the class RDBMUserIdentityStore method updateUser.

protected void updateUser(final int userId, final IPerson person, final TemplateUser templateUser) throws Exception {
    // Remove my existing group memberships
    IGroupMember me = GroupService.getGroupMember(person.getEntityIdentifier());
    for (IEntityGroup eg : me.getParentGroups()) {
        ILockableEntityGroup leg = getSafeLockableGroup(eg, me);
        if (leg != null) {
            removePersonFromGroup(person, me, leg);
        }
    }
    // Copy template user's groups memberships
    IGroupMember template = GroupService.getEntity(templateUser.getUserName(), IPerson.class);
    for (IEntityGroup eg : template.getParentGroups()) {
        ILockableEntityGroup leg = getSafeLockableGroup(eg, me);
        if (leg != null) {
            addPersonToGroup(person, me, leg);
        }
    }
    this.transactionOperations.execute(new TransactionCallback<Object>() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            return jdbcOperations.execute(new ConnectionCallback<Object>() {

                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                    PreparedStatement deleteStmt = null;
                    PreparedStatement queryStmt = null;
                    PreparedStatement insertStmt = null;
                    try {
                        // Update UP_USER
                        String update = "UPDATE UP_USER " + "SET USER_DFLT_USR_ID=?, " + "USER_DFLT_LAY_ID=?, " + "NEXT_STRUCT_ID=null " + "WHERE USER_ID=?";
                        insertStmt = con.prepareStatement(update);
                        insertStmt.setInt(1, templateUser.getUserId());
                        insertStmt.setInt(2, templateUser.getDefaultLayoutId());
                        insertStmt.setInt(3, userId);
                        if (log.isDebugEnabled())
                            log.debug("RDBMUserIdentityStore::addNewUser(): " + update);
                        insertStmt.executeUpdate();
                        insertStmt.close();
                        // Start copying...
                        ResultSet rs = null;
                        String delete = null;
                        String query = null;
                        String insert = null;
                        try {
                            // Update UP_USER_PROFILE
                            delete = "DELETE FROM UP_USER_PROFILE " + "WHERE USER_ID=?";
                            deleteStmt = con.prepareStatement(delete);
                            deleteStmt.setInt(1, userId);
                            if (log.isDebugEnabled())
                                log.debug("RDBMUserIdentityStore::updateUser(USER_ID=" + userId + "): " + delete);
                            deleteStmt.executeUpdate();
                            deleteStmt.close();
                            query = "SELECT USER_ID, PROFILE_FNAME, PROFILE_NAME, DESCRIPTION, " + "STRUCTURE_SS_ID, THEME_SS_ID " + "FROM UP_USER_PROFILE " + "WHERE USER_ID=?";
                            queryStmt = con.prepareStatement(query);
                            queryStmt.setInt(1, templateUser.getUserId());
                            if (log.isDebugEnabled())
                                log.debug("RDBMUserIdentityStore::updateUser(USER_ID=" + templateUser.getUserId() + "): " + query);
                            rs = queryStmt.executeQuery();
                            insert = "INSERT INTO UP_USER_PROFILE (USER_ID, PROFILE_ID, PROFILE_FNAME, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID) " + "VALUES(?, ?, ?, ?, ?, NULL, ?, ?)";
                            insertStmt = con.prepareStatement(insert);
                            while (rs.next()) {
                                int id = getNextKey();
                                String profileFname = rs.getString("PROFILE_FNAME");
                                String profileName = rs.getString("PROFILE_NAME");
                                String description = rs.getString("DESCRIPTION");
                                int structure = rs.getInt("STRUCTURE_SS_ID");
                                int theme = rs.getInt("THEME_SS_ID");
                                insertStmt.setInt(1, userId);
                                insertStmt.setInt(2, id);
                                insertStmt.setString(3, profileFname);
                                insertStmt.setString(4, profileName);
                                insertStmt.setString(5, description);
                                insertStmt.setInt(6, structure);
                                insertStmt.setInt(7, theme);
                                if (log.isDebugEnabled())
                                    log.debug("RDBMUserIdentityStore::updateUser(USER_ID=" + userId + ", PROFILE_FNAME=" + profileFname + ", PROFILE_NAME=" + profileName + ", DESCRIPTION=" + description + "): " + insert);
                                insertStmt.executeUpdate();
                            }
                            rs.close();
                            queryStmt.close();
                            insertStmt.close();
                            // If we made it all the way though, commit the transaction
                            if (RDBMServices.getDbMetaData().supportsTransactions())
                                con.commit();
                        } finally {
                            try {
                                rs.close();
                            } catch (Exception e) {
                            }
                        }
                    } finally {
                        try {
                            deleteStmt.close();
                        } catch (Exception e) {
                        }
                        try {
                            queryStmt.close();
                        } catch (Exception e) {
                        }
                        try {
                            insertStmt.close();
                        } catch (Exception e) {
                        }
                    }
                    return null;
                }
            });
        }
    });
}
Also used : Connection(java.sql.Connection) ILockableEntityGroup(org.apereo.portal.groups.ILockableEntityGroup) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatement(java.sql.PreparedStatement) DataAccessException(org.springframework.dao.DataAccessException) SQLException(java.sql.SQLException) IEntityGroup(org.apereo.portal.groups.IEntityGroup) IGroupMember(org.apereo.portal.groups.IGroupMember) ResultSet(java.sql.ResultSet) SerializableObject(org.apereo.portal.utils.SerializableObject) ConnectionCallback(org.springframework.jdbc.core.ConnectionCallback)

Aggregations

IEntityGroup (org.apereo.portal.groups.IEntityGroup)74 IGroupMember (org.apereo.portal.groups.IGroupMember)27 ArrayList (java.util.ArrayList)18 IAuthorizationPrincipal (org.apereo.portal.security.IAuthorizationPrincipal)14 EntityIdentifier (org.apereo.portal.EntityIdentifier)12 HashSet (java.util.HashSet)10 EntityEnum (org.apereo.portal.portlets.groupselector.EntityEnum)9 HashMap (java.util.HashMap)8 LinkedList (java.util.LinkedList)8 AggregatedGroupMapping (org.apereo.portal.events.aggr.groups.AggregatedGroupMapping)8 GroupsException (org.apereo.portal.groups.GroupsException)8 JsonEntityBean (org.apereo.portal.layout.dlm.remoting.JsonEntityBean)8 IPermission (org.apereo.portal.security.IPermission)8 CompositeName (javax.naming.CompositeName)7 CallableWithoutResult (org.apereo.portal.concurrency.CallableWithoutResult)7 IPortletDefinition (org.apereo.portal.portlet.om.IPortletDefinition)7 IPerson (org.apereo.portal.security.IPerson)7 BaseAggrEventsJpaDaoTest (org.apereo.portal.test.BaseAggrEventsJpaDaoTest)7 DateTime (org.joda.time.DateTime)7 Test (org.junit.Test)7