/**
  * Retrieve a task list for the user. Tasks are retrieved from the storage for the user performing
  * the request.
  *
  * @return A list of tasks
  */
 private List<Task> retrieveTaskList() {
   List<Task> lstTasks = new LinkedList<>();
   EntityManager em = getEntityManager();
   EntityTransaction et = null;
   List<Object[]> taskList = null;
   try {
     et = em.getTransaction();
     et.begin();
     taskList =
         em.createNamedQuery("tasks.userAll").setParameter("user", getUser()).getResultList();
     et.commit();
   } catch (RuntimeException re) {
     if (et != null && et.isActive()) {
       et.rollback();
     }
     log.error("Impossible to retrieve the task list");
     log.error(re);
     throw new RuntimeException("Impossible to access the task list");
   } finally {
     em.close();
   }
   if (taskList != null && !taskList.isEmpty()) {
     for (Object[] elem : taskList) {
       int idElem = 0;
       Task tmpTask = new Task();
       tmpTask.setId((String) elem[idElem++]);
       tmpTask.setDescription((String) elem[idElem++]);
       tmpTask.setState((Task.STATE) elem[idElem++]);
       tmpTask.setDateCreated((Date) elem[idElem]);
       lstTasks.add(tmpTask);
     }
   }
   return lstTasks;
 }
  /** Test of action method, of class Pending. */
  @Test
  public final void callAction() {
    final Task task = TestData.createTask(TestData.TASKTYPE.SSH);
    task.setState(Task.STATE.CANCELLED);

    try {
      final TaskState taskState = task.getStateManager();
      taskState.action(this.executorService, this.blockingQueue, this.storage);
    } catch (TaskException ex) {
      Assert.fail("Call action failed for: " + ex.getMessage());
    }
    Assert.assertEquals("Called action on cancelled state.", Task.STATE.CANCELLED, task.getState());
  }
 /**
  * Register a new task.
  *
  * @param task The task to register
  * @return The task registered
  */
 @POST
 @Status(Response.Status.CREATED)
 @Consumes({MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE})
 @Produces(Constants.INDIGOMIMETYPE)
 public final Task createTask(final Task task) {
   if (task.getApplicationId() == null) {
     throw new BadRequestException("A valid application for the task" + " must be provided");
   }
   task.setDateCreated(new Date());
   task.setUserName(getUser());
   task.setState(Task.STATE.PENDING);
   EntityManager em = getEntityManager();
   EntityTransaction et = null;
   try {
     et = em.getTransaction();
     et.begin();
     Application app = em.find(Application.class, task.getApplicationId());
     if (app == null) {
       throw new BadRequestException("Application id not valid");
     }
     task.setApplicationDetail(app);
     em.persist(task);
     et.commit();
     log.debug("New task registered: " + task.getId());
   } catch (BadRequestException bre) {
     throw bre;
   } catch (RuntimeException re) {
     log.error("Impossible to create a task");
     log.debug(re);
     throw re;
   } finally {
     if (et != null && et.isActive()) {
       et.rollback();
     }
     em.close();
   }
   log.debug("Created cache storate for the task");
   getStorage().createCache(Storage.RESOURCE.TASKS, task.getId());
   log.debug("Adding the observer");
   task.addObserver(
       new TaskObserver(
           getEntityManagerFactory(), getSubmissionThreadPool(), getStorage(), getMonitorQueue()));
   log.debug("Task in waiting for the next step");
   task.setState(Task.STATE.WAITING);
   return task;
 }
  /** Test task delete. */
  @Test
  public final void testTaskDelete() {
    Response rs;
    rs = target("/v1.0/tasks/" + UUID.randomUUID()).request().delete();
    Assert.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rs.getStatus());

    Task testTask = TestDataIT.createTask();
    testTask.setApplicationId(apps.get((int) (Math.random() * apps.size())));
    rs =
        target("/v1.0/tasks")
            .request(Constants.INDIGOMIMETYPE)
            .post(Entity.entity(testTask, Constants.INDIGOMIMETYPE));
    String id = rs.readEntity(Task.class).getId();
    rs = target("/v1.0/tasks/" + id).request().delete();
    Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), rs.getStatus());
    rs = target("/v1.0/tasks/" + id).request().delete();
    Assert.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rs.getStatus());
  }
  /** Tests the details retrieval. */
  @Test
  public final void testTaskDetails() {
    Task newTask = TestDataIT.createTask();
    newTask.setApplicationId(apps.get((int) (Math.random() * apps.size())));
    Response rs;
    rs =
        target("/v1.0/tasks")
            .request(Constants.INDIGOMIMETYPE)
            .post(Entity.entity(newTask, Constants.INDIGOMIMETYPE));
    rs =
        target("/v1.0/tasks/" + rs.readEntity(Application.class).getId())
            .request(Constants.INDIGOMIMETYPE)
            .get();

    Assert.assertEquals(Response.Status.OK.getStatusCode(), rs.getStatus());
    Task task = rs.readEntity(Task.class);
    Assert.assertNotNull(task);
    Assert.assertNotNull(task.getId());
    Assert.assertNotNull(task.getDateCreated());
    Assert.assertNotNull(task.getLastChange());
    Assert.assertEquals(newTask.getDescription(), task.getDescription());
    Assert.assertEquals(newTask.getApplicationId(), task.getApplicationId());
    Transformer<TaskFile, String> transformer =
        new Transformer<TaskFile, String>() {
          @Override
          public String transform(final TaskFile file) {
            return file.getName();
          }
        };
    if (newTask.getInputFiles() != null) {
      Assert.assertNotNull(task.getInputFiles());
      Assert.assertEquals(
          IterableUtils.toString(newTask.getInputFiles(), transformer),
          IterableUtils.toString(task.getInputFiles(), transformer));
    }
    if (newTask.getOutputFiles() != null) {
      Assert.assertNotNull(task.getOutputFiles());
      Assert.assertEquals(
          IterableUtils.toString(newTask.getOutputFiles(), transformer),
          IterableUtils.toString(task.getOutputFiles(), transformer));
    }
    target("/v1.0/tasks/" + task.getId()).request().delete();
  }