Search in sources :

Example 46 with Organization

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

the class SchedulerServiceImpl method repopulate.

@Override
public void repopulate(final String indexName) {
    notEmpty(indexName, "indexName");
    final String destinationId = SchedulerItem.SCHEDULER_QUEUE_PREFIX + WordUtils.capitalize(indexName);
    Organization organization = new DefaultOrganization();
    SecurityUtil.runAs(securityService, organization, SecurityUtil.createSystemUser(systemUserName, organization), new Effect0() {

        @Override
        protected void run() {
            int current = 1;
            AQueryBuilder query = assetManager.createQuery();
            Props p = new Props(query);
            AResult result = query.select(query.snapshot(), p.agent().target(), p.start().target(), p.end().target(), p.optOut().target(), p.presenters().target(), p.reviewDate().target(), p.reviewStatus().target(), p.recordingStatus().target(), p.recordingLastHeard().target(), query.propertiesOf(CA_NAMESPACE)).where(withOrganization(query).and(query.hasPropertiesOf(p.namespace())).and(withVersion(query))).run();
            final int total = (int) Math.min(result.getSize(), Integer.MAX_VALUE);
            logger.info("Re-populating '{}' index with scheduled events. There are {} scheduled events to add to the index.", indexName, total);
            final int responseInterval = (total < 100) ? 1 : (total / 100);
            try {
                for (ARecord record : result.getRecords()) {
                    String agentId = record.getProperties().apply(Properties.getString(AGENT_CONFIG));
                    boolean optOut = record.getProperties().apply(Properties.getBoolean(OPTOUT_CONFIG));
                    Date start = record.getProperties().apply(Properties.getDate(START_DATE_CONFIG));
                    Date end = record.getProperties().apply(Properties.getDate(END_DATE_CONFIG));
                    Set<String> presenters = getPresenters(record.getProperties().apply(getStringOpt(PRESENTERS_CONFIG)).getOr(""));
                    boolean blacklisted = isBlacklisted(record.getMediaPackageId(), start, end, agentId, presenters);
                    Map<String, String> caMetadata = record.getProperties().filter(filterByNamespace._2(CA_NAMESPACE)).group(toKey, toValue);
                    ReviewStatus reviewStatus = record.getProperties().apply(getStringOpt(REVIEW_STATUS_CONFIG)).map(toReviewStatus).getOr(UNSENT);
                    Date reviewDate = record.getProperties().apply(Properties.getDateOpt(REVIEW_DATE_CONFIG)).orNull();
                    Opt<String> recordingStatus = record.getProperties().apply(Properties.getStringOpt(RECORDING_STATE_CONFIG));
                    Opt<Long> lastHeard = record.getProperties().apply(Properties.getLongOpt(RECORDING_LAST_HEARD_CONFIG));
                    Opt<AccessControlList> acl = loadEpisodeAclFromAsset(record.getSnapshot().get());
                    Opt<DublinCoreCatalog> dublinCore = loadEpisodeDublinCoreFromAsset(record.getSnapshot().get());
                    sendUpdateAddEvent(record.getMediaPackageId(), acl, dublinCore, Opt.some(start), Opt.some(end), Opt.some(presenters), Opt.some(agentId), Opt.some(caMetadata), Opt.some(optOut));
                    messageSender.sendObjectMessage(destinationId, MessageSender.DestinationType.Queue, SchedulerItem.updateBlacklist(record.getMediaPackageId(), blacklisted));
                    messageSender.sendObjectMessage(destinationId, MessageSender.DestinationType.Queue, SchedulerItem.updateReviewStatus(record.getMediaPackageId(), reviewStatus, reviewDate));
                    if (((current % responseInterval) == 0) || (current == total)) {
                        messageSender.sendObjectMessage(IndexProducer.RESPONSE_QUEUE, MessageSender.DestinationType.Queue, IndexRecreateObject.update(indexName, IndexRecreateObject.Service.Scheduler, total, current));
                    }
                    if (recordingStatus.isSome() && lastHeard.isSome())
                        sendRecordingUpdate(new RecordingImpl(record.getMediaPackageId(), recordingStatus.get(), lastHeard.get()));
                    current++;
                }
            } catch (Exception e) {
                logger.warn("Unable to index scheduled instances:", e);
                throw new ServiceException(e.getMessage());
            }
        }
    });
    SecurityUtil.runAs(securityService, organization, SecurityUtil.createSystemUser(systemUserName, organization), new Effect0() {

        @Override
        protected void run() {
            messageSender.sendObjectMessage(IndexProducer.RESPONSE_QUEUE, MessageSender.DestinationType.Queue, IndexRecreateObject.end(indexName, IndexRecreateObject.Service.Scheduler));
        }
    });
}
Also used : Organization(org.opencastproject.security.api.Organization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) Set(java.util.Set) HashSet(java.util.HashSet) AQueryBuilder(org.opencastproject.assetmanager.api.query.AQueryBuilder) RecordingImpl(org.opencastproject.scheduler.api.RecordingImpl) Log.getHumanReadableTimeString(org.opencastproject.util.Log.getHumanReadableTimeString) Date(java.util.Date) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) IOException(java.io.IOException) ServiceException(org.osgi.framework.ServiceException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) ConfigurationException(org.osgi.service.cm.ConfigurationException) SeriesException(org.opencastproject.series.api.SeriesException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) ValidationException(net.fortuna.ical4j.model.ValidationException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) ARecord(org.opencastproject.assetmanager.api.query.ARecord) Opt(com.entwinemedia.fn.data.Opt) Properties.getStringOpt(org.opencastproject.assetmanager.api.fn.Properties.getStringOpt) ServiceException(org.osgi.framework.ServiceException) Effect0(org.opencastproject.util.data.Effect0) SchedulerUtil.toReviewStatus(org.opencastproject.scheduler.impl.SchedulerUtil.toReviewStatus) AResult(org.opencastproject.assetmanager.api.query.AResult) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization)

