@Test
 public void testMetadata() throws Exception {
   MediaPackage mp = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().createNew();
   Assert.assertNull(mp.getTitle());
   // now run the mediapackage through the metadata population process. This works here because the
   // mock always
   // returns metadata.
   service.populateMediaPackageMetadata(mp);
   Assert.assertEquals(TITLE, mp.getTitle());
   Assert.assertEquals(SERIES, mp.getSeriesTitle());
 }
  /**
   * {@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#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);
    }
  }