/**
   * Get the solution and stores it in MongoDB after an <code>async</code> request.
   *
   * @param jobid the job id.
   */
  private void completedAsync(String jobid) {
    LOG.log(Level.INFO, "Complete async job {0}", jobid);
    try {
      // create the request
      TruckingJobOutput updater = new TruckingJobOutput(this.mongoDB);
      JobRequest request =
          jobclient.newRequest().output(updater).timeout(60, TimeUnit.SECONDS).build();
      updater.setRequest(request);

      executor.monitor(request, jobid, null).get();

    } catch (Exception e) {
      LOG.log(Level.WARNING, "Error while completing job", e);
      e.printStackTrace();
    } finally {
      // always cleanup the job by deleting it
      if (jobid != null) {
        try {
          jobclient.deleteJob(jobid);
        } catch (Exception e) {
          // ignore any exception
        }
      }
      requestJobDone();
    }
  }
 @Override
 public void deleteAllJobs() {
   try {
     jobclient.deleteAllJobs();
   } catch (OperationException e) {
     LOG.log(Level.WARNING, e.getLocalizedMessage(), e);
   }
 }
  @Override
  public void solveAsync() throws Exception {
    if (requestJob() == null) {
      LOG.log(Level.INFO, "Optim is already requested, ignoring...");
      return;
    }

    String jobid = null;
    try {
      // create the request
      JobRequest request =
          jobclient
              .newRequest()
              .input("model.mod", modFile)
              .input(new TruckingJobInput(this.mongoDB))
              .build();

      // submit and get the job id
      Future<JobResponse> submit = executor.submit(request, null);
      jobid = request.getJobId();
      requestJobCreated(jobid);
      LOG.log(Level.INFO, "Job submitted " + jobid);
      StatusEventEndpoint.broadcastStatus(
          new RequestStatus(true, jobid, JobExecutionStatus.CREATED));

      // wait for completion of submission
      submit.get(60, TimeUnit.SECONDS);

    } catch (Exception e) {
      LOG.log(Level.WARNING, "Error submitting executing job", e);

      // always cleanup the job by deleting it
      if (jobid != null) {
        try {
          jobclient.deleteJob(jobid);
        } catch (Exception e1) {
          // ignore any exception
        }
      }
      requestJobDone();
      broadcastLatestSolution();
      throw e;
    }
  }
  @Override
  public void solve() {
    if (requestJob() == null) {
      LOG.log(Level.INFO, "Job is already requested, ignoring...");
      return;
    }

    String jobid = null;
    JobExecutionStatus status = null;
    try {
      // create the request
      TruckingJobOutput updater = new TruckingJobOutput(this.mongoDB);
      JobRequest request =
          jobclient
              .newRequest()
              .input("model.mod", modFile)
              .input(new TruckingJobInput(this.mongoDB))
              .livelog(System.out)
              .output(updater)
              .timeout(5, TimeUnit.MINUTES)
              .build();
      updater.setRequest(request);

      // submit and get the job id
      Future<JobResponse> submit = executor.execute(request);
      jobid = request.getJobId();
      requestJobCreated(jobid);
      requestJobProcessed(jobid);

      StatusEventEndpoint.broadcastStatus(
          new RequestStatus(true, jobid, JobExecutionStatus.CREATED));
      LOG.info("Job submitted " + jobid);

      // wait for completion
      JobResponse response = submit.get();

      status = response.getJob().getExecutionStatus();

      switch (status) {
        case PROCESSED:
          break;
        case FAILED:
          // get failure message if defined
          String message = "";
          if (response.getJob().getFailureInfo() != null) {
            message = response.getJob().getFailureInfo().getMessage();
          }
          LOG.warning("Failed " + message);
          break;
        default:
          break;
      }

    } catch (Exception e) {
      LOG.log(Level.WARNING, "Error while executing job", e);
    } finally {
      // always cleanup the job by deleting it
      if (jobid != null) {
        try {
          jobclient.deleteJob(jobid);
        } catch (Exception e) {
          // ignore any exception
        }
      }
      requestJobDone();
      broadcastLatestSolution();
    }
  }
        public void run() {
          DBObject obj = isJobRequested();
          if (obj == null) {
            // if there is not current active request just make sure all
            // clients
            // have the latest solution
            broadcastLatestSolution();

          } else {
            // if there is request, check its staus

            Object jobid = obj.get("jobid");
            if (jobid == null) {
              // if the jobid was not assigned after 10 seconds, there
              // must be an issue
              // so cancel the request.
              Object ts = obj.get("ts");
              Date now = new Date();
              if (jobid == null && ts != null && (now.getTime() - ((Date) ts).getTime()) > 10000) {
                LOG.log(Level.WARNING, "Cancelling job because the jobid was not set");
                requestJobDone();
                broadcastLatestSolution();
              }

            } else {
              // check execution status
              String id = (String) jobid;
              try {
                JobExecutionStatus status = jobclient.getJobExecutionStatus(id);
                switch (status) {
                  case CREATED:
                  case NOT_STARTED:
                  case RUNNING:
                  case INTERRUPTING:
                    StatusEventEndpoint.broadcastStatus(new RequestStatus(true, id, status));
                    break;

                  case FAILED:
                    JobFailureInfo failure = jobclient.getFailureInfo(id);
                    LOG.warning("Failed " + failure.getMessage());
                    StatusEventEndpoint.broadcastStatus(
                        new RequestStatus(false, id, status, failure.getMessage()));
                    try {
                      jobclient.deleteJob(id);
                    } catch (Exception e) {
                      // ignore any exception
                    }
                    requestJobDone();
                    broadcastLatestSolution();
                    break;
                  case INTERRUPTED:

                  case PROCESSED:
                    if (requestJobProcessed(id) != null) {
                      completedAsync(id);
                    }
                    broadcastLatestSolution();
                    break;
                }

              } catch (JobNotFoundException e) {
                // job was not found, already processed
                requestJobDone();
                broadcastLatestSolution();

              } catch (OperationException e) {
                // ignore will retry at next monitor execution
              }
            }
          }
        }