Search in sources :

Example 1 with JValue

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

the class JSONUtilsTest method testFiltersToJSON.

/**
 * Test method for
 * {@link JSONUtils#filtersToJSON(org.opencastproject.index.service.resources.list.api.ResourceListQuery, org.opencastproject.index.service.resources.list.api.ListProvidersService, org.opencastproject.security.api.Organization)}
 * (filters, listProviderService, query, org)}
 */
@Test
public void testFiltersToJSON() throws Exception {
    String expectedJSON = IOUtils.toString(getClass().getResource("/filters.json"));
    JaxbOrganization defaultOrganization = new DefaultOrganization();
    ListProvidersServiceImpl listProvidersService = new ListProvidersServiceImpl();
    SimpleSerializer serializer = new SimpleSerializer();
    final Map<String, String> license = new HashMap<String, String>();
    license.put("contributor1", "My first contributor");
    license.put("contributor2", "My second contributor");
    license.put("contributor3", "My third contributor");
    // Create test list provider
    listProvidersService.addProvider(new ResourceListProvider() {

        @Override
        public String[] getListNames() {
            return new String[] { ContributorsListProvider.DEFAULT };
        }

        @Override
        public Map<String, String> getList(String listName, ResourceListQuery query, Organization organization) throws ListProviderException {
            return ListProviderUtil.filterMap(license, query);
        }

        @Override
        public boolean isTranslatable(String listName) {
            return false;
        }

        @Override
        public String getDefault() {
            return null;
        }
    });
    // Prepare mock query
    List<ResourceListFilter<?>> filters = new ArrayList<ResourceListFilter<?>>();
    filters.add(SeriesListQuery.createContributorsFilter(Option.<String>none()));
    filters.add(new StringListFilter(""));
    ResourceListQueryImpl query = EasyMock.createNiceMock(ResourceListQueryImpl.class);
    EasyMock.expect(query.getAvailableFilters()).andReturn(filters).anyTimes();
    EasyMock.expect(query.getFilters()).andReturn(new ArrayList<ResourceListFilter<?>>()).anyTimes();
    EasyMock.expect(query.getLimit()).andReturn(Option.<Integer>none()).anyTimes();
    EasyMock.expect(query.getOffset()).andReturn(Option.<Integer>none()).anyTimes();
    EasyMock.replay(query);
    JValue result = JSONUtils.filtersToJSON(query, listProvidersService, defaultOrganization);
    StreamingOutput stream = RestUtils.stream(serializer.fn.toJson(result));
    ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
    try {
        stream.write(resultStream);
        assertThat(expectedJSON, SameJSONAs.sameJSONAs(resultStream.toString()));
    } finally {
        IOUtils.closeQuietly(resultStream);
    }
}
Also used : SimpleSerializer(com.entwinemedia.fn.data.json.SimpleSerializer) ResourceListProvider(org.opencastproject.index.service.resources.list.api.ResourceListProvider) Organization(org.opencastproject.security.api.Organization) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) ListProvidersServiceImpl(org.opencastproject.index.service.resources.list.impl.ListProvidersServiceImpl) HashMap(java.util.HashMap) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) ArrayList(java.util.ArrayList) ListProviderException(org.opencastproject.index.service.exception.ListProviderException) ResourceListQueryImpl(org.opencastproject.index.service.resources.list.query.ResourceListQueryImpl) StreamingOutput(javax.ws.rs.core.StreamingOutput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ResourceListQuery(org.opencastproject.index.service.resources.list.api.ResourceListQuery) ResourceListFilter(org.opencastproject.index.service.resources.list.api.ResourceListFilter) JValue(com.entwinemedia.fn.data.json.JValue) HashMap(java.util.HashMap) Map(java.util.Map) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) StringListFilter(org.opencastproject.index.service.resources.list.query.StringListFilter) Test(org.junit.Test)

Example 2 with JValue

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

the class SeriesRestService method getSeriesElements.

