use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class AssetManagerWithSecurityTest method runWith.
/**
* Evaluate product <code>p</code> in a given security context.
*
* @param user
* the user under whose roles and organization <code>p</code> shall be evaluated
* @param assertAccess
* if true assert that the current user is authorized to evaluate <code>p</code>,
* if false assert that the current user is prohibited to evaluate <code>p</code>
* @param p
* the product that contains the calls to the asset manager
* @return the result of the evaluation of <code>p</code>
*/
private <A> A runWith(User user, boolean assertAccess, P1<A> p) {
final User stashedUser = currentUser;
currentUser = user;
A result = null;
try {
result = p.get1();
if (!assertAccess) {
fail("Access should be prohibited");
}
} catch (Exception e) {
if ((e instanceof UnauthorizedException) && assertAccess) {
fail("Access should be granted");
} else if (!(e instanceof UnauthorizedException)) {
Prelude.chuck(e);
}
}
currentUser = stashedUser;
return result;
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class IngestRestService method schedule.
@POST
@Path("schedule/{wdID}")
@RestQuery(name = "schedule", description = "Schedule an event based on the given media package", pathParameters = { @RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The media package", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(description = "Event scheduled", responseCode = HttpServletResponse.SC_CREATED), @RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "")
public Response schedule(@PathParam("wdID") String wdID, MultivaluedMap<String, String> formData) {
if (StringUtils.isBlank(wdID)) {
logger.trace("workflow definition id is not specified");
return Response.status(Response.Status.BAD_REQUEST).build();
}
Map<String, String> wfConfig = getWorkflowConfig(formData);
if (StringUtils.isNotBlank(wdID)) {
wfConfig.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, wdID);
}
logger.debug("Schedule with workflow definition '{}'", wfConfig.get(WORKFLOW_DEFINITION_ID_PARAM));
String mediaPackageXml = formData.getFirst("mediaPackage");
if (StringUtils.isBlank(mediaPackageXml)) {
logger.debug("Rejected schedule without media package");
return Response.status(Status.BAD_REQUEST).build();
}
MediaPackage mp = null;
try {
mp = factory.newMediaPackageBuilder().loadFromXml(mediaPackageXml);
if (MediaPackageSupport.sanityCheck(mp).isSome()) {
throw new MediaPackageException("Insane media package");
}
} catch (MediaPackageException e) {
logger.debug("Rejected ingest with invalid media package {}", mp);
return Response.status(Status.BAD_REQUEST).build();
}
MediaPackageElement[] mediaPackageElements = mp.getElementsByFlavor(MediaPackageElements.EPISODE);
if (mediaPackageElements.length != 1) {
logger.debug("There can be only one (and exactly one) episode dublin core catalog: https://youtu.be/_J3VeogFUOs");
return Response.status(Status.BAD_REQUEST).build();
}
try {
ingestService.schedule(mp, wdID, wfConfig);
return Response.status(Status.CREATED).build();
} catch (IngestException e) {
return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (SchedulerConflictException e) {
return Response.status(Status.CONFLICT).entity(e.getMessage()).build();
} catch (NotFoundException | UnauthorizedException | SchedulerException e) {
return Response.serverError().build();
}
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class IngestServiceImpl method addZippedMediaPackage.
/**
* {@inheritDoc}
*
* @see org.opencastproject.ingest.api.IngestService#addZippedMediaPackage(java.io.InputStream, java.lang.String,
* java.util.Map, java.lang.Long)
*/
@Override
public WorkflowInstance addZippedMediaPackage(InputStream zipStream, String workflowDefinitionId, Map<String, String> workflowConfig, Long workflowInstanceId) throws MediaPackageException, IOException, IngestException, NotFoundException, UnauthorizedException {
// Start a job synchronously. We can't keep the open input stream waiting around.
Job job = null;
if (StringUtils.isNotBlank(workflowDefinitionId)) {
try {
workflowService.getWorkflowDefinitionById(workflowDefinitionId);
} catch (WorkflowDatabaseException e) {
throw new IngestException(e);
} catch (NotFoundException nfe) {
logger.warn("Workflow definition {} not found, using default workflow {} instead", workflowDefinitionId, defaultWorkflowDefinionId);
workflowDefinitionId = defaultWorkflowDefinionId;
}
}
if (workflowInstanceId != null) {
logger.warn("Deprecated method! Ingesting zipped mediapackage with workflow {}", workflowInstanceId);
} else {
logger.info("Ingesting zipped mediapackage");
}
ZipArchiveInputStream zis = null;
Set<String> collectionFilenames = new HashSet<>();
try {
// We don't need anybody to do the dispatching for us. Therefore we need to make sure that the job is never in
// QUEUED state but set it to INSTANTIATED in the beginning and then manually switch it to RUNNING.
job = serviceRegistry.createJob(JOB_TYPE, INGEST_ZIP, null, null, false, ingestZipJobLoad);
job.setStatus(Status.RUNNING);
job = serviceRegistry.updateJob(job);
// Create the working file target collection for this ingest operation
String wfrCollectionId = Long.toString(job.getId());
zis = new ZipArchiveInputStream(zipStream);
ZipArchiveEntry entry;
MediaPackage mp = null;
Map<String, URI> uris = new HashMap<>();
// Sequential number to append to file names so that, if two files have the same
// name, one does not overwrite the other (see MH-9688)
int seq = 1;
// Folder name to compare with next one to figure out if there's a root folder
String folderName = null;
// Indicates if zip has a root folder or not, initialized as true
boolean hasRootFolder = true;
// While there are entries write them to a collection
while ((entry = zis.getNextZipEntry()) != null) {
try {
if (entry.isDirectory() || entry.getName().contains("__MACOSX"))
continue;
if (entry.getName().endsWith("manifest.xml") || entry.getName().endsWith("index.xml")) {
// Build the mediapackage
mp = loadMediaPackageFromManifest(new ZipEntryInputStream(zis, entry.getSize()));
} else {
logger.info("Storing zip entry {}/{} in working file repository collection '{}'", job.getId(), entry.getName(), wfrCollectionId);
// Since the directory structure is not being mirrored, makes sure the file
// name is different than the previous one(s) by adding a sequential number
String fileName = FilenameUtils.getBaseName(entry.getName()) + "_" + seq++ + "." + FilenameUtils.getExtension(entry.getName());
URI contentUri = workingFileRepository.putInCollection(wfrCollectionId, fileName, new ZipEntryInputStream(zis, entry.getSize()));
collectionFilenames.add(fileName);
// Key is the zip entry name as it is
String key = entry.getName();
uris.put(key, contentUri);
ingestStatistics.add(entry.getSize());
logger.info("Zip entry {}/{} stored at {}", job.getId(), entry.getName(), contentUri);
// Figures out if there's a root folder. Does entry name starts with a folder?
int pos = entry.getName().indexOf('/');
if (pos == -1) {
// No, we can conclude there's no root folder
hasRootFolder = false;
} else if (hasRootFolder && folderName != null && !folderName.equals(entry.getName().substring(0, pos))) {
// Folder name different from previous so there's no root folder
hasRootFolder = false;
} else if (folderName == null) {
// Just initialize folder name
folderName = entry.getName().substring(0, pos);
}
}
} catch (IOException e) {
logger.warn("Unable to process zip entry {}: {}", entry.getName(), e);
throw e;
}
}
if (mp == null)
throw new MediaPackageException("No manifest found in this zip");
// Determine the mediapackage identifier
if (mp.getIdentifier() == null || isBlank(mp.getIdentifier().toString()))
mp.setIdentifier(new UUIDIdBuilderImpl().createNew());
String mediaPackageId = mp.getIdentifier().toString();
logger.info("Ingesting mediapackage {} is named '{}'", mediaPackageId, mp.getTitle());
// Make sure there are tracks in the mediapackage
if (mp.getTracks().length == 0) {
logger.warn("Mediapackage {} has no media tracks", mediaPackageId);
}
// Update the element uris to point to their working file repository location
for (MediaPackageElement element : mp.elements()) {
// Key has root folder name if there is one
URI uri = uris.get((hasRootFolder ? folderName + "/" : "") + element.getURI().toString());
if (uri == null)
throw new MediaPackageException("Unable to map element name '" + element.getURI() + "' to workspace uri");
logger.info("Ingested mediapackage element {}/{} located at {}", mediaPackageId, element.getIdentifier(), uri);
URI dest = workingFileRepository.moveTo(wfrCollectionId, FilenameUtils.getName(uri.toString()), mediaPackageId, element.getIdentifier(), FilenameUtils.getName(element.getURI().toString()));
element.setURI(dest);
// TODO: This should be triggered somehow instead of being handled here
if (MediaPackageElements.SERIES.equals(element.getFlavor())) {
logger.info("Ingested mediapackage {} contains updated series information", mediaPackageId);
updateSeries(element.getURI());
}
}
// Now that all elements are in place, start with ingest
logger.info("Initiating processing of ingested mediapackage {}", mediaPackageId);
WorkflowInstance workflowInstance = ingest(mp, workflowDefinitionId, workflowConfig, workflowInstanceId);
logger.info("Ingest of mediapackage {} done", mediaPackageId);
job.setStatus(Job.Status.FINISHED);
return workflowInstance;
} catch (ServiceRegistryException e) {
throw new IngestException(e);
} catch (MediaPackageException e) {
job.setStatus(Job.Status.FAILED, Job.FailureReason.DATA);
throw e;
} catch (Exception e) {
if (e instanceof IngestException)
throw (IngestException) e;
throw new IngestException(e);
} finally {
IOUtils.closeQuietly(zis);
finallyUpdateJob(job);
for (String filename : collectionFilenames) {
workingFileRepository.deleteFromCollection(Long.toString(job.getId()), filename, true);
}
}
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class IndexServiceImpl method createSeries.
@Override
public String createSeries(String metadata) throws IllegalArgumentException, IndexServiceException, UnauthorizedException {
JSONObject metadataJson = null;
try {
metadataJson = (JSONObject) new JSONParser().parse(metadata);
} catch (Exception e) {
logger.warn("Unable to parse metadata {}", metadata);
throw new IllegalArgumentException("Unable to parse metadata" + metadata);
}
if (metadataJson == null)
throw new IllegalArgumentException("No metadata set to create series");
JSONArray seriesMetadataJson = (JSONArray) metadataJson.get("metadata");
if (seriesMetadataJson == null)
throw new IllegalArgumentException("No metadata field in metadata");
JSONObject options = (JSONObject) metadataJson.get("options");
if (options == null)
throw new IllegalArgumentException("No options field in metadata");
Opt<Long> themeId = Opt.none();
Long theme = (Long) metadataJson.get("theme");
if (theme != null) {
themeId = Opt.some(theme);
}
Map<String, String> optionsMap;
try {
optionsMap = JSONUtils.toMap(new org.codehaus.jettison.json.JSONObject(options.toJSONString()));
} catch (JSONException e) {
logger.warn("Unable to parse options to map: {}", getStackTrace(e));
throw new IllegalArgumentException("Unable to parse options to map");
}
DublinCoreCatalog dc = DublinCores.mkOpencastSeries().getCatalog();
dc.set(PROPERTY_IDENTIFIER, UUID.randomUUID().toString());
dc.set(DublinCore.PROPERTY_CREATED, EncodingSchemeUtils.encodeDate(new Date(), Precision.Second));
for (Entry<String, String> entry : optionsMap.entrySet()) {
dc.set(new EName(DublinCores.OC_PROPERTY_NS_URI, entry.getKey()), entry.getValue());
}
MetadataList metadataList;
try {
metadataList = getMetadataListWithAllSeriesCatalogUIAdapters();
metadataList.fromJSON(seriesMetadataJson.toJSONString());
} catch (Exception e) {
logger.warn("Not able to parse the series metadata {}: {}", seriesMetadataJson, getStackTrace(e));
throw new IllegalArgumentException("Not able to parse the series metadata");
}
Opt<MetadataCollection> seriesMetadata = metadataList.getMetadataByFlavor(MediaPackageElements.SERIES.toString());
if (seriesMetadata.isSome()) {
DublinCoreMetadataUtil.updateDublincoreCatalog(dc, seriesMetadata.get());
}
AccessControlList acl = getAccessControlList(metadataJson);
String seriesId;
try {
DublinCoreCatalog createdSeries = seriesService.updateSeries(dc);
seriesId = createdSeries.getFirst(PROPERTY_IDENTIFIER);
seriesService.updateAccessControl(seriesId, acl);
for (Long id : themeId) seriesService.updateSeriesProperty(seriesId, THEME_PROPERTY_NAME, Long.toString(id));
} catch (Exception e) {
logger.error("Unable to create new series: {}", getStackTrace(e));
throw new IndexServiceException("Unable to create new series");
}
updateSeriesMetadata(seriesId, metadataList);
return seriesId;
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class IndexServiceImpl method updateMediaPackageMetadata.
private void updateMediaPackageMetadata(MediaPackage mp, MetadataList metadataList) {
String oldSeriesId = mp.getSeries();
for (EventCatalogUIAdapter catalogUIAdapter : getEventCatalogUIAdapters()) {
Opt<MetadataCollection> metadata = metadataList.getMetadataByAdapter(catalogUIAdapter);
if (metadata.isSome() && metadata.get().isUpdated()) {
catalogUIAdapter.storeFields(mp, metadata.get());
}
}
// update series catalogs
if (!StringUtils.equals(oldSeriesId, mp.getSeries())) {
List<String> seriesDcTags = new ArrayList<>();
List<String> seriesAclTags = new ArrayList<>();
Map<String, List<String>> seriesExtDcTags = new HashMap<>();
if (StringUtils.isNotBlank(oldSeriesId)) {
// remove series dublincore from the media package
for (MediaPackageElement mpe : mp.getElementsByFlavor(MediaPackageElements.SERIES)) {
mp.remove(mpe);
for (String tag : mpe.getTags()) {
seriesDcTags.add(tag);
}
}
// remove series ACL from the media package
for (MediaPackageElement mpe : mp.getElementsByFlavor(MediaPackageElements.XACML_POLICY_SERIES)) {
mp.remove(mpe);
for (String tag : mpe.getTags()) {
seriesAclTags.add(tag);
}
}
// remove series extended metadata from the media package
try {
Opt<Map<String, byte[]>> oldSeriesElementsOpt = seriesService.getSeriesElements(oldSeriesId);
for (Map<String, byte[]> oldSeriesElements : oldSeriesElementsOpt) {
for (String oldSeriesElementType : oldSeriesElements.keySet()) {
for (MediaPackageElement mpe : mp.getElementsByFlavor(MediaPackageElementFlavor.flavor(oldSeriesElementType, "series"))) {
mp.remove(mpe);
String elementType = mpe.getFlavor().getType();
if (StringUtils.isNotBlank(elementType)) {
// remember the tags for this type of element
if (!seriesExtDcTags.containsKey(elementType)) {
// initialize the tags list on the first occurrence of this element type
seriesExtDcTags.put(elementType, new ArrayList<>());
}
for (String tag : mpe.getTags()) {
seriesExtDcTags.get(elementType).add(tag);
}
}
}
}
}
} catch (SeriesException e) {
logger.info("Unable to retrieve series element types from series service for the series {}", oldSeriesId, e);
}
}
if (StringUtils.isNotBlank(mp.getSeries())) {
// add updated series dublincore to the media package
try {
DublinCoreCatalog seriesDC = seriesService.getSeries(mp.getSeries());
if (seriesDC != null) {
mp.setSeriesTitle(seriesDC.getFirst(DublinCore.PROPERTY_TITLE));
try (InputStream in = IOUtils.toInputStream(seriesDC.toXmlString(), "UTF-8")) {
String elementId = UUID.randomUUID().toString();
URI catalogUrl = workspace.put(mp.getIdentifier().compact(), elementId, "dublincore.xml", in);
MediaPackageElement mpe = mp.add(catalogUrl, MediaPackageElement.Type.Catalog, MediaPackageElements.SERIES);
mpe.setIdentifier(elementId);
mpe.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, workspace.read(catalogUrl)));
if (StringUtils.isNotBlank(oldSeriesId)) {
for (String tag : seriesDcTags) {
mpe.addTag(tag);
}
} else {
// add archive tag to the element if the media package had no series set before
mpe.addTag("archive");
}
} catch (IOException e) {
throw new IllegalStateException("Unable to add the series dublincore to the media package " + mp.getIdentifier(), e);
}
}
} catch (SeriesException e) {
throw new IllegalStateException("Unable to retrieve series dublincore catalog for the series " + mp.getSeries(), e);
} catch (NotFoundException | UnauthorizedException e) {
throw new IllegalArgumentException("Unable to retrieve series dublincore catalog for the series " + mp.getSeries(), e);
}
// add updated series ACL to the media package
try {
AccessControlList seriesAccessControl = seriesService.getSeriesAccessControl(mp.getSeries());
if (seriesAccessControl != null) {
mp = authorizationService.setAcl(mp, AclScope.Series, seriesAccessControl).getA();
for (MediaPackageElement seriesAclMpe : mp.getElementsByFlavor(MediaPackageElements.XACML_POLICY_SERIES)) {
if (StringUtils.isNotBlank(oldSeriesId)) {
for (String tag : seriesAclTags) {
seriesAclMpe.addTag(tag);
}
} else {
// add archive tag to the element if the media package had no series set before
seriesAclMpe.addTag("archive");
}
}
}
} catch (SeriesException e) {
throw new IllegalStateException("Unable to retrieve series ACL for series " + oldSeriesId, e);
} catch (NotFoundException e) {
logger.debug("There is no ACL set for the series {}", mp.getSeries());
}
// add updated series extended metadata to the media package
try {
Opt<Map<String, byte[]>> seriesElementsOpt = seriesService.getSeriesElements(mp.getSeries());
for (Map<String, byte[]> seriesElements : seriesElementsOpt) {
for (String seriesElementType : seriesElements.keySet()) {
try (InputStream in = new ByteArrayInputStream(seriesElements.get(seriesElementType))) {
String elementId = UUID.randomUUID().toString();
URI catalogUrl = workspace.put(mp.getIdentifier().compact(), elementId, "dublincore.xml", in);
MediaPackageElement mpe = mp.add(catalogUrl, MediaPackageElement.Type.Catalog, MediaPackageElementFlavor.flavor(seriesElementType, "series"));
mpe.setIdentifier(elementId);
mpe.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, workspace.read(catalogUrl)));
if (StringUtils.isNotBlank(oldSeriesId)) {
if (seriesExtDcTags.containsKey(seriesElementType)) {
for (String tag : seriesExtDcTags.get(seriesElementType)) {
mpe.addTag(tag);
}
}
} else {
// add archive tag to the element if the media package had no series set before
mpe.addTag("archive");
}
} catch (IOException e) {
throw new IllegalStateException(String.format("Unable to serialize series element %s for the series %s", seriesElementType, mp.getSeries()), e);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Unable to retrieve series element dublincore catalog for the series " + mp.getSeries(), e);
}
}
}
} catch (SeriesException e) {
throw new IllegalStateException("Unable to retrieve series elements for the series " + mp.getSeries(), e);
}
}
}
}
Aggregations