/**
   * {@inheritDoc}
   *
   * @see
   *     org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
   *     JobContext)
   */
  public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context)
      throws WorkflowOperationException {
    logger.debug("Running apply-acl workflow operation");

    MediaPackage mediaPackage = workflowInstance.getMediaPackage();
    String seriesId = mediaPackage.getSeries();
    if (seriesId == null) {
      return createResult(mediaPackage, Action.CONTINUE);
    }
    try {
      AccessControlList acl = seriesService.getSeriesAccessControl(seriesId);
      if (acl != null) {
        authorizationService.setAccessControl(mediaPackage, acl);
      }
      return createResult(mediaPackage, Action.CONTINUE);
    } catch (SeriesException e) {
      throw new WorkflowOperationException(e);
    } catch (MediaPackageException e) {
      throw new WorkflowOperationException(e);
    } catch (NotFoundException e) {
      throw new WorkflowOperationException(e);
    }
  }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.opencastproject.workflow.api.WorkflowOperationHandler#skip(org.opencastproject.workflow.api.WorkflowInstance,
  *     JobContext)
  */
 @Override
 public WorkflowOperationResult skip(WorkflowInstance workflowInstance, JobContext context)
     throws WorkflowOperationException {
   return new WorkflowOperationResultImpl(
       workflowInstance.getMediaPackage(), null, Action.SKIP, 0);
 }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
   *     JobContext)
   */
  @Override
  public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context)
      throws WorkflowOperationException {

    MediaPackage mediaPackage = workflowInstance.getMediaPackage();
    WorkflowOperationInstance operation = workflowInstance.getCurrentOperation();

    logger.debug("Running execute workflow operation with ID {}", operation.getId());

    // Get operation parameters
    String exec = StringUtils.trimToNull(operation.getConfiguration(EXEC_PROPERTY));
    String params = StringUtils.trimToNull(operation.getConfiguration(PARAMS_PROPERTY));
    String sourceFlavor =
        StringUtils.trimToNull(operation.getConfiguration(SOURCE_FLAVOR_PROPERTY));
    String sourceTags = StringUtils.trimToNull(operation.getConfiguration(SOURCE_TAGS_PROPERTY));
    String targetFlavorStr =
        StringUtils.trimToNull(operation.getConfiguration(TARGET_FLAVOR_PROPERTY));
    String targetTags = StringUtils.trimToNull(operation.getConfiguration(TARGET_TAGS_PROPERTY));
    String outputFilename =
        StringUtils.trimToNull(operation.getConfiguration(OUTPUT_FILENAME_PROPERTY));
    String expectedTypeStr =
        StringUtils.trimToNull(operation.getConfiguration(EXPECTED_TYPE_PROPERTY));

    MediaPackageElementFlavor matchingFlavor = null;
    if (sourceFlavor != null) matchingFlavor = MediaPackageElementFlavor.parseFlavor(sourceFlavor);

    // Unmarshall target flavor
    MediaPackageElementFlavor targetFlavor = null;
    if (targetFlavorStr != null)
      targetFlavor = MediaPackageElementFlavor.parseFlavor(targetFlavorStr);

    // Unmarshall expected mediapackage element type
    MediaPackageElement.Type expectedType = null;
    if (expectedTypeStr != null) {
      for (MediaPackageElement.Type type : MediaPackageElement.Type.values())
        if (type.toString().equalsIgnoreCase(expectedTypeStr)) {
          expectedType = type;
          break;
        }

      if (expectedType == null)
        throw new WorkflowOperationException(
            "'" + expectedTypeStr + "' is not a valid element type");
    }

    List<String> sourceTagList = asList(sourceTags);

    // Select the tracks based on source flavors and tags
    Set<MediaPackageElement> inputSet = new HashSet<MediaPackageElement>();
    for (MediaPackageElement element : mediaPackage.getElementsByTags(sourceTagList)) {
      MediaPackageElementFlavor elementFlavor = element.getFlavor();
      if (sourceFlavor == null
          || (elementFlavor != null && elementFlavor.matches(matchingFlavor))) {
        inputSet.add(element);
      }
    }

    if (inputSet.size() == 0) {
      logger.warn(
          "Mediapackage {} has no suitable elements to execute the command {} based on tags {} and flavor {}",
          new Object[] {mediaPackage, exec, sourceTags, sourceFlavor});
      return createResult(mediaPackage, Action.CONTINUE);
    }

    MediaPackageElement[] inputElements =
        inputSet.toArray(new MediaPackageElement[inputSet.size()]);

    try {
      Job[] jobs = new Job[inputElements.length];
      MediaPackageElement[] resultElements = new MediaPackageElement[inputElements.length];
      long totalTimeInQueue = 0;

      for (int i = 0; i < inputElements.length; i++)
        jobs[i] =
            executeService.execute(exec, params, inputElements[i], outputFilename, expectedType);

      // Wait for all jobs to be finished
      if (!waitForStatus(jobs).isSuccess())
        throw new WorkflowOperationException("Execute operation failed");

      // Find which output elements are tracks and inspect them
      HashMap<Integer, Job> jobMap = new HashMap<Integer, Job>();
      for (int i = 0; i < jobs.length; i++) {
        // Add this job's queue time to the total
        totalTimeInQueue += jobs[i].getQueueTime();
        if (StringUtils.trimToNull(jobs[i].getPayload()) != null) {
          resultElements[i] = MediaPackageElementParser.getFromXml(jobs[i].getPayload());
          if (resultElements[i].getElementType() == MediaPackageElement.Type.Track) {
            jobMap.put(i, inspectionService.inspect(resultElements[i].getURI()));
          }
        } else resultElements[i] = inputElements[i];
      }

      if (jobMap.size() > 0) {
        if (!waitForStatus(jobMap.values().toArray(new Job[jobMap.size()])).isSuccess())
          throw new WorkflowOperationException("Execute operation failed in track inspection");

        for (Entry<Integer, Job> entry : jobMap.entrySet()) {
          // Add this job's queue time to the total
          totalTimeInQueue += entry.getValue().getQueueTime();
          resultElements[entry.getKey()] =
              MediaPackageElementParser.getFromXml(entry.getValue().getPayload());
        }
      }

      for (int i = 0; i < resultElements.length; i++) {
        if (resultElements[i] != inputElements[i]) {
          // Store new element to mediaPackage
          mediaPackage.addDerived(resultElements[i], inputElements[i]);
          // Store new element to mediaPackage
          URI uri =
              workspace.moveTo(
                  resultElements[i].getURI(),
                  mediaPackage.getIdentifier().toString(),
                  resultElements[i].getIdentifier(),
                  outputFilename);

          resultElements[i].setURI(uri);

          // Set new flavor
          if (targetFlavor != null) resultElements[i].setFlavor(targetFlavor);
        }

        // Set new tags
        if (targetTags != null)
          // Assume the tags starting with "-" means we want to eliminate such tags form the result
          // element
          for (String tag : asList(targetTags)) {
            if (tag.startsWith("-"))
              // We remove the tag resulting from stripping all the '-' characters at the beginning
              // of the tag
              resultElements[i].removeTag(tag.replaceAll("^-+", ""));
            else resultElements[i].addTag(tag);
          }
      }

      WorkflowOperationResult result =
          createResult(mediaPackage, Action.CONTINUE, totalTimeInQueue);
      logger.debug("Execute operation {} completed", operation.getId());

      return result;

    } catch (ExecuteException e) {
      throw new WorkflowOperationException(e);
    } catch (MediaPackageException e) {
      throw new WorkflowOperationException("Some result element couldn't be serialized", e);
    } catch (NotFoundException e) {
      throw new WorkflowOperationException("Could not find mediapackage", e);
    } catch (IOException e) {
      throw new WorkflowOperationException("Error unmarshalling a result mediapackage element", e);
    } catch (MediaInspectionException e) {
      throw new WorkflowOperationException("Error inspecting one of the created tracks", e);
    }
  }
  /**
   * Resumes a workflow instance associated with this capture, if one exists.
   *
   * @param recordingId the recording id, which is assumed to correspond to the scheduled event id
   * @param state the new state for this recording
   */
  protected void updateWorkflow(String recordingId, String state) {
    if (!RecordingState.CAPTURING.equals(state)
        && !RecordingState.UPLOADING.equals(state)
        && !state.endsWith("_error")) {
      logger.debug("Recording state updated to {}.  Not updating an associated workflow.", state);
      return;
    }

    WorkflowInstance workflowToUpdate = null;
    try {
      workflowToUpdate = workflowService.getWorkflowById(Long.parseLong(recordingId));
    } catch (NumberFormatException e) {
      logger.info("Recording id '{}' is not a long, assuming an unscheduled capture", recordingId);
      return;
    } catch (WorkflowDatabaseException e) {
      logger.warn("Unable to update workflow for recording {}: {}", recordingId, e);
      return;
    } catch (NotFoundException e) {
      logger.warn("Unable to find a workflow with id='{}'", recordingId);
      return;
    } catch (UnauthorizedException e) {
      logger.warn("Can not update workflow: {}", e.getMessage());
    }

    // Does the workflow exist?
    if (workflowToUpdate == null) {
      logger.warn("The workflow '{}' cannot be updated because it does not exist", recordingId);
      return;
    }

    WorkflowState wfState = workflowToUpdate.getState();
    switch (workflowToUpdate.getState()) {
      case FAILED:
      case FAILING:
      case STOPPED:
      case SUCCEEDED:
        logger.debug(
            "The workflow '{}' should not be updated because it is {}",
            recordingId,
            wfState.toString().toLowerCase());
        return;
      default:
        break;
    }

    try {
      if (state.endsWith("_error")) {
        workflowToUpdate
            .getCurrentOperation()
            .setState(WorkflowOperationInstance.OperationState.FAILED);
        workflowToUpdate.setState(WorkflowState.FAILED);
        workflowService.update(workflowToUpdate);
        logger.info(
            "Recording status changed to '{}', failing workflow '{}'",
            state,
            workflowToUpdate.getId());
      } else {
        workflowService.resume(workflowToUpdate.getId());
        logger.info(
            "Recording status changed to '{}', resuming workflow '{}'",
            state,
            workflowToUpdate.getId());
      }
    } catch (Exception e) {
      logger.warn("Unable to update workflow {}: {}", workflowToUpdate.getId(), e);
    }
  }