/** Creates the task element, corressponding to <define name="task"> */
  private Element createTaskElement(Document doc, Task task) {
    Element taskE = doc.createElementNS(Schemas.SCHEMA_LATEST.namespace, XMLTags.TASK.getXMLName());

    // **** attributes *****
    // **** common attributes ***

    if (task.getOnTaskErrorProperty().isSet()) {
      setAttribute(
          taskE,
          XMLAttributes.COMMON_ON_TASK_ERROR,
          task.getOnTaskErrorProperty().getValue().toString(),
          true);
    }
    if (task.getMaxNumberOfExecutionProperty().isSet()) {
      setAttribute(
          taskE,
          XMLAttributes.COMMON_MAX_NUMBER_OF_EXECUTION,
          Integer.toString(task.getMaxNumberOfExecution()));
    }
    setAttribute(taskE, XMLAttributes.COMMON_NAME, task.getName(), true);
    if (task.getRestartTaskOnErrorProperty().isSet()) {
      setAttribute(
          taskE,
          XMLAttributes.COMMON_RESTART_TASK_ON_ERROR,
          task.getRestartTaskOnError().toString());
    }

    // *** task attributes ***
    if (task.getWallTime() != 0) {
      setAttribute(taskE, XMLAttributes.TASK_WALLTIME, formatDate(task.getWallTime()));
    }

    if (task.isRunAsMe()) {
      setAttribute(taskE, XMLAttributes.TASK_RUN_AS_ME, "true");
    }

    if (task.isPreciousResult()) {
      setAttribute(taskE, XMLAttributes.TASK_PRECIOUS_RESULT, "true");
    }

    if (task.isPreciousLogs()) {
      setAttribute(taskE, XMLAttributes.TASK_PRECIOUS_LOGS, "true");
    }

    // *** elements ****

    // <ref name="variables"/>
    if (task.getVariables() != null && !task.getVariables().isEmpty()) {
      Element variablesE = createTaskVariablesElement(doc, task.getVariables());
      taskE.appendChild(variablesE);
    }

    // <ref name="taskDescription"/>
    if (task.getDescription() != null) {
      Element descrNode =
          createElement(doc, XMLTags.COMMON_DESCRIPTION.getXMLName(), task.getDescription());
      taskE.appendChild(descrNode);
    }

    // <ref name="genericInformation"/>
    if ((task.getGenericInformation() != null) && (task.getGenericInformation().size() > 0)) {
      Element genericInfoE = createGenericInformation(doc, task.getGenericInformation());
      taskE.appendChild(genericInfoE);
    }

    // <ref name="depends"/>
    List<Task> dependencies = task.getDependencesList();
    if ((dependencies != null) && (dependencies.size() > 0)) {
      Element dependsE =
          doc.createElementNS(
              Schemas.SCHEMA_LATEST.namespace, XMLTags.TASK_DEPENDENCES.getXMLName());
      for (Task dep : dependencies) {
        Element dependsTask =
            doc.createElementNS(
                Schemas.SCHEMA_LATEST.namespace, XMLTags.TASK_DEPENDENCES_TASK.getXMLName());
        setAttribute(dependsTask, XMLAttributes.TASK_DEPENDS_REF, dep.getName(), true);
        dependsE.appendChild(dependsTask);
      }
      taskE.appendChild(dependsE);
    } // if has dependencies

    // <ref name="inputFiles"/>
    List<InputSelector> inputFiles = task.getInputFilesList();
    if (inputFiles != null) {
      Element inputFilesE =
          doc.createElementNS(Schemas.SCHEMA_LATEST.namespace, XMLTags.DS_INPUT_FILES.getXMLName());
      for (InputSelector inputSelector : inputFiles) {
        FileSelector fs = inputSelector.getInputFiles();
        Element filesE =
            doc.createElementNS(Schemas.SCHEMA_LATEST.namespace, XMLTags.DS_FILES.getXMLName());
        // the xml only supports one value for the includes/excludes
        // pattern
        if (!fs.getIncludes().isEmpty())
          setAttribute(filesE, XMLAttributes.DS_INCLUDES, fs.getIncludes().iterator().next(), true);
        if (!fs.getExcludes().isEmpty())
          setAttribute(filesE, XMLAttributes.DS_EXCLUDES, fs.getExcludes().iterator().next(), true);
        if (inputSelector.getMode() != null) {
          setAttribute(
              filesE, XMLAttributes.DS_ACCESS_MODE, inputSelector.getMode().toString(), true);
        }
        inputFilesE.appendChild(filesE);
      }
      taskE.appendChild(inputFilesE);
    }

    // <ref name="parallel"/>
    Element parallelEnvE = createParallelEnvironment(doc, task);
    if (parallelEnvE != null) taskE.appendChild(parallelEnvE);

    // <ref name="selection"/>
    List<SelectionScript> selectionScripts = task.getSelectionScripts();
    if (selectionScripts != null && selectionScripts.size() > 0) {
      Element selectionE =
          doc.createElementNS(
              Schemas.SCHEMA_LATEST.namespace, XMLTags.SCRIPT_SELECTION.getXMLName());
      for (SelectionScript selectionScript : selectionScripts) {
        Element scriptE = createScriptElement(doc, selectionScript);
        selectionE.appendChild(scriptE);
      }
      taskE.appendChild(selectionE);
    }

    // <ref name="forkEnvironment"/>
    if (task.getForkEnvironment() != null) {
      Element forkEnvE = createForkEnvironmentElement(doc, task.getForkEnvironment());
      taskE.appendChild(forkEnvE);
    }

    // <ref name="pre"/>
    Script preScript = task.getPreScript();
    if (preScript != null) {
      Element preE =
          doc.createElementNS(Schemas.SCHEMA_LATEST.namespace, XMLTags.SCRIPT_PRE.getXMLName());
      Element scriptE = createScriptElement(doc, preScript);
      preE.appendChild(scriptE);
      taskE.appendChild(preE);
    }

    // <ref name="executable"/>
    Element executableE = null;
    if (task instanceof JavaTask) {
      executableE = createJavaExecutableElement(doc, (JavaTask) task);
    } else if (task instanceof NativeTask) {
      executableE = createNativeExecutableElement(doc, (NativeTask) task);
    } else if (task instanceof ScriptTask) {
      executableE = createScriptExecutableElement(doc, (ScriptTask) task);
    }
    taskE.appendChild(executableE);

    // <ref name="flow"/>
    Element controlFlowE = createFlowControlElement(doc, task);
    if (controlFlowE != null) taskE.appendChild(controlFlowE);

    // <ref name="post"/>
    Script postScript = task.getPostScript();
    if (postScript != null) {
      Element postE =
          doc.createElementNS(Schemas.SCHEMA_LATEST.namespace, XMLTags.SCRIPT_POST.getXMLName());
      Element scriptE = createScriptElement(doc, postScript);
      postE.appendChild(scriptE);
      taskE.appendChild(postE);
    }

    // <ref name="cleaning"/>
    Script cleanScript = task.getCleaningScript();
    if (cleanScript != null) {
      Element cleanE =
          doc.createElementNS(
              Schemas.SCHEMA_LATEST.namespace, XMLTags.SCRIPT_CLEANING.getXMLName());
      Element scriptE = createScriptElement(doc, cleanScript);
      cleanE.appendChild(scriptE);
      taskE.appendChild(cleanE);
    }

    // <ref name="outputFiles"/>
    List<OutputSelector> outputFiles = task.getOutputFilesList();
    if (outputFiles != null) {
      Element outputFilesE =
          doc.createElementNS(
              Schemas.SCHEMA_LATEST.namespace, XMLTags.DS_OUTPUT_FILES.getXMLName());
      for (OutputSelector outputSelector : outputFiles) {
        FileSelector fs = outputSelector.getOutputFiles();
        Element filesE =
            doc.createElementNS(Schemas.SCHEMA_LATEST.namespace, XMLTags.DS_FILES.getXMLName());
        // the xml only supports one value for the includes/excludes
        // pattern
        if (!fs.getIncludes().isEmpty())
          setAttribute(filesE, XMLAttributes.DS_INCLUDES, fs.getIncludes().iterator().next(), true);
        if (!fs.getExcludes().isEmpty())
          setAttribute(filesE, XMLAttributes.DS_EXCLUDES, fs.getExcludes().iterator().next(), true);
        if (outputSelector.getMode() != null) {
          setAttribute(
              filesE, XMLAttributes.DS_ACCESS_MODE, outputSelector.getMode().toString(), true);
        }
        outputFilesE.appendChild(filesE);
      }
      taskE.appendChild(outputFilesE);
    }
    return taskE;
  }
  /**
   * Creates and submit a job from an XML job descriptor, and check, with assertions, event related
   * to this job submission : 1/ job submitted event 2/ job passing from pending to running (with
   * state set to running). 3/ every task passing from pending to running (with state set to
   * running). 4/ every task finish without error ; passing from running to finished (with state set
   * to finished). 5/ and finally job passing from running to finished (with state set to finished).
   * Then returns.
   *
   * <p>This is the simplest events sequence of a job submission. If you need to test specific
   * events or task states (failures, rescheduling etc, you must not use this helper and check
   * events sequence with waitForEvent**() functions.
   *
   * @param jobToSubmit job object to schedule.
   * @return JobId, the job's identifier.
   * @throws Exception if an error occurs at job submission, or during verification of events
   *     sequence.
   */
  public JobId testJobSubmission(Job jobToSubmit) throws Exception {
    Scheduler userInt = getSchedulerInterface();

    JobId id = userInt.submit(jobToSubmit);

    log("Job submitted, id " + id.toString());

    log("Waiting for jobSubmitted");
    JobState receivedState = waitForEventJobSubmitted(id);
    Assert.assertEquals(id, receivedState.getId());

    log("Waiting for job running");
    JobInfo jInfo = waitForEventJobRunning(id);

    Assert.assertEquals(jInfo.getJobId(), id);
    Assert.assertEquals("Job " + jInfo.getJobId(), JobStatus.RUNNING, jInfo.getStatus());

    if (jobToSubmit instanceof TaskFlowJob) {

      for (Task t : ((TaskFlowJob) jobToSubmit).getTasks()) {
        log("Waiting for task running : " + t.getName());
        TaskInfo ti = waitForEventTaskRunning(id, t.getName());
        Assert.assertEquals(t.getName(), ti.getTaskId().getReadableName());
        Assert.assertEquals("Task " + t.getName(), TaskStatus.RUNNING, ti.getStatus());
      }

      for (Task t : ((TaskFlowJob) jobToSubmit).getTasks()) {
        log("Waiting for task finished : " + t.getName());
        TaskInfo ti = waitForEventTaskFinished(id, t.getName());
        Assert.assertEquals(t.getName(), ti.getTaskId().getReadableName());
        if (ti.getStatus() == TaskStatus.FAULTY) {
          TaskResult tres = userInt.getTaskResult(jInfo.getJobId(), t.getName());
          Assert.assertNotNull("Task result of " + t.getName(), tres);
          if (tres.getOutput() != null) {
            System.err.println("Output of failing task (" + t.getName() + ") :");
            System.err.println(tres.getOutput().getAllLogs(true));
          }
          if (tres.hadException()) {
            System.err.println("Exception occurred in task (" + t.getName() + ") :");
            tres.getException().printStackTrace(System.err);
          }
        }
        Assert.assertEquals("Task " + t.getName(), TaskStatus.FINISHED, ti.getStatus());
      }
    }

    log("Waiting for job finished");
    jInfo = waitForEventJobFinished(id);
    Assert.assertEquals("Job " + jInfo.getJobId(), JobStatus.FINISHED, jInfo.getStatus());

    log("Job finished");
    return id;
  }