Search in sources :

Example 66 with RestQuery

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

the class GroupsEndpoint method getGroups.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("groups.json")
@RestQuery(name = "allgroupsasjson", description = "Returns a list of groups", returnDescription = "List of groups for the current user's organization as JSON.", restParameters = { @RestParameter(name = "filter", isRequired = false, type = STRING, description = "Filter used for the query, formatted like: 'filter1:value1,filter2:value2'"), @RestParameter(name = "sort", isRequired = false, type = STRING, description = "The sort order. May include any of the following: NAME, DESCRIPTION, ROLE. " + "Add '_DESC' to reverse the sort order (e.g. NAME_DESC)."), @RestParameter(name = "limit", isRequired = false, type = INTEGER, defaultValue = "100", description = "The maximum number of items to return per page."), @RestParameter(name = "offset", isRequired = false, type = INTEGER, defaultValue = "0", description = "The page number.") }, reponses = { @RestResponse(responseCode = SC_OK, description = "The groups.") })
public Response getGroups(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") int offset, @QueryParam("limit") int limit) throws IOException {
    GroupSearchQuery query = new GroupSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
    Opt<String> optSort = Opt.nul(trimToNull(sort));
    Option<Integer> optOffset = Option.option(offset);
    Option<Integer> optLimit = Option.option(limit);
    // 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 (GroupsListQuery.FILTER_NAME_NAME.equals(name)) {
            query.withName(filters.get(name));
        } else if (GroupsListQuery.FILTER_TEXT_NAME.equals(name)) {
            query.withText(QueryPreprocessor.sanitize(filters.get(name)));
        }
    }
    if (optSort.isSome()) {
        Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        for (SortCriterion criterion : sortCriteria) {
            switch(criterion.getFieldName()) {
                case GroupIndexSchema.NAME:
                    query.sortByName(criterion.getOrder());
                    break;
                case GroupIndexSchema.DESCRIPTION:
                    query.sortByDescription(criterion.getOrder());
                    break;
                case GroupIndexSchema.ROLE:
                    query.sortByRole(criterion.getOrder());
                    break;
                case GroupIndexSchema.MEMBERS:
                    query.sortByMembers(criterion.getOrder());
                    break;
                case GroupIndexSchema.ROLES:
                    query.sortByRoles(criterion.getOrder());
                    break;
                default:
                    throw new WebApplicationException(Status.BAD_REQUEST);
            }
        }
    }
    if (optLimit.isSome())
        query.withLimit(optLimit.get());
    if (optOffset.isSome())
        query.withOffset(optOffset.get());
    SearchResult<Group> results;
    try {
        results = searchIndex.getByQuery(query);
    } catch (SearchIndexException e) {
        logger.error("The External Search Index was not able to get the groups list.", e);
        return RestUtil.R.serverError();
    }
    List<JValue> groupsJSON = new ArrayList<>();
    for (SearchResultItem<Group> item : results.getItems()) {
        Group group = item.getSource();
        List<Field> fields = new ArrayList<>();
        fields.add(f("id", v(group.getIdentifier())));
        fields.add(f("name", v(group.getName(), Jsons.BLANK)));
        fields.add(f("description", v(group.getDescription(), Jsons.BLANK)));
        fields.add(f("role", v(group.getRole())));
        fields.add(f("users", membersToJSON(group.getMembers())));
        groupsJSON.add(obj(fields));
    }
    return okJsonList(groupsJSON, offset, limit, results.getHitCount());
}
Also used : Group(org.opencastproject.index.service.impl.index.group.Group) WebApplicationException(javax.ws.rs.WebApplicationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ArrayList(java.util.ArrayList) GroupSearchQuery(org.opencastproject.index.service.impl.index.group.GroupSearchQuery) Field(com.entwinemedia.fn.data.json.Field) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 67 with RestQuery

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

the class GroupsEndpoint method getGroup.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@RestQuery(name = "getGroup", description = "Get a single group", returnDescription = "Return the status codes", pathParameters = { @RestParameter(name = "id", description = "The group identifier", isRequired = true, type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "Group found and returned as JSON"), @RestResponse(responseCode = SC_NOT_FOUND, description = "Group not found") })
public Response getGroup(@PathParam("id") String groupId) throws NotFoundException, SearchIndexException {
    Opt<Group> groupOpt = indexService.getGroup(groupId, searchIndex);
    if (groupOpt.isNone())
        throw new NotFoundException("Group " + groupId + " does not exist.");
    Group group = groupOpt.get();
    return RestUtils.okJson(obj(f("id", v(group.getIdentifier())), f("name", v(group.getName(), Jsons.BLANK)), f("description", v(group.getDescription(), Jsons.BLANK)), f("role", v(group.getRole(), Jsons.BLANK)), f("roles", rolesToJSON(group.getRoles())), f("users", membersToJSON(group.getMembers()))));
}
Also used : Group(org.opencastproject.index.service.impl.index.group.Group) NotFoundException(org.opencastproject.util.NotFoundException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 68 with RestQuery

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

the class ListProvidersEndpoint method getList.

@GET
@Path("{source}.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "list", description = "Provides key-value list from the given source", pathParameters = { @RestParameter(name = "source", description = "The source for the key-value list", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The maximum number of items to return per page", isRequired = false, name = "limit", type = RestParameter.Type.INTEGER), @RestParameter(description = "The offset", isRequired = false, name = "offset", type = RestParameter.Type.INTEGER), @RestParameter(description = "Filters", isRequired = false, name = "filter", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Returns the key-value list for the given source.", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "")
public Response getList(@PathParam("source") final String source, @QueryParam("limit") final int limit, @QueryParam("filter") final String filter, @QueryParam("offset") final int offset, @Context HttpHeaders headers) {
    if (listProvidersService.hasProvider(source)) {
        ResourceListQueryImpl query = new ResourceListQueryImpl();
        query.setLimit(limit);
        query.setOffset(offset);
        addRequestFiltersToQuery(filter, query);
        Map<String, String> autocompleteList;
        try {
            autocompleteList = listProvidersService.getList(source, query, securityService.getOrganization(), false);
        } catch (ListProviderException e) {
            logger.error("Not able to get list from provider {}: {}", source, e);
            return SERVER_ERROR;
        }
        JSONObject jsonList;
        try {
            jsonList = generateJSONObject(autocompleteList);
        } catch (JsonCreationException e) {
            logger.error("Not able to generate resources list JSON from source {}: {}", source, e);
            return SERVER_ERROR;
        }
        return Response.ok(jsonList.toString()).build();
    }
    return NOT_FOUND;
}
Also used : EndpointUtil.generateJSONObject(org.opencastproject.adminui.endpoint.EndpointUtil.generateJSONObject) JSONObject(org.json.simple.JSONObject) ResourceListQueryImpl(org.opencastproject.index.service.resources.list.query.ResourceListQueryImpl) ListProviderException(org.opencastproject.index.service.exception.ListProviderException) JsonCreationException(org.opencastproject.adminui.exception.JsonCreationException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 69 with RestQuery

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

the class TasksEndpoint method createNewTask.

@POST
@Path("/new")
@RestQuery(name = "createNewTask", description = "Creates a new task by the given metadata as JSON", returnDescription = "The task identifiers", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Task sucessfully added"), @RestResponse(responseCode = SC_NOT_FOUND, description = "If the workflow definition is not found"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed") })
public Response createNewTask(@FormParam("metadata") String metadata) throws NotFoundException {
    if (StringUtils.isBlank(metadata)) {
        logger.warn("No metadata set");
        return RestUtil.R.badRequest("No metadata set");
    }
    Gson gson = new Gson();
    Map metadataJson = null;
    try {
        metadataJson = gson.fromJson(metadata, Map.class);
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        return RestUtil.R.badRequest("Unable to parse metadata");
    }
    String workflowId = (String) metadataJson.get("workflow");
    if (StringUtils.isBlank(workflowId))
        return RestUtil.R.badRequest("No workflow set");
    List eventIds = (List) metadataJson.get("eventIds");
    if (eventIds == null)
        return RestUtil.R.badRequest("No eventIds set");
    Map<String, String> configuration = (Map<String, String>) metadataJson.get("configuration");
    if (configuration == null) {
        configuration = new HashMap<>();
    } else {
        Iterator<String> confKeyIter = configuration.keySet().iterator();
        while (confKeyIter.hasNext()) {
            String confKey = confKeyIter.next();
            if (StringUtils.equalsIgnoreCase("eventIds", confKey)) {
                confKeyIter.remove();
            }
        }
    }
    WorkflowDefinition wfd;
    try {
        wfd = workflowService.getWorkflowDefinitionById(workflowId);
    } catch (WorkflowDatabaseException e) {
        logger.error("Unable to get workflow definition {}: {}", workflowId, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }
    final Workflows workflows = new Workflows(assetManager, workspace, workflowService);
    final List<WorkflowInstance> instances = workflows.applyWorkflowToLatestVersion(eventIds, workflow(wfd, configuration)).toList();
    if (eventIds.size() != instances.size()) {
        logger.debug("Can't start one or more tasks.");
        return Response.status(Status.BAD_REQUEST).build();
    }
    return Response.status(Status.CREATED).entity(gson.toJson($(instances).map(getWorkflowIds).toList())).build();
}
Also used : Workflows(org.opencastproject.assetmanager.util.Workflows) Gson(com.google.gson.Gson) WorkflowDefinition(org.opencastproject.workflow.api.WorkflowDefinition) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 70 with RestQuery

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

the class TasksEndpoint method getProcessing.

@GET
@Path("processing.json")
@RestQuery(name = "getProcessing", description = "Returns all the data related to the processing tab in the new tasks modal as JSON", returnDescription = "All the data related to the tasks processing tab as JSON", restParameters = { @RestParameter(name = "tags", isRequired = false, description = "A comma separated list of tags to filter the workflow definitions", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "Returns all the data related to the tasks processing tab as JSON") })
public Response getProcessing(@QueryParam("tags") String tagsString) {
    List<String> tags = RestUtil.splitCommaSeparatedParam(Option.option(tagsString)).value();
    // This is the JSON Object which will be returned by this request
    List<JValue> actions = new ArrayList<>();
    try {
        List<WorkflowDefinition> workflowsDefinitions = workflowService.listAvailableWorkflowDefinitions();
        for (WorkflowDefinition wflDef : workflowsDefinitions) {
            if (wflDef.containsTag(tags)) {
                actions.add(obj(f("id", v(wflDef.getId())), f("title", v(nul(wflDef.getTitle()).getOr(""))), f("description", v(nul(wflDef.getDescription()).getOr(""))), f("configuration_panel", v(nul(wflDef.getConfigurationPanel()).getOr("")))));
            }
        }
    } catch (WorkflowDatabaseException e) {
        logger.error("Unable to get available workflow definitions: {}", ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }
    return okJson(arr(actions));
}
Also used : WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) JValue(com.entwinemedia.fn.data.json.JValue) ArrayList(java.util.ArrayList) WorkflowDefinition(org.opencastproject.workflow.api.WorkflowDefinition) Path(javax.ws.rs.Path) 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