Search in sources :

Example 6 with MediaPackageElementFlavor

use of org.opencastproject.mediapackage.MediaPackageElementFlavor in project opencast by opencast.

the class AbstractMediaPackageElementSelector method addFlavorAt.

/**
 * Adds the given flavor to the list of flavors.
 * <p>
 * Note that the order is relevant to the selection of the track returned by this selector.
 *
 * @param index
 *          the position in the list
 * @param flavor
 *          the flavor to add
 */
public void addFlavorAt(int index, String flavor) {
    if (flavor == null)
        throw new IllegalArgumentException("Flavor must not be null");
    MediaPackageElementFlavor f = MediaPackageElementFlavor.parseFlavor(flavor);
    flavors.add(index, f);
    for (int i = index + 1; i < flavors.size(); i++) {
        if (flavors.get(i).equals(f))
            flavors.remove(i);
    }
}
Also used : MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor)

Example 7 with MediaPackageElementFlavor

use of org.opencastproject.mediapackage.MediaPackageElementFlavor in project opencast by opencast.

the class IndexServiceImpl method createEvent.

@Override
public String createEvent(HttpServletRequest request) throws IndexServiceException {
    JSONObject metadataJson = null;
    MediaPackage mp = null;
    // regex for form field name matching an attachment or a catalog
    // The first sub items identifies if the file is an attachment or catalog
    // The second is the item flavor
    // Example form field names:  "catalog/captions/timedtext" and "attachment/captions/vtt"
    // The prefix of field name for attachment and catalog
    List<String> assetList = new LinkedList<String>();
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            mp = ingestService.createMediaPackage();
            for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext(); ) {
                FileItemStream item = iter.next();
                String fieldName = item.getFieldName();
                if (item.isFormField()) {
                    if ("metadata".equals(fieldName)) {
                        String metadata = Streams.asString(item.openStream());
                        try {
                            metadataJson = (JSONObject) new JSONParser().parse(metadata);
                        } catch (Exception e) {
                            logger.warn("Unable to parse metadata {}", metadata);
                            throw new IllegalArgumentException("Unable to parse metadata");
                        }
                    }
                } else {
                    if ("presenter".equals(item.getFieldName())) {
                        mp = ingestService.addTrack(item.openStream(), item.getName(), MediaPackageElements.PRESENTER_SOURCE, mp);
                    } else if ("presentation".equals(item.getFieldName())) {
                        mp = ingestService.addTrack(item.openStream(), item.getName(), MediaPackageElements.PRESENTATION_SOURCE, mp);
                    } else if ("audio".equals(item.getFieldName())) {
                        mp = ingestService.addTrack(item.openStream(), item.getName(), new MediaPackageElementFlavor("presenter-audio", "source"), mp);
                    // For dynamic uploads, cannot get flavor at this point, so saving with temporary flavor
                    } else if (item.getFieldName().toLowerCase().matches(attachmentRegex)) {
                        assetList.add(item.getFieldName());
                        mp = ingestService.addAttachment(item.openStream(), item.getName(), new MediaPackageElementFlavor(item.getFieldName(), "*"), mp);
                    } else if (item.getFieldName().toLowerCase().matches(catalogRegex)) {
                        // Cannot get flavor at this point, so saving with temporary flavor
                        assetList.add(item.getFieldName());
                        mp = ingestService.addCatalog(item.openStream(), item.getName(), new MediaPackageElementFlavor(item.getFieldName(), "*"), mp);
                    } else if (item.getFieldName().toLowerCase().matches(trackRegex)) {
                        // Cannot get flavor at this point, so saving with temporary flavor
                        assetList.add(item.getFieldName());
                        mp = ingestService.addTrack(item.openStream(), item.getName(), new MediaPackageElementFlavor(item.getFieldName(), "*"), mp);
                    } else {
                        logger.warn("Unknown field name found {}", item.getFieldName());
                    }
                }
            }
            // MH-12085 update the flavors of any newly added assets.
            try {
                JSONArray assetMetadata = (JSONArray) ((JSONObject) metadataJson.get("assets")).get("options");
                if (assetMetadata != null) {
                    mp = updateMpAssetFlavor(assetList, mp, assetMetadata, isOverwriteExistingAsset);
                }
            } catch (Exception e) {
                // Assuming a parse error versus a file error and logging the error type
                logger.warn("Unable to process asset metadata {}", metadataJson.get("assets"), e);
                throw new IllegalArgumentException("Unable to parse metadata", e);
            }
        } else {
            throw new IllegalArgumentException("No multipart content");
        }
        // MH-10834 If there is only an audio track, change the flavor from presenter-audio/source to presenter/source.
        if (mp.getTracks().length == 1 && mp.getTracks()[0].getFlavor().equals(new MediaPackageElementFlavor("presenter-audio", "source"))) {
            Track audioTrack = mp.getTracks()[0];
            mp.remove(audioTrack);
            audioTrack.setFlavor(MediaPackageElements.PRESENTER_SOURCE);
            mp.add(audioTrack);
        }
        return createEvent(metadataJson, mp);
    } catch (Exception e) {
        logger.error("Unable to create event: {}", getStackTrace(e));
        throw new IndexServiceException(e.getMessage());
    }
}
Also used : JSONArray(org.json.simple.JSONArray) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) LinkedList(java.util.LinkedList) 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) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) JSONObject(org.json.simple.JSONObject) FileItemStream(org.apache.commons.fileupload.FileItemStream) MediaPackage(org.opencastproject.mediapackage.MediaPackage) JSONParser(org.json.simple.parser.JSONParser) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) Track(org.opencastproject.mediapackage.Track) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Example 8 with MediaPackageElementFlavor

