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));
}
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);
}
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);
}
}
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);
}
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;
}
Aggregations