Search in sources :

Example 6 with UnauthorizedException

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

the class IndexServiceImpl method createEvent.

@Override
public String createEvent(EventHttpServletRequest eventHttpServletRequest) throws ParseException, IOException, MediaPackageException, IngestException, NotFoundException, SchedulerException, UnauthorizedException {
    // Preconditions
    if (eventHttpServletRequest.getAcl().isNone()) {
        throw new IllegalArgumentException("No access control list available to create new event.");
    }
    if (eventHttpServletRequest.getMediaPackage().isNone()) {
        throw new IllegalArgumentException("No mediapackage available to create new event.");
    }
    if (eventHttpServletRequest.getMetadataList().isNone()) {
        throw new IllegalArgumentException("No metadata list available to create new event.");
    }
    if (eventHttpServletRequest.getProcessing().isNone()) {
        throw new IllegalArgumentException("No processing metadata available to create new event.");
    }
    if (eventHttpServletRequest.getSource().isNone()) {
        throw new IllegalArgumentException("No source field metadata available to create new event.");
    }
    // Get Workflow
    String workflowTemplate = (String) eventHttpServletRequest.getProcessing().get().get("workflow");
    if (workflowTemplate == null)
        throw new IllegalArgumentException("No workflow template in metadata");
    // Get Type of Source
    SourceType type = getSourceType(eventHttpServletRequest.getSource().get());
    MetadataCollection eventMetadata = eventHttpServletRequest.getMetadataList().get().getMetadataByAdapter(eventCatalogUIAdapter).get();
    JSONObject sourceMetadata = (JSONObject) eventHttpServletRequest.getSource().get().get("metadata");
    if (sourceMetadata != null && (type.equals(SourceType.SCHEDULE_SINGLE) || type.equals(SourceType.SCHEDULE_MULTIPLE))) {
        try {
            MetadataField<?> current = eventMetadata.getOutputFields().get("location");
            eventMetadata.updateStringField(current, (String) sourceMetadata.get("device"));
        } catch (Exception e) {
            logger.warn("Unable to parse device {}", sourceMetadata.get("device"));
            throw new IllegalArgumentException("Unable to parse device");
        }
    }
    Date currentStartDate = null;
    MetadataField<?> starttime = eventMetadata.getOutputFields().get(DublinCore.PROPERTY_TEMPORAL.getLocalName());
    if (starttime != null && starttime.isUpdated() && starttime.getValue().isSome()) {
        DCMIPeriod period = EncodingSchemeUtils.decodeMandatoryPeriod((DublinCoreValue) starttime.getValue().get());
        currentStartDate = period.getStart();
    }
    MetadataField<?> created = eventMetadata.getOutputFields().get(DublinCore.PROPERTY_CREATED.getLocalName());
    if (created == null || !created.isUpdated() || created.getValue().isNone()) {
        eventMetadata.removeField(created);
        MetadataField<String> newCreated = MetadataUtils.copyMetadataField(created);
        if (currentStartDate != null) {
            newCreated.setValue(EncodingSchemeUtils.encodeDate(currentStartDate, Precision.Second).getValue());
        } else {
            newCreated.setValue(EncodingSchemeUtils.encodeDate(new Date(), Precision.Second).getValue());
        }
        eventMetadata.addField(newCreated);
    }
    // Get presenter usernames for use as technical presenters
    Set<String> presenterUsernames = new HashSet<>();
    Opt<Set<String>> technicalPresenters = updatePresenters(eventMetadata);
    if (technicalPresenters.isSome()) {
        presenterUsernames = technicalPresenters.get();
    }
    eventHttpServletRequest.getMetadataList().get().add(eventCatalogUIAdapter, eventMetadata);
    updateMediaPackageMetadata(eventHttpServletRequest.getMediaPackage().get(), eventHttpServletRequest.getMetadataList().get());
    DublinCoreCatalog dc = getDublinCoreCatalog(eventHttpServletRequest);
    String captureAgentId = null;
    TimeZone tz = null;
    org.joda.time.DateTime start = null;
    org.joda.time.DateTime end = null;
    long duration = 0L;
    Properties caProperties = new Properties();
    RRule rRule = null;
    if (sourceMetadata != null && (type.equals(SourceType.SCHEDULE_SINGLE) || type.equals(SourceType.SCHEDULE_MULTIPLE))) {
        Properties configuration;
        try {
            captureAgentId = (String) sourceMetadata.get("device");
            configuration = captureAgentStateService.getAgentConfiguration((String) sourceMetadata.get("device"));
        } catch (Exception e) {
            logger.warn("Unable to parse device {}: because: {}", sourceMetadata.get("device"), getStackTrace(e));
            throw new IllegalArgumentException("Unable to parse device");
        }
        String durationString = (String) sourceMetadata.get("duration");
        if (StringUtils.isBlank(durationString))
            throw new IllegalArgumentException("No duration in source metadata");
        // Create timezone based on CA's reported TZ.
        String agentTimeZone = configuration.getProperty("capture.device.timezone");
        if (StringUtils.isNotBlank(agentTimeZone)) {
            tz = TimeZone.getTimeZone(agentTimeZone);
            dc.set(DublinCores.OC_PROPERTY_AGENT_TIMEZONE, tz.getID());
        } else {
            // No timezone was present, assume the serve's local timezone.
            tz = TimeZone.getDefault();
            logger.debug("The field 'capture.device.timezone' has not been set in the agent configuration. The default server timezone will be used.");
        }
        org.joda.time.DateTime now = new org.joda.time.DateTime(DateTimeZone.UTC);
        start = now.withMillis(DateTimeSupport.fromUTC((String) sourceMetadata.get("start")));
        end = now.withMillis(DateTimeSupport.fromUTC((String) sourceMetadata.get("end")));
        duration = Long.parseLong(durationString);
        DublinCoreValue period = EncodingSchemeUtils.encodePeriod(new DCMIPeriod(start.toDate(), start.plus(duration).toDate()), Precision.Second);
        String inputs = (String) sourceMetadata.get("inputs");
        caProperties.putAll(configuration);
        dc.set(DublinCore.PROPERTY_TEMPORAL, period);
        caProperties.put(CaptureParameters.CAPTURE_DEVICE_NAMES, inputs);
    }
    if (type.equals(SourceType.SCHEDULE_MULTIPLE)) {
        rRule = new RRule((String) sourceMetadata.get("rrule"));
    }
    Map<String, String> configuration = new HashMap<>();
    if (eventHttpServletRequest.getProcessing().get().get("configuration") != null) {
        configuration = new HashMap<>((JSONObject) eventHttpServletRequest.getProcessing().get().get("configuration"));
    }
    for (Entry<String, String> entry : configuration.entrySet()) {
        caProperties.put(WORKFLOW_CONFIG_PREFIX.concat(entry.getKey()), entry.getValue());
    }
    caProperties.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, workflowTemplate);
    eventHttpServletRequest.setMediaPackage(authorizationService.setAcl(eventHttpServletRequest.getMediaPackage().get(), AclScope.Episode, eventHttpServletRequest.getAcl().get()).getA());
    MediaPackage mediaPackage;
    switch(type) {
        case UPLOAD:
        case UPLOAD_LATER:
            eventHttpServletRequest.setMediaPackage(updateDublincCoreCatalog(eventHttpServletRequest.getMediaPackage().get(), dc));
            configuration.put("workflowDefinitionId", workflowTemplate);
            WorkflowInstance ingest = ingestService.ingest(eventHttpServletRequest.getMediaPackage().get(), workflowTemplate, configuration);
            return eventHttpServletRequest.getMediaPackage().get().getIdentifier().compact();
        case SCHEDULE_SINGLE:
            mediaPackage = updateDublincCoreCatalog(eventHttpServletRequest.getMediaPackage().get(), dc);
            eventHttpServletRequest.setMediaPackage(mediaPackage);
            try {
                schedulerService.addEvent(start.toDate(), start.plus(duration).toDate(), captureAgentId, presenterUsernames, mediaPackage, configuration, (Map) caProperties, Opt.<Boolean>none(), Opt.<String>none(), SchedulerService.ORIGIN);
            } finally {
                for (MediaPackageElement mediaPackageElement : mediaPackage.getElements()) {
                    try {
                        workspace.delete(mediaPackage.getIdentifier().toString(), mediaPackageElement.getIdentifier());
                    } catch (NotFoundException | IOException e) {
                        logger.warn("Failed to delete media package element", e);
                    }
                }
            }
            return mediaPackage.getIdentifier().compact();
        case SCHEDULE_MULTIPLE:
            List<Period> periods = schedulerService.calculatePeriods(rRule, start.toDate(), end.toDate(), duration, tz);
            Map<String, Period> scheduled = new LinkedHashMap<>();
            scheduled = schedulerService.addMultipleEvents(rRule, start.toDate(), end.toDate(), duration, tz, captureAgentId, presenterUsernames, eventHttpServletRequest.getMediaPackage().get(), configuration, (Map) caProperties, Opt.none(), Opt.none(), SchedulerService.ORIGIN);
            return StringUtils.join(scheduled.keySet(), ",");
        default:
            logger.warn("Unknown source type {}", type);
            throw new IllegalArgumentException("Unknown source type");
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) WorkflowSet(org.opencastproject.workflow.api.WorkflowSet) RRule(net.fortuna.ical4j.model.property.RRule) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) NotFoundException(org.opencastproject.util.NotFoundException) Properties(java.util.Properties) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) LinkedHashMap(java.util.LinkedHashMap) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) HashSet(java.util.HashSet) DublinCoreValue(org.opencastproject.metadata.dublincore.DublinCoreValue) DCMIPeriod(org.opencastproject.metadata.dublincore.DCMIPeriod) Period(net.fortuna.ical4j.model.Period) DCMIPeriod(org.opencastproject.metadata.dublincore.DCMIPeriod) IOException(java.io.IOException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) IngestException(org.opencastproject.ingest.api.IngestException) WebApplicationException(javax.ws.rs.WebApplicationException) MetadataParsingException(org.opencastproject.metadata.dublincore.MetadataParsingException) EventCommentException(org.opencastproject.event.comment.EventCommentException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) SeriesException(org.opencastproject.series.api.SeriesException) WorkflowException(org.opencastproject.workflow.api.WorkflowException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException) Date(java.util.Date) DateTimeZone(org.joda.time.DateTimeZone) TimeZone(java.util.TimeZone) JSONObject(org.json.simple.JSONObject) MediaPackage(org.opencastproject.mediapackage.MediaPackage) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 7 with UnauthorizedException

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

