Search in sources :

Example 1 with JObject

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);
}
Also used : Field(com.entwinemedia.fn.data.json.Field) ArrayList(java.util.ArrayList) JObject(com.entwinemedia.fn.data.json.JObject)

Example 2 with JObject

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;
}
Also used : WorkflowSet(org.opencastproject.workflow.api.WorkflowSet) ArrayList(java.util.ArrayList) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) Date(java.util.Date) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) JValue(com.entwinemedia.fn.data.json.JValue) JObject(com.entwinemedia.fn.data.json.JObject)

Example 3 with JObject

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))));
}
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 4 with JObject

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();
}
Also used : WorkflowQuery(org.opencastproject.workflow.api.WorkflowQuery) WebApplicationException(javax.ws.rs.WebApplicationException) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) Sort(org.opencastproject.workflow.api.WorkflowQuery.Sort) NotFoundException(org.opencastproject.util.NotFoundException) ParseException(java.text.ParseException) 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)

Aggregations

JObject (com.entwinemedia.fn.data.json.JObject)4 ArrayList (java.util.ArrayList)3 JValue (com.entwinemedia.fn.data.json.JValue)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 RestQuery (org.opencastproject.util.doc.rest.RestQuery)2 Field (com.entwinemedia.fn.data.json.Field)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 ParseException (java.text.ParseException)1 Date (java.util.Date)1 JobEndpointException (org.opencastproject.adminui.exception.JobEndpointException)1 Event (org.opencastproject.index.service.impl.index.event.Event)1 SortCriterion (org.opencastproject.matterhorn.search.SortCriterion)1 Attachment (org.opencastproject.mediapackage.Attachment)1 MediaPackage (org.opencastproject.mediapackage.MediaPackage)1 MediaPackageElement (org.opencastproject.mediapackage.MediaPackageElement)1 UrlSigningException (org.opencastproject.security.urlsigning.exception.UrlSigningException)1