@GET
@Path("{seriesId}/elements.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getSeriesElements", description = "Returns all the element types of a series", returnDescription = "Returns a JSON array with all the types of elements of the given series.", pathParameters = { @RestParameter(name = "seriesId", description = "The series identifier", type = STRING, isRequired = true) }, reponses = { @RestResponse(responseCode = SC_OK, description = "Series found"), @RestResponse(responseCode = SC_NOT_FOUND, description = "Series not found"), @RestResponse(responseCode = SC_INTERNAL_SERVER_ERROR, description = "Error while processing the request") })
public Response getSeriesElements(@PathParam("seriesId") String seriesId) {
    try {
        Opt<Map<String, byte[]>> optSeriesElements = seriesService.getSeriesElements(seriesId);
        if (optSeriesElements.isSome()) {
            Map<String, byte[]> seriesElements = optSeriesElements.get();
            JValue jsonArray = Jsons.arr(Stream.$(seriesElements.keySet()).map(Jsons.Functions.stringToJValue));
            return Response.ok(new SimpleSerializer().toJson(jsonArray)).build();
        } else {
            return R.notFound();
        }
    } catch (SeriesException e) {
        logger.warn("Error while retrieving elements for sieres '{}': {}", seriesId, ExceptionUtils.getStackTrace(e));
        return R.serverError();
    }
}
Also used : SimpleSerializer(com.entwinemedia.fn.data.json.SimpleSerializer) JValue(com.entwinemedia.fn.data.json.JValue) SeriesException(org.opencastproject.series.api.SeriesException) Map(java.util.Map) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 3 with JValue

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

the class AbstractEventEndpoint method getNewConflicts.

