use of com.entwinemedia.fn.data.json.JObject in project opencast by opencast.
the class MessageTemplate method toJValue.
public JValue toJValue() {
JObject creatorObj = obj(f("name", v(creator.getName(), BLANK)), f("username", v(creator.getUsername())), f("email", v(creator.getEmail(), BLANK)));
List<Field> fields = new ArrayList<>();
fields.add(f("id", v(id)));
fields.add(f("name", v(name)));
fields.add(f("subject", v(getSubject())));
fields.add(f("body", v(body)));
fields.add(f("creator", creatorObj));
fields.add(f("hidden", v(hidden)));
fields.add(f("type", v(type.getType().toString())));
fields.add(f("creationDate", v(DateTimeSupport.toUTC(creationDate.getTime()))));
return obj(fields);
}
use of com.entwinemedia.fn.data.json.JObject in project opencast by opencast.
the class JobEndpoint method getTasksAsJSON.
/**
* Returns the list of tasks matching the given query as JSON Object
*
* @param query
* The worklfow query
* @return The list of matching tasks as JSON Object
* @throws JobEndpointException
* @throws NotFoundException
*/
public JObject getTasksAsJSON(WorkflowQuery query) throws JobEndpointException, NotFoundException {
// Get results
WorkflowSet workflowInstances = null;
long totalWithoutFilters = 0;
List<JValue> jsonList = new ArrayList<>();
try {
workflowInstances = workflowService.getWorkflowInstances(query);
totalWithoutFilters = workflowService.countWorkflowInstances();
} catch (WorkflowDatabaseException e) {
throw new JobEndpointException(String.format("Not able to get the list of job from the database: %s", e), e.getCause());
}
WorkflowInstance[] items = workflowInstances.getItems();
for (WorkflowInstance instance : items) {
long instanceId = instance.getId();
String series = instance.getMediaPackage().getSeriesTitle();
// Retrieve submission date with the workflow instance main job
Date created;
try {
created = serviceRegistry.getJob(instanceId).getDateCreated();
} catch (ServiceRegistryException e) {
throw new JobEndpointException(String.format("Error when retrieving job %s from the service registry: %s", instanceId, e), e.getCause());
}
jsonList.add(obj(f("id", v(instanceId)), f("title", v(nul(instance.getMediaPackage().getTitle()).getOr(""))), f("series", v(series, Jsons.BLANK)), f("workflow", v(instance.getTitle(), Jsons.BLANK)), f("status", v(instance.getState().toString())), f("submitted", v(created != null ? DateTimeSupport.toUTC(created.getTime()) : ""))));
}
JObject json = obj(f("results", arr(jsonList)), f("count", v(workflowInstances.getTotalCount())), f("offset", v(query.getStartPage())), f("limit", v(jsonList.size())), f("total", v(totalWithoutFilters)));
return json;
}
use of com.entwinemedia.fn.data.json.JObject 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))));
}
use of com.entwinemedia.fn.data.json.JObject in project opencast by opencast.
the class JobEndpoint method getTasks.
@GET
@Path("tasks.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(description = "Returns the list of tasks", name = "tasks", 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 = "status", isRequired = false, description = "Filter results by workflows' current state", type = STRING), @RestParameter(name = "q", isRequired = false, description = "Filter results by free text query", type = STRING), @RestParameter(name = "seriesId", isRequired = false, description = "Filter results by series identifier", type = STRING), @RestParameter(name = "seriesTitle", isRequired = false, description = "Filter results by series title", type = STRING), @RestParameter(name = "creator", isRequired = false, description = "Filter results by the mediapackage's creator", type = STRING), @RestParameter(name = "contributor", isRequired = false, description = "Filter results by the mediapackage's contributor", type = STRING), @RestParameter(name = "fromdate", isRequired = false, description = "Filter results by workflow start date.", type = STRING), @RestParameter(name = "todate", isRequired = false, description = "Filter results by workflow start date.", type = STRING), @RestParameter(name = "language", isRequired = false, description = "Filter results by mediapackage's language.", type = STRING), @RestParameter(name = "title", isRequired = false, description = "Filter results by mediapackage's title.", type = STRING), @RestParameter(name = "subject", isRequired = false, description = "Filter results by mediapackage's subject.", type = STRING), @RestParameter(name = "workflow", isRequired = false, description = "Filter results by workflow definition.", type = STRING), @RestParameter(name = "operation", isRequired = false, description = "Filter results by workflows' current operation.", type = STRING), @RestParameter(name = "sort", isRequired = false, description = "The sort order. May include any " + "of the following: DATE_CREATED, TITLE, SERIES_TITLE, SERIES_ID, MEDIA_PACKAGE_ID, WORKFLOW_DEFINITION_ID, CREATOR, " + "CONTRIBUTOR, LANGUAGE, LICENSE, SUBJECT. The suffix must be :ASC for ascending or :DESC for descending sort order (e.g. TITLE:DESC).", type = STRING) }, reponses = { @RestResponse(description = "Returns the list of tasks from Opencast", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The list of tasks as JSON")
public Response getTasks(@QueryParam("limit") final int limit, @QueryParam("offset") final int offset, @QueryParam("status") List<String> states, @QueryParam("q") String text, @QueryParam("seriesId") String seriesId, @QueryParam("seriesTitle") String seriesTitle, @QueryParam("creator") String creator, @QueryParam("contributor") String contributor, @QueryParam("fromdate") String fromDate, @QueryParam("todate") String toDate, @QueryParam("language") String language, @QueryParam("title") String title, @QueryParam("subject") String subject, @QueryParam("workflowdefinition") String workflowDefinitionId, @QueryParam("mp") String mediapackageId, @QueryParam("operation") List<String> currentOperations, @QueryParam("sort") String sort, @Context HttpHeaders headers) throws JobEndpointException {
WorkflowQuery query = new WorkflowQuery();
query.withStartPage(offset);
query.withCount(limit);
// Add filters
query.withText(text);
query.withSeriesId(seriesId);
query.withSeriesTitle(seriesTitle);
query.withSubject(subject);
query.withMediaPackage(mediapackageId);
query.withCreator(creator);
query.withContributor(contributor);
try {
query.withDateAfter(SolrUtils.parseDate(fromDate));
} catch (ParseException e) {
logger.error("Not able to parse the date {}: {}", fromDate, e.getMessage());
}
try {
query.withDateBefore(SolrUtils.parseDate(toDate));
} catch (ParseException e) {
logger.error("Not able to parse the date {}: {}", fromDate, e.getMessage());
}
query.withLanguage(language);
query.withTitle(title);
query.withWorkflowDefintion(workflowDefinitionId);
if (states != null && states.size() > 0) {
try {
for (String state : states) {
if (StringUtils.isBlank(state)) {
continue;
} else if (state.startsWith(NEGATE_PREFIX)) {
query.withoutState(WorkflowState.valueOf(state.substring(1).toUpperCase()));
} else {
query.withState(WorkflowState.valueOf(state.toUpperCase()));
}
}
} catch (IllegalArgumentException e) {
logger.debug("Unknown workflow state.", e);
}
}
if (currentOperations != null && currentOperations.size() > 0) {
for (String op : currentOperations) {
if (StringUtils.isBlank(op)) {
continue;
}
if (op.startsWith(NEGATE_PREFIX)) {
query.withoutCurrentOperation(op.substring(1));
} else {
query.withCurrentOperation(op);
}
}
}
// Sorting
if (StringUtils.isNotBlank(sort)) {
try {
SortCriterion sortCriterion = RestUtils.parseSortQueryParameter(sort).iterator().next();
Sort sortKey = Sort.valueOf(sortCriterion.getFieldName().toUpperCase());
boolean ascending = SearchQuery.Order.Ascending == sortCriterion.getOrder() || SearchQuery.Order.None == sortCriterion.getOrder();
query.withSort(sortKey, ascending);
} 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);
}
}
JObject json;
try {
json = getTasksAsJSON(query);
} catch (NotFoundException e) {
return NOT_FOUND;
}
return Response.ok(stream(serializer.fn.toJson(json)), MediaType.APPLICATION_JSON_TYPE).build();
}
Aggregations