Search in sources :

Example 16 with Organization

use of org.opencastproject.security.api.Organization in project opencast by opencast.

the class OaiPmhUpdatedEventHandler method handleEvent.

public void handleEvent(AssetManagerItem.TakeSnapshot snapshotItem) {
    if (!propagateEpisode) {
        logger.trace("Skipping automatic propagation of episode meta data to OAI-PMH since it is turned off.");
        return;
    }
    // An episode or its ACL has been updated. Construct the MediaPackage and publish it to OAI-PMH.
    logger.debug("Handling update event for media package {}", snapshotItem.getMediapackage().getIdentifier().compact());
    // We must be an administrative user to make a query to the OaiPmhPublicationService
    final User prevUser = securityService.getUser();
    final Organization prevOrg = securityService.getOrganization();
    try {
        securityService.setUser(SecurityUtil.createSystemUser(systemAccount, prevOrg));
        // Check weather the media package contains elements to republish
        MediaPackage snapshotMp = snapshotItem.getMediapackage();
        SimpleElementSelector mpeSelector = new SimpleElementSelector();
        for (String flavor : flavors) {
            mpeSelector.addFlavor(flavor);
        }
        for (String tag : tags) {
            mpeSelector.addTag(tag);
        }
        Collection<MediaPackageElement> elementsToUpdate = mpeSelector.select(snapshotMp, true);
        if (elementsToUpdate == null || elementsToUpdate.isEmpty()) {
            logger.debug("The media package {} does not contain any elements matching the given flavors and tags", snapshotMp.getIdentifier().compact());
            return;
        }
        SearchResult result = oaiPmhPersistence.search(QueryBuilder.query().mediaPackageId(snapshotMp).isDeleted(false).build());
        for (SearchResultItem searchResultItem : result.getItems()) {
            try {
                Job job = oaiPmhPublicationService.updateMetadata(snapshotMp, searchResultItem.getRepository(), flavors, tags, false);
            // we don't want to wait for job completion here because it will block the message queue
            } catch (Exception e) {
                logger.error("Unable to update OAI-PMH publication for the media package {} in repository {}", snapshotItem.getMediapackage().getIdentifier().compact(), searchResultItem.getRepository(), e);
            }
        }
    } finally {
        securityService.setOrganization(prevOrg);
        securityService.setUser(prevUser);
    }
}
Also used : User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) SearchResultItem(org.opencastproject.oaipmh.persistence.SearchResultItem) SearchResult(org.opencastproject.oaipmh.persistence.SearchResult) SimpleElementSelector(org.opencastproject.mediapackage.selector.SimpleElementSelector) Job(org.opencastproject.job.api.Job) ConfigurationException(org.osgi.service.cm.ConfigurationException)

Example 17 with Organization

use of org.opencastproject.security.api.Organization in project opencast by opencast.

the class SeriesUpdatedEventHandler method handleEvent.

