use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.
the class AbstractEventEndpoint method getEventMetadata.
@GET
@Path("{eventId}/metadata.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "geteventmetadata", description = "Returns all the data related to the metadata tab in the event details modal as JSON", returnDescription = "All the data related to the event metadata tab as JSON", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Returns all the data related to the event metadata tab as JSON", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response getEventMetadata(@PathParam("eventId") String eventId) throws Exception {
Opt<Event> optEvent = getIndexService().getEvent(eventId, getIndex());
if (optEvent.isNone())
return notFound("Cannot find an event with id '%s'.", eventId);
MetadataList metadataList = new MetadataList();
List<EventCatalogUIAdapter> catalogUIAdapters = getIndexService().getEventCatalogUIAdapters();
catalogUIAdapters.remove(getIndexService().getCommonEventCatalogUIAdapter());
MediaPackage mediaPackage = getIndexService().getEventMediapackage(optEvent.get());
for (EventCatalogUIAdapter catalogUIAdapter : catalogUIAdapters) {
metadataList.add(catalogUIAdapter, catalogUIAdapter.getFields(mediaPackage));
}
metadataList.add(getIndexService().getCommonEventCatalogUIAdapter(), EventUtils.getEventMetadata(optEvent.get(), getIndexService().getCommonEventCatalogUIAdapter()));
final String wfState = optEvent.get().getWorkflowState();
if (wfState != null && WorkflowUtil.isActive(WorkflowInstance.WorkflowState.valueOf(wfState)))
metadataList.setLocked(Locked.WORKFLOW_RUNNING);
return okJson(metadataList.toJSON());
}
use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.
the class AbstractEventEndpoint method updateEventWorkflow.
@PUT
@Path("{eventId}/workflows")
@RestQuery(name = "updateEventWorkflow", description = "Update the workflow configuration for the scheduled event with the given id", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(name = "configuration", isRequired = true, description = "The workflow configuration as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(description = "Request executed succesfully", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) }, returnDescription = "The method does not retrun any content.")
public Response updateEventWorkflow(@PathParam("eventId") String id, @FormParam("configuration") String configuration) throws SearchIndexException, UnauthorizedException {
Opt<Event> optEvent = getIndexService().getEvent(id, getIndex());
if (optEvent.isNone())
return notFound("Cannot find an event with id '%s'.", id);
if (!optEvent.get().hasRecordingStarted()) {
try {
JSONObject configJSON;
try {
configJSON = (JSONObject) new JSONParser().parse(configuration);
} catch (Exception e) {
logger.warn("Unable to parse the workflow configuration {}", configuration);
return badRequest();
}
Opt<Map<String, String>> caMetadataOpt = Opt.none();
Opt<Map<String, String>> workflowConfigOpt = Opt.none();
String workflowId = (String) configJSON.get("id");
Map<String, String> caMetadata = new HashMap<>(getSchedulerService().getCaptureAgentConfiguration(id));
if (!workflowId.equals(caMetadata.get(CaptureParameters.INGEST_WORKFLOW_DEFINITION))) {
caMetadata.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, workflowId);
caMetadataOpt = Opt.some(caMetadata);
}
Map<String, String> workflowConfig = new HashMap<>((JSONObject) configJSON.get("configuration"));
Map<String, String> oldWorkflowConfig = new HashMap<>(getSchedulerService().getWorkflowConfig(id));
if (!oldWorkflowConfig.equals(workflowConfig))
workflowConfigOpt = Opt.some(workflowConfig);
if (caMetadataOpt.isNone() && workflowConfigOpt.isNone())
return Response.noContent().build();
getSchedulerService().updateEvent(id, Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), Opt.<MediaPackage>none(), workflowConfigOpt, caMetadataOpt, Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
return Response.noContent().build();
} catch (NotFoundException e) {
return notFound("Cannot find event %s in scheduler service", id);
} catch (SchedulerException e) {
logger.error("Unable to update scheduling workflow data for event with id {}", id);
throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
}
} else {
return badRequest(String.format("Event %s workflow can not be updated as the recording already started.", id));
}
}
use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.
the class AbstractEventEndpoint method getNewConflicts.
@POST
@Path("new/conflicts")
@RestQuery(name = "checkNewConflicts", description = "Checks if the current scheduler parameters are in a conflict with another event", returnDescription = "Returns NO CONTENT if no event are in conflict within specified period or list of conflicting recordings in JSON", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "No conflicting events found"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "There is a conflict"), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid parameters") })
public Response getNewConflicts(@FormParam("metadata") String metadata) throws NotFoundException {
if (StringUtils.isBlank(metadata)) {
logger.warn("Metadata is not specified");
return Response.status(Status.BAD_REQUEST).build();
}
JSONParser parser = new JSONParser();
JSONObject metadataJson;
try {
metadataJson = (JSONObject) parser.parse(metadata);
} catch (Exception e) {
logger.warn("Unable to parse metadata {}", metadata);
return RestUtil.R.badRequest("Unable to parse metadata");
}
String device;
String startDate;
String endDate;
try {
device = (String) metadataJson.get("device");
startDate = (String) metadataJson.get("start");
endDate = (String) metadataJson.get("end");
} catch (Exception e) {
logger.warn("Unable to parse metadata {}", metadata);
return RestUtil.R.badRequest("Unable to parse metadata");
}
if (StringUtils.isBlank(device) || StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
logger.warn("Either device, start date or end date were not specified");
return Response.status(Status.BAD_REQUEST).build();
}
Date start;
try {
start = new Date(DateTimeSupport.fromUTC(startDate));
} catch (Exception e) {
logger.warn("Unable to parse start date {}", startDate);
return RestUtil.R.badRequest("Unable to parse start date");
}
Date end;
try {
end = new Date(DateTimeSupport.fromUTC(endDate));
} catch (Exception e) {
logger.warn("Unable to parse end date {}", endDate);
return RestUtil.R.badRequest("Unable to parse end date");
}
String rruleString = (String) metadataJson.get("rrule");
RRule rrule = null;
TimeZone timeZone = TimeZone.getDefault();
String durationString = null;
if (StringUtils.isNotEmpty(rruleString)) {
try {
rrule = new RRule(rruleString);
rrule.validate();
} catch (Exception e) {
logger.warn("Unable to parse rrule {}: {}", rruleString, e.getMessage());
return Response.status(Status.BAD_REQUEST).build();
}
durationString = (String) metadataJson.get("duration");
if (StringUtils.isBlank(durationString)) {
logger.warn("If checking recurrence, must include duration.");
return Response.status(Status.BAD_REQUEST).build();
}
Agent agent = getCaptureAgentStateService().getAgent(device);
String timezone = agent.getConfiguration().getProperty("capture.device.timezone");
if (StringUtils.isBlank(timezone)) {
timezone = TimeZone.getDefault().getID();
logger.warn("No 'capture.device.timezone' set on agent {}. The default server timezone {} will be used.", device, timezone);
}
timeZone = TimeZone.getTimeZone(timezone);
}
String eventId = (String) metadataJson.get("id");
try {
List<MediaPackage> events = null;
if (StringUtils.isNotEmpty(rruleString)) {
events = getSchedulerService().findConflictingEvents(device, rrule, start, end, Long.parseLong(durationString), timeZone);
} else {
events = getSchedulerService().findConflictingEvents(device, start, end);
}
if (!events.isEmpty()) {
List<JValue> eventsJSON = new ArrayList<>();
for (MediaPackage event : events) {
Opt<Event> eventOpt = getIndexService().getEvent(event.getIdentifier().compact(), getIndex());
if (eventOpt.isSome()) {
final Event e = eventOpt.get();
if (StringUtils.isNotEmpty(eventId) && eventId.equals(e.getIdentifier()))
continue;
eventsJSON.add(obj(f("start", v(e.getTechnicalStartTime())), f("end", v(e.getTechnicalEndTime())), f("title", v(e.getTitle()))));
} else {
logger.warn("Index out of sync! Conflicting event catalog {} not found on event index!", event.getIdentifier().compact());
}
}
if (!eventsJSON.isEmpty())
return conflictJson(arr(eventsJSON));
}
return Response.noContent().build();
} catch (Exception e) {
logger.error("Unable to find conflicting events for {}, {}, {}: {}", device, startDate, endDate, ExceptionUtils.getStackTrace(e));
return RestUtil.R.serverError();
}
}
use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.
the class AbstractEventEndpoint method getEvents.
@GET
@Path("events.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getevents", description = "Returns all the events as JSON", returnDescription = "All the events as JSON", restParameters = { @RestParameter(name = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2:value2'", type = STRING), @RestParameter(name = "sort", description = "The order instructions used to sort the query result. Must be in the form '<field name>:(ASC|DESC)'", isRequired = false, type = STRING), @RestParameter(name = "limit", description = "The maximum number of items to return per page.", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "offset", description = "The page number.", isRequired = false, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "Returns all events as JSON", responseCode = HttpServletResponse.SC_OK) })
public Response getEvents(@QueryParam("id") String id, @QueryParam("commentReason") String reasonFilter, @QueryParam("commentResolution") String resolutionFilter, @QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") Integer offset, @QueryParam("limit") Integer limit) {
Option<Integer> optLimit = Option.option(limit);
Option<Integer> optOffset = Option.option(offset);
Option<String> optSort = Option.option(trimToNull(sort));
ArrayList<JValue> eventsList = new ArrayList<>();
EventSearchQuery query = new EventSearchQuery(getSecurityService().getOrganization().getId(), getSecurityService().getUser());
// If the limit is set to 0, this is not taken into account
if (optLimit.isSome() && limit == 0) {
optLimit = Option.none();
}
Map<String, String> filters = RestUtils.parseFilter(filter);
for (String name : filters.keySet()) {
if (EventListQuery.FILTER_PRESENTERS_BIBLIOGRAPHIC_NAME.equals(name))
query.withPresenter(filters.get(name));
if (EventListQuery.FILTER_PRESENTERS_TECHNICAL_NAME.equals(name))
query.withTechnicalPresenters(filters.get(name));
if (EventListQuery.FILTER_CONTRIBUTORS_NAME.equals(name))
query.withContributor(filters.get(name));
if (EventListQuery.FILTER_LOCATION_NAME.equals(name))
query.withLocation(filters.get(name));
if (EventListQuery.FILTER_AGENT_NAME.equals(name))
query.withAgentId(filters.get(name));
if (EventListQuery.FILTER_TEXT_NAME.equals(name))
query.withText(QueryPreprocessor.sanitize(filters.get(name)));
if (EventListQuery.FILTER_SERIES_NAME.equals(name))
query.withSeriesId(filters.get(name));
if (EventListQuery.FILTER_STATUS_NAME.equals(name))
query.withEventStatus(filters.get(name));
if (EventListQuery.FILTER_OPTEDOUT_NAME.equals(name))
query.withOptedOut(Boolean.parseBoolean(filters.get(name)));
if (EventListQuery.FILTER_REVIEW_STATUS_NAME.equals(name))
query.withReviewStatus(filters.get(name));
if (EventListQuery.FILTER_COMMENTS_NAME.equals(name)) {
switch(Comments.valueOf(filters.get(name))) {
case NONE:
query.withComments(false);
break;
case OPEN:
query.withOpenComments(true);
break;
case RESOLVED:
query.withComments(true);
query.withOpenComments(false);
break;
default:
logger.info("Unknown comment {}", filters.get(name));
return Response.status(SC_BAD_REQUEST).build();
}
}
if (EventListQuery.FILTER_STARTDATE_NAME.equals(name)) {
try {
Tuple<Date, Date> fromAndToCreationRange = RestUtils.getFromAndToDateRange(filters.get(name));
query.withTechnicalStartFrom(fromAndToCreationRange.getA());
query.withTechnicalStartTo(fromAndToCreationRange.getB());
} catch (IllegalArgumentException e) {
return RestUtil.R.badRequest(e.getMessage());
}
}
}
if (optSort.isSome()) {
Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
for (SortCriterion criterion : sortCriteria) {
switch(criterion.getFieldName()) {
case EventIndexSchema.TITLE:
query.sortByTitle(criterion.getOrder());
break;
case EventIndexSchema.PRESENTER:
query.sortByPresenter(criterion.getOrder());
break;
case EventIndexSchema.TECHNICAL_START:
case "technical_date":
query.sortByTechnicalStartDate(criterion.getOrder());
break;
case EventIndexSchema.TECHNICAL_END:
query.sortByTechnicalEndDate(criterion.getOrder());
break;
case EventIndexSchema.PUBLICATION:
query.sortByPublicationIgnoringInternal(criterion.getOrder());
break;
case EventIndexSchema.START_DATE:
case "date":
query.sortByStartDate(criterion.getOrder());
break;
case EventIndexSchema.END_DATE:
query.sortByEndDate(criterion.getOrder());
break;
case EventIndexSchema.SERIES_NAME:
query.sortBySeriesName(criterion.getOrder());
break;
case EventIndexSchema.LOCATION:
query.sortByLocation(criterion.getOrder());
break;
case EventIndexSchema.EVENT_STATUS:
query.sortByEventStatus(criterion.getOrder());
break;
default:
throw new WebApplicationException(Status.BAD_REQUEST);
}
}
}
// TODO: Add the comment resolution filter to the query
EventCommentsListProvider.RESOLUTION resolution = null;
if (StringUtils.isNotBlank(resolutionFilter)) {
try {
resolution = EventCommentsListProvider.RESOLUTION.valueOf(resolutionFilter);
} catch (Exception e) {
logger.warn("Unable to parse comment resolution filter {}", resolutionFilter);
return Response.status(Status.BAD_REQUEST).build();
}
}
if (optLimit.isSome())
query.withLimit(optLimit.get());
if (optOffset.isSome())
query.withOffset(offset);
// TODO: Add other filters to the query
SearchResult<Event> results = null;
try {
results = getIndex().getByQuery(query);
} catch (SearchIndexException e) {
logger.error("The admin UI Search Index was not able to get the events list:", e);
return RestUtil.R.serverError();
}
// If the results list if empty, we return already a response.
if (results.getPageSize() == 0) {
logger.debug("No events match the given filters.");
return okJsonList(eventsList, nul(offset).getOr(0), nul(limit).getOr(0), 0);
}
for (SearchResultItem<Event> item : results.getItems()) {
Event source = item.getSource();
source.updatePreview(getAdminUIConfiguration().getPreviewSubtype());
eventsList.add(eventToJSON(source));
}
return okJsonList(eventsList, nul(offset).getOr(0), nul(limit).getOr(0), results.getHitCount());
}
use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.
the class AbstractEventEndpoint method deleteEventComment.
@DELETE
@Path("{eventId}/comment/{commentId}")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "deleteeventcomment", description = "Deletes a event related comment by its identifier", returnDescription = "No content", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "commentId", description = "The comment id", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "The event related comment has been deleted.", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "No event or comment with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response deleteEventComment(@PathParam("eventId") String eventId, @PathParam("commentId") long commentId) throws Exception {
Opt<Event> optEvent = getIndexService().getEvent(eventId, getIndex());
if (optEvent.isNone())
return notFound("Cannot find an event with id '%s'.", eventId);
try {
getEventCommentService().deleteComment(commentId);
List<EventComment> comments = getEventCommentService().getComments(eventId);
getIndexService().updateCommentCatalog(optEvent.get(), comments);
return Response.noContent().build();
} catch (NotFoundException e) {
throw e;
} catch (Exception e) {
logger.error("Unable to delete comment {} on event {}: {}", commentId, eventId, ExceptionUtils.getStackTrace(e));
throw new WebApplicationException(e);
}
}
Aggregations