Search in sources :

Example 66 with UnauthorizedException

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

the class EventsEndpoint method updateEvent.

private Response updateEvent(String eventId, HttpServletRequest request) {
    try {
        Opt<String> startDatePattern = configuredMetadataFields.containsKey("startDate") ? configuredMetadataFields.get("startDate").getPattern() : Opt.none();
        Opt<String> startTimePattern = configuredMetadataFields.containsKey("startTime") ? configuredMetadataFields.get("startTime").getPattern() : Opt.none();
        for (final Event event : indexService.getEvent(eventId, externalIndex)) {
            EventHttpServletRequest eventHttpServletRequest = EventHttpServletRequest.updateFromHttpServletRequest(event, request, getEventCatalogUIAdapters(), startDatePattern, startTimePattern);
            if (eventHttpServletRequest.getMetadataList().isSome()) {
                indexService.updateEventMetadata(eventId, eventHttpServletRequest.getMetadataList().get(), externalIndex);
            }
            if (eventHttpServletRequest.getAcl().isSome()) {
                indexService.updateEventAcl(eventId, eventHttpServletRequest.getAcl().get(), externalIndex);
            }
            return ApiResponses.Json.noContent(ApiVersion.VERSION_1_0_0);
        }
        return ApiResponses.notFound("Cannot find an event with id '%s'.", eventId);
    } catch (NotFoundException e) {
        return ApiResponses.notFound("Cannot find an event with id '%s'.", eventId);
    } catch (UnauthorizedException e) {
        return Response.status(Status.UNAUTHORIZED).build();
    } catch (IllegalArgumentException e) {
        logger.debug("Unable to update event '{}' because: {}", eventId, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.badRequest(e.getMessage());
    } catch (IndexServiceException e) {
        logger.error("Unable to get multi part fields or file for event '{}' because: {}", eventId, ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    } catch (SearchIndexException e) {
        logger.error("Unable to update event '{}' because: {}", eventId, ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : EventHttpServletRequest(org.opencastproject.index.service.impl.index.event.EventHttpServletRequest) WebApplicationException(javax.ws.rs.WebApplicationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) Event(org.opencastproject.index.service.impl.index.event.Event) NotFoundException(org.opencastproject.util.NotFoundException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Example 67 with UnauthorizedException

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

the class SeriesEndpoint method getSeriesList.

@GET
@Path("")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "getseries", description = "Returns a list of series.", returnDescription = "", restParameters = { @RestParameter(name = "filter", isRequired = false, description = "A comma seperated list of filters to limit the results with. A filter is the filter's name followed by a colon \":\" and then the value to filter with so it is the form <Filter Name>:<Value to Filter With>.", type = STRING), @RestParameter(name = "sort", description = "Sort the results based upon a list of comma seperated sorting criteria. In the comma seperated list each type of sorting is specified as a pair such as: <Sort Name>:ASC or <Sort Name>:DESC. Adding the suffix ASC or DESC sets the order as ascending or descending order and is mandatory.", isRequired = false, type = STRING), @RestParameter(name = "limit", description = "The maximum number of results to return for a single request.", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "offset", description = "Number of results to skip based on the limit. 0 is the first set of results up to the limit, 1 is the second set of results after the first limit, 2 is third set of results after skipping the first two sets of results etc.", isRequired = false, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "A (potentially empty) list of series is returned.", responseCode = HttpServletResponse.SC_OK) })
public Response getSeriesList(@HeaderParam("Accept") String acceptHeader, @QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("order") String order, @QueryParam("offset") int offset, @QueryParam("limit") int limit) throws UnauthorizedException {
    try {
        SeriesSearchQuery query = new SeriesSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
        Option<String> optSort = Option.option(trimToNull(sort));
        if (offset > 0) {
            query.withOffset(offset);
        }
        // If limit is 0, we set the default limit
        query.withLimit(limit < 1 ? DEFAULT_LIMIT : limit);
        // Parse the filters
        if (StringUtils.isNotBlank(filter)) {
            for (String f : filter.split(",")) {
                String[] filterTuple = f.split(":");
                if (filterTuple.length != 2) {
                    logger.info("No value for filter {} in filters list: {}", filterTuple[0], filter);
                    continue;
                }
                String name = filterTuple[0];
                String value = filterTuple[1];
                if ("managedAcl".equals(name)) {
                    query.withAccessPolicy(value);
                } else if ("contributors".equals(name)) {
                    query.withContributor(value);
                } else if ("CreationDate".equals(name)) {
                    if (name.split("/").length == 2) {
                        try {
                            Tuple<Date, Date> fromAndToCreationRange = getFromAndToCreationRange(name.split("/")[0], name.split("/")[1]);
                            query.withCreatedFrom(fromAndToCreationRange.getA());
                            query.withCreatedTo(fromAndToCreationRange.getB());
                        } catch (IllegalArgumentException e) {
                            return RestUtil.R.badRequest(e.getMessage());
                        }
                    }
                    query.withCreator(value);
                } else if ("Creator".equals(name)) {
                    query.withCreator(value);
                } else if ("textFilter".equals(name)) {
                    query.withText("*" + value + "*");
                } else if ("language".equals(name)) {
                    query.withLanguage(value);
                } else if ("license".equals(name)) {
                    query.withLicense(value);
                } else if ("organizers".equals(name)) {
                    query.withOrganizer(value);
                } else if ("subject".equals(name)) {
                    query.withSubject(value);
                } else if ("title".equals(name)) {
                    query.withTitle(value);
                }
            }
        }
        if (optSort.isSome()) {
            Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
            for (SortCriterion criterion : sortCriteria) {
                switch(criterion.getFieldName()) {
                    case SeriesIndexSchema.TITLE:
                        query.sortByTitle(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CONTRIBUTORS:
                        query.sortByContributors(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CREATOR:
                        query.sortByOrganizers(criterion.getOrder());
                        break;
                    case EventIndexSchema.CREATED:
                        query.sortByCreatedDateTime(criterion.getOrder());
                        break;
                    default:
                        logger.info("Unknown filter criteria {}", criterion.getFieldName());
                        return Response.status(SC_BAD_REQUEST).build();
                }
            }
        }
        logger.trace("Using Query: " + query.toString());
        SearchResult<Series> result = externalIndex.getByQuery(query);
        return ApiResponses.Json.ok(VERSION_1_0_0, arr($(result.getItems()).map(new Fn<SearchResultItem<Series>, JValue>() {

            @Override
            public JValue apply(SearchResultItem<Series> a) {
                final Series s = a.getSource();
                JValue subjects;
                if (s.getSubject() == null) {
                    subjects = arr();
                } else {
                    subjects = arr(splitSubjectIntoArray(s.getSubject()));
                }
                Date createdDate = s.getCreatedDateTime();
                return obj(f("identifier", v(s.getIdentifier())), f("title", v(s.getTitle())), f("creator", v(s.getCreator(), BLANK)), f("created", v(createdDate != null ? toUTC(createdDate.getTime()) : null, BLANK)), f("subjects", subjects), f("contributors", arr($(s.getContributors()).map(Functions.stringToJValue))), f("organizers", arr($(s.getOrganizers()).map(Functions.stringToJValue))), f("publishers", arr($(s.getPublishers()).map(Functions.stringToJValue))));
            }
        }).toList()));
    } catch (Exception e) {
        logger.warn("Could not perform search query: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SeriesSearchQuery(org.opencastproject.index.service.impl.index.series.SeriesSearchQuery) Fn(com.entwinemedia.fn.Fn) SearchResultItem(org.opencastproject.matterhorn.search.SearchResultItem) Date(java.util.Date) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) SeriesException(org.opencastproject.series.api.SeriesException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) WebApplicationException(javax.ws.rs.WebApplicationException) ParseException(org.json.simple.parser.ParseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Series(org.opencastproject.index.service.impl.index.series.Series) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 68 with UnauthorizedException

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

the class AssetManagerWithSecurity method takeSnapshot.

@Override
public Snapshot takeSnapshot(String owner, MediaPackage mp) {
    if (isAuthorizedByAcl(mp, WRITE_ACTION)) {
        final Snapshot snapshot = super.takeSnapshot(owner, mp);
        final AccessControlList acl = authSvc.getActiveAcl(mp).getA();
        storeAclAsProperties(snapshot, acl);
        return snapshot;
    } else {
        return chuck(new UnauthorizedException("Not allowed to take snapshot of media package " + mp.getIdentifier().toString()));
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) Snapshot(org.opencastproject.assetmanager.api.Snapshot) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException)

Example 69 with UnauthorizedException

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

the class PublishEngageWorkflowOperationHandler method retractFromEngage.

/**
 * Removes every Publication for Searchindex from Mediapackage
 * Removes Mediapackage from Searchindex
 * @param mediaPackage Mediapackage
 * @param mediaPackageForSearch Mediapackage prepared for searchIndex
 * @throws WorkflowOperationException
 */
private void retractFromEngage(MediaPackage mediaPackage) throws WorkflowOperationException {
    List<Job> jobs = new ArrayList<Job>();
    Set<String> elementIds = new HashSet<String>();
    try {
        MediaPackage distributedMediaPackage = getDistributedMediapackage(mediaPackage.toString());
        if (distributedMediaPackage != null) {
            for (MediaPackageElement element : distributedMediaPackage.getElements()) {
                elementIds.add(element.getIdentifier());
            }
            // bulk retraction
            if (elementIds.size() > 0) {
                Job retractDownloadDistributionJob = downloadDistributionService.retract(CHANNEL_ID, distributedMediaPackage, elementIds);
                if (retractDownloadDistributionJob != null) {
                    jobs.add(retractDownloadDistributionJob);
                }
            }
            if (distributeStreaming) {
                for (MediaPackageElement element : distributedMediaPackage.getElements()) {
                    Job retractStreamingJob = streamingDistributionService.retract(CHANNEL_ID, distributedMediaPackage, element.getIdentifier());
                    if (retractStreamingJob != null) {
                        jobs.add(retractStreamingJob);
                    }
                }
            }
            Job deleteSearchJob = null;
            logger.info("Retracting already published Elements for Mediapackage: {}", mediaPackage.getIdentifier().toString());
            deleteSearchJob = searchService.delete(mediaPackage.getIdentifier().toString());
            if (deleteSearchJob != null) {
                jobs.add(deleteSearchJob);
            }
        }
        // Wait until all retraction jobs have returned
        if (!waitForStatus(jobs.toArray(new Job[jobs.size()])).isSuccess()) {
            throw new WorkflowOperationException("One of the retraction jobs did not complete successfully");
        }
    } catch (DistributionException e) {
        throw new WorkflowOperationException(e);
    } catch (SearchException e) {
        throw new WorkflowOperationException("Error retracting media package", e);
    } catch (UnauthorizedException | NotFoundException ex) {
        logger.error("Retraction failed of Mediapackage: { }", mediaPackage.getIdentifier().toString(), ex);
    }
}
Also used : ArrayList(java.util.ArrayList) SearchException(org.opencastproject.search.api.SearchException) NotFoundException(org.opencastproject.util.NotFoundException) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) DistributionException(org.opencastproject.distribution.api.DistributionException) Job(org.opencastproject.job.api.Job) HashSet(java.util.HashSet)

Example 70 with UnauthorizedException

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

the class IndexServiceImpl method updateCommonEventMetadata.

@Override
public MetadataList updateCommonEventMetadata(String id, String metadataJSON, AbstractSearchIndex index) throws IllegalArgumentException, IndexServiceException, SearchIndexException, NotFoundException, UnauthorizedException {
    MetadataList metadataList;
    try {
        metadataList = getMetadataListWithCommonEventCatalogUIAdapter();
        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)

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