Search in sources :

Example 96 with NotFoundException

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);
}
Also used : SoxException(org.opencastproject.sox.api.SoxException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) URI(java.net.URI) FileInputStream(java.io.FileInputStream) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) SoxException(org.opencastproject.sox.api.SoxException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) File(java.io.File) Track(org.opencastproject.mediapackage.Track)

Example 97 with NotFoundException

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;
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) NotFoundException(org.opencastproject.util.NotFoundException) JpaJob(org.opencastproject.job.jpa.JpaJob) JpaJob.fnToJob(org.opencastproject.job.jpa.JpaJob.fnToJob) Job(org.opencastproject.job.api.Job) JpaJob(org.opencastproject.job.jpa.JpaJob) Date(java.util.Date)

Example 98 with NotFoundException

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()))));
}
Also used : Group(org.opencastproject.index.service.impl.index.group.Group) NotFoundException(org.opencastproject.util.NotFoundException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 99 with NotFoundException

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();
}
Also used : Workflows(org.opencastproject.assetmanager.util.Workflows) Gson(com.google.gson.Gson) WorkflowDefinition(org.opencastproject.workflow.api.WorkflowDefinition) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 100 with NotFoundException

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();
}
Also used : JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) BulkOperationResult(org.opencastproject.rest.BulkOperationResult) WebApplicationException(javax.ws.rs.WebApplicationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) SeriesException(org.opencastproject.series.api.SeriesException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

NotFoundException (org.opencastproject.util.NotFoundException)382 IOException (java.io.IOException)137 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)130 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)79 MediaPackage (org.opencastproject.mediapackage.MediaPackage)69 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)67 EntityManager (javax.persistence.EntityManager)55 SeriesException (org.opencastproject.series.api.SeriesException)53 Path (javax.ws.rs.Path)52 WebApplicationException (javax.ws.rs.WebApplicationException)52 RestQuery (org.opencastproject.util.doc.rest.RestQuery)51 ConfigurationException (org.osgi.service.cm.ConfigurationException)51 URI (java.net.URI)50 SchedulerConflictException (org.opencastproject.scheduler.api.SchedulerConflictException)50 SchedulerTransactionLockException (org.opencastproject.scheduler.api.SchedulerTransactionLockException)49 Date (java.util.Date)48 Test (org.junit.Test)47 File (java.io.File)46 HttpResponse (org.apache.http.HttpResponse)46 ServiceRegistryException (org.opencastproject.serviceregistry.api.ServiceRegistryException)46