Search in sources :

Example 1 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class AbstractEventEndpoint method getNewConflicts.

@POST
@Path("new/conflicts")
@RestQuery(name = "checkNewConflicts", description = "Checks if the current scheduler parameters are in a conflict with another event", returnDescription = "Returns NO CONTENT if no event are in conflict within specified period or list of conflicting recordings in JSON", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "No conflicting events found"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "There is a conflict"), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid parameters") })
public Response getNewConflicts(@FormParam("metadata") String metadata) throws NotFoundException {
    if (StringUtils.isBlank(metadata)) {
        logger.warn("Metadata is not specified");
        return Response.status(Status.BAD_REQUEST).build();
    }
    JSONParser parser = new JSONParser();
    JSONObject metadataJson;
    try {
        metadataJson = (JSONObject) parser.parse(metadata);
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        return RestUtil.R.badRequest("Unable to parse metadata");
    }
    String device;
    String startDate;
    String endDate;
    try {
        device = (String) metadataJson.get("device");
        startDate = (String) metadataJson.get("start");
        endDate = (String) metadataJson.get("end");
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        return RestUtil.R.badRequest("Unable to parse metadata");
    }
    if (StringUtils.isBlank(device) || StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
        logger.warn("Either device, start date or end date were not specified");
        return Response.status(Status.BAD_REQUEST).build();
    }
    Date start;
    try {
        start = new Date(DateTimeSupport.fromUTC(startDate));
    } catch (Exception e) {
        logger.warn("Unable to parse start date {}", startDate);
        return RestUtil.R.badRequest("Unable to parse start date");
    }
    Date end;
    try {
        end = new Date(DateTimeSupport.fromUTC(endDate));
    } catch (Exception e) {
        logger.warn("Unable to parse end date {}", endDate);
        return RestUtil.R.badRequest("Unable to parse end date");
    }
    String rruleString = (String) metadataJson.get("rrule");
    RRule rrule = null;
    TimeZone timeZone = TimeZone.getDefault();
    String durationString = null;
    if (StringUtils.isNotEmpty(rruleString)) {
        try {
            rrule = new RRule(rruleString);
            rrule.validate();
        } catch (Exception e) {
            logger.warn("Unable to parse rrule {}: {}", rruleString, e.getMessage());
            return Response.status(Status.BAD_REQUEST).build();
        }
        durationString = (String) metadataJson.get("duration");
        if (StringUtils.isBlank(durationString)) {
            logger.warn("If checking recurrence, must include duration.");
            return Response.status(Status.BAD_REQUEST).build();
        }
        Agent agent = getCaptureAgentStateService().getAgent(device);
        String timezone = agent.getConfiguration().getProperty("capture.device.timezone");
        if (StringUtils.isBlank(timezone)) {
            timezone = TimeZone.getDefault().getID();
            logger.warn("No 'capture.device.timezone' set on agent {}. The default server timezone {} will be used.", device, timezone);
        }
        timeZone = TimeZone.getTimeZone(timezone);
    }
    String eventId = (String) metadataJson.get("id");
    try {
        List<MediaPackage> events = null;
        if (StringUtils.isNotEmpty(rruleString)) {
            events = getSchedulerService().findConflictingEvents(device, rrule, start, end, Long.parseLong(durationString), timeZone);
        } else {
            events = getSchedulerService().findConflictingEvents(device, start, end);
        }
        if (!events.isEmpty()) {
            List<JValue> eventsJSON = new ArrayList<>();
            for (MediaPackage event : events) {
                Opt<Event> eventOpt = getIndexService().getEvent(event.getIdentifier().compact(), getIndex());
                if (eventOpt.isSome()) {
                    final Event e = eventOpt.get();
                    if (StringUtils.isNotEmpty(eventId) && eventId.equals(e.getIdentifier()))
                        continue;
                    eventsJSON.add(obj(f("start", v(e.getTechnicalStartTime())), f("end", v(e.getTechnicalEndTime())), f("title", v(e.getTitle()))));
                } else {
                    logger.warn("Index out of sync! Conflicting event catalog {} not found on event index!", event.getIdentifier().compact());
                }
            }
            if (!eventsJSON.isEmpty())
                return conflictJson(arr(eventsJSON));
        }
        return Response.noContent().build();
    } catch (Exception e) {
        logger.error("Unable to find conflicting events for {}, {}, {}: {}", device, startDate, endDate, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) RRule(net.fortuna.ical4j.model.property.RRule) ArrayList(java.util.ArrayList) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Date(java.util.Date) DateTimeZone(org.joda.time.DateTimeZone) TimeZone(java.util.TimeZone) JSONObject(org.json.simple.JSONObject) JValue(com.entwinemedia.fn.data.json.JValue) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 2 with Agent

use of org.opencastproject.capture.admin.api.Agent 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)

Example 3 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class TestEventEndpoint method getAgent.

private Agent getAgent() {
    return new Agent() {

        @Override
        public void setUrl(String agentUrl) {
        }

        @Override
        public void setState(String newState) {
        }

        @Override
        public void setLastHeardFrom(Long time) {
        }

        @Override
        public void setConfiguration(Properties configuration) {
        }

        @Override
        public String getUrl() {
            return "10.234.12.323";
        }

        @Override
        public String getState() {
            return "idle";
        }

        @Override
        public String getName() {
            return "testagent";
        }

        @Override
        public Long getLastHeardFrom() {
            return 13345L;
        }

        @Override
        public Properties getConfiguration() {
            Properties properties = new Properties();
            properties.put(CaptureParameters.CAPTURE_DEVICE_NAMES, "input1,input2");
            properties.put(CaptureParameters.AGENT_NAME, "testagent");
            properties.put("capture.device.timezone.offset", "-360");
            properties.put("capture.device.timezone", "America/Los_Angeles");
            return properties;
        }

        @Override
        public Properties getCapabilities() {
            Properties properties = new Properties();
            properties.put(CaptureParameters.CAPTURE_DEVICE_NAMES, "input1,input2");
            return properties;
        }
    };
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) EasyMock.anyString(org.easymock.EasyMock.anyString) CatalogAdapterUtil.getCatalogProperties(org.opencastproject.index.service.util.CatalogAdapterUtil.getCatalogProperties) Properties(java.util.Properties)

Example 4 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class CaptureAgentStateRestService method getKnownAgents.

@GET
@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_JSON })
@Path("agents.{type:xml|json}")
@RestQuery(name = "getKnownAgents", description = "Return all of the known capture agents on the system", pathParameters = { @RestParameter(description = "The Document type", isRequired = true, name = "type", type = Type.STRING) }, restParameters = {}, reponses = { @RestResponse(description = "An XML representation of the agent capabilities", responseCode = SC_OK) }, returnDescription = "")
public Response getKnownAgents(@PathParam("type") String type) {
    if (service == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).build();
    logger.debug("Returning list of known agents...");
    LinkedList<AgentStateUpdate> update = new LinkedList<AgentStateUpdate>();
    Map<String, Agent> data = service.getKnownAgents();
    logger.debug("Agents: {}", data);
    // Run through and build a map of updates (rather than states)
    for (Entry<String, Agent> e : data.entrySet()) {
        update.add(new AgentStateUpdate(e.getValue()));
    }
    if ("json".equals(type)) {
        return Response.ok(new AgentStateUpdateList(update)).type(MediaType.APPLICATION_JSON).build();
    } else {
        return Response.ok(new AgentStateUpdateList(update)).type(MediaType.TEXT_XML).build();
    }
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) AgentStateUpdate(org.opencastproject.capture.admin.api.AgentStateUpdate) LinkedList(java.util.LinkedList) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 5 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class CaptureAgentStateServiceImpl method deleteAgentFromDatabase.