@POST
@Path("new/conflicts")
@RestQuery(name = "checkNewConflicts", description = "Checks if the current scheduler parameters are in a conflict with another event", returnDescription = "Returns NO CONTENT if no event are in conflict within specified period or list of conflicting recordings in JSON", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "No conflicting events found"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "There is a conflict"), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid parameters") })
public Response getNewConflicts(@FormParam("metadata") String metadata) throws NotFoundException {
    if (StringUtils.isBlank(metadata)) {
        logger.warn("Metadata is not specified");
        return Response.status(Status.BAD_REQUEST).build();
    }
    JSONParser parser = new JSONParser();
    JSONObject metadataJson;
    try {
        metadataJson = (JSONObject) parser.parse(metadata);
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        return RestUtil.R.badRequest("Unable to parse metadata");
    }
    String device;
    String startDate;
    String endDate;
    try {
        device = (String) metadataJson.get("device");
        startDate = (String) metadataJson.get("start");
        endDate = (String) metadataJson.get("end");
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        return RestUtil.R.badRequest("Unable to parse metadata");
    }
    if (StringUtils.isBlank(device) || StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
        logger.warn("Either device, start date or end date were not specified");
        return Response.status(Status.BAD_REQUEST).build();
    }
    Date start;
    try {
        start = new Date(DateTimeSupport.fromUTC(startDate));
    } catch (Exception e) {
        logger.warn("Unable to parse start date {}", startDate);
        return RestUtil.R.badRequest("Unable to parse start date");
    }
    Date end;
    try {
        end = new Date(DateTimeSupport.fromUTC(endDate));
    } catch (Exception e) {
        logger.warn("Unable to parse end date {}", endDate);
        return RestUtil.R.badRequest("Unable to parse end date");
    }
    String rruleString = (String) metadataJson.get("rrule");
    RRule rrule = null;
    TimeZone timeZone = TimeZone.getDefault();
    String durationString = null;
    if (StringUtils.isNotEmpty(rruleString)) {
        try {
            rrule = new RRule(rruleString);
            rrule.validate();
        } catch (Exception e) {
            logger.warn("Unable to parse rrule {}: {}", rruleString, e.getMessage());
            return Response.status(Status.BAD_REQUEST).build();
        }
        durationString = (String) metadataJson.get("duration");
        if (StringUtils.isBlank(durationString)) {
            logger.warn("If checking recurrence, must include duration.");
            return Response.status(Status.BAD_REQUEST).build();
        }
        Agent agent = getCaptureAgentStateService().getAgent(device);
        String timezone = agent.getConfiguration().getProperty("capture.device.timezone");
        if (StringUtils.isBlank(timezone)) {
            timezone = TimeZone.getDefault().getID();
            logger.warn("No 'capture.device.timezone' set on agent {}. The default server timezone {} will be used.", device, timezone);
        }
        timeZone = TimeZone.getTimeZone(timezone);
    }
    String eventId = (String) metadataJson.get("id");
    try {
        List<MediaPackage> events = null;
        if (StringUtils.isNotEmpty(rruleString)) {
            events = getSchedulerService().findConflictingEvents(device, rrule, start, end, Long.parseLong(durationString), timeZone);
        } else {
            events = getSchedulerService().findConflictingEvents(device, start, end);
        }
        if (!events.isEmpty()) {
            List<JValue> eventsJSON = new ArrayList<>();
            for (MediaPackage event : events) {
                Opt<Event> eventOpt = getIndexService().getEvent(event.getIdentifier().compact(), getIndex());
                if (eventOpt.isSome()) {
                    final Event e = eventOpt.get();
                    if (StringUtils.isNotEmpty(eventId) && eventId.equals(e.getIdentifier()))
                        continue;
                    eventsJSON.add(obj(f("start", v(e.getTechnicalStartTime())), f("end", v(e.getTechnicalEndTime())), f("title", v(e.getTitle()))));
                } else {
                    logger.warn("Index out of sync! Conflicting event catalog {} not found on event index!", event.getIdentifier().compact());
                }
            }
            if (!eventsJSON.isEmpty())
                return conflictJson(arr(eventsJSON));
        }
        return Response.noContent().build();
    } catch (Exception e) {
        logger.error("Unable to find conflicting events for {}, {}, {}: {}", device, startDate, endDate, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) RRule(net.fortuna.ical4j.model.property.RRule) ArrayList(java.util.ArrayList) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Date(java.util.Date) DateTimeZone(org.joda.time.DateTimeZone) TimeZone(java.util.TimeZone) JSONObject(org.json.simple.JSONObject) JValue(com.entwinemedia.fn.data.json.JValue) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 4 with JValue

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

the class AbstractEventEndpoint method getEvents.

@GET
@Path("events.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getevents", description = "Returns all the events as JSON", returnDescription = "All the events as JSON", 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", 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 = "limit", description = "The maximum number of items to return per page.", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "offset", description = "The page number.", isRequired = false, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "Returns all events as JSON", responseCode = HttpServletResponse.SC_OK) })
public Response getEvents(@QueryParam("id") String id, @QueryParam("commentReason") String reasonFilter, @QueryParam("commentResolution") String resolutionFilter, @QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") Integer offset, @QueryParam("limit") Integer limit) {
    Option<Integer> optLimit = Option.option(limit);
    Option<Integer> optOffset = Option.option(offset);
    Option<String> optSort = Option.option(trimToNull(sort));
    ArrayList<JValue> eventsList = new ArrayList<>();
    EventSearchQuery query = new EventSearchQuery(getSecurityService().getOrganization().getId(), getSecurityService().getUser());
    // 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 (EventListQuery.FILTER_PRESENTERS_BIBLIOGRAPHIC_NAME.equals(name))
            query.withPresenter(filters.get(name));
        if (EventListQuery.FILTER_PRESENTERS_TECHNICAL_NAME.equals(name))
            query.withTechnicalPresenters(filters.get(name));
        if (EventListQuery.FILTER_CONTRIBUTORS_NAME.equals(name))
            query.withContributor(filters.get(name));
        if (EventListQuery.FILTER_LOCATION_NAME.equals(name))
            query.withLocation(filters.get(name));
        if (EventListQuery.FILTER_AGENT_NAME.equals(name))
            query.withAgentId(filters.get(name));
        if (EventListQuery.FILTER_TEXT_NAME.equals(name))
            query.withText(QueryPreprocessor.sanitize(filters.get(name)));
        if (EventListQuery.FILTER_SERIES_NAME.equals(name))
            query.withSeriesId(filters.get(name));
        if (EventListQuery.FILTER_STATUS_NAME.equals(name))
            query.withEventStatus(filters.get(name));
        if (EventListQuery.FILTER_OPTEDOUT_NAME.equals(name))
            query.withOptedOut(Boolean.parseBoolean(filters.get(name)));
        if (EventListQuery.FILTER_REVIEW_STATUS_NAME.equals(name))
            query.withReviewStatus(filters.get(name));
        if (EventListQuery.FILTER_COMMENTS_NAME.equals(name)) {
            switch(Comments.valueOf(filters.get(name))) {
                case NONE:
                    query.withComments(false);
                    break;
                case OPEN:
                    query.withOpenComments(true);
                    break;
                case RESOLVED:
                    query.withComments(true);
                    query.withOpenComments(false);
                    break;
                default:
                    logger.info("Unknown comment {}", filters.get(name));
                    return Response.status(SC_BAD_REQUEST).build();
            }
        }
        if (EventListQuery.FILTER_STARTDATE_NAME.equals(name)) {
            try {
                Tuple<Date, Date> fromAndToCreationRange = RestUtils.getFromAndToDateRange(filters.get(name));
                query.withTechnicalStartFrom(fromAndToCreationRange.getA());
                query.withTechnicalStartTo(fromAndToCreationRange.getB());
            } catch (IllegalArgumentException e) {
                return RestUtil.R.badRequest(e.getMessage());
            }
        }
    }
    if (optSort.isSome()) {
        Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        for (SortCriterion criterion : sortCriteria) {
            switch(criterion.getFieldName()) {
                case EventIndexSchema.TITLE:
                    query.sortByTitle(criterion.getOrder());
                    break;
                case EventIndexSchema.PRESENTER:
                    query.sortByPresenter(criterion.getOrder());
                    break;
                case EventIndexSchema.TECHNICAL_START:
                case "technical_date":
                    query.sortByTechnicalStartDate(criterion.getOrder());
                    break;
                case EventIndexSchema.TECHNICAL_END:
                    query.sortByTechnicalEndDate(criterion.getOrder());
                    break;
                case EventIndexSchema.PUBLICATION:
                    query.sortByPublicationIgnoringInternal(criterion.getOrder());
                    break;
                case EventIndexSchema.START_DATE:
                case "date":
                    query.sortByStartDate(criterion.getOrder());
                    break;
                case EventIndexSchema.END_DATE:
                    query.sortByEndDate(criterion.getOrder());
                    break;
                case EventIndexSchema.SERIES_NAME:
                    query.sortBySeriesName(criterion.getOrder());
                    break;
                case EventIndexSchema.LOCATION:
                    query.sortByLocation(criterion.getOrder());
                    break;
                case EventIndexSchema.EVENT_STATUS:
                    query.sortByEventStatus(criterion.getOrder());
                    break;
                default:
                    throw new WebApplicationException(Status.BAD_REQUEST);
            }
        }
    }
    // TODO: Add the comment resolution filter to the query
    EventCommentsListProvider.RESOLUTION resolution = null;
    if (StringUtils.isNotBlank(resolutionFilter)) {
        try {
            resolution = EventCommentsListProvider.RESOLUTION.valueOf(resolutionFilter);
        } catch (Exception e) {
            logger.warn("Unable to parse comment resolution filter {}", resolutionFilter);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
    if (optLimit.isSome())
        query.withLimit(optLimit.get());
    if (optOffset.isSome())
        query.withOffset(offset);
    // TODO: Add other filters to the query
    SearchResult<Event> results = null;
    try {
        results = getIndex().getByQuery(query);
    } catch (SearchIndexException e) {
        logger.error("The admin UI Search Index was not able to get the events list:", e);
        return RestUtil.R.serverError();
    }
    // If the results list if empty, we return already a response.
    if (results.getPageSize() == 0) {
        logger.debug("No events match the given filters.");
        return okJsonList(eventsList, nul(offset).getOr(0), nul(limit).getOr(0), 0);
    }
    for (SearchResultItem<Event> item : results.getItems()) {
        Event source = item.getSource();
        source.updatePreview(getAdminUIConfiguration().getPreviewSubtype());
        eventsList.add(eventToJSON(source));
    }
    return okJsonList(eventsList, nul(offset).getOr(0), nul(limit).getOr(0), results.getHitCount());
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) EventCommentsListProvider(org.opencastproject.index.service.resources.list.provider.EventCommentsListProvider) EventSearchQuery(org.opencastproject.index.service.impl.index.event.EventSearchQuery) ArrayList(java.util.ArrayList) Date(java.util.Date) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) JValue(com.entwinemedia.fn.data.json.JValue) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) Event(org.opencastproject.index.service.impl.index.event.Event) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 5 with JValue

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

the class AbstractEventEndpoint method getCatalogAdapters.

@GET
@Path("catalogAdapters")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getcataloguiadapters", description = "Returns the available catalog UI adapters as JSON", returnDescription = "The catalog UI adapters as JSON", reponses = { @RestResponse(description = "Returns the available catalog UI adapters as JSON", responseCode = HttpServletResponse.SC_OK) })
public Response getCatalogAdapters() {
    List<JValue> adapters = new ArrayList<>();
    for (EventCatalogUIAdapter adapter : getIndexService().getEventCatalogUIAdapters()) {
        List<Field> fields = new ArrayList<>();
        fields.add(f("flavor", v(adapter.getFlavor().toString())));
        fields.add(f("title", v(adapter.getUITitle())));
        adapters.add(obj(fields));
    }
    return okJson(arr(adapters));
}
Also used : Field(com.entwinemedia.fn.data.json.Field) JValue(com.entwinemedia.fn.data.json.JValue) ArrayList(java.util.ArrayList) EventCatalogUIAdapter(org.opencastproject.metadata.dublincore.EventCatalogUIAdapter) 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