Search in sources :

Example 6 with JValue

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

the class AbstractEventEndpoint method streamsToJSON.

private List<Field> streamsToJSON(org.opencastproject.mediapackage.Stream[] streams) {
    List<Field> fields = new ArrayList<>();
    List<JValue> audioList = new ArrayList<>();
    List<JValue> videoList = new ArrayList<>();
    for (org.opencastproject.mediapackage.Stream stream : streams) {
        // TODO There is a bug with the stream ids, see MH-10325
        if (stream instanceof AudioStreamImpl) {
            List<Field> audio = new ArrayList<>();
            AudioStream audioStream = (AudioStream) stream;
            audio.add(f("id", v(audioStream.getIdentifier(), BLANK)));
            audio.add(f("type", v(audioStream.getFormat(), BLANK)));
            audio.add(f("channels", v(audioStream.getChannels(), BLANK)));
            audio.add(f("bitrate", v(audioStream.getBitRate(), BLANK)));
            audio.add(f("bitdepth", v(audioStream.getBitDepth(), BLANK)));
            audio.add(f("samplingrate", v(audioStream.getSamplingRate(), BLANK)));
            audio.add(f("framecount", v(audioStream.getFrameCount(), BLANK)));
            audio.add(f("peakleveldb", v(audioStream.getPkLevDb(), BLANK)));
            audio.add(f("rmsleveldb", v(audioStream.getRmsLevDb(), BLANK)));
            audio.add(f("rmspeakdb", v(audioStream.getRmsPkDb(), BLANK)));
            audioList.add(obj(audio));
        } else if (stream instanceof VideoStreamImpl) {
            List<Field> video = new ArrayList<>();
            VideoStream videoStream = (VideoStream) stream;
            video.add(f("id", v(videoStream.getIdentifier(), BLANK)));
            video.add(f("type", v(videoStream.getFormat(), BLANK)));
            video.add(f("bitrate", v(videoStream.getBitRate(), BLANK)));
            video.add(f("framerate", v(videoStream.getFrameRate(), BLANK)));
            video.add(f("resolution", v(videoStream.getFrameWidth() + "x" + videoStream.getFrameHeight(), BLANK)));
            video.add(f("framecount", v(videoStream.getFrameCount(), BLANK)));
            video.add(f("scantype", v(videoStream.getScanType(), BLANK)));
            video.add(f("scanorder", v(videoStream.getScanOrder(), BLANK)));
            videoList.add(obj(video));
        } else {
            throw new IllegalArgumentException("Stream must be either audio or video");
        }
    }
    fields.add(f("audio", arr(audioList)));
    fields.add(f("video", arr(videoList)));
    return fields;
}
Also used : ArrayList(java.util.ArrayList) AudioStreamImpl(org.opencastproject.mediapackage.track.AudioStreamImpl) VideoStream(org.opencastproject.mediapackage.VideoStream) VideoStreamImpl(org.opencastproject.mediapackage.track.VideoStreamImpl) AudioStream(org.opencastproject.mediapackage.AudioStream) Field(com.entwinemedia.fn.data.json.Field) JValue(com.entwinemedia.fn.data.json.JValue) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) ArrayList(java.util.ArrayList) AccessControlList(org.opencastproject.security.api.AccessControlList) List(java.util.List) RestUtils.okJsonList(org.opencastproject.index.service.util.RestUtils.okJsonList)

Example 7 with JValue

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

the class AclEndpoint method getAclsAsJson.