the class IndexServiceImpl method updateAllEventMetadata.

@Override
public MetadataList updateAllEventMetadata(String id, String metadataJSON, AbstractSearchIndex index) throws IllegalArgumentException, IndexServiceException, NotFoundException, SearchIndexException, UnauthorizedException {
    MetadataList metadataList;
    try {
        metadataList = getMetadataListWithAllEventCatalogUIAdapters();
        metadataList.fromJSON(metadataJSON);
    } catch (Exception e) {
        logger.warn("Not able to parse the event metadata {}: {}", metadataJSON, getStackTrace(e));
        throw new IllegalArgumentException("Not able to parse the event metadata " + metadataJSON, e);
    }
    return updateEventMetadata(id, metadataList, index);
}
Also used : MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) IngestException(org.opencastproject.ingest.api.IngestException) WebApplicationException(javax.ws.rs.WebApplicationException) MetadataParsingException(org.opencastproject.metadata.dublincore.MetadataParsingException) EventCommentException(org.opencastproject.event.comment.EventCommentException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) SeriesException(org.opencastproject.series.api.SeriesException) WorkflowException(org.opencastproject.workflow.api.WorkflowException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException)

Example 8 with UnauthorizedException

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

the class IndexServiceImpl method getEventMediapackage.

@Override
public MediaPackage getEventMediapackage(Event event) throws IndexServiceException {
    switch(getEventSource(event)) {
        case WORKFLOW:
            Opt<WorkflowInstance> currentWorkflowInstance = getCurrentWorkflowInstance(event.getIdentifier());
            if (currentWorkflowInstance.isNone()) {
                logger.error("No workflow instance for event {} found!", event.getIdentifier());
                throw new IndexServiceException("No workflow instance found for event " + event.getIdentifier());
            }
            return currentWorkflowInstance.get().getMediaPackage();
        case ARCHIVE:
            final AQueryBuilder q = assetManager.createQuery();
            final AResult r = q.select(q.snapshot()).where(q.mediaPackageId(event.getIdentifier()).and(q.version().isLatest())).run();
            if (r.getSize() > 0) {
                logger.debug("Found event in archive with id {}", event.getIdentifier());
                return enrich(r).getSnapshots().head2().getMediaPackage();
            }
            logger.error("No event with id {} found from archive!", event.getIdentifier());
            throw new IndexServiceException("No archived event found with id " + event.getIdentifier());
        case SCHEDULE:
            try {
                MediaPackage mediaPackage = schedulerService.getMediaPackage(event.getIdentifier());
                logger.debug("Found event in scheduler with id {}", event.getIdentifier());
                return mediaPackage;
            } catch (NotFoundException e) {
                logger.error("No scheduled event with id {} found!", event.getIdentifier());
                throw new IndexServiceException(e.getMessage(), e);
            } catch (UnauthorizedException e) {
                logger.error("Unauthorized to get event with id {} from scheduler because {}", event.getIdentifier(), getStackTrace(e));
                throw new IndexServiceException(e.getMessage(), e);
            } catch (SchedulerException e) {
                logger.error("Unable to get event with id {} from scheduler because {}", event.getIdentifier(), getStackTrace(e));
                throw new IndexServiceException(e.getMessage(), e);
            }
        default:
            throw new IllegalStateException("Unknown event type!");
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) AQueryBuilder(org.opencastproject.assetmanager.api.query.AQueryBuilder) AResult(org.opencastproject.assetmanager.api.query.AResult) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Example 9 with UnauthorizedException

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

the class SeriesListProvider method getList.

@Override
public Map<String, String> getList(String listName, ResourceListQuery query, Organization organization) throws ListProviderException {
    Map<String, String> series = new HashMap<String, String>();
    SeriesQuery q = new SeriesQuery().setCount(Integer.MAX_VALUE);
    if (query != null) {
        if (query.hasFilter(FILTER_TEXT)) {
            StringListFilter filter = (StringListFilter) query.getFilter(FILTER_TEXT);
            if (filter.getValue().isSome())
                q.setText(filter.getValue().get());
        }
        if (query.getLimit().isSome())
            q.setCount(query.getLimit().get());
        if (query.getOffset().isSome())
            q.setStartPage(query.getOffset().get());
    }
    List<DublinCoreCatalog> result = null;
    try {
        if (!CONTRIBUTORS.equals(listName) && !ORGANIZERS.equals(listName) && !TITLE_EXTENDED.equals(listName)) {
            return seriesService.getIdTitleMapOfAllSeries();
        }
        result = seriesService.getSeries(q).getCatalogList();
    } catch (SeriesException e) {
        throw new ListProviderException("Error appends on the series service: " + e);
    } catch (UnauthorizedException e) {
        throw new ListProviderException("Unauthorized access to series service: " + e);
    }
    for (DublinCoreCatalog dc : result) {
        if (CONTRIBUTORS.equals(listName)) {
            String contributor = dc.getFirst(DublinCore.PROPERTY_CONTRIBUTOR);
            if (StringUtils.isNotBlank(contributor))
                series.put(contributor, contributor);
        } else if (ORGANIZERS.equals(listName)) {
            String organizer = dc.getFirst(DublinCore.PROPERTY_CREATOR);
            if (StringUtils.isNotBlank(organizer))
                series.put(organizer, organizer);
        } else if (TITLE_EXTENDED.equals(listName)) {
            String created = dc.getFirst(DublinCoreCatalog.PROPERTY_CREATED);
            String organizer = dc.getFirst(DublinCore.PROPERTY_CREATOR);
            StringBuilder sb = new StringBuilder(dc.getFirst(DublinCoreCatalog.PROPERTY_TITLE));
            if (StringUtils.isNotBlank(created) && StringUtils.isNotBlank(organizer)) {
                List<String> extendedTitleData = new ArrayList<>();
                if (StringUtils.isNotBlank(created)) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(EncodingSchemeUtils.decodeDate(created));
                    extendedTitleData.add(Integer.toString(calendar.get(Calendar.YEAR)));
                }
                if (StringUtils.isNotBlank(organizer))
                    extendedTitleData.add(organizer);
                sb.append(" (").append(StringUtils.join(extendedTitleData, ", ")).append(")");
            }
            series.put(dc.getFirst(DublinCore.PROPERTY_IDENTIFIER), sb.toString());
        } else {
            series.put(dc.getFirst(DublinCore.PROPERTY_IDENTIFIER), dc.getFirst(DublinCoreCatalog.PROPERTY_TITLE));
        }
    }
    return series;
}
Also used : SeriesQuery(org.opencastproject.series.api.SeriesQuery) HashMap(java.util.HashMap) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) ListProviderException(org.opencastproject.index.service.exception.ListProviderException) SeriesException(org.opencastproject.series.api.SeriesException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) StringListFilter(org.opencastproject.index.service.resources.list.query.StringListFilter)

