Search in sources :

Example 81 with NotFoundException

use of org.opencastproject.util.NotFoundException 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 82 with NotFoundException

use of org.opencastproject.util.NotFoundException 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)

Example 83 with NotFoundException

use of org.opencastproject.util.NotFoundException 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);
    }
}
Also used : EventComment(org.opencastproject.event.comment.EventComment) WebApplicationException(javax.ws.rs.WebApplicationException) Event(org.opencastproject.index.service.impl.index.event.Event) 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) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 84 with NotFoundException

use of org.opencastproject.util.NotFoundException in project opencast by opencast.

the class AbstractEventEndpoint method resolveEventComment.

@POST
@Path("{eventId}/comment/{commentId}")
@RestQuery(name = "resolveeventcomment", description = "Resolves an event comment", returnDescription = "The resolved comment.", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "commentId", isRequired = true, description = "The comment identifier", type = STRING) }, reponses = { @RestResponse(responseCode = SC_NOT_FOUND, description = "The event or comment to resolve has not been found."), @RestResponse(responseCode = SC_OK, description = "The resolved comment as JSON.") })
public Response resolveEventComment(@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 {
        EventComment dto = getEventCommentService().getComment(commentId);
        EventComment updatedComment = EventComment.create(dto.getId(), dto.getEventId(), dto.getOrganization(), dto.getText(), dto.getAuthor(), dto.getReason(), true, dto.getCreationDate(), new Date(), dto.getReplies());
        updatedComment = getEventCommentService().updateComment(updatedComment);
        List<EventComment> comments = getEventCommentService().getComments(eventId);
        getIndexService().updateCommentCatalog(optEvent.get(), comments);
        return Response.ok(updatedComment.toJson().toJson()).build();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not resolve comment {}: {}", commentId, ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(e);
    }
}
Also used : EventComment(org.opencastproject.event.comment.EventComment) WebApplicationException(javax.ws.rs.WebApplicationException) Event(org.opencastproject.index.service.impl.index.event.Event) NotFoundException(org.opencastproject.util.NotFoundException) Date(java.util.Date) 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) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 85 with NotFoundException

use of org.opencastproject.util.NotFoundException in project opencast by opencast.

the class AbstractEventEndpoint method workflowAction.

@PUT
@Path("{eventId}/workflows/{workflowId}/action/{action}")
@RestQuery(name = "workflowAction", description = "Performs the given action for the given workflow.", returnDescription = "", pathParameters = { @RestParameter(name = "eventId", description = "The id of the media package", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "workflowId", description = "The id of the workflow", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "action", description = "The action to take: STOP, RETRY or NONE (abort processing)", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "Workflow resumed."), @RestResponse(responseCode = SC_NOT_FOUND, description = "Event or workflow instance not found."), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Invalid action entered."), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "You do not have permission to perform the action. Maybe you need to authenticate."), @RestResponse(responseCode = SC_INTERNAL_SERVER_ERROR, description = "An exception occurred.") })
public Response workflowAction(@PathParam("eventId") String id, @PathParam("workflowId") long wfId, @PathParam("action") String action) {
    if (StringUtils.isEmpty(id) || StringUtils.isEmpty(action)) {
        return badRequest();
    }
    try {
        final Opt<Event> optEvent = getIndexService().getEvent(id, getIndex());
        if (optEvent.isNone()) {
            return notFound("Cannot find an event with id '%s'.", id);
        }
        final WorkflowInstance wfInstance = getWorkflowService().getWorkflowById(wfId);
        if (!wfInstance.getMediaPackage().getIdentifier().toString().equals(id)) {
            return badRequest(String.format("Workflow %s is not associated to event %s", wfId, id));
        }
        if (RetryStrategy.NONE.toString().equalsIgnoreCase(action) || RetryStrategy.RETRY.toString().equalsIgnoreCase(action)) {
            getWorkflowService().resume(wfId, Collections.singletonMap("retryStrategy", action));
            return ok();
        }
        if (WORKFLOW_ACTION_STOP.equalsIgnoreCase(action)) {
            getWorkflowService().stop(wfId);
            return ok();
        }
        return badRequest("Action not supported: " + action);
    } catch (NotFoundException e) {
        return notFound("Workflow not found: '%d'.", wfId);
    } catch (IllegalStateException e) {
        return badRequest(String.format("Action %s not allowed for current workflow state. EventId: %s", action, id));
    } catch (UnauthorizedException e) {
        return forbidden();
    } catch (Exception e) {
        return serverError();
    }
}
Also used : UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) Event(org.opencastproject.index.service.impl.index.event.Event) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) 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) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Aggregations

NotFoundException (org.opencastproject.util.NotFoundException)382 IOException (java.io.IOException)137 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)130 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)79 MediaPackage (org.opencastproject.mediapackage.MediaPackage)69 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)67 EntityManager (javax.persistence.EntityManager)55 SeriesException (org.opencastproject.series.api.SeriesException)53 Path (javax.ws.rs.Path)52 WebApplicationException (javax.ws.rs.WebApplicationException)52 RestQuery (org.opencastproject.util.doc.rest.RestQuery)51 ConfigurationException (org.osgi.service.cm.ConfigurationException)51 URI (java.net.URI)50 SchedulerConflictException (org.opencastproject.scheduler.api.SchedulerConflictException)50 SchedulerTransactionLockException (org.opencastproject.scheduler.api.SchedulerTransactionLockException)49 Date (java.util.Date)48 Test (org.junit.Test)47 File (java.io.File)46 HttpResponse (org.apache.http.HttpResponse)46 ServiceRegistryException (org.opencastproject.serviceregistry.api.ServiceRegistryException)46