@GET
@Path("acls.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "allaclasjson", description = "Returns a list of acls", returnDescription = "Returns a JSON representation of the list of acls available the current user's organization", 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", isRequired = false, description = "The sort order. May include any of the following: NAME. Add '_DESC' to reverse the sort order (e.g. NAME_DESC).", type = STRING), @RestParameter(defaultValue = "100", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The list of ACL's has successfully been returned") })
public Response getAclsAsJson(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") int offset, @QueryParam("limit") int limit) throws IOException {
    if (limit < 1)
        limit = 100;
    Opt<String> optSort = Opt.nul(trimToNull(sort));
    Option<String> filterName = Option.none();
    Option<String> filterText = Option.none();
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        String value = filters.get(name);
        if (AclsListQuery.FILTER_NAME_NAME.equals(name)) {
            filterName = Option.some(value);
        } else if ((AclsListQuery.FILTER_TEXT_NAME.equals(name)) && (StringUtils.isNotBlank(value))) {
            filterText = Option.some(value);
        }
    }
    // Filter acls by filter criteria
    List<ManagedAcl> filteredAcls = new ArrayList<>();
    for (ManagedAcl acl : aclService().getAcls()) {
        // Filter list
        if ((filterName.isSome() && !filterName.get().equals(acl.getName())) || (filterText.isSome() && !TextFilter.match(filterText.get(), acl.getName()))) {
            continue;
        }
        filteredAcls.add(acl);
    }
    int total = filteredAcls.size();
    // Sort by name, description or role
    if (optSort.isSome()) {
        final Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        Collections.sort(filteredAcls, new Comparator<ManagedAcl>() {

            @Override
            public int compare(ManagedAcl acl1, ManagedAcl acl2) {
                for (SortCriterion criterion : sortCriteria) {
                    Order order = criterion.getOrder();
                    switch(criterion.getFieldName()) {
                        case "name":
                            if (order.equals(Order.Descending))
                                return ObjectUtils.compare(acl2.getName(), acl1.getName());
                            return ObjectUtils.compare(acl1.getName(), acl2.getName());
                        default:
                            logger.info("Unkown sort type: {}", criterion.getFieldName());
                            return 0;
                    }
                }
                return 0;
            }
        });
    }
    // Apply Limit and offset
    List<JValue> aclJSON = Stream.$(filteredAcls).drop(offset).apply(limit > 0 ? StreamOp.<ManagedAcl>id().take(limit) : StreamOp.<ManagedAcl>id()).map(fullManagedAcl).toList();
    return okJsonList(aclJSON, offset, limit, total);
}
Also used : Order(org.opencastproject.matterhorn.search.SearchQuery.Order) ManagedAcl(org.opencastproject.authorization.xacml.manager.api.ManagedAcl) ArrayList(java.util.ArrayList) 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 8 with JValue

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

the class MetadataField method createIterableStringMetadataField.