Example 47 with Organization

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

the class OaiPmhRepositoryPersistenceTest method oaiPmhDatabase.

private static AbstractOaiPmhDatabase oaiPmhDatabase(MediaPackage... mps) {
    try {
        final Organization org = new DefaultOrganization();
        final SecurityService secSvc = EasyMock.createNiceMock(SecurityService.class);
        // security service
        final User user = createSystemUser("admin", org);
        expect(secSvc.getOrganization()).andReturn(org).anyTimes();
        expect(secSvc.getUser()).andReturn(user).anyTimes();
        EasyMock.replay(secSvc);
        // series service
        final SeriesService seriesService = EasyMock.createNiceMock(SeriesService.class);
        final String xacml = IOUtils.toString(OaiPmhRepositoryPersistenceTest.class.getResource("/xacml.xml").toURI());
        final AccessControlList securityACL = AccessControlParser.parseAcl(xacml);
        EasyMock.expect(seriesService.getSeriesAccessControl("10.0000/1")).andReturn(securityACL).anyTimes();
        EasyMock.replay(seriesService);
        // workspace
        final Workspace workspace = EasyMock.createNiceMock(Workspace.class);
        final File episodeDublinCore = new File(OaiPmhRepositoryPersistenceTest.class.getResource("/episode-dublincore.xml").toURI());
        final File seriesDublinCore = new File(OaiPmhRepositoryPersistenceTest.class.getResource("/series-dublincore.xml").toURI());
        expect(workspace.read(EasyMock.anyObject())).andAnswer(() -> {
            final String uri = getCurrentArguments()[0].toString();
            if ("dublincore.xml".equals(uri))
                return new FileInputStream(episodeDublinCore);
            if ("series-dublincore.xml".equals(uri))
                return new FileInputStream(seriesDublinCore);
            throw new Error("Workspace mock does not know about file " + uri);
        }).anyTimes();
        EasyMock.replay(workspace);
        // oai-pmh database
        final EntityManagerFactory emf = PersistenceUtil.newTestEntityManagerFactory(OaiPmhDatabaseImpl.PERSISTENCE_UNIT_NAME);
        final AbstractOaiPmhDatabase db = new AbstractOaiPmhDatabase() {

            @Override
            public EntityManagerFactory getEmf() {
                return emf;
            }

            @Override
            public SecurityService getSecurityService() {
                return secSvc;
            }

            @Override
            public Workspace getWorkspace() {
                return workspace;
            }

            @Override
            public Date currentDate() {
                return new Date();
            }
        };
        for (MediaPackage mp : mps) db.store(mp, REPOSITORY_ID);
        return db;
    } catch (Exception e) {
        return chuck(e);
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) AbstractOaiPmhDatabase(org.opencastproject.oaipmh.persistence.impl.AbstractOaiPmhDatabase) Organization(org.opencastproject.security.api.Organization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) User(org.opencastproject.security.api.User) SecurityUtil.createSystemUser(org.opencastproject.security.util.SecurityUtil.createSystemUser) FileInputStream(java.io.FileInputStream) Date(java.util.Date) EncodingSchemeUtils.encodeDate(org.opencastproject.metadata.dublincore.EncodingSchemeUtils.encodeDate) TransformerException(javax.xml.transform.TransformerException) SeriesService(org.opencastproject.series.api.SeriesService) SecurityService(org.opencastproject.security.api.SecurityService) EntityManagerFactory(javax.persistence.EntityManagerFactory) MediaPackage(org.opencastproject.mediapackage.MediaPackage) File(java.io.File) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) Workspace(org.opencastproject.workspace.api.Workspace)

Example 48 with Organization

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

the class PresetProviderImplTest method setUp.

