Search in sources :

Example 31 with JValue

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

the class JobEndpoint method getJobs.

@GET
@Path("jobs.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(description = "Returns the list of active jobs", name = "jobs", restParameters = { @RestParameter(name = "limit", description = "The maximum number of items to return per page", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "offset", description = "The offset", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "filter", description = "Filter results by hostname, status or free text query", isRequired = false, type = RestParameter.Type.STRING), @RestParameter(name = "sort", description = "The sort order. May include any of the following: CREATOR, OPERATION, PROCESSINGHOST, STATUS, STARTED, SUBMITTED or TYPE. " + "The suffix must be :ASC for ascending or :DESC for descending sort order (e.g. OPERATION:DESC)", isRequired = false, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Returns the list of active jobs from Opencast", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The list of jobs as JSON")
public Response getJobs(@QueryParam("limit") final int limit, @QueryParam("offset") final int offset, @QueryParam("filter") final String filter, @QueryParam("sort") final String sort) {
    JobsListQuery query = new JobsListQuery();
    EndpointUtil.addRequestFiltersToQuery(filter, query);
    query.setLimit(limit);
    query.setOffset(offset);
    String fHostname = null;
    if (query.getHostname().isSome())
        fHostname = StringUtils.trimToNull(query.getHostname().get());
    String fStatus = null;
    if (query.getStatus().isSome())
        fStatus = StringUtils.trimToNull(query.getStatus().get());
    String fFreeText = null;
    if (query.getFreeText().isSome())
        fFreeText = StringUtils.trimToNull(query.getFreeText().get());
    List<Job> jobs = new ArrayList<>();
    try {
        for (Job job : serviceRegistry.getActiveJobs()) {
            // filter workflow jobs
            if (StringUtils.equals(WorkflowService.JOB_TYPE, job.getJobType()) && StringUtils.equals("START_WORKFLOW", job.getOperation()))
                continue;
            // filter by hostname
            if (fHostname != null && !StringUtils.equalsIgnoreCase(job.getProcessingHost(), fHostname))
                continue;
            // filter by status
            if (fStatus != null && !StringUtils.equalsIgnoreCase(job.getStatus().toString(), fStatus))
                continue;
            // fitler by user free text
            if (fFreeText != null && !StringUtils.equalsIgnoreCase(job.getProcessingHost(), fFreeText) && !StringUtils.equalsIgnoreCase(job.getJobType(), fFreeText) && !StringUtils.equalsIgnoreCase(job.getOperation(), fFreeText) && !StringUtils.equalsIgnoreCase(job.getCreator(), fFreeText) && !StringUtils.equalsIgnoreCase(job.getStatus().toString(), fFreeText) && !StringUtils.equalsIgnoreCase(Long.toString(job.getId()), fFreeText) && (job.getRootJobId() != null && !StringUtils.equalsIgnoreCase(Long.toString(job.getRootJobId()), fFreeText)))
                continue;
            jobs.add(job);
        }
    } catch (ServiceRegistryException ex) {
        logger.error("Failed to retrieve jobs list from service registry.", ex);
        return RestUtil.R.serverError();
    }
    JobSort sortKey = JobSort.SUBMITTED;
    boolean ascending = true;
    if (StringUtils.isNotBlank(sort)) {
        try {
            SortCriterion sortCriterion = RestUtils.parseSortQueryParameter(sort).iterator().next();
            sortKey = JobSort.valueOf(sortCriterion.getFieldName().toUpperCase());
            ascending = SearchQuery.Order.Ascending == sortCriterion.getOrder() || SearchQuery.Order.None == sortCriterion.getOrder();
        } catch (WebApplicationException ex) {
            logger.warn("Failed to parse sort criterion \"{}\", invalid format.", sort);
        } catch (IllegalArgumentException ex) {
            logger.warn("Can not apply sort criterion \"{}\", no field with this name.", sort);
        }
    }
    JobComparator comparator = new JobComparator(sortKey, ascending);
    Collections.sort(jobs, comparator);
    List<JValue> json = getJobsAsJSON(new SmartIterator(query.getLimit().getOrElse(0), query.getOffset().getOrElse(0)).applyLimitAndOffset(jobs));
    return RestUtils.okJsonList(json, offset, limit, jobs.size());
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SmartIterator(org.opencastproject.util.SmartIterator) ArrayList(java.util.ArrayList) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) JobsListQuery(org.opencastproject.index.service.resources.list.query.JobsListQuery) Job(org.opencastproject.job.api.Job) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 32 with JValue

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

the class ServerEndpoint method getServersListAsJson.

/**
 * Transform each list item to JValue representation.
 * @param servers list with servers JSONObjects
 * @return servers list
 */
private List<JValue> getServersListAsJson(List<JSONObject> servers) {
    List<JValue> jsonServers = new ArrayList<JValue>();
    for (JSONObject server : servers) {
        Boolean vOnline = (Boolean) server.get(KEY_ONLINE);
        Boolean vMaintenance = (Boolean) server.get(KEY_MAINTENANCE);
        String vHostname = (String) server.get(KEY_HOSTNAME);
        Integer vCores = (Integer) server.get(KEY_CORES);
        Integer vRunning = (Integer) server.get(KEY_RUNNING);
        Integer vQueued = (Integer) server.get(KEY_QUEUED);
        Long vCompleted = (Long) server.get(KEY_COMPLETED);
        Long vMeanRunTime = (Long) server.get(KEY_MEAN_RUN_TIME);
        Long vMeanQueueTime = (Long) server.get(KEY_MEAN_QUEUE_TIME);
        jsonServers.add(obj(f(KEY_ONLINE, v(vOnline)), f(KEY_MAINTENANCE, v(vMaintenance)), f(KEY_HOSTNAME, v(vHostname)), f(KEY_CORES, v(vCores)), f(KEY_RUNNING, v(vRunning)), f(KEY_QUEUED, v(vQueued)), f(KEY_COMPLETED, v(vCompleted)), f(KEY_MEAN_RUN_TIME, v(vMeanRunTime)), f(KEY_MEAN_QUEUE_TIME, v(vMeanQueueTime))));
    }
    return jsonServers;
}
Also used : JSONObject(org.json.simple.JSONObject) JValue(com.entwinemedia.fn.data.json.JValue) ArrayList(java.util.ArrayList)

Example 33 with JValue

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

the class SeriesEndpoint method getSeries.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("series.json")
@RestQuery(name = "listSeriesAsJson", description = "Returns the series matching the query parameters", returnDescription = "Returns the series search results as JSON", restParameters = { @RestParameter(name = "sortorganizer", isRequired = false, description = "The sort type to apply to the series organizer or organizers either Ascending or Descending.", type = STRING), @RestParameter(name = "sort", description = "The order instructions used to sort the query result. Must be in the form '<field name>:(ASC|DESC)'", isRequired = false, type = STRING), @RestParameter(name = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2,value2'", type = STRING), @RestParameter(name = "offset", isRequired = false, description = "The page offset", type = INTEGER, defaultValue = "0"), @RestParameter(name = "optedOut", isRequired = false, description = "Whether this series is opted out", type = BOOLEAN), @RestParameter(name = "limit", isRequired = false, description = "Results per page (max 100)", type = INTEGER, defaultValue = "100") }, reponses = { @RestResponse(responseCode = SC_OK, description = "The access control list."), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
public Response getSeries(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") int offset, @QueryParam("limit") int limit, @QueryParam("optedOut") Boolean optedOut) throws UnauthorizedException {
    try {
        logger.debug("Requested series list");
        SeriesSearchQuery query = new SeriesSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
        Option<String> optSort = Option.option(trimToNull(sort));
        if (offset != 0) {
            query.withOffset(offset);
        }
        // If limit is 0, we set the default limit
        query.withLimit(limit == 0 ? DEFAULT_LIMIT : limit);
        if (optedOut != null)
            query.withOptedOut(optedOut);
        Map<String, String> filters = RestUtils.parseFilter(filter);
        for (String name : filters.keySet()) {
            if (SeriesListQuery.FILTER_ACL_NAME.equals(name)) {
                query.withManagedAcl(filters.get(name));
            } else if (SeriesListQuery.FILTER_CONTRIBUTORS_NAME.equals(name)) {
                query.withContributor(filters.get(name));
            } else if (SeriesListQuery.FILTER_CREATIONDATE_NAME.equals(name)) {
                try {
                    Tuple<Date, Date> fromAndToCreationRange = RestUtils.getFromAndToDateRange(filters.get(name));
                    query.withCreatedFrom(fromAndToCreationRange.getA());
                    query.withCreatedTo(fromAndToCreationRange.getB());
                } catch (IllegalArgumentException e) {
                    return RestUtil.R.badRequest(e.getMessage());
                }
            } else if (SeriesListQuery.FILTER_CREATOR_NAME.equals(name)) {
                query.withCreator(filters.get(name));
            } else if (SeriesListQuery.FILTER_TEXT_NAME.equals(name)) {
                query.withText(QueryPreprocessor.sanitize(filters.get(name)));
            } else if (SeriesListQuery.FILTER_LANGUAGE_NAME.equals(name)) {
                query.withLanguage(filters.get(name));
            } else if (SeriesListQuery.FILTER_LICENSE_NAME.equals(name)) {
                query.withLicense(filters.get(name));
            } else if (SeriesListQuery.FILTER_ORGANIZERS_NAME.equals(name)) {
                query.withOrganizer(filters.get(name));
            } else if (SeriesListQuery.FILTER_SUBJECT_NAME.equals(name)) {
                query.withSubject(filters.get(name));
            } else if (SeriesListQuery.FILTER_TITLE_NAME.equals(name)) {
                query.withTitle(filters.get(name));
            }
        }
        if (optSort.isSome()) {
            Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
            for (SortCriterion criterion : sortCriteria) {
                switch(criterion.getFieldName()) {
                    case SeriesIndexSchema.TITLE:
                        query.sortByTitle(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CONTRIBUTORS:
                        query.sortByContributors(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CREATOR:
                        query.sortByOrganizers(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CREATED_DATE_TIME:
                        query.sortByCreatedDateTime(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.MANAGED_ACL:
                        query.sortByManagedAcl(criterion.getOrder());
                        break;
                    default:
                        logger.info("Unknown filter criteria {}", criterion.getFieldName());
                        return Response.status(SC_BAD_REQUEST).build();
                }
            }
        }
        logger.trace("Using Query: " + query.toString());
        SearchResult<Series> result = searchIndex.getByQuery(query);
        if (logger.isDebugEnabled()) {
            logger.debug("Found {} results in {} ms", result.getDocumentCount(), result.getSearchTime());
        }
        List<JValue> series = new ArrayList<>();
        for (SearchResultItem<Series> item : result.getItems()) {
            List<Field> fields = new ArrayList<>();
            Series s = item.getSource();
            String sId = s.getIdentifier();
            fields.add(f("id", v(sId)));
            fields.add(f("optedOut", v(s.isOptedOut())));
            fields.add(f("title", v(s.getTitle(), Jsons.BLANK)));
            fields.add(f("organizers", arr($(s.getOrganizers()).map(Functions.stringToJValue))));
            fields.add(f("contributors", arr($(s.getContributors()).map(Functions.stringToJValue))));
            if (s.getCreator() != null) {
                fields.add(f("createdBy", v(s.getCreator())));
            }
            if (s.getCreatedDateTime() != null) {
                fields.add(f("creation_date", v(toUTC(s.getCreatedDateTime().getTime()), Jsons.BLANK)));
            }
            if (s.getLanguage() != null) {
                fields.add(f("language", v(s.getLanguage())));
            }
            if (s.getLicense() != null) {
                fields.add(f("license", v(s.getLicense())));
            }
            if (s.getRightsHolder() != null) {
                fields.add(f("rightsHolder", v(s.getRightsHolder())));
            }
            if (StringUtils.isNotBlank(s.getManagedAcl())) {
                fields.add(f("managedAcl", v(s.getManagedAcl())));
            }
            series.add(obj(fields));
        }
        logger.debug("Request done");
        return okJsonList(series, offset, limit, result.getHitCount());
    } catch (Exception e) {
        logger.warn("Could not perform search query: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SeriesSearchQuery(org.opencastproject.index.service.impl.index.series.SeriesSearchQuery) ArrayList(java.util.ArrayList) Date(java.util.Date) WebApplicationException(javax.ws.rs.WebApplicationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) SeriesException(org.opencastproject.series.api.SeriesException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Series(org.opencastproject.index.service.impl.index.series.Series) Field(com.entwinemedia.fn.data.json.Field) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) 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 34 with JValue

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

the class ThemesEndpoint method getThemes.

@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("themes.json")
@RestQuery(name = "getThemes", description = "Return all of the known themes on the system", restParameters = { @RestParameter(name = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2:value2'", type = STRING), @RestParameter(defaultValue = "0", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.INTEGER), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.INTEGER), @RestParameter(name = "sort", isRequired = false, description = "The sort order. May include any of the following: NAME, CREATOR.  Add '_DESC' to reverse the sort order (e.g. CREATOR_DESC).", type = STRING) }, reponses = { @RestResponse(description = "A JSON representation of the themes", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "")
public Response getThemes(@QueryParam("filter") String filter, @QueryParam("limit") int limit, @QueryParam("offset") int offset, @QueryParam("sort") String sort) {
    Option<Integer> optLimit = Option.option(limit);
    Option<Integer> optOffset = Option.option(offset);
    Option<String> optSort = Option.option(trimToNull(sort));
    ThemeSearchQuery query = new ThemeSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
    // If the limit is set to 0, this is not taken into account
    if (optLimit.isSome() && limit == 0) {
        optLimit = Option.none();
    }
    if (optLimit.isSome())
        query.withLimit(optLimit.get());
    if (optOffset.isSome())
        query.withOffset(offset);
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        if (ThemesListQuery.FILTER_CREATOR_NAME.equals(name))
            query.withCreator(filters.get(name));
        if (ThemesListQuery.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 ThemeIndexSchema.NAME:
                    query.sortByName(criterion.getOrder());
                    break;
                case ThemeIndexSchema.DESCRIPTION:
                    query.sortByDescription(criterion.getOrder());
                    break;
                case ThemeIndexSchema.CREATOR:
                    query.sortByCreator(criterion.getOrder());
                    break;
                case ThemeIndexSchema.DEFAULT:
                    query.sortByDefault(criterion.getOrder());
                    break;
                case ThemeIndexSchema.CREATION_DATE:
                    query.sortByCreatedDateTime(criterion.getOrder());
                    break;
                default:
                    logger.info("Unknown sort criteria {}", criterion.getFieldName());
                    return Response.status(SC_BAD_REQUEST).build();
            }
        }
    }
    logger.trace("Using Query: " + query.toString());
    SearchResult<org.opencastproject.index.service.impl.index.theme.Theme> results = null;
    try {
        results = searchIndex.getByQuery(query);
    } catch (SearchIndexException e) {
        logger.error("The admin UI Search Index was not able to get the themes list:", e);
        return RestUtil.R.serverError();
    }
    List<JValue> themesJSON = new ArrayList<JValue>();
    // If the results list if empty, we return already a response.
    if (results.getPageSize() == 0) {
        logger.debug("No themes match the given filters.");
        return okJsonList(themesJSON, nul(offset).getOr(0), nul(limit).getOr(0), 0);
    }
    for (SearchResultItem<org.opencastproject.index.service.impl.index.theme.Theme> item : results.getItems()) {
        org.opencastproject.index.service.impl.index.theme.Theme theme = item.getSource();
        themesJSON.add(themeToJSON(theme, false));
    }
    return okJsonList(themesJSON, nul(offset).getOr(0), nul(limit).getOr(0), results.getHitCount());
}
Also used : SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ArrayList(java.util.ArrayList) ThemeSearchQuery(org.opencastproject.index.service.impl.index.theme.ThemeSearchQuery) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) Theme(org.opencastproject.themes.Theme) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 35 with JValue

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

the class BaseEndpoint method getEndpointInfo.

@GET
@Path("")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "getendpointinfo", description = "Returns key characteristics of the API such as the server name and the default version.", returnDescription = "", reponses = { @RestResponse(description = "The api information is returned.", responseCode = HttpServletResponse.SC_OK) })
public Response getEndpointInfo() {
    Organization organization = securityService.getOrganization();
    String orgExternalAPIUrl = organization.getProperties().get(OpencastConstants.EXTERNAL_API_URL_ORG_PROPERTY);
    JString url;
    if (StringUtils.isNotBlank(orgExternalAPIUrl)) {
        url = v(orgExternalAPIUrl);
    } else {
        url = v(endpointBaseUrl);
    }
    JValue json = obj(f("url", url), f("version", v(ApiVersion.CURRENT_VERSION.toString())));
    return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(json));
}
Also used : Organization(org.opencastproject.security.api.Organization) JValue(com.entwinemedia.fn.data.json.JValue) JString(com.entwinemedia.fn.data.json.JString) JString(com.entwinemedia.fn.data.json.JString) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

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