Search in sources :

Example 16 with RestQuery

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

the class IncidentServiceEndpoint method postIncident.

@POST
@Produces(MediaType.APPLICATION_XML)
@Path("/")
@RestQuery(name = "postincident", description = "Creates a new job incident and returns it as XML", returnDescription = "Returns the created job incident as XML", restParameters = { @RestParameter(name = "job", isRequired = true, description = "The job on where to create the incident", type = Type.TEXT), @RestParameter(name = "date", isRequired = true, description = "The incident creation date", type = Type.STRING), @RestParameter(name = "code", isRequired = true, description = "The incident error code", type = Type.STRING), @RestParameter(name = "severity", isRequired = true, description = "The incident error code", type = Type.STRING), @RestParameter(name = "details", isRequired = false, description = "The incident details", type = Type.TEXT), @RestParameter(name = "params", isRequired = false, description = "The incident parameters", type = Type.TEXT) }, reponses = { @RestResponse(responseCode = SC_CREATED, description = "New job incident has been created"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Unable to parse the one of the form params"), @RestResponse(responseCode = SC_CONFLICT, description = "No job incident related job exists") })
public Response postIncident(@FormParam("job") String jobXml, @FormParam("date") String date, @FormParam("code") String code, @FormParam("severity") String severityString, @FormParam("details") String details, @FormParam("params") LocalHashMap params) {
    Job job;
    Date timestamp;
    Severity severity;
    Map<String, String> map = new HashMap<String, String>();
    List<Tuple<String, String>> list = new ArrayList<Tuple<String, String>>();
    try {
        job = JobParser.parseJob(jobXml);
        timestamp = new Date(DateTimeSupport.fromUTC(date));
        severity = Severity.valueOf(severityString);
        if (params != null)
            map = params.getMap();
        if (StringUtils.isNotBlank(details)) {
            final JSONArray array = (JSONArray) JSONValue.parse(details);
            for (int i = 0; i < array.size(); i++) {
                JSONObject tuple = (JSONObject) array.get(i);
                list.add(Tuple.tuple((String) tuple.get("title"), (String) tuple.get("content")));
            }
        }
    } catch (Exception e) {
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
    }
    try {
        Incident incident = svc.storeIncident(job, timestamp, code, severity, map, list);
        String uri = UrlSupport.concat(serverUrl, serviceUrl, Long.toString(incident.getId()), ".xml");
        return Response.created(new URI(uri)).entity(new JaxbIncident(incident)).build();
    } catch (IllegalStateException e) {
        return Response.status(Status.CONFLICT).build();
    } catch (Exception e) {
        logger.warn("Unable to post incident for job {}: {}", job.getId(), e);
        throw new WebApplicationException(INTERNAL_SERVER_ERROR);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) LocalHashMap(org.opencastproject.util.LocalHashMap) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) Severity(org.opencastproject.job.api.Incident.Severity) URI(java.net.URI) Date(java.util.Date) WebApplicationException(javax.ws.rs.WebApplicationException) IncidentServiceException(org.opencastproject.serviceregistry.api.IncidentServiceException) NotFoundException(org.opencastproject.util.NotFoundException) JSONObject(org.json.simple.JSONObject) JaxbIncident(org.opencastproject.job.api.JaxbIncident) JaxbIncident(org.opencastproject.job.api.JaxbIncident) Incident(org.opencastproject.job.api.Incident) Job(org.opencastproject.job.api.Job) Tuple(org.opencastproject.util.data.Tuple) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 17 with RestQuery

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

the class ServiceRegistryEndpoint method removeParentlessJobs.

@POST
@Path("removejobs")
@RestQuery(name = "removejobs", description = "Removes all given jobs and their child jobs", returnDescription = "No data is returned, just the HTTP status code", restParameters = { @RestParameter(name = "jobIds", isRequired = true, description = "The IDs of the jobs to delete", type = Type.TEXT) }, reponses = { @RestResponse(responseCode = SC_NO_CONTENT, description = "Jobs successfully removed"), @RestResponse(responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR, description = "Error while removing jobs") })
public Response removeParentlessJobs(@FormParam("jobIds") String jobIds) throws NotFoundException {
    try {
        final JSONArray array = (JSONArray) JSONValue.parse(jobIds);
        final List<Long> jobIdList = Arrays.asList((Long[]) array.toArray(new Long[0]));
        serviceRegistry.removeJobs(jobIdList);
        return Response.noContent().build();
    } catch (ServiceRegistryException e) {
        throw new WebApplicationException(e);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) JSONArray(org.json.simple.JSONArray) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 18 with RestQuery

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

the class IncidentServiceEndpoint method getIncidentsOfJobAsList.

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("job/incidents.{type:xml|json}")
@RestQuery(name = "incidentsofjobaslist", description = "Returns the job incidents with the given identifiers.", returnDescription = "Returns the job incidents.", pathParameters = { @RestParameter(name = "type", isRequired = true, description = "The media type of the response [xml|json]", defaultValue = "xml", type = Type.STRING) }, restParameters = { @RestParameter(name = "id", isRequired = true, description = "The job identifiers.", type = Type.INTEGER), @RestParameter(name = "format", isRequired = false, description = "The response format [full|digest|sys]. Defaults to sys", defaultValue = "sys", type = Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The job incidents.") })
public Response getIncidentsOfJobAsList(@Context HttpServletRequest request, @QueryParam("id") final List<Long> jobIds, @QueryParam("format") @DefaultValue(FMT_DEFAULT) final String format, @PathParam("type") final String type) {
    try {
        final List<Incident> incidents = svc.getIncidentsOfJob(jobIds);
        final MediaType mt = getResponseType(type);
        if (eq(FMT_SYS, format)) {
            return ok(mt, new JaxbIncidentList(incidents));
        } else if (eq(FMT_DIGEST, format)) {
            return ok(mt, new JaxbIncidentDigestList(svc, request.getLocale(), incidents));
        } else if (eq(FMT_FULL, format)) {
            return ok(mt, new JaxbIncidentFullList(svc, request.getLocale(), incidents));
        } else {
            return unknownFormat();
        }
    } catch (NotFoundException e) {
        // should not happen
        logger.error("Unable to get job incident for id {}! Consistency issue!");
        throw new WebApplicationException(e, INTERNAL_SERVER_ERROR);
    } catch (IncidentServiceException e) {
        logger.warn("Unable to get job incident for id {}: {}", jobIds, e.getMessage());
        throw new WebApplicationException(INTERNAL_SERVER_ERROR);
    }
}
Also used : JaxbIncidentDigestList(org.opencastproject.job.api.JaxbIncidentDigestList) WebApplicationException(javax.ws.rs.WebApplicationException) IncidentServiceException(org.opencastproject.serviceregistry.api.IncidentServiceException) MediaType(javax.ws.rs.core.MediaType) JaxbIncidentList(org.opencastproject.job.api.JaxbIncidentList) NotFoundException(org.opencastproject.util.NotFoundException) JaxbIncident(org.opencastproject.job.api.JaxbIncident) Incident(org.opencastproject.job.api.Incident) JaxbIncidentFullList(org.opencastproject.job.api.JaxbIncidentFullList) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 19 with RestQuery

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

the class SearchRestService method getEpisode.

// CHECKSTYLE:OFF
@GET
@Path("episode.{format:xml|json}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@RestQuery(name = "episodes", description = "Search for episodes matching the query parameters.", pathParameters = { @RestParameter(description = "The output format (json or xml) of the response body.", isRequired = true, name = "format", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The ID of the single episode to be returned, if it exists.", isRequired = false, name = "id", type = RestParameter.Type.STRING), @RestParameter(description = "Any episode that matches this free-text query.", isRequired = false, name = "q", type = RestParameter.Type.STRING), @RestParameter(description = "Any episode that belongs to specified series id.", isRequired = false, name = "sid", type = RestParameter.Type.STRING), // isRequired = false, name = "episodes", type = RestParameter.Type.STRING),
@RestParameter(name = "sort", isRequired = false, description = "The sort order.  May include any " + "of the following: DATE_CREATED, DATE_PUBLISHED, TITLE, SERIES_ID, MEDIA_PACKAGE_ID, CREATOR, " + "CONTRIBUTOR, LANGUAGE, LICENSE, SUBJECT, DESCRIPTION, PUBLISHER.  Add '_DESC' to reverse the sort order (e.g. TITLE_DESC).", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "20", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "false", description = "Whether this is an administrative query", isRequired = false, name = "admin", type = RestParameter.Type.BOOLEAN) }, reponses = { @RestResponse(description = "The request was processed succesfully.", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The search results, expressed as xml or json.")
public Response getEpisode(@QueryParam("id") String id, @QueryParam("q") String text, @QueryParam("sid") String seriesId, @QueryParam("sort") String sort, @QueryParam("tag") String[] tags, @QueryParam("flavor") String[] flavors, @QueryParam("limit") int limit, @QueryParam("offset") int offset, @QueryParam("admin") boolean admin, @PathParam("format") String format) throws SearchException, UnauthorizedException {
    // CHECKSTYLE:ON
    // Prepare the flavors
    List<MediaPackageElementFlavor> flavorSet = new ArrayList<MediaPackageElementFlavor>();
    if (flavors != null) {
        for (String f : flavors) {
            try {
                flavorSet.add(MediaPackageElementFlavor.parseFlavor(f));
            } catch (IllegalArgumentException e) {
                logger.debug("invalid flavor '{}' specified in query", f);
            }
        }
    }
    SearchQuery search = new SearchQuery();
    search.withId(id).withSeriesId(seriesId).withElementFlavors(flavorSet.toArray(new MediaPackageElementFlavor[flavorSet.size()])).withElementTags(tags).withLimit(limit).withOffset(offset);
    if (StringUtils.isNotBlank(text)) {
        search.withText(text);
    }
    search.withSort(SearchQuery.Sort.DATE_CREATED, false);
    if (StringUtils.isNotBlank(sort)) {
        // Parse the sort field and direction
        SearchQuery.Sort sortField = null;
        if (sort.endsWith(DESCENDING_SUFFIX)) {
            String enumKey = sort.substring(0, sort.length() - DESCENDING_SUFFIX.length()).toUpperCase();
            try {
                sortField = SearchQuery.Sort.valueOf(enumKey);
                search.withSort(sortField, false);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", enumKey);
            }
        } else {
            try {
                sortField = SearchQuery.Sort.valueOf(sort);
                search.withSort(sortField);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", sort);
            }
        }
    }
    // Build the response
    ResponseBuilder rb = Response.ok();
    if (admin) {
        rb.entity(searchService.getForAdministrativeRead(search));
    } else {
        rb.entity(searchService.getByQuery(search));
    }
    if ("json".equals(format)) {
        rb.type(MediaType.APPLICATION_JSON);
    } else {
        rb.type(MediaType.TEXT_XML);
    }
    return rb.build();
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery) ArrayList(java.util.ArrayList) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 20 with RestQuery

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

the class SearchRestService method getByLuceneQuery.

@GET
@Path("lucene.{format:xml|json}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@RestQuery(name = "lucene", description = "Search a lucene query.", pathParameters = { @RestParameter(description = "The output format (json or xml) of the response body.", isRequired = true, name = "format", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(defaultValue = "", description = "The lucene query.", isRequired = false, name = "q", type = RestParameter.Type.STRING), @RestParameter(name = "sort", isRequired = false, description = "The sort order.  May include any " + "of the following: DATE_CREATED, DATE_PUBLISHED, TITLE, SERIES_ID, MEDIA_PACKAGE_ID, CREATOR, " + "CONTRIBUTOR, LANGUAGE, LICENSE, SUBJECT, DESCRIPTION, PUBLISHER.  Add '_DESC' to reverse the sort order (e.g. TITLE_DESC).", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "20", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "false", description = "Whether this is an administrative query", isRequired = false, name = "admin", type = RestParameter.Type.BOOLEAN) }, reponses = { @RestResponse(description = "The request was processed succesfully.", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The search results, expressed as xml or json")
public Response getByLuceneQuery(@QueryParam("q") String q, @QueryParam("sort") String sort, @QueryParam("limit") int limit, @QueryParam("offset") int offset, @QueryParam("admin") boolean admin, @PathParam("format") String format) throws SearchException, UnauthorizedException {
    SearchQuery query = new SearchQuery();
    if (!StringUtils.isBlank(q))
        query.withQuery(q);
    query.withSort(SearchQuery.Sort.DATE_CREATED, false);
    if (StringUtils.isNotBlank(sort)) {
        // Parse the sort field and direction
        SearchQuery.Sort sortField = null;
        if (sort.endsWith(DESCENDING_SUFFIX)) {
            String enumKey = sort.substring(0, sort.length() - DESCENDING_SUFFIX.length()).toUpperCase();
            try {
                sortField = SearchQuery.Sort.valueOf(enumKey);
                query.withSort(sortField, false);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", enumKey);
            }
        } else {
            try {
                sortField = SearchQuery.Sort.valueOf(sort);
                query.withSort(sortField);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", sort);
            }
        }
    }
    query.withLimit(limit);
    query.withOffset(offset);
    // Build the response
    ResponseBuilder rb = Response.ok();
    if (admin) {
        rb.entity(searchService.getForAdministrativeRead(query));
    } else {
        rb.entity(searchService.getByQuery(query));
    }
    if ("json".equals(format)) {
        rb.type(MediaType.APPLICATION_JSON);
    } else {
        rb.type(MediaType.TEXT_XML);
    }
    return rb.build();
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) 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