Search in sources :

Example 36 with JValue

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

the class BaseEndpoint method getOrganizationInfo.

@GET
@Path("info/organization")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "getorganizationinfo", description = "Returns the current organization.", returnDescription = "", reponses = { @RestResponse(description = "The organization details are returned.", responseCode = HttpServletResponse.SC_OK) })
public Response getOrganizationInfo() {
    final Organization org = securityService.getOrganization();
    JValue json = obj(f("adminRole", v(org.getAdminRole())), f("anonymousRole", v(org.getAnonymousRole())), f("id", v(org.getId())), f("name", v(org.getName())));
    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) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 37 with JValue

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

the class EventsEndpoint method eventToJSON.

/**
 * Transform an {@link Event} to Json
 *
 * @param event
 *          The event to transform into json
 * @param withAcl
 *          Whether to add the acl information for the event
 * @param withMetadata
 *          Whether to add all the metadata for the event
 * @param withPublications
 *          Whether to add the publications
 * @param withSignedUrls
 *          Whether to sign the urls if they are protected by stream security.
 * @return The event in json format.
 * @throws IndexServiceException
 *           Thrown if unable to get the metadata for the event.
 * @throws SearchIndexException
 *           Thrown if unable to get event publications from search service
 * @throws NotFoundException
 *           Thrown if unable to find all of the metadata
 */
protected JValue eventToJSON(Event event, Boolean withAcl, Boolean withMetadata, Boolean withPublications, Boolean withSignedUrls) throws IndexServiceException, SearchIndexException, NotFoundException {
    List<Field> fields = new ArrayList<>();
    if (event.getArchiveVersion() != null)
        fields.add(f("archive_version", v(event.getArchiveVersion())));
    fields.add(f("created", v(event.getCreated(), Jsons.BLANK)));
    fields.add(f("creator", v(event.getCreator(), Jsons.BLANK)));
    fields.add(f("contributor", arr($(event.getContributors()).map(Functions.stringToJValue))));
    fields.add(f("description", v(event.getDescription(), Jsons.BLANK)));
    fields.add(f("has_previews", v(event.hasPreview())));
    fields.add(f("identifier", v(event.getIdentifier(), BLANK)));
    fields.add(f("location", v(event.getLocation(), BLANK)));
    fields.add(f("presenter", arr($(event.getPresenters()).map(Functions.stringToJValue))));
    List<JValue> publicationIds = new ArrayList<>();
    if (event.getPublications() != null) {
        for (Publication publication : event.getPublications()) {
            publicationIds.add(v(publication.getChannel()));
        }
    }
    fields.add(f("publication_status", arr(publicationIds)));
    fields.add(f("processing_state", v(event.getWorkflowState(), BLANK)));
    fields.add(f("start", v(event.getTechnicalStartTime(), BLANK)));
    if (event.getTechnicalEndTime() != null) {
        long duration = new DateTime(event.getTechnicalEndTime()).getMillis() - new DateTime(event.getTechnicalStartTime()).getMillis();
        fields.add(f("duration", v(duration)));
    }
    if (StringUtils.trimToNull(event.getSubject()) != null) {
        fields.add(f("subjects", arr(splitSubjectIntoArray(event.getSubject()))));
    } else {
        fields.add(f("subjects", arr()));
    }
    fields.add(f("title", v(event.getTitle(), BLANK)));
    if (withAcl != null && withAcl) {
        AccessControlList acl = getAclFromEvent(event);
        fields.add(f("acl", arr(AclUtils.serializeAclToJson(acl))));
    }
    if (withMetadata != null && withMetadata) {
        try {
            Opt<MetadataList> metadata = getEventMetadata(event);
            if (metadata.isSome()) {
                fields.add(f("metadata", metadata.get().toJSON()));
            }
        } catch (Exception e) {
            logger.error("Unable to get metadata for event '{}' because: {}", event.getIdentifier(), ExceptionUtils.getStackTrace(e));
            throw new IndexServiceException("Unable to add metadata to event", e);
        }
    }
    if (withPublications != null && withPublications) {
        List<JValue> publications = getPublications(event, withSignedUrls);
        fields.add(f("publications", arr(publications)));
    }
    return obj(fields);
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) ArrayList(java.util.ArrayList) Publication(org.opencastproject.mediapackage.Publication) DateTime(org.joda.time.DateTime) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) IngestException(org.opencastproject.ingest.api.IngestException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) ConfigurationException(org.osgi.service.cm.ConfigurationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) ParseException(org.json.simple.parser.ParseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) Field(com.entwinemedia.fn.data.json.Field) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) JValue(com.entwinemedia.fn.data.json.JValue) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Example 38 with JValue

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

