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);
}
}
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());
}
}
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;
}
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();
}
}
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();
}
Aggregations