@Before
public void setUp() throws SeriesException, NotFoundException, UnauthorizedException {
    Map<String, String> properties = new TreeMap<String, String>();
    properties.put(ORG_PROPERTY_NAME, ORG_PROPERTY_VALUE);
    organization = EasyMock.createMock(Organization.class);
    EasyMock.expect(organization.getProperties()).andReturn(properties).anyTimes();
    EasyMock.replay(organization);
    SecurityService securityService = EasyMock.createMock(SecurityService.class);
    EasyMock.expect(securityService.getOrganization()).andReturn(organization);
    EasyMock.replay(securityService);
    seriesService = EasyMock.createMock(SeriesService.class);
    EasyMock.expect(seriesService.getSeriesProperty(SERIES_ID, SERIES_PROPERTY_NAME)).andReturn(SERIES_PROPERTY_VALUE).anyTimes();
    EasyMock.expect(seriesService.getSeriesProperty(SERIES_ID, ORG_PROPERTY_NAME)).andThrow(new NotFoundException()).anyTimes();
    EasyMock.expect(seriesService.getSeriesProperty(SERIES_ID, NOT_FOUND_NAME)).andThrow(new NotFoundException()).anyTimes();
    EasyMock.replay(seriesService);
    presetProviderImpl = new PresetProviderImpl();
    presetProviderImpl.setSeriesService(seriesService);
    presetProviderImpl.setSecurityService(securityService);
}
Also used : Organization(org.opencastproject.security.api.Organization) SeriesService(org.opencastproject.series.api.SeriesService) SecurityService(org.opencastproject.security.api.SecurityService) NotFoundException(org.opencastproject.util.NotFoundException) TreeMap(java.util.TreeMap) Before(org.junit.Before)

Example 49 with Organization

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

the class RuntimeInfo method getRuntimeInfo.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("components.json")
@RestQuery(name = "services", description = "List the REST services and user interfaces running on this host", reponses = { @RestResponse(description = "The components running on this host", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "")
@SuppressWarnings("unchecked")
public String getRuntimeInfo(@Context HttpServletRequest request) throws MalformedURLException {
    Organization organization = securityService.getOrganization();
    // Get request protocol and port
    String targetScheme = request.getScheme();
    // Create the engage target URL
    URL targetEngageBaseUrl = null;
    String orgEngageBaseUrl = organization.getProperties().get(ENGAGE_URL_PROPERTY);
    if (StringUtils.isNotBlank(orgEngageBaseUrl)) {
        try {
            targetEngageBaseUrl = new URL(orgEngageBaseUrl);
        } catch (MalformedURLException e) {
            logger.warn("Engage url '{}' of organization '{}' is malformed", orgEngageBaseUrl, organization.getId());
        }
    }
    if (targetEngageBaseUrl == null) {
        logger.debug("Using 'org.opencastproject.server.url' as a fallback for the non-existing organization level key '{}' for the components.json response", ENGAGE_URL_PROPERTY);
        targetEngageBaseUrl = new URL(targetScheme, serverUrl.getHost(), serverUrl.getPort(), serverUrl.getFile());
    }
    // Create the admin target URL
    URL targetAdminBaseUrl = null;
    String orgAdminBaseUrl = organization.getProperties().get(ADMIN_URL_PROPERTY);
    if (StringUtils.isNotBlank(orgAdminBaseUrl)) {
        try {
            targetAdminBaseUrl = new URL(orgAdminBaseUrl);
        } catch (MalformedURLException e) {
            logger.warn("Admin url '{}' of organization '{}' is malformed", orgAdminBaseUrl, organization.getId());
        }
    }
    if (targetAdminBaseUrl == null) {
        logger.debug("Using 'org.opencastproject.server.url' as a fallback for the non-existing organization level key '{}' for the components.json response", ADMIN_URL_PROPERTY);
        targetAdminBaseUrl = new URL(targetScheme, serverUrl.getHost(), serverUrl.getPort(), serverUrl.getFile());
    }
    JSONObject json = new JSONObject();
    json.put("engage", targetEngageBaseUrl.toString());
    json.put("admin", targetAdminBaseUrl.toString());
    json.put("rest", getRestEndpointsAsJson(request));
    json.put("ui", getUserInterfacesAsJson());
    return json.toJSONString();
}
Also used : MalformedURLException(java.net.MalformedURLException) Organization(org.opencastproject.security.api.Organization) JSONObject(org.json.simple.JSONObject) URL(java.net.URL) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 50 with Organization

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

the class WorkflowServiceImpl method getHoldWorkflows.

private List<WorkflowInstance> getHoldWorkflows() throws WorkflowDatabaseException {
    List<WorkflowInstance> workflows = new ArrayList<WorkflowInstance>();
    Organization organization = securityService.getOrganization();
    try {
        for (Organization org : organizationDirectoryService.getOrganizations()) {
            securityService.setOrganization(org);
            WorkflowQuery workflowQuery = new WorkflowQuery().withState(WorkflowInstance.WorkflowState.PAUSED).withCount(Integer.MAX_VALUE);
            WorkflowSet workflowSet = getWorkflowInstances(workflowQuery);
            workflows.addAll(Arrays.asList(workflowSet.getItems()));
        }
    } finally {
        securityService.setOrganization(organization);
    }
    return workflows;
}
Also used : WorkflowSet(org.opencastproject.workflow.api.WorkflowSet) WorkflowQuery(org.opencastproject.workflow.api.WorkflowQuery) Organization(org.opencastproject.security.api.Organization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance)

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