use of org.opencastproject.metadata.dublincore.MetadataField 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.metadata.dublincore.MetadataField in project opencast by opencast.
the class MetadataUtils method copyMetadataField.
/**
* Copy a {@link MetadataField} into a new field.
*
* @param other
* The other {@link MetadataField} to copy the state from.
* @return A new {@link MetadataField} with the same settings as the passed in {@link MetadataField}
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static MetadataField copyMetadataField(MetadataField other) {
MetadataField newField = new MetadataField();
newField.setCollection(other.getCollection());
newField.setCollectionID(other.getCollectionID());
newField.setInputId(other.getInputID());
newField.setIsTranslatable(other.isTranslatable());
newField.setLabel(other.getLabel());
newField.setListprovider(other.getListprovider());
newField.setNamespace(other.getNamespace());
newField.setOutputID(Opt.some(other.getOutputID()));
newField.setPattern(other.getPattern());
newField.setOrder(other.getOrder());
newField.setReadOnly(other.isReadOnly());
newField.setRequired(other.isRequired());
newField.setJsonType(other.getJsonType());
newField.setJsonToValue(other.getJsonToValue());
newField.setValueToJSON(other.getValueToJSON());
newField.setType(other.getType());
if (other.getValue().isSome()) {
newField.setValue(other.getValue().get());
}
return newField;
}
use of org.opencastproject.metadata.dublincore.MetadataField in project opencast by opencast.
the class EventsEndpoint method updateEventMetadataByType.
@PUT
@Path("{eventId}/metadata")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "updateeventmetadata", description = "Update the metadata with the matching type of the specified event. For a metadata catalog there is the flavor such as 'dublincore/episode' and this is the unique type.", returnDescription = "", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = STRING) }, restParameters = { @RestParameter(name = "type", isRequired = true, description = "The type of metadata to update", type = STRING), @RestParameter(name = "metadata", description = "Metadata catalog in JSON format", isRequired = true, type = STRING) }, reponses = { @RestResponse(description = "The metadata of the given namespace has been updated.", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "The request is invalid or inconsistent.", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "The specified event does not exist.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response updateEventMetadataByType(@HeaderParam("Accept") String acceptHeader, @PathParam("eventId") String id, @QueryParam("type") String type, @FormParam("metadata") String metadataJSON) throws Exception {
Map<String, String> updatedFields;
JSONParser parser = new JSONParser();
try {
updatedFields = RequestUtils.getKeyValueMap(metadataJSON);
} catch (ParseException e) {
logger.debug("Unable to update event '{}' with metadata type '{}' and content '{}' because: {}", id, type, metadataJSON, ExceptionUtils.getStackTrace(e));
return RestUtil.R.badRequest(String.format("Unable to parse metadata fields as json from '%s' because '%s'", metadataJSON, ExceptionUtils.getStackTrace(e)));
} catch (IllegalArgumentException e) {
logger.debug("Unable to update event '{}' with metadata type '{}' and content '{}' because: {}", id, type, metadataJSON, ExceptionUtils.getStackTrace(e));
return RestUtil.R.badRequest(e.getMessage());
}
if (updatedFields == null || updatedFields.size() == 0) {
return RestUtil.R.badRequest(String.format("Unable to parse metadata fields as json from '%s' because there were no fields to update.", metadataJSON));
}
Opt<MediaPackageElementFlavor> flavor = getFlavor(type);
if (flavor.isNone()) {
return R.badRequest(String.format("Unable to parse type '%s' as a flavor so unable to find the matching catalog.", type));
}
MetadataCollection collection = null;
EventCatalogUIAdapter adapter = null;
for (final Event event : indexService.getEvent(id, externalIndex)) {
MetadataList metadataList = new MetadataList();
// Try the main catalog first as we load it from the index.
if (flavor.get().equals(eventCatalogUIAdapter.getFlavor())) {
collection = EventUtils.getEventMetadata(event, eventCatalogUIAdapter);
adapter = eventCatalogUIAdapter;
} else {
metadataList.add(eventCatalogUIAdapter, EventUtils.getEventMetadata(event, eventCatalogUIAdapter));
}
// Try the other catalogs
List<EventCatalogUIAdapter> catalogUIAdapters = getEventCatalogUIAdapters();
catalogUIAdapters.remove(eventCatalogUIAdapter);
MediaPackage mediaPackage = indexService.getEventMediapackage(event);
if (catalogUIAdapters.size() > 0) {
for (EventCatalogUIAdapter catalogUIAdapter : catalogUIAdapters) {
if (flavor.get().equals(catalogUIAdapter.getFlavor())) {
collection = catalogUIAdapter.getFields(mediaPackage);
adapter = eventCatalogUIAdapter;
} else {
metadataList.add(catalogUIAdapter, catalogUIAdapter.getFields(mediaPackage));
}
}
}
if (collection == null) {
return ApiResponses.notFound("Cannot find a catalog with type '%s' for event with id '%s'.", type, id);
}
for (String key : updatedFields.keySet()) {
if ("subjects".equals(key)) {
MetadataField<?> field = collection.getOutputFields().get(DublinCore.PROPERTY_SUBJECT.getLocalName());
Opt<Response> error = validateField(field, key, id, type, updatedFields);
if (error.isSome()) {
return error.get();
}
collection.removeField(field);
JSONArray subjectArray = (JSONArray) parser.parse(updatedFields.get(key));
collection.addField(MetadataField.copyMetadataFieldWithValue(field, StringUtils.join(subjectArray.iterator(), ",")));
} 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);
Opt<Response> error = validateField(field, key, id, type, updatedFields);
if (error.isSome()) {
return error.get();
}
String apiPattern = field.getPattern().get();
if (configuredMetadataFields.containsKey("startDate")) {
apiPattern = configuredMetadataFields.get("startDate").getPattern().getOr(apiPattern);
}
SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(apiPattern);
SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
DateTime newStartDate = new DateTime(apiSdf.parse(updatedFields.get(key)), DateTimeZone.UTC);
DateTime updatedStartDate = oldStartDate.withDate(newStartDate.year().get(), newStartDate.monthOfYear().get(), newStartDate.dayOfMonth().get());
collection.removeField(field);
collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(updatedStartDate.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");
Opt<Response> error = validateField(field, "startDate", id, type, updatedFields);
if (error.isSome()) {
return error.get();
}
String apiPattern = "HH:mm";
if (configuredMetadataFields.containsKey("startTime")) {
apiPattern = configuredMetadataFields.get("startTime").getPattern().getOr(apiPattern);
}
SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(apiPattern);
SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
DateTime newStartDate = new DateTime(apiSdf.parse(updatedFields.get(key)), DateTimeZone.UTC);
DateTime updatedStartDate = oldStartDate.withTime(newStartDate.hourOfDay().get(), newStartDate.minuteOfHour().get(), newStartDate.secondOfMinute().get(), newStartDate.millisOfSecond().get());
collection.removeField(field);
collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(updatedStartDate.toDate())));
} else {
MetadataField<?> field = collection.getOutputFields().get(key);
Opt<Response> error = validateField(field, key, id, type, updatedFields);
if (error.isSome()) {
return error.get();
}
collection.removeField(field);
collection.addField(MetadataField.copyMetadataFieldWithValue(field, updatedFields.get(key)));
}
}
metadataList.add(adapter, collection);
indexService.updateEventMetadata(id, metadataList, externalIndex);
return ApiResponses.Json.noContent(ApiVersion.VERSION_1_0_0);
}
return ApiResponses.notFound("Cannot find an event with id '%s'.", id);
}
use of org.opencastproject.metadata.dublincore.MetadataField in project opencast by opencast.
the class EventsEndpoint method convertStartDateTimeToApiV1.
private void convertStartDateTimeToApiV1(MetadataCollection collection) throws java.text.ParseException {
if (!collection.getOutputFields().containsKey("startDate"))
return;
MetadataField<String> oldStartDateField = (MetadataField<String>) collection.getOutputFields().get("startDate");
SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(oldStartDateField.getPattern().get());
Date startDate = sdf.parse(oldStartDateField.getValue().get());
if (configuredMetadataFields.containsKey("startDate")) {
MetadataField<String> startDateField = (MetadataField<String>) configuredMetadataFields.get("startDate");
startDateField = MetadataField.createTemporalStartDateMetadata(startDateField.getInputID(), Opt.some(startDateField.getOutputID()), startDateField.getLabel(), startDateField.isReadOnly(), startDateField.isRequired(), startDateField.getPattern().getOr("yyyy-MM-dd"), startDateField.getOrder(), startDateField.getNamespace());
sdf.applyPattern(startDateField.getPattern().get());
startDateField.setValue(sdf.format(startDate));
collection.removeField(oldStartDateField);
collection.addField(startDateField);
}
if (configuredMetadataFields.containsKey("startTime")) {
MetadataField<String> startTimeField = (MetadataField<String>) configuredMetadataFields.get("startTime");
startTimeField = MetadataField.createTemporalStartTimeMetadata(startTimeField.getInputID(), Opt.some(startTimeField.getOutputID()), startTimeField.getLabel(), startTimeField.isReadOnly(), startTimeField.isRequired(), startTimeField.getPattern().getOr("HH:mm"), startTimeField.getOrder(), startTimeField.getNamespace());
sdf.applyPattern(startTimeField.getPattern().get());
startTimeField.setValue(sdf.format(startDate));
collection.addField(startTimeField);
}
}
use of org.opencastproject.metadata.dublincore.MetadataField in project opencast by opencast.
the class DublinCoreMetadataUtil method getDublinCoreProperties.
@SuppressWarnings("unchecked")
public static Map<String, MetadataField<?>> getDublinCoreProperties(Dictionary configProperties) {
Map<String, MetadataField<?>> dublinCorePropertyMapByConfigurationName = new HashMap<String, MetadataField<?>>();
for (Object configObject : Collections.list(configProperties.keys())) {
String property = configObject.toString();
if (getDublinCorePropertyName(property).isSome()) {
MetadataField<?> dublinCoreProperty = dublinCorePropertyMapByConfigurationName.get(getDublinCorePropertyName(property).get());
if (dublinCoreProperty == null) {
dublinCoreProperty = new MetadataField();
}
dublinCoreProperty.setValue(getDublinCorePropertyKey(property).get(), configProperties.get(property).toString());
dublinCorePropertyMapByConfigurationName.put(getDublinCorePropertyName(property).get(), dublinCoreProperty);
}
}
Map<String, MetadataField<?>> dublinCorePropertyMap = new TreeMap<String, MetadataField<?>>();
for (MetadataField dublinCoreProperty : dublinCorePropertyMapByConfigurationName.values()) {
dublinCorePropertyMap.put(dublinCoreProperty.getOutputID(), dublinCoreProperty);
}
return dublinCorePropertyMap;
}
Aggregations