/**
 * Removes an agent from the database.
 *
 * @param agentName
 *          The name of the agent you wish to remove.
 */
private void deleteAgentFromDatabase(String agentName) throws NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String org = securityService.getOrganization().getId();
        Agent existing = getAgentEntity(agentName, org, em);
        if (existing == null)
            throw new NotFoundException();
        em.remove(existing);
        tx.commit();
        agentCache.invalidate(agentName.concat(DELIMITER).concat(org));
    } catch (RollbackException e) {
        logger.warn("Unable to commit to DB in deleteAgent.");
    } finally {
        if (em != null)
            em.close();
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) Agent(org.opencastproject.capture.admin.api.Agent) EntityManager(javax.persistence.EntityManager) NotFoundException(org.opencastproject.util.NotFoundException) RollbackException(javax.persistence.RollbackException)

Aggregations

Agent (org.opencastproject.capture.admin.api.Agent)15 Path (javax.ws.rs.Path)5 RestQuery (org.opencastproject.util.doc.rest.RestQuery)5 Produces (javax.ws.rs.Produces)4 Test (org.junit.Test)4 NotFoundException (org.opencastproject.util.NotFoundException)4 GET (javax.ws.rs.GET)3 JValue (com.entwinemedia.fn.data.json.JValue)2 ParseException (java.text.ParseException)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 EntityManager (javax.persistence.EntityManager)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 AgentStateUpdate (org.opencastproject.capture.admin.api.AgentStateUpdate)2 MediaPackage (org.opencastproject.mediapackage.MediaPackage)2 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)2 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)2 IOException (java.io.IOException)1 LinkedList (java.util.LinkedList)1 Properties (java.util.Properties)1