public void handleEvent(final SeriesItem seriesItem) {
    // A series or its ACL has been updated. Find any mediapackages with that series, and update them.
    logger.debug("Handling {}", seriesItem);
    String seriesId = seriesItem.getSeriesId();
    // We must be an administrative user to make this query
    final User prevUser = securityService.getUser();
    final Organization prevOrg = securityService.getOrganization();
    try {
        securityService.setUser(SecurityUtil.createSystemUser(systemAccount, prevOrg));
        SearchQuery q = new SearchQuery().withSeriesId(seriesId);
        SearchResult result = searchService.getForAdministrativeRead(q);
        for (SearchResultItem item : result.getItems()) {
            MediaPackage mp = item.getMediaPackage();
            Organization org = organizationDirectoryService.getOrganization(item.getOrganization());
            securityService.setOrganization(org);
            // to the distribution channels as well
            if (SeriesItem.Type.UpdateAcl.equals(seriesItem.getType())) {
                // Build a new XACML file for this mediapackage
                Attachment fileRepoCopy = authorizationService.setAcl(mp, AclScope.Series, seriesItem.getAcl()).getB();
                // Distribute the updated XACML file
                Job distributionJob = distributionService.distribute(CHANNEL_ID, mp, fileRepoCopy.getIdentifier());
                JobBarrier barrier = new JobBarrier(null, serviceRegistry, distributionJob);
                Result jobResult = barrier.waitForJobs();
                if (jobResult.getStatus().get(distributionJob).equals(FINISHED)) {
                    mp.remove(fileRepoCopy);
                    mp.add(getFromXml(serviceRegistry.getJob(distributionJob.getId()).getPayload()));
                } else {
                    logger.error("Unable to distribute XACML {}", fileRepoCopy.getIdentifier());
                    continue;
                }
            }
            // Update the series dublin core
            if (SeriesItem.Type.UpdateCatalog.equals(seriesItem.getType())) {
                DublinCoreCatalog seriesDublinCore = seriesItem.getMetadata();
                mp.setSeriesTitle(seriesDublinCore.getFirst(DublinCore.PROPERTY_TITLE));
                // Update the series dublin core
                Catalog[] seriesCatalogs = mp.getCatalogs(MediaPackageElements.SERIES);
                if (seriesCatalogs.length == 1) {
                    Catalog c = seriesCatalogs[0];
                    String filename = FilenameUtils.getName(c.getURI().toString());
                    URI uri = workspace.put(mp.getIdentifier().toString(), c.getIdentifier(), filename, dublinCoreService.serialize(seriesDublinCore));
                    c.setURI(uri);
                    // setting the URI to a new source so the checksum will most like be invalid
                    c.setChecksum(null);
                    // Distribute the updated series dc
                    Job distributionJob = distributionService.distribute(CHANNEL_ID, mp, c.getIdentifier());
                    JobBarrier barrier = new JobBarrier(null, serviceRegistry, distributionJob);
                    Result jobResult = barrier.waitForJobs();
                    if (jobResult.getStatus().get(distributionJob).equals(FINISHED)) {
                        mp.remove(c);
                        mp.add(getFromXml(serviceRegistry.getJob(distributionJob.getId()).getPayload()));
                    } else {
                        logger.error("Unable to distribute series catalog {}", c.getIdentifier());
                        continue;
                    }
                }
            }
            // Remove the series catalog and isPartOf from episode catalog
            if (SeriesItem.Type.Delete.equals(seriesItem.getType())) {
                mp.setSeries(null);
                mp.setSeriesTitle(null);
                boolean retractSeriesCatalog = retractSeriesCatalog(mp);
                boolean updateEpisodeCatalog = updateEpisodeCatalog(mp);
                if (!retractSeriesCatalog || !updateEpisodeCatalog)
                    continue;
            }
            // Update the search index with the modified mediapackage
            Job searchJob = searchService.add(mp);
            JobBarrier barrier = new JobBarrier(null, serviceRegistry, searchJob);
            barrier.waitForJobs();
        }
    } catch (SearchException e) {
        logger.warn("Unable to find mediapackages in search: ", e.getMessage());
    } catch (UnauthorizedException e) {
        logger.warn(e.getMessage());
    } catch (MediaPackageException e) {
        logger.warn(e.getMessage());
    } catch (ServiceRegistryException e) {
        logger.warn(e.getMessage());
    } catch (NotFoundException e) {
        logger.warn(e.getMessage());
    } catch (IOException e) {
        logger.warn(e.getMessage());
    } catch (DistributionException e) {
        logger.warn(e.getMessage());
    } finally {
        securityService.setOrganization(prevOrg);
        securityService.setUser(prevUser);
    }
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) SearchResultItem(org.opencastproject.search.api.SearchResultItem) SearchException(org.opencastproject.search.api.SearchException) NotFoundException(org.opencastproject.util.NotFoundException) SearchResult(org.opencastproject.search.api.SearchResult) Attachment(org.opencastproject.mediapackage.Attachment) IOException(java.io.IOException) JobBarrier(org.opencastproject.job.api.JobBarrier) URI(java.net.URI) Catalog(org.opencastproject.mediapackage.Catalog) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) Result(org.opencastproject.job.api.JobBarrier.Result) SearchResult(org.opencastproject.search.api.SearchResult) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) DistributionException(org.opencastproject.distribution.api.DistributionException) Job(org.opencastproject.job.api.Job) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog)

Example 18 with Organization

use of org.opencastproject.security.api.Organization in project opencast by opencast.

the class JpaGroupRoleProvider method repopulate.

@Override
public void repopulate(final String indexName) {
    final String destinationId = GroupItem.GROUP_QUEUE_PREFIX + WordUtils.capitalize(indexName);
    for (final Organization organization : organizationDirectoryService.getOrganizations()) {
        SecurityUtil.runAs(securityService, organization, SecurityUtil.createSystemUser(cc, organization), new Effect0() {

            @Override
            protected void run() {
                final List<JpaGroup> groups = UserDirectoryPersistenceUtil.findGroups(organization.getId(), 0, 0, emf);
                int total = groups.size();
                final int responseInterval = (total < 100) ? 1 : (total / 100);
                int current = 1;
                logger.info("Re-populating index '{}' with groups of organization {}. There are {} group(s) to add to the index.", indexName, securityService.getOrganization().getId(), total);
                for (JpaGroup group : groups) {
                    messageSender.sendObjectMessage(destinationId, MessageSender.DestinationType.Queue, GroupItem.update(JaxbGroup.fromGroup(group)));
                    if (((current % responseInterval) == 0) || (current == total)) {
                        messageSender.sendObjectMessage(IndexProducer.RESPONSE_QUEUE, MessageSender.DestinationType.Queue, IndexRecreateObject.update(indexName, IndexRecreateObject.Service.Groups, total, current));
                    }
                    current++;
                }
            }
        });
    }
    Organization organization = new DefaultOrganization();
    SecurityUtil.runAs(securityService, organization, SecurityUtil.createSystemUser(cc, organization), new Effect0() {

        @Override
        protected void run() {
            messageSender.sendObjectMessage(IndexProducer.RESPONSE_QUEUE, MessageSender.DestinationType.Queue, IndexRecreateObject.end(indexName, IndexRecreateObject.Service.Groups));
        }
    });
}
Also used : JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) Organization(org.opencastproject.security.api.Organization) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) Effect0(org.opencastproject.util.data.Effect0) List(java.util.List) ArrayList(java.util.ArrayList) JaxbGroupList(org.opencastproject.security.api.JaxbGroupList) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization)

