Search in sources :

Example 16 with JValue

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

Example 17 with JValue

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

the class ServicesEndpoint method getServices.

@GET
@Path("services.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(description = "Returns the list of services", name = "services", 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 name, host, actions, status or free text query", isRequired = false, type = STRING), @RestParameter(name = "sort", description = "The sort order.  May include any " + "of the following: host, name, running, queued, completed,  meanRunTime, meanQueueTime, " + "status. The sort suffix must be :asc for ascending sort order and :desc for descending.", isRequired = false, type = STRING) }, reponses = { @RestResponse(description = "Returns the list of services from Opencast", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The list of services")
public Response getServices(@QueryParam("limit") final int limit, @QueryParam("offset") final int offset, @QueryParam("filter") String filter, @QueryParam("sort") String sort) throws Exception {
    Option<String> sortOpt = Option.option(StringUtils.trimToNull(sort));
    ServicesListQuery query = new ServicesListQuery();
    EndpointUtil.addRequestFiltersToQuery(filter, query);
    String fName = null;
    if (query.getName().isSome())
        fName = StringUtils.trimToNull(query.getName().get());
    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<Service> services = new ArrayList<Service>();
    for (ServiceStatistics stats : serviceRegistry.getServiceStatistics()) {
        Service service = new Service(stats);
        if (fName != null && !StringUtils.equalsIgnoreCase(service.getName(), fName))
            continue;
        if (fHostname != null && !StringUtils.equalsIgnoreCase(service.getHost(), fHostname))
            continue;
        if (fStatus != null && !StringUtils.equalsIgnoreCase(service.getStatus().toString(), fStatus))
            continue;
        if (query.getActions().isSome()) {
            ServiceState serviceState = service.getStatus();
            if (query.getActions().get()) {
                if (ServiceState.NORMAL == serviceState)
                    continue;
            } else {
                if (ServiceState.NORMAL != serviceState)
                    continue;
            }
        }
        if (fFreeText != null && !StringUtils.containsIgnoreCase(service.getName(), fFreeText) && !StringUtils.containsIgnoreCase(service.getHost(), fFreeText) && !StringUtils.containsIgnoreCase(service.getStatus().toString(), fFreeText))
            continue;
        services.add(service);
    }
    int total = services.size();
    if (sortOpt.isSome()) {
        Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(sortOpt.get());
        if (!sortCriteria.isEmpty()) {
            try {
                SortCriterion sortCriterion = sortCriteria.iterator().next();
                Collections.sort(services, new ServiceStatisticsComparator(sortCriterion.getFieldName(), sortCriterion.getOrder() == SearchQuery.Order.Ascending));
            } catch (Exception ex) {
                logger.warn("Failed to sort services collection.", ex);
            }
        }
    }
    List<JValue> jsonList = new ArrayList<JValue>();
    for (Service s : new SmartIterator<Service>(limit, offset).applyLimitAndOffset(services)) {
        jsonList.add(s.toJSON());
    }
    return RestUtils.okJsonList(jsonList, offset, limit, total);
}
Also used : ServiceState(org.opencastproject.serviceregistry.api.ServiceState) ArrayList(java.util.ArrayList) RestService(org.opencastproject.util.doc.rest.RestService) ServiceStatistics(org.opencastproject.serviceregistry.api.ServiceStatistics) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) ServicesListQuery(org.opencastproject.index.service.resources.list.query.ServicesListQuery) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 18 with JValue

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

the class ThemesEndpoint method getThemeUsage.

@GET
@Path("{themeId}/usage.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getThemeUsage", description = "Returns the theme usage by the given id as JSON", returnDescription = "The theme usage as JSON", pathParameters = { @RestParameter(name = "themeId", description = "The theme id", isRequired = true, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "Returns the theme usage as JSON", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "Theme with the given id does not exist", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response getThemeUsage(@PathParam("themeId") long themeId) throws Exception {
    Opt<org.opencastproject.index.service.impl.index.theme.Theme> theme = getTheme(themeId);
    if (theme.isNone())
        return notFound("Cannot find a theme with id {}", themeId);
    SeriesSearchQuery query = new SeriesSearchQuery(securityService.getOrganization().getId(), securityService.getUser()).withTheme(themeId);
    SearchResult<Series> results = null;
    try {
        results = searchIndex.getByQuery(query);
    } catch (SearchIndexException e) {
        logger.error("The admin UI Search Index was not able to get the series with theme '{}': {}", themeId, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }
    List<JValue> seriesValues = new ArrayList<JValue>();
    for (SearchResultItem<Series> item : results.getItems()) {
        Series series = item.getSource();
        seriesValues.add(obj(f("id", v(series.getIdentifier())), f("title", v(series.getTitle()))));
    }
    return okJson(obj(f("series", arr(seriesValues))));
}
Also used : SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) SeriesSearchQuery(org.opencastproject.index.service.impl.index.series.SeriesSearchQuery) ArrayList(java.util.ArrayList) Series(org.opencastproject.index.service.impl.index.series.Series) 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 19 with JValue

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

the class ToolsEndpoint method getVideoEditor.

@GET
@Path("{mediapackageid}/editor.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getVideoEditor", description = "Returns all the information required to get the editor tool started", returnDescription = "JSON object", pathParameters = { @RestParameter(name = "mediapackageid", description = "The id of the media package", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Media package found", responseCode = SC_OK), @RestResponse(description = "Media package not found", responseCode = SC_NOT_FOUND) })
public Response getVideoEditor(@PathParam("mediapackageid") final String mediaPackageId) throws IndexServiceException, NotFoundException {
    if (!isEditorAvailable(mediaPackageId))
        return R.notFound();
    // Select tracks
    final Event event = getEvent(mediaPackageId).get();
    final MediaPackage mp = index.getEventMediapackage(event);
    List<MediaPackageElement> previewPublications = getPreviewElementsFromPublication(getInternalPublication(mp));
    // Collect previews and tracks
    List<JValue> jPreviews = new ArrayList<>();
    List<JValue> jTracks = new ArrayList<>();
    for (MediaPackageElement element : previewPublications) {
        final URI elementUri;
        if (urlSigningService.accepts(element.getURI().toString())) {
            try {
                String clientIP = null;
                if (signWithClientIP) {
                    clientIP = securityService.getUserIP();
                }
                elementUri = new URI(urlSigningService.sign(element.getURI().toString(), expireSeconds, null, clientIP));
            } catch (URISyntaxException e) {
                logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
            } catch (UrlSigningException e) {
                logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            elementUri = element.getURI();
        }
        jPreviews.add(obj(f("uri", v(elementUri.toString())), f("flavor", v(element.getFlavor().getType()))));
        if (!Type.Track.equals(element.getElementType()))
            continue;
        JObject jTrack = obj(f("id", v(element.getIdentifier())), f("flavor", v(element.getFlavor().getType())));
        // Check if there's a waveform for the current track
        Opt<Attachment> optWaveform = getWaveformForTrack(mp, element);
        if (optWaveform.isSome()) {
            final URI waveformUri;
            if (urlSigningService.accepts(element.getURI().toString())) {
                try {
                    waveformUri = new URI(urlSigningService.sign(optWaveform.get().getURI().toString(), expireSeconds, null, null));
                } catch (URISyntaxException e) {
                    logger.error("Error while trying to serialize the waveform urls because: {}", getStackTrace(e));
                    throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
                } catch (UrlSigningException e) {
                    logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                    throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
                }
            } else {
                waveformUri = optWaveform.get().getURI();
            }
            jTracks.add(jTrack.merge(obj(f("waveform", v(waveformUri.toString())))));
        } else {
            jTracks.add(jTrack);
        }
    }
    // Get existing segments
    List<JValue> jSegments = new ArrayList<>();
    for (Tuple<Long, Long> segment : getSegments(mp)) {
        jSegments.add(obj(f(START_KEY, v(segment.getA())), f(END_KEY, v(segment.getB()))));
    }
    // Get workflows
    List<JValue> jWorkflows = new ArrayList<>();
    for (WorkflowDefinition workflow : getEditingWorkflows()) {
        jWorkflows.add(obj(f("id", v(workflow.getId())), f("name", v(workflow.getTitle(), Jsons.BLANK))));
    }
    return RestUtils.okJson(obj(f("title", v(mp.getTitle(), Jsons.BLANK)), f("date", v(event.getRecordingStartDate(), Jsons.BLANK)), f("series", obj(f("id", v(event.getSeriesId(), Jsons.BLANK)), f("title", v(event.getSeriesName(), Jsons.BLANK)))), f("presenters", arr($(event.getPresenters()).map(Functions.stringToJValue))), f("previews", arr(jPreviews)), f(TRACKS_KEY, arr(jTracks)), f("duration", v(mp.getDuration())), f(SEGMENTS_KEY, arr(jSegments)), f("workflows", arr(jWorkflows))));
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ArrayList(java.util.ArrayList) WorkflowDefinition(org.opencastproject.workflow.api.WorkflowDefinition) Attachment(org.opencastproject.mediapackage.Attachment) URISyntaxException(java.net.URISyntaxException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) URI(java.net.URI) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) JValue(com.entwinemedia.fn.data.json.JValue) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JObject(com.entwinemedia.fn.data.json.JObject) 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 JValue

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

the class UsersEndpoint method getUsers.

@GET
@Path("users.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "allusers", description = "Returns a list of users", returnDescription = "Returns a JSON representation of the list of user accounts", 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(name = "sort", isRequired = false, description = "The sort order. May include any of the following: STATUS, NAME OR LAST_UPDATED.  Add '_DESC' to reverse the sort order (e.g. STATUS_DESC).", type = STRING), @RestParameter(defaultValue = "100", 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) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The user accounts.") })
public Response getUsers(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("limit") int limit, @QueryParam("offset") int offset) throws IOException {
    if (limit < 1)
        limit = 100;
    Option<String> optSort = Option.option(trimToNull(sort));
    Option<String> filterName = Option.none();
    Option<String> filterRole = Option.none();
    Option<String> filterProvider = Option.none();
    Option<String> filterText = Option.none();
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        String value = filters.get(name);
        if (UsersListQuery.FILTER_NAME_NAME.equals(name)) {
            filterName = Option.some(value);
        } else if (UsersListQuery.FILTER_ROLE_NAME.equals(name)) {
            filterRole = Option.some(value);
        } else if (UsersListQuery.FILTER_PROVIDER_NAME.equals(name)) {
            filterProvider = Option.some(value);
        } else if ((UsersListQuery.FILTER_TEXT_NAME.equals(name)) && (StringUtils.isNotBlank(value))) {
            filterText = Option.some(value);
        }
    }
    // Filter users by filter criteria
    List<User> filteredUsers = new ArrayList<>();
    for (Iterator<User> i = userDirectoryService.getUsers(); i.hasNext(); ) {
        User user = i.next();
        // Filter list
        if (filterName.isSome() && !filterName.get().equals(user.getName()) || (filterRole.isSome() && !Stream.$(user.getRoles()).map(getRoleName).toSet().contains(filterRole.get())) || (filterProvider.isSome() && !filterProvider.get().equals(user.getProvider())) || (filterText.isSome() && !TextFilter.match(filterText.get(), user.getUsername(), user.getName(), user.getEmail(), user.getProvider()) && !TextFilter.match(filterText.get(), Stream.$(user.getRoles()).map(getRoleName).mkString(" ")))) {
            continue;
        }
        filteredUsers.add(user);
    }
    int total = filteredUsers.size();
    // Sort by name, description or role
    if (optSort.isSome()) {
        final Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        Collections.sort(filteredUsers, new Comparator<User>() {

            @Override
            public int compare(User user1, User user2) {
                for (SortCriterion criterion : sortCriteria) {
                    Order order = criterion.getOrder();
                    switch(criterion.getFieldName()) {
                        case "name":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getName()), trimToEmpty(user1.getName()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getName()), trimToEmpty(user2.getName()));
                        case "username":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getUsername()), trimToEmpty(user1.getUsername()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getUsername()), trimToEmpty(user2.getUsername()));
                        case "email":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getEmail()), trimToEmpty(user1.getEmail()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getEmail()), trimToEmpty(user2.getEmail()));
                        case "roles":
                            String roles1 = Stream.$(user1.getRoles()).map(getRoleName).sort(sortByName).mkString(",");
                            String roles2 = Stream.$(user2.getRoles()).map(getRoleName).sort(sortByName).mkString(",");
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(roles2), trimToEmpty(roles1));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(roles1), trimToEmpty(roles2));
                        case "provider":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getProvider()), trimToEmpty(user1.getProvider()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getProvider()), trimToEmpty(user2.getProvider()));
                        default:
                            logger.info("Unkown sort type: {}", criterion.getFieldName());
                            return 0;
                    }
                }
                return 0;
            }
        });
    }
    // Apply Limit and offset
    filteredUsers = new SmartIterator<User>(limit, offset).applyLimitAndOffset(filteredUsers);
    List<JValue> usersJSON = new ArrayList<>();
    for (User user : filteredUsers) {
        usersJSON.add(generateJsonUser(user));
    }
    return okJsonList(usersJSON, offset, limit, total);
}
Also used : Order(org.opencastproject.matterhorn.search.SearchQuery.Order) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) User(org.opencastproject.security.api.User) SmartIterator(org.opencastproject.util.SmartIterator) ArrayList(java.util.ArrayList) 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)

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