Search in sources :

Example 36 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery 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());
}
Also used : MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) EventCatalogUIAdapter(org.opencastproject.metadata.dublincore.EventCatalogUIAdapter) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 37 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery in project opencast by opencast.

the class AbstractEventEndpoint method updateAssets.

// MH-12085 Add manually uploaded assets, multipart file upload has to be a POST
@POST
@Path("{eventId}/assets")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@RestQuery(name = "updateAssets", description = "Update or create an asset for the eventId by the given metadata as JSON and files in the body", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(name = "metadata", isRequired = true, type = RestParameter.Type.TEXT, description = "The list of asset metadata") }, reponses = { @RestResponse(description = "The asset has been added.", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "Could not add asset, problem with the metadata or files.", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) }, returnDescription = "The workflow identifier")
public Response updateAssets(@PathParam("eventId") final String eventId, @Context HttpServletRequest request) throws Exception {
    try {
        MediaPackage mp = getMediaPackageByEventId(eventId);
        String result = getIndexService().updateEventAssets(mp, request);
        return Response.status(Status.CREATED).entity(result).build();
    } catch (NotFoundException e) {
        return notFound("Cannot find an event with id '%s'.", eventId);
    } catch (IllegalArgumentException e) {
        return RestUtil.R.badRequest(e.getMessage());
    } catch (Exception e) {
        return RestUtil.R.serverError();
    }
}
Also used : MediaPackage(org.opencastproject.mediapackage.MediaPackage) NotFoundException(org.opencastproject.util.NotFoundException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 38 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery 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));
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) NotFoundException(org.opencastproject.util.NotFoundException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) JSONObject(org.json.simple.JSONObject) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 39 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery in project opencast by opencast.

the class AbstractEventEndpoint method deleteEvents.

@POST
@Path("deleteEvents")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "deleteevents", description = "Deletes a json list of events by their given ids e.g. [\"1dbe7255-e17d-4279-811d-a5c7ced689bf\", \"04fae22b-0717-4f59-8b72-5f824f76d529\"]", returnDescription = "Returns a JSON object containing a list of event ids that were deleted, not found or if there was a server error.", reponses = { @RestResponse(description = "Events have been deleted", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "The list of ids could not be parsed into a json list.", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "If the current user is not authorized to perform this action", responseCode = HttpServletResponse.SC_UNAUTHORIZED) })
public Response deleteEvents(String eventIdsContent) throws UnauthorizedException {
    if (StringUtils.isBlank(eventIdsContent)) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    JSONParser parser = new JSONParser();
    JSONArray eventIdsJsonArray;
    try {
        eventIdsJsonArray = (JSONArray) parser.parse(eventIdsContent);
    } catch (org.json.simple.parser.ParseException e) {
        logger.error("Unable to parse '{}' because: {}", eventIdsContent, ExceptionUtils.getStackTrace(e));
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (ClassCastException e) {
        logger.error("Unable to cast '{}' because: {}", eventIdsContent, ExceptionUtils.getStackTrace(e));
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    BulkOperationResult result = new BulkOperationResult();
    for (Object eventIdObject : eventIdsJsonArray) {
        String eventId = eventIdObject.toString();
        try {
            if (!getIndexService().removeEvent(eventId)) {
                result.addServerError(eventId);
            } else {
                result.addOk(eventId);
            }
        } catch (NotFoundException e) {
            result.addNotFound(eventId);
        }
    }
    return Response.ok(result.toJson()).build();
}
Also used : JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) JObject(com.entwinemedia.fn.data.json.JObject) BulkOperationResult(org.opencastproject.rest.BulkOperationResult) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 40 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery 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();
    }
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) RRule(net.fortuna.ical4j.model.property.RRule) ArrayList(java.util.ArrayList) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Date(java.util.Date) DateTimeZone(org.joda.time.DateTimeZone) TimeZone(java.util.TimeZone) JSONObject(org.json.simple.JSONObject) JValue(com.entwinemedia.fn.data.json.JValue) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

RestQuery (org.opencastproject.util.doc.rest.RestQuery)228 Path (javax.ws.rs.Path)226 Produces (javax.ws.rs.Produces)172 GET (javax.ws.rs.GET)97 POST (javax.ws.rs.POST)89 WebApplicationException (javax.ws.rs.WebApplicationException)83 NotFoundException (org.opencastproject.util.NotFoundException)83 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)55 MediaPackage (org.opencastproject.mediapackage.MediaPackage)52 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)46 Event (org.opencastproject.index.service.impl.index.event.Event)34 ParseException (java.text.ParseException)33 JSONObject (org.json.simple.JSONObject)33 IOException (java.io.IOException)32 SearchIndexException (org.opencastproject.matterhorn.search.SearchIndexException)32 AclServiceException (org.opencastproject.authorization.xacml.manager.api.AclServiceException)31 Job (org.opencastproject.job.api.Job)30 Date (java.util.Date)29 ArrayList (java.util.ArrayList)28 PUT (javax.ws.rs.PUT)28