Example 19 with Organization

use of org.opencastproject.security.api.Organization in project opencast by opencast.

the class UserIdRoleProvider method findRoles.

/**
 * @see org.opencastproject.security.api.RoleProvider#findRoles(String,Role.Target, int, int)
 */
@Override
public Iterator<Role> findRoles(String query, Role.Target target, int offset, int limit) {
    if (query == null)
        throw new IllegalArgumentException("Query must be set");
    // These roles are not meaningful for users/groups
    if (target == Role.Target.USER) {
        return Collections.emptyIterator();
    }
    logger.debug("findRoles(query={} offset={} limit={})", query, offset, limit);
    HashSet<Role> foundRoles = new HashSet<Role>();
    Organization organization = securityService.getOrganization();
    // Return authenticated user role if it matches the query pattern
    if (like(ROLE_USER, query)) {
        foundRoles.add(new JaxbRole(ROLE_USER, JaxbOrganization.fromOrganization(organization), "The authenticated user role", Role.Type.SYSTEM));
    }
    // (iterating through users may be slow)
    if (!"%".equals(query) && !query.startsWith(userRolePrefix)) {
        return foundRoles.iterator();
    }
    String userQuery = "%";
    if (query.startsWith(userRolePrefix)) {
        userQuery = query.substring(userRolePrefix.length());
    }
    Iterator<User> users = userDirectoryService.findUsers(userQuery, offset, limit);
    while (users.hasNext()) {
        User u = users.next();
        // We exclude the digest user, but then add the global ROLE_USER above
        if (!"system".equals(u.getProvider())) {
            foundRoles.add(new JaxbRole(getUserIdRole(u.getUsername()), JaxbOrganization.fromOrganization(u.getOrganization()), "User id role", Role.Type.SYSTEM));
        }
    }
    return foundRoles.iterator();
}
Also used : Role(org.opencastproject.security.api.Role) JaxbRole(org.opencastproject.security.api.JaxbRole) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) Organization(org.opencastproject.security.api.Organization) JaxbRole(org.opencastproject.security.api.JaxbRole) User(org.opencastproject.security.api.User) HashSet(java.util.HashSet)

Example 20 with Organization

use of org.opencastproject.security.api.Organization in project opencast by opencast.

the class UserIdRoleProvider method getRolesForUser.

/**
 * @see org.opencastproject.security.api.RoleProvider#getRolesForUser(String)
 */
@Override
public List<Role> getRolesForUser(String userName) {
    Organization organization = securityService.getOrganization();
    List<Role> roles = new ArrayList<Role>();
    roles.add(new JaxbRole(getUserIdRole(userName), JaxbOrganization.fromOrganization(organization), "The user id role", Role.Type.SYSTEM));
    roles.add(new JaxbRole(ROLE_USER, JaxbOrganization.fromOrganization(organization), "The authenticated user role", Role.Type.SYSTEM));
    return Collections.unmodifiableList(roles);
}
Also used : Role(org.opencastproject.security.api.Role) JaxbRole(org.opencastproject.security.api.JaxbRole) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) Organization(org.opencastproject.security.api.Organization) JaxbRole(org.opencastproject.security.api.JaxbRole) ArrayList(java.util.ArrayList)

Aggregations

Organization (org.opencastproject.security.api.Organization)135 User (org.opencastproject.security.api.User)60 DefaultOrganization (org.opencastproject.security.api.DefaultOrganization)46 NotFoundException (org.opencastproject.util.NotFoundException)43 JaxbOrganization (org.opencastproject.security.api.JaxbOrganization)29 SecurityService (org.opencastproject.security.api.SecurityService)29 IOException (java.io.IOException)24 Before (org.junit.Before)24 ArrayList (java.util.ArrayList)23 AccessControlList (org.opencastproject.security.api.AccessControlList)22 OrganizationDirectoryService (org.opencastproject.security.api.OrganizationDirectoryService)22 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)22 JaxbRole (org.opencastproject.security.api.JaxbRole)21 MediaPackage (org.opencastproject.mediapackage.MediaPackage)20 JaxbUser (org.opencastproject.security.api.JaxbUser)20 UserDirectoryService (org.opencastproject.security.api.UserDirectoryService)19 File (java.io.File)18 HashMap (java.util.HashMap)17 WorkflowInstance (org.opencastproject.workflow.api.WorkflowInstance)17 Test (org.junit.Test)15