/**
 * Create a metadata field of type iterable String
 *
 * @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 field can be or not edited
 * @param required
 *          Define if the new metadata field is or not required
 * @param isTranslatable
 *          If the field value is not human readable and should be translated before
 * @param collection
 *          If the field has a limited list of possible value, the option should contain this one. Otherwise it should
 *          be none.
 * @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<Iterable<String>> createIterableStringMetadataField(String inputID, Opt<String> outputID, String label, boolean readOnly, boolean required, Opt<Boolean> isTranslatable, Opt<Map<String, String>> collection, Opt<String> collectionId, Opt<Integer> order, Opt<String> namespace) {
    Fn<Opt<Iterable<String>>, JValue> iterableToJSON = new Fn<Opt<Iterable<String>>, JValue>() {

        @Override
        public JValue apply(Opt<Iterable<String>> value) {
            if (value.isNone())
                return arr();
            Object val = value.get();
            List<JValue> list = new ArrayList<>();
            if (val instanceof String) {
                // The value is a string so we need to split it.
                String stringVal = (String) val;
                for (String entry : stringVal.split(",")) {
                    list.add(v(entry, Jsons.BLANK));
                }
            } else {
                // The current value is just an iterable string.
                for (Object v : value.get()) {
                    list.add(v(v, Jsons.BLANK));
                }
            }
            return arr(list);
        }
    };
    Fn<Object, Iterable<String>> jsonToIterable = new Fn<Object, Iterable<String>>() {

        @Override
        public Iterable<String> apply(Object arrayIn) {
            JSONArray array = (JSONArray) arrayIn;
            if (array == null)
                return null;
            String[] arrayOut = new String[array.size()];
            for (int i = 0; i < array.size(); i++) {
                arrayOut[i] = (String) array.get(i);
            }
            return Arrays.asList(arrayOut);
        }
    };
    return new MetadataField<>(inputID, outputID, label, readOnly, required, new ArrayList<String>(), isTranslatable, Type.ITERABLE_TEXT, JsonType.TEXT, collection, collectionId, iterableToJSON, jsonToIterable, order, namespace);
}
Also used : Fn(com.entwinemedia.fn.Fn) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) Opt(com.entwinemedia.fn.data.Opt) JValue(com.entwinemedia.fn.data.json.JValue) JObject(com.entwinemedia.fn.data.json.JObject)

Example 9 with JValue

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

the class MetadataField method createMixedIterableStringMetadataField.

/**
 * Create a metadata field of type mixed iterable String
 *
 * @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 field can be or not edited
 * @param required
 *          Define if the new metadata field is or not required
 * @param isTranslatable
 *          If the field value is not human readable and should be translated before
 * @param collection
 *          If the field has a limited list of possible value, the option should contain this one. Otherwise it should
 *          be none.
 * @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<Iterable<String>> createMixedIterableStringMetadataField(String inputID, Opt<String> outputID, String label, boolean readOnly, boolean required, Opt<Boolean> isTranslatable, Opt<Map<String, String>> collection, Opt<String> collectionId, Opt<Integer> order, Opt<String> namespace) {
    Fn<Opt<Iterable<String>>, JValue> iterableToJSON = new Fn<Opt<Iterable<String>>, JValue>() {

        @Override
        public JValue apply(Opt<Iterable<String>> value) {
            if (value.isNone())
                return arr();
            Object val = value.get();
            List<JValue> list = new ArrayList<>();
            if (val instanceof String) {
                // The value is a string so we need to split it.
                String stringVal = (String) val;
                for (String entry : stringVal.split(",")) {
                    if (StringUtils.isNotBlank(entry))
                        list.add(v(entry, Jsons.BLANK));
                }
            } else {
                // The current value is just an iterable string.
                for (Object v : value.get()) {
                    list.add(v(v, Jsons.BLANK));
                }
            }
            return arr(list);
        }
    };
    Fn<Object, Iterable<String>> jsonToIterable = new Fn<Object, Iterable<String>>() {

        @Override
        public Iterable<String> apply(Object arrayIn) {
            JSONParser parser = new JSONParser();
            JSONArray array;
            if (arrayIn instanceof String) {
                try {
                    array = (JSONArray) parser.parse((String) arrayIn);
                } catch (ParseException e) {
                    throw new IllegalArgumentException("Unable to parse Mixed Iterable value into a JSONArray:", e);
                }
            } else {
                array = (JSONArray) arrayIn;
            }
            if (array == null)
                return new ArrayList<>();
            String[] arrayOut = new String[array.size()];
            for (int i = 0; i < array.size(); i++) {
                arrayOut[i] = (String) array.get(i);
            }
            return Arrays.asList(arrayOut);
        }
    };
    return new MetadataField<>(inputID, outputID, label, readOnly, required, new ArrayList<String>(), isTranslatable, Type.MIXED_TEXT, JsonType.MIXED_TEXT, collection, collectionId, iterableToJSON, jsonToIterable, order, namespace);
}
Also used : Fn(com.entwinemedia.fn.Fn) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) Opt(com.entwinemedia.fn.data.Opt) JValue(com.entwinemedia.fn.data.json.JValue) JObject(com.entwinemedia.fn.data.json.JObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 10 with JValue

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

the class CaptureAgentsEndpoint method getAgents.

@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("agents.json")
@RestQuery(name = "getAgents", description = "Return all of the known capture agents on the system", 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(defaultValue = "100", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "false", description = "Define if the inputs should or not returned with the capture agent.", isRequired = false, name = "inputs", type = RestParameter.Type.BOOLEAN), @RestParameter(name = "sort", isRequired = false, description = "The sort order. May include any of the following: STATUS, NAME OR LAST_UPDATED.  Add '_DESC' to reverse the sort order (e.g. STATUS_DESC).", type = STRING) }, reponses = { @RestResponse(description = "An XML representation of the agent capabilities", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "")
public Response getAgents(@QueryParam("limit") int limit, @QueryParam("offset") int offset, @QueryParam("inputs") boolean inputs, @QueryParam("filter") String filter, @QueryParam("sort") String sort) {
    Option<String> filterName = Option.none();
    Option<String> filterStatus = Option.none();
    Option<Long> filterLastUpdated = Option.none();
    Option<String> filterText = Option.none();
    Option<String> optSort = Option.option(trimToNull(sort));
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        if (AgentsListQuery.FILTER_NAME_NAME.equals(name))
            filterName = Option.some(filters.get(name));
        if (AgentsListQuery.FILTER_STATUS_NAME.equals(name))
            filterStatus = Option.some(filters.get(name));
        if (AgentsListQuery.FILTER_LAST_UPDATED.equals(name)) {
            try {
                filterLastUpdated = Option.some(Long.parseLong(filters.get(name)));
            } catch (NumberFormatException e) {
                logger.info("Unable to parse long {}", filters.get(name));
                return Response.status(Status.BAD_REQUEST).build();
            }
        }
        if (AgentsListQuery.FILTER_TEXT_NAME.equals(name) && StringUtils.isNotBlank(filters.get(name)))
            filterText = Option.some(filters.get(name));
    }
    // Filter agents by filter criteria
    List<Agent> filteredAgents = new ArrayList<>();
    for (Entry<String, Agent> entry : service.getKnownAgents().entrySet()) {
        Agent agent = entry.getValue();
        // Filter list
        if ((filterName.isSome() && !filterName.get().equals(agent.getName())) || (filterStatus.isSome() && !filterStatus.get().equals(agent.getState())) || (filterLastUpdated.isSome() && filterLastUpdated.get() != agent.getLastHeardFrom()) || (filterText.isSome() && !TextFilter.match(filterText.get(), agent.getName(), agent.getState())))
            continue;
        filteredAgents.add(agent);
    }
    int total = filteredAgents.size();
    // Sort by status, name or last updated date
    if (optSort.isSome()) {
        final Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        Collections.sort(filteredAgents, new Comparator<Agent>() {

            @Override
            public int compare(Agent agent1, Agent agent2) {
                for (SortCriterion criterion : sortCriteria) {
                    Order order = criterion.getOrder();
                    switch(criterion.getFieldName()) {
                        case "status":
                            if (order.equals(Order.Descending))
                                return agent2.getState().compareTo(agent1.getState());
                            return agent1.getState().compareTo(agent2.getState());
                        case "name":
                            if (order.equals(Order.Descending))
                                return agent2.getName().compareTo(agent1.getName());
                            return agent1.getName().compareTo(agent2.getName());
                        case "updated":
                            if (order.equals(Order.Descending))
                                return agent2.getLastHeardFrom().compareTo(agent1.getLastHeardFrom());
                            return agent1.getLastHeardFrom().compareTo(agent2.getLastHeardFrom());
                        default:
                            logger.info("Unknown sort type: {}", criterion.getFieldName());
                            return 0;
                    }
                }
                return 0;
            }
        });
    }
    // Apply Limit and offset
    filteredAgents = new SmartIterator<Agent>(limit, offset).applyLimitAndOffset(filteredAgents);
    // Run through and build a map of updates (rather than states)
    List<JValue> agentsJSON = new ArrayList<>();
    for (Agent agent : filteredAgents) {
        agentsJSON.add(generateJsonAgent(agent, /* Option.option(room), blacklist, */
        inputs, false));
    }
    return okJsonList(agentsJSON, offset, limit, total);
}
Also used : Order(org.opencastproject.matterhorn.search.SearchQuery.Order) Agent(org.opencastproject.capture.admin.api.Agent) SmartIterator(org.opencastproject.util.SmartIterator) ArrayList(java.util.ArrayList) 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)

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