the class SeriesEndpoint method getSeriesList.

@GET
@Path("")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "getseries", description = "Returns a list of series.", returnDescription = "", restParameters = { @RestParameter(name = "filter", isRequired = false, description = "A comma seperated list of filters to limit the results with. A filter is the filter's name followed by a colon \":\" and then the value to filter with so it is the form <Filter Name>:<Value to Filter With>.", type = STRING), @RestParameter(name = "sort", description = "Sort the results based upon a list of comma seperated sorting criteria. In the comma seperated list each type of sorting is specified as a pair such as: <Sort Name>:ASC or <Sort Name>:DESC. Adding the suffix ASC or DESC sets the order as ascending or descending order and is mandatory.", isRequired = false, type = STRING), @RestParameter(name = "limit", description = "The maximum number of results to return for a single request.", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "offset", description = "Number of results to skip based on the limit. 0 is the first set of results up to the limit, 1 is the second set of results after the first limit, 2 is third set of results after skipping the first two sets of results etc.", isRequired = false, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "A (potentially empty) list of series is returned.", responseCode = HttpServletResponse.SC_OK) })
public Response getSeriesList(@HeaderParam("Accept") String acceptHeader, @QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("order") String order, @QueryParam("offset") int offset, @QueryParam("limit") int limit) throws UnauthorizedException {
    try {
        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 < 1 ? DEFAULT_LIMIT : limit);
        // Parse the filters
        if (StringUtils.isNotBlank(filter)) {
            for (String f : filter.split(",")) {
                String[] filterTuple = f.split(":");
                if (filterTuple.length != 2) {
                    logger.info("No value for filter {} in filters list: {}", filterTuple[0], filter);
                    continue;
                }
                String name = filterTuple[0];
                String value = filterTuple[1];
                if ("managedAcl".equals(name)) {
                    query.withAccessPolicy(value);
                } else if ("contributors".equals(name)) {
                    query.withContributor(value);
                } else if ("CreationDate".equals(name)) {
                    if (name.split("/").length == 2) {
                        try {
                            Tuple<Date, Date> fromAndToCreationRange = getFromAndToCreationRange(name.split("/")[0], name.split("/")[1]);
                            query.withCreatedFrom(fromAndToCreationRange.getA());
                            query.withCreatedTo(fromAndToCreationRange.getB());
                        } catch (IllegalArgumentException e) {
                            return RestUtil.R.badRequest(e.getMessage());
                        }
                    }
                    query.withCreator(value);
                } else if ("Creator".equals(name)) {
                    query.withCreator(value);
                } else if ("textFilter".equals(name)) {
                    query.withText("*" + value + "*");
                } else if ("language".equals(name)) {
                    query.withLanguage(value);
                } else if ("license".equals(name)) {
                    query.withLicense(value);
                } else if ("organizers".equals(name)) {
                    query.withOrganizer(value);
                } else if ("subject".equals(name)) {
                    query.withSubject(value);
                } else if ("title".equals(name)) {
                    query.withTitle(value);
                }
            }
        }
        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 EventIndexSchema.CREATED:
                        query.sortByCreatedDateTime(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 = externalIndex.getByQuery(query);
        return ApiResponses.Json.ok(VERSION_1_0_0, arr($(result.getItems()).map(new Fn<SearchResultItem<Series>, JValue>() {

            @Override
            public JValue apply(SearchResultItem<Series> a) {
                final Series s = a.getSource();
                JValue subjects;
                if (s.getSubject() == null) {
                    subjects = arr();
                } else {
                    subjects = arr(splitSubjectIntoArray(s.getSubject()));
                }
                Date createdDate = s.getCreatedDateTime();
                return obj(f("identifier", v(s.getIdentifier())), f("title", v(s.getTitle())), f("creator", v(s.getCreator(), BLANK)), f("created", v(createdDate != null ? toUTC(createdDate.getTime()) : null, BLANK)), f("subjects", subjects), f("contributors", arr($(s.getContributors()).map(Functions.stringToJValue))), f("organizers", arr($(s.getOrganizers()).map(Functions.stringToJValue))), f("publishers", arr($(s.getPublishers()).map(Functions.stringToJValue))));
            }
        }).toList()));
    } catch (Exception e) {
        logger.warn("Could not perform search query: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SeriesSearchQuery(org.opencastproject.index.service.impl.index.series.SeriesSearchQuery) Fn(com.entwinemedia.fn.Fn) SearchResultItem(org.opencastproject.matterhorn.search.SearchResultItem) Date(java.util.Date) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) SeriesException(org.opencastproject.series.api.SeriesException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) WebApplicationException(javax.ws.rs.WebApplicationException) ParseException(org.json.simple.parser.ParseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Series(org.opencastproject.index.service.impl.index.series.Series) 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 39 with JValue

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

the class EventCommentReply method toJValue.

public JValue toJValue() {
    JValue authorObj = obj(f("name", v(author.getName(), BLANK)), f("username", v(author.getUsername())), f("email", v(author.getEmail(), BLANK)));
    JValue idValue = com.entwinemedia.fn.data.json.Jsons.ZERO;
    if (id.isSome())
        idValue = v(id.get());
    List<Field> fields = new ArrayList<>();
    fields.add(f("id", idValue));
    fields.add(f("text", v(text)));
    fields.add(f("author", authorObj));
    fields.add(f("creationDate", v(DateTimeSupport.toUTC(creationDate.getTime()))));
    fields.add(f("modificationDate", v(DateTimeSupport.toUTC(modificationDate.getTime()))));
    return obj(fields);
}
Also used : Field(com.entwinemedia.fn.data.json.Field) JValue(com.entwinemedia.fn.data.json.JValue) ArrayList(java.util.ArrayList)

Example 40 with JValue

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

the class MetadataField method createDateMetadata.

/**
 * Create a metadata field based on a {@link Date}.
 *
 * @param inputID
 *          The identifier of the new metadata field
 * @param label
 *          The label of the new metadata field
 * @param readOnly
 *          Define if the new metadata is or not a readonly field
 * @param required
 *          Define if the new metadata field is or not required
 * @param pattern
 *          The date pattern for {@link SimpleDateFormat}.
 * @param order
 *          The ui order for the new field, 0 at the top and progressively down from there.
 * @return The new metadata field
 */
public static MetadataField<Date> createDateMetadata(String inputID, Opt<String> outputID, String label, boolean readOnly, boolean required, final String pattern, Opt<Integer> order, Opt<String> namespace) {
    final SimpleDateFormat dateFormat = getSimpleDateFormatter(pattern);
    Fn<Opt<Date>, JValue> dateToJSON = new Fn<Opt<Date>, JValue>() {

        @Override
        public JValue apply(Opt<Date> date) {
            if (date.isNone())
                return Jsons.BLANK;
            else {
                return v(dateFormat.format(date.get()), Jsons.BLANK);
            }
        }
    };
    Fn<Object, Date> jsonToDate = new Fn<Object, Date>() {

        @Override
        public Date apply(Object value) {
            try {
                String date = (String) value;
                if (StringUtils.isBlank(date))
                    return null;
                return dateFormat.parse(date);
            } catch (java.text.ParseException e) {
                logger.error("Not able to parse date {}: {}", value, e.getMessage());
                return null;
            }
        }
    };
    MetadataField<Date> dateField = new MetadataField<>(inputID, outputID, label, readOnly, required, null, Opt.none(), Type.DATE, JsonType.DATE, Opt.<Map<String, String>>none(), Opt.<String>none(), dateToJSON, jsonToDate, order, namespace);
    if (StringUtils.isNotBlank(pattern)) {
        dateField.setPattern(Opt.some(pattern));
    }
    return dateField;
}
Also used : Fn(com.entwinemedia.fn.Fn) Date(java.util.Date) Opt(com.entwinemedia.fn.data.Opt) JValue(com.entwinemedia.fn.data.json.JValue) JObject(com.entwinemedia.fn.data.json.JObject) SimpleDateFormat(java.text.SimpleDateFormat)

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