use of org.opencastproject.mediapackage.MediaPackageElementFlavor in project opencast by opencast.

the class EventHttpServletRequest method deserializeMetadataList.

/**
 * Change the simplified fields of key values provided to the external api into a {@link MetadataList}.
 *
 * @param json
 *          The json string that contains an array of metadata field lists for the different catalogs.
 * @param startDatePattern
 *          The pattern to use to parse the start date from the json payload.
 * @param startTimePattern
 *          The pattern to use to parse the start time from the json payload.
 * @return A {@link MetadataList} with the fields populated with the values provided.
 * @throws ParseException
 *           Thrown if unable to parse the json string.
 * @throws NotFoundException
 *           Thrown if unable to find the catalog or field that the json refers to.
 */
protected static MetadataList deserializeMetadataList(String json, List<EventCatalogUIAdapter> catalogAdapters, Opt<String> startDatePattern, Opt<String> startTimePattern) throws ParseException, NotFoundException, java.text.ParseException {
    MetadataList metadataList = new MetadataList();
    JSONParser parser = new JSONParser();
    JSONArray jsonCatalogs = (JSONArray) parser.parse(json);
    for (int i = 0; i < jsonCatalogs.size(); i++) {
        JSONObject catalog = (JSONObject) jsonCatalogs.get(i);
        if (catalog.get("flavor") == null || StringUtils.isBlank(catalog.get("flavor").toString())) {
            throw new IllegalArgumentException("Unable to create new event as no flavor was given for one of the metadata collections");
        }
        String flavorString = catalog.get("flavor").toString();
        MediaPackageElementFlavor flavor = MediaPackageElementFlavor.parseFlavor(flavorString);
        MetadataCollection collection = null;
        EventCatalogUIAdapter adapter = null;
        for (EventCatalogUIAdapter eventCatalogUIAdapter : catalogAdapters) {
            if (eventCatalogUIAdapter.getFlavor().equals(flavor)) {
                adapter = eventCatalogUIAdapter;
                collection = eventCatalogUIAdapter.getRawFields();
            }
        }
        if (collection == null) {
            throw new IllegalArgumentException(String.format("Unable to find an EventCatalogUIAdapter with Flavor '%s'", flavorString));
        }
        String fieldsJson = catalog.get("fields").toString();
        if (StringUtils.trimToNull(fieldsJson) != null) {
            Map<String, String> fields = RequestUtils.getKeyValueMap(fieldsJson);
            for (String key : fields.keySet()) {
                if ("subjects".equals(key)) {
                    // Handle the special case of allowing subjects to be an array.
                    MetadataField<?> field = collection.getOutputFields().get(DublinCore.PROPERTY_SUBJECT.getLocalName());
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id 'subject' from Catalog with Flavor '%s'.", flavorString));
                    }
                    collection.removeField(field);
                    try {
                        JSONArray subjects = (JSONArray) parser.parse(fields.get(key));
                        collection.addField(MetadataField.copyMetadataFieldWithValue(field, StringUtils.join(subjects.iterator(), ",")));
                    } catch (ParseException e) {
                        throw new IllegalArgumentException(String.format("Unable to parse the 'subjects' metadata array field because: %s", e.toString()));
                    }
                } else if ("startDate".equals(key)) {
                    // Special handling for start date since in API v1 we expect start date and start time to be separate fields.
                    MetadataField<String> field = (MetadataField<String>) collection.getOutputFields().get(key);
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", key, flavorString));
                    }
                    SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(startDatePattern.getOr(field.getPattern().get()));
                    SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
                    DateTime newStartDate = new DateTime(apiSdf.parse(fields.get(key)), DateTimeZone.UTC);
                    if (field.getValue().isSome()) {
                        DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
                        newStartDate = oldStartDate.withDate(newStartDate.year().get(), newStartDate.monthOfYear().get(), newStartDate.dayOfMonth().get());
                    }
                    collection.removeField(field);
                    collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(newStartDate.toDate())));
                } else if ("startTime".equals(key)) {
                    // Special handling for start time since in API v1 we expect start date and start time to be separate fields.
                    MetadataField<String> field = (MetadataField<String>) collection.getOutputFields().get("startDate");
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", "startDate", flavorString));
                    }
                    SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(startTimePattern.getOr("HH:mm"));
                    SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
                    DateTime newStartDate = new DateTime(apiSdf.parse(fields.get(key)), DateTimeZone.UTC);
                    if (field.getValue().isSome()) {
                        DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
                        newStartDate = oldStartDate.withTime(newStartDate.hourOfDay().get(), newStartDate.minuteOfHour().get(), newStartDate.secondOfMinute().get(), newStartDate.millisOfSecond().get());
                    }
                    collection.removeField(field);
                    collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(newStartDate.toDate())));
                } else {
                    MetadataField<?> field = collection.getOutputFields().get(key);
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", key, flavorString));
                    }
                    collection.removeField(field);
                    collection.addField(MetadataField.copyMetadataFieldWithValue(field, fields.get(key)));
                }
            }
        }
        metadataList.add(adapter, collection);
    }
    setStartDateAndTimeIfUnset(metadataList);
    return metadataList;
}
Also used : JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) DateTime(org.joda.time.DateTime) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) JSONObject(org.json.simple.JSONObject) EventCatalogUIAdapter(org.opencastproject.metadata.dublincore.EventCatalogUIAdapter) JSONParser(org.json.simple.parser.JSONParser) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) ParseException(org.json.simple.parser.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 9 with MediaPackageElementFlavor

use of org.opencastproject.mediapackage.MediaPackageElementFlavor in project opencast by opencast.

the class FileUploadRestService method getNewJob.

// </editor-fold>
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("newjob")
@RestQuery(name = "newjob", description = "Creates a new upload job and returns the jobs ID.", restParameters = { @RestParameter(description = "The name of the file that will be uploaded", isRequired = false, name = REQUESTFIELD_FILENAME, type = RestParameter.Type.STRING), @RestParameter(description = "The size of the file that will be uploaded", isRequired = false, name = REQUESTFIELD_FILESIZE, type = RestParameter.Type.STRING), @RestParameter(description = "The size of the chunks that will be uploaded", isRequired = false, name = REQUESTFIELD_CHUNKSIZE, type = RestParameter.Type.STRING), @RestParameter(description = "The flavor of this track", isRequired = false, name = REQUESTFIELD_FLAVOR, type = RestParameter.Type.STRING), @RestParameter(description = "The mediapackage the file should belong to", isRequired = false, name = REQUESTFIELD_MEDIAPACKAGE, type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(description = "job was successfully created", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "upload service gave an error", responseCode = HttpServletResponse.SC_NO_CONTENT) }, returnDescription = "The ID of the newly created upload job")
public Response getNewJob(@FormParam(REQUESTFIELD_FILENAME) String filename, @FormParam(REQUESTFIELD_FILESIZE) long filesize, @FormParam(REQUESTFIELD_CHUNKSIZE) int chunksize, @FormParam(REQUESTFIELD_MEDIAPACKAGE) String mediapackage, @FormParam(REQUESTFIELD_FLAVOR) String flav) {
    try {
        if (StringUtils.isBlank(filename)) {
            filename = "john.doe";
        }
        if (filesize < 1) {
            filesize = -1;
        }
        if (chunksize < 1) {
            chunksize = -1;
        }
        MediaPackage mp = null;
        if (StringUtils.isNotBlank(mediapackage)) {
            mp = factory.newMediaPackageBuilder().loadFromXml(mediapackage);
        }
        MediaPackageElementFlavor flavor = null;
        if (StringUtils.isNotBlank(flav)) {
            flavor = new MediaPackageElementFlavor(flav.split("/")[0], flav.split("/")[1]);
        }
        FileUploadJob job = uploadService.createJob(filename, filesize, chunksize, mp, flavor);
        return Response.ok(job.getId()).build();
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        return Response.status(Response.Status.NO_CONTENT).entity(e.getMessage()).build();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.serverError().entity(buildUnexpectedErrorMessage(e)).build();
    }
}
Also used : FileUploadJob(org.opencastproject.fileupload.api.job.FileUploadJob) MediaPackage(org.opencastproject.mediapackage.MediaPackage) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) FileUploadException(org.opencastproject.fileupload.api.exception.FileUploadException) FileUploadException(org.opencastproject.fileupload.api.exception.FileUploadException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 10 with MediaPackageElementFlavor

use of org.opencastproject.mediapackage.MediaPackageElementFlavor in project opencast by opencast.

the class SearchServiceRemoteImpl method getSearchUrl.

/**
 * Builds the a search URL.
 *
 * @param q
 *          the search query
 * @param admin
 *          whether this is for an administrative read
 * @return the search URL
 */
private String getSearchUrl(SearchQuery q, boolean admin) {
    StringBuilder url = new StringBuilder();
    List<NameValuePair> queryStringParams = new ArrayList<NameValuePair>();
    // MH-10216, Choose "/expisode.xml" endpoint when querying by mediapackage id (i.e. episode id ) to recieve full mp data
    if (q.getId() != null || q.getSeriesId() != null || q.getElementFlavors() != null || q.getElementTags() != null) {
        url.append("/episode.xml?");
        if (q.getSeriesId() != null)
            queryStringParams.add(new BasicNameValuePair("sid", q.getSeriesId()));
        if (q.getElementFlavors() != null) {
            for (MediaPackageElementFlavor f : q.getElementFlavors()) {
                queryStringParams.add(new BasicNameValuePair("flavor", f.toString()));
            }
        }
        if (q.getElementTags() != null) {
            for (String t : q.getElementTags()) {
                queryStringParams.add(new BasicNameValuePair("tag", t));
            }
        }
    } else {
        url.append("/series.xml?");
        queryStringParams.add(new BasicNameValuePair("series", Boolean.toString(q.isIncludeSeries())));
        queryStringParams.add(new BasicNameValuePair("episodes", Boolean.toString(q.isIncludeEpisodes())));
    }
    // General query parameters
    if (q.getText() != null)
        queryStringParams.add(new BasicNameValuePair("q", q.getText()));
    if (q.getId() != null)
        queryStringParams.add(new BasicNameValuePair("id", q.getId()));
    if (admin) {
        queryStringParams.add(new BasicNameValuePair("admin", Boolean.TRUE.toString()));
    } else {
        queryStringParams.add(new BasicNameValuePair("admin", Boolean.FALSE.toString()));
    }
    queryStringParams.add(new BasicNameValuePair("limit", Integer.toString(q.getLimit())));
    queryStringParams.add(new BasicNameValuePair("offset", Integer.toString(q.getOffset())));
    url.append(URLEncodedUtils.format(queryStringParams, "UTF-8"));
    return url.toString();
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor)

Aggregations

MediaPackageElementFlavor (org.opencastproject.mediapackage.MediaPackageElementFlavor)109 MediaPackage (org.opencastproject.mediapackage.MediaPackage)49 Track (org.opencastproject.mediapackage.Track)34 URI (java.net.URI)31 Test (org.junit.Test)31 WorkflowOperationException (org.opencastproject.workflow.api.WorkflowOperationException)28 IOException (java.io.IOException)27 NotFoundException (org.opencastproject.util.NotFoundException)27 ArrayList (java.util.ArrayList)26 WorkflowOperationResult (org.opencastproject.workflow.api.WorkflowOperationResult)26 HashMap (java.util.HashMap)23 MediaPackageElement (org.opencastproject.mediapackage.MediaPackageElement)22 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)22 Job (org.opencastproject.job.api.Job)21 WorkflowOperationInstance (org.opencastproject.workflow.api.WorkflowOperationInstance)19 InputStream (java.io.InputStream)18 TrackImpl (org.opencastproject.mediapackage.track.TrackImpl)17 TrackSelector (org.opencastproject.mediapackage.selector.TrackSelector)16 File (java.io.File)13 Catalog (org.opencastproject.mediapackage.Catalog)13