Example 10 with UnauthorizedException

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

the class SeriesServiceDatabaseImpl method deleteSeries.

/*
   * (non-Javadoc)
   *
   * @see org.opencastproject.series.impl.SeriesServiceDatabase#deleteSeries(java.lang.String)
   */
@Override
public void deleteSeries(String seriesId) throws SeriesServiceDatabaseException, NotFoundException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            throw new NotFoundException("Series with ID " + seriesId + " does not exist");
        }
        // Ensure this user is allowed to delete this series
        String accessControlXml = entity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, Permissions.Action.WRITE.toString())) {
                throw new UnauthorizedException(currentUser + " is not authorized to update series " + seriesId);
            }
        }
        em.remove(entity);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete series: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) SeriesServiceDatabaseException(org.opencastproject.series.impl.SeriesServiceDatabaseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) NoResultException(javax.persistence.NoResultException) SeriesServiceDatabaseException(org.opencastproject.series.impl.SeriesServiceDatabaseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) AccessControlParsingException(org.opencastproject.security.api.AccessControlParsingException)

Aggregations

UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)133 NotFoundException (org.opencastproject.util.NotFoundException)109 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)52 IOException (java.io.IOException)42 SchedulerConflictException (org.opencastproject.scheduler.api.SchedulerConflictException)39 SchedulerTransactionLockException (org.opencastproject.scheduler.api.SchedulerTransactionLockException)38 HttpResponse (org.apache.http.HttpResponse)37 SeriesException (org.opencastproject.series.api.SeriesException)36 WebApplicationException (javax.ws.rs.WebApplicationException)33 Path (javax.ws.rs.Path)29 RestQuery (org.opencastproject.util.doc.rest.RestQuery)29 ParseException (java.text.ParseException)28 MediaPackage (org.opencastproject.mediapackage.MediaPackage)27 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)26 AccessControlList (org.opencastproject.security.api.AccessControlList)22 ArrayList (java.util.ArrayList)21 User (org.opencastproject.security.api.User)21 WorkflowDatabaseException (org.opencastproject.workflow.api.WorkflowDatabaseException)21 HttpGet (org.apache.http.client.methods.HttpGet)19 Date (java.util.Date)18