use of org.opencastproject.util.NotFoundException in project opencast by opencast.
the class SoxServiceImpl method normalize.
private Option<Track> normalize(Job job, TrackImpl audioTrack, Float targetRmsLevDb) throws SoxException {
if (!audioTrack.hasAudio())
throw new SoxException("No audio stream available");
if (audioTrack.hasVideo())
throw new SoxException("It must not have a video stream");
if (audioTrack.getAudio().size() < 1)
throw new SoxException("No audio stream metadata available");
if (audioTrack.getAudio().get(0).getRmsLevDb() == null)
throw new SoxException("No RMS Lev dB metadata available");
final String targetTrackId = idBuilder.createNew().toString();
Float rmsLevDb = audioTrack.getAudio().get(0).getRmsLevDb();
// Get the tracks and make sure they exist
final File audioFile;
try {
audioFile = workspace.get(audioTrack.getURI());
} catch (NotFoundException e) {
throw new SoxException("Requested audio track " + audioTrack + " is not found");
} catch (IOException e) {
throw new SoxException("Unable to access audio track " + audioTrack);
}
String outDir = audioFile.getAbsoluteFile().getParent();
String outFileName = FilenameUtils.getBaseName(audioFile.getName()) + "_" + UUID.randomUUID().toString();
String suffix = "-norm." + FilenameUtils.getExtension(audioFile.getName());
File normalizedFile = new File(outDir, outFileName + suffix);
logger.info("Normalizing audio track {} to {}", audioTrack.getIdentifier(), targetTrackId);
// Do the work
ArrayList<String> command = new ArrayList<String>();
command.add(binary);
command.add(audioFile.getAbsolutePath());
command.add(normalizedFile.getAbsolutePath());
command.add("remix");
command.add("-");
command.add("gain");
if (targetRmsLevDb > rmsLevDb)
command.add("-l");
command.add(new Float(targetRmsLevDb - rmsLevDb).toString());
command.add("stats");
List<String> normalizeResult = launchSoxProcess(command);
if (normalizedFile.length() == 0)
throw new SoxException("Normalization failed: Output file is empty!");
// Put the file in the workspace
URI returnURL = null;
InputStream in = null;
try {
in = new FileInputStream(normalizedFile);
returnURL = workspace.putInCollection(COLLECTION, job.getId() + "." + FilenameUtils.getExtension(normalizedFile.getAbsolutePath()), in);
logger.info("Copied the normalized file to the workspace at {}", returnURL);
if (normalizedFile.delete()) {
logger.info("Deleted the local copy of the normalized file at {}", normalizedFile.getAbsolutePath());
} else {
logger.warn("Unable to delete the normalized output at {}", normalizedFile);
}
} catch (Exception e) {
throw new SoxException("Unable to put the normalized file into the workspace", e);
} finally {
IOUtils.closeQuietly(in);
FileSupport.deleteQuietly(normalizedFile);
}
Track normalizedTrack = (Track) audioTrack.clone();
normalizedTrack.setURI(returnURL);
normalizedTrack.setIdentifier(targetTrackId);
// Add audio metadata and return audio track
normalizedTrack = addAudioMetadata(normalizedTrack, normalizeResult);
return some(normalizedTrack);
}
use of org.opencastproject.util.NotFoundException in project opencast by opencast.
the class ServiceRegistryJpaImpl method removeParentlessJobs.
@Override
public void removeParentlessJobs(int lifetime) throws ServiceRegistryException {
EntityManager em = null;
EntityTransaction tx = null;
Date d = DateUtils.addDays(new Date(), -lifetime);
int count = 0;
try {
em = emf.createEntityManager();
tx = em.getTransaction();
TypedQuery<JpaJob> query = em.createNamedQuery("Job.withoutParent", JpaJob.class);
List<JpaJob> jobs = query.getResultList();
tx.begin();
for (JpaJob jpaJob : jobs) {
Job job = jpaJob.toJob();
if (job.getDateCreated().after(d))
continue;
// DO NOT DELETE workflow instances and operations!
if (START_OPERATION.equals(job.getOperation()) || START_WORKFLOW.equals(job.getOperation()) || RESUME.equals(job.getOperation()))
continue;
if (job.getStatus().isTerminated()) {
try {
removeJobs(Collections.singletonList(job.getId()));
logger.debug("Parentless job '{}' removed", job.getId());
count++;
} catch (NotFoundException e) {
logger.debug("Parentless job '{} ' not found in database: {}", job.getId(), e);
}
}
}
tx.commit();
if (count > 0)
logger.info("Successfully removed {} parentless jobs", count);
else
logger.info("No parentless jobs found to remove", count);
} finally {
if (em != null)
em.close();
}
return;
}
use of org.opencastproject.util.NotFoundException in project opencast by opencast.
the class GroupsEndpoint method getGroup.
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@RestQuery(name = "getGroup", description = "Get a single group", returnDescription = "Return the status codes", pathParameters = { @RestParameter(name = "id", description = "The group identifier", isRequired = true, type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "Group found and returned as JSON"), @RestResponse(responseCode = SC_NOT_FOUND, description = "Group not found") })
public Response getGroup(@PathParam("id") String groupId) throws NotFoundException, SearchIndexException {
Opt<Group> groupOpt = indexService.getGroup(groupId, searchIndex);
if (groupOpt.isNone())
throw new NotFoundException("Group " + groupId + " does not exist.");
Group group = groupOpt.get();
return RestUtils.okJson(obj(f("id", v(group.getIdentifier())), f("name", v(group.getName(), Jsons.BLANK)), f("description", v(group.getDescription(), Jsons.BLANK)), f("role", v(group.getRole(), Jsons.BLANK)), f("roles", rolesToJSON(group.getRoles())), f("users", membersToJSON(group.getMembers()))));
}
use of org.opencastproject.util.NotFoundException in project opencast by opencast.
the class TasksEndpoint method createNewTask.
@POST
@Path("/new")
@RestQuery(name = "createNewTask", description = "Creates a new task by the given metadata as JSON", returnDescription = "The task identifiers", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Task sucessfully added"), @RestResponse(responseCode = SC_NOT_FOUND, description = "If the workflow definition is not found"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed") })
public Response createNewTask(@FormParam("metadata") String metadata) throws NotFoundException {
if (StringUtils.isBlank(metadata)) {
logger.warn("No metadata set");
return RestUtil.R.badRequest("No metadata set");
}
Gson gson = new Gson();
Map metadataJson = null;
try {
metadataJson = gson.fromJson(metadata, Map.class);
} catch (Exception e) {
logger.warn("Unable to parse metadata {}", metadata);
return RestUtil.R.badRequest("Unable to parse metadata");
}
String workflowId = (String) metadataJson.get("workflow");
if (StringUtils.isBlank(workflowId))
return RestUtil.R.badRequest("No workflow set");
List eventIds = (List) metadataJson.get("eventIds");
if (eventIds == null)
return RestUtil.R.badRequest("No eventIds set");
Map<String, String> configuration = (Map<String, String>) metadataJson.get("configuration");
if (configuration == null) {
configuration = new HashMap<>();
} else {
Iterator<String> confKeyIter = configuration.keySet().iterator();
while (confKeyIter.hasNext()) {
String confKey = confKeyIter.next();
if (StringUtils.equalsIgnoreCase("eventIds", confKey)) {
confKeyIter.remove();
}
}
}
WorkflowDefinition wfd;
try {
wfd = workflowService.getWorkflowDefinitionById(workflowId);
} catch (WorkflowDatabaseException e) {
logger.error("Unable to get workflow definition {}: {}", workflowId, ExceptionUtils.getStackTrace(e));
return RestUtil.R.serverError();
}
final Workflows workflows = new Workflows(assetManager, workspace, workflowService);
final List<WorkflowInstance> instances = workflows.applyWorkflowToLatestVersion(eventIds, workflow(wfd, configuration)).toList();
if (eventIds.size() != instances.size()) {
logger.debug("Can't start one or more tasks.");
return Response.status(Status.BAD_REQUEST).build();
}
return Response.status(Status.CREATED).entity(gson.toJson($(instances).map(getWorkflowIds).toList())).build();
}
use of org.opencastproject.util.NotFoundException in project opencast by opencast.
the class SeriesEndpoint method changeOptOuts.
@POST
@Path("optouts")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "changeOptOuts", description = "Change the opt out status of many series", returnDescription = "A JSON array listing which series were or were not opted out.", restParameters = { @RestParameter(name = "seriesIds", description = "A JSON array of ids of the series to opt out or in", defaultValue = "[]", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "optout", description = "Whether to opt out or not either true or false.", defaultValue = "false", isRequired = true, type = RestParameter.Type.BOOLEAN) }, reponses = { @RestResponse(description = "Returns a JSON object with the results for the different opted out or in elements such as ok, notFound or error.", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "Unable to parse boolean value to opt out, or parse JSON array of opt out series", responseCode = HttpServletResponse.SC_BAD_REQUEST) })
public Response changeOptOuts(@FormParam("optout") boolean optout, @FormParam("seriesIds") String seriesIds) {
JSONParser parser = new JSONParser();
JSONArray seriesIdsArray;
try {
seriesIdsArray = (JSONArray) parser.parse(seriesIds);
} catch (org.json.simple.parser.ParseException e) {
logger.warn("Unable to parse series ids {} : {}", seriesIds, ExceptionUtils.getStackTrace(e));
return Response.status(Status.BAD_REQUEST).build();
} catch (NullPointerException e) {
logger.warn("Unable to parse series ids because it was null {}", seriesIds);
return Response.status(Status.BAD_REQUEST).build();
} catch (ClassCastException e) {
logger.warn("Unable to parse series ids because it was the wrong class {} : {}", seriesIds, ExceptionUtils.getStackTrace(e));
return Response.status(Status.BAD_REQUEST).build();
}
BulkOperationResult result = new BulkOperationResult();
for (Object seriesId : seriesIdsArray) {
try {
seriesService.updateOptOutStatus(seriesId.toString(), optout);
result.addOk(seriesId.toString());
} catch (NotFoundException e) {
result.addNotFound(seriesId.toString());
} catch (Exception e) {
logger.error("Could not update opt out status of series {}: {}", seriesId.toString(), ExceptionUtils.getStackTrace(e));
result.addServerError(seriesId.toString());
}
}
return Response.ok(result.toJson()).build();
}
Aggregations