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