Search in sources :

Example 11 with JValue

use of com.entwinemedia.fn.data.json.JValue 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 12 with JValue

use of com.entwinemedia.fn.data.json.JValue in project opencast by opencast.

the class JobEndpoint method getTasksAsJSON.

/**
 * Returns the list of tasks matching the given query as JSON Object
 *
 * @param query
 *          The worklfow query
 * @return The list of matching tasks as JSON Object
 * @throws JobEndpointException
 * @throws NotFoundException
 */
public JObject getTasksAsJSON(WorkflowQuery query) throws JobEndpointException, NotFoundException {
    // Get results
    WorkflowSet workflowInstances = null;
    long totalWithoutFilters = 0;
    List<JValue> jsonList = new ArrayList<>();
    try {
        workflowInstances = workflowService.getWorkflowInstances(query);
        totalWithoutFilters = workflowService.countWorkflowInstances();
    } catch (WorkflowDatabaseException e) {
        throw new JobEndpointException(String.format("Not able to get the list of job from the database: %s", e), e.getCause());
    }
    WorkflowInstance[] items = workflowInstances.getItems();
    for (WorkflowInstance instance : items) {
        long instanceId = instance.getId();
        String series = instance.getMediaPackage().getSeriesTitle();
        // Retrieve submission date with the workflow instance main job
        Date created;
        try {
            created = serviceRegistry.getJob(instanceId).getDateCreated();
        } catch (ServiceRegistryException e) {
            throw new JobEndpointException(String.format("Error when retrieving job %s from the service registry: %s", instanceId, e), e.getCause());
        }
        jsonList.add(obj(f("id", v(instanceId)), f("title", v(nul(instance.getMediaPackage().getTitle()).getOr(""))), f("series", v(series, Jsons.BLANK)), f("workflow", v(instance.getTitle(), Jsons.BLANK)), f("status", v(instance.getState().toString())), f("submitted", v(created != null ? DateTimeSupport.toUTC(created.getTime()) : ""))));
    }
    JObject json = obj(f("results", arr(jsonList)), f("count", v(workflowInstances.getTotalCount())), f("offset", v(query.getStartPage())), f("limit", v(jsonList.size())), f("total", v(totalWithoutFilters)));
    return json;
}
Also used : WorkflowSet(org.opencastproject.workflow.api.WorkflowSet) ArrayList(java.util.ArrayList) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) Date(java.util.Date) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) JValue(com.entwinemedia.fn.data.json.JValue) JObject(com.entwinemedia.fn.data.json.JObject)

Example 13 with JValue

use of com.entwinemedia.fn.data.json.JValue in project opencast by opencast.

the class JobEndpoint method getOperationsAsJSON.

/**
 * Returns the list of operations for a given workflow instance
 *
 * @param jobId
 *          the workflow instance id
 * @return the list of workflow operations as JSON object
 * @throws JobEndpointException
 * @throws NotFoundException
 */
public JValue getOperationsAsJSON(long jobId) throws JobEndpointException, NotFoundException {
    WorkflowInstance instance = getWorkflowById(jobId);
    List<WorkflowOperationInstance> operations = instance.getOperations();
    List<JValue> operationsJSON = new ArrayList<>();
    for (WorkflowOperationInstance wflOp : operations) {
        List<Field> fields = new ArrayList<>();
        for (String key : wflOp.getConfigurationKeys()) {
            fields.add(f(key, v(wflOp.getConfiguration(key), Jsons.BLANK)));
        }
        operationsJSON.add(obj(f("status", v(wflOp.getState(), Jsons.BLANK)), f("title", v(wflOp.getTemplate(), Jsons.BLANK)), f("description", v(wflOp.getDescription(), Jsons.BLANK)), f("id", v(wflOp.getId(), Jsons.BLANK)), f("configuration", obj(fields))));
    }
    return arr(operationsJSON);
}
Also used : Field(com.entwinemedia.fn.data.json.Field) WorkflowOperationInstance(org.opencastproject.workflow.api.WorkflowOperationInstance) JValue(com.entwinemedia.fn.data.json.JValue) ArrayList(java.util.ArrayList) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance)

Example 14 with JValue

use of com.entwinemedia.fn.data.json.JValue in project opencast by opencast.

the class JobEndpoint method getJobsAsJSON.

public List<JValue> getJobsAsJSON(List<Job> jobs) {
    List<JValue> jsonList = new ArrayList<>();
    for (Job job : jobs) {
        long id = job.getId();
        String jobType = job.getJobType();
        String operation = job.getOperation();
        Job.Status status = job.getStatus();
        Date dateCreated = job.getDateCreated();
        String created = null;
        if (dateCreated != null)
            created = DateTimeSupport.toUTC(dateCreated.getTime());
        Date dateStarted = job.getDateStarted();
        String started = null;
        if (dateStarted != null)
            started = DateTimeSupport.toUTC(dateStarted.getTime());
        String creator = job.getCreator();
        String processingHost = job.getProcessingHost();
        jsonList.add(obj(f("id", v(id)), f("type", v(jobType)), f("operation", v(operation)), f("status", v(status.toString())), f("submitted", v(created, Jsons.BLANK)), f("started", v(started, Jsons.BLANK)), f("creator", v(creator, Jsons.BLANK)), f("processingHost", v(processingHost, Jsons.BLANK))));
    }
    return jsonList;
}
Also used : JValue(com.entwinemedia.fn.data.json.JValue) ArrayList(java.util.ArrayList) Job(org.opencastproject.job.api.Job) Date(java.util.Date)

Example 15 with JValue

use of com.entwinemedia.fn.data.json.JValue in project opencast by opencast.

the class JobEndpoint method getIncidentsAsJSON.

/**
 * Returns the list of incidents for a given workflow instance
 *
 * @param jobId
 *          the workflow instance id
 * @param locale
 *          the language in which title and description shall be returned
 * @param cascade
 *          if true, return the incidents of the given job and those of of its descendants
 * @return the list incidents as JSON array
 * @throws JobEndpointException
 * @throws NotFoundException
 */
public JValue getIncidentsAsJSON(long jobId, final Locale locale, boolean cascade) throws JobEndpointException, NotFoundException {
    final List<Incident> incidents;
    try {
        final IncidentTree it = incidentService.getIncidentsOfJob(jobId, cascade);
        incidents = cascade ? flatten(it) : it.getIncidents();
    } catch (IncidentServiceException e) {
        throw new JobEndpointException(String.format("Not able to get the incidents for the job %d from the incident service : %s", jobId, e), e.getCause());
    }
    final Stream<JValue> json = $(incidents).map(new Fn<Incident, JValue>() {

        @Override
        public JValue apply(Incident i) {
            return obj(f("id", v(i.getId())), f("severity", v(i.getSeverity(), Jsons.BLANK)), f("timestamp", v(toUTC(i.getTimestamp().getTime()), Jsons.BLANK))).merge(localizeIncident(i, locale));
        }
    });
    return arr(json);
}
Also used : JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) IncidentServiceException(org.opencastproject.serviceregistry.api.IncidentServiceException) JValue(com.entwinemedia.fn.data.json.JValue) Incident(org.opencastproject.job.api.Incident) IncidentTree(org.opencastproject.job.api.IncidentTree)

Aggregations

JValue (com.entwinemedia.fn.data.json.JValue)42 ArrayList (java.util.ArrayList)31 Path (javax.ws.rs.Path)25 GET (javax.ws.rs.GET)24 RestQuery (org.opencastproject.util.doc.rest.RestQuery)24 Produces (javax.ws.rs.Produces)22 Field (com.entwinemedia.fn.data.json.Field)10 SortCriterion (org.opencastproject.matterhorn.search.SortCriterion)10 Date (java.util.Date)8 WebApplicationException (javax.ws.rs.WebApplicationException)8 SearchIndexException (org.opencastproject.matterhorn.search.SearchIndexException)8 JObject (com.entwinemedia.fn.data.json.JObject)6 Fn (com.entwinemedia.fn.Fn)5 IndexServiceException (org.opencastproject.index.service.exception.IndexServiceException)5 Event (org.opencastproject.index.service.impl.index.event.Event)5 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)5 NotFoundException (org.opencastproject.util.NotFoundException)5 Opt (com.entwinemedia.fn.data.Opt)4 JobEndpointException (org.opencastproject.adminui.exception.JobEndpointException)4 Series (org.opencastproject.index.service.impl.index.series.Series)4