Esempio n. 1
0
  @Test
  public void testExecute() throws Exception {
    JobStatus jobStatus = jobExecutor.getJobStatus();
    assertFalse(jobStatus.isRunning());

    assertTrue(jobExecutor.execute(context));

    verify(job).execute();
    assertEquals(jobStatus.getJobStatusType(), JobStatusType.FINISHED);
  }
Esempio n. 2
0
  @Test
  public void testExecuteFailure() throws Exception {
    MigratorException failure = new MigratorException("Failure");
    willThrow(failure).given(job).execute();

    JobStatus jobStatus = jobExecutor.getJobStatus();
    assertFalse(jobStatus.isRunning());

    assertTrue(jobExecutor.execute(context));

    verify(job).execute();
    assertEquals(failure, jobStatus.getFailure());
    assertEquals(jobStatus.getJobStatusType(), JobStatusType.FINISHED);
  }
  @Override
  public AttachmentDAO getAttachmentInfo(final String id) throws AttachmentMgtException {
    try {
      AttachmentDAO resultantDAO =
          jobExecutor.execTransaction(
              new Callable<AttachmentDAO>() {
                @Override
                public AttachmentDAO call() throws Exception {
                  AttachmentDAO attachmentDAO = null;
                  attachmentDAO = entityManager.find(AttachmentDAOImpl.class, Long.parseLong(id));
                  return attachmentDAO;
                }
              });

      if (resultantDAO != null) {
        return resultantDAO;
      } else {
        throw new AttachmentMgtException("Attachment not found for id : " + id);
      }
    } catch (Exception e) {
      String errorMsg =
          "org.wso2.carbon.attachment.mgt.core.dao.impl.hibernate.AttachmentMgtDAOFactoryImpl.getAttachmentInfo operation failed. "
              + "Reason: "
              + e.getLocalizedMessage();
      log.error(errorMsg, e);
      throw new AttachmentMgtException(errorMsg, e);
    }
  }
  @Override
  public AttachmentDAO addAttachment(final Attachment attachment) throws AttachmentMgtException {
    try {
      AttachmentDAO resultantDAO =
          jobExecutor.execTransaction(
              new Callable<AttachmentDAO>() {
                @Override
                public AttachmentDAO call() throws Exception {
                  AttachmentDAO attachmentDAO = new AttachmentDAOImpl();
                  attachmentDAO.setName(attachment.getName());
                  attachmentDAO.setCreatedBy(attachment.getCreatedBy());
                  attachmentDAO.setContentType(attachment.getContentType());
                  attachmentDAO.setUrl(URLGeneratorUtil.generateURL());
                  attachmentDAO.setContent(attachment.getContent());

                  entityManager.persist(attachmentDAO);
                  if (entityManager.contains(attachmentDAO)) {
                    return attachmentDAO;
                  } else {
                    String errorMsg = "Attachment couldn't persist in the Data Store";
                    throw new AttachmentMgtException(errorMsg);
                  }
                }
              });
      return resultantDAO;
    } catch (Exception e) {
      String errorMsg =
          "org.wso2.carbon.attachment.mgt.core.dao.impl.hibernate.AttachmentMgtDAOFactoryImpl.addAttachment operation failed. "
              + "Reason: "
              + e.getLocalizedMessage();
      log.error(errorMsg, e);
      throw new AttachmentMgtException(errorMsg, e);
    }
  }
 @Override
 public boolean removeAttachment(final String id) throws AttachmentMgtException {
   try {
     boolean isRemoved = false;
     isRemoved =
         jobExecutor.execTransaction(
             new Callable<Boolean>() {
               @Override
               public Boolean call() throws Exception {
                 Query query =
                     entityManager.createQuery(
                         "DELETE FROM org.wso2.carbon.attachment.mgt.core.dao.impl"
                             + ".jpa.openjpa.entity.AttachmentDAOImpl x WHERE x.id = "
                             + ":attachmentID");
                 query.setParameter("attachmentID", Long.parseLong(id));
                 int noOfRowsUpdated = query.executeUpdate();
                 // entityManager.remove(getAttachmentInfo(id));
                 if (noOfRowsUpdated == 1) {
                   return true;
                 } else {
                   return false;
                 }
               }
             });
     return isRemoved;
   } catch (Exception e) {
     String errorMsg =
         "org.wso2.carbon.attachment.mgt.core.dao.impl.hibernate.AttachmentMgtDAOFactoryImpl.removeAttachment operation failed. "
             + "Reason: "
             + e.getLocalizedMessage();
     log.error(errorMsg, e);
     throw new AttachmentMgtException(errorMsg, e);
   }
 }
 protected void putAcquiredJobDbidsOnQueue(Collection<Long> acquiredJobDbids) {
   log.debug("pushing jobs on the queue " + acquiredJobDbids);
   while (acquiredJobDbids != null) {
     try {
       jobExecutor.getJobDbidsQueue().put(acquiredJobDbids);
       log.trace("jobs " + acquiredJobDbids + " were put on the queue");
       acquiredJobDbids = null;
     } catch (InterruptedException e) {
       log.trace("putting acquired job dbids got interrupted. retrying...");
     }
   }
 }
 protected long getWaitPeriod() {
   long interval = jobExecutor.getIdleMillis();
   Date nextDueDate = getNextDueDate();
   if (nextDueDate != null) {
     long currentTimeMillis = System.currentTimeMillis();
     long nextDueDateTime = nextDueDate.getTime();
     if (nextDueDateTime < currentTimeMillis + currentIdleInterval) {
       interval = nextDueDateTime - currentTimeMillis;
     }
   }
   if (interval < 0) {
     interval = 0;
   }
   return interval;
 }
  @Override
  public AttachmentDAO getAttachmentInfoFromURL(final String attachmentURI)
      throws AttachmentMgtException {
    try {
      AttachmentDAO resultantDAO =
          jobExecutor.execTransaction(
              new Callable<AttachmentDAO>() {
                @Override
                public AttachmentDAO call() throws Exception {
                  Query query =
                      entityManager.createQuery(
                          "SELECT x FROM org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.openjpa.entity.AttachmentDAOImpl AS x WHERE x.url = :attachmentURI");
                  query.setParameter("attachmentURI", attachmentURI);

                  List<AttachmentDAO> daoList = query.getResultList();

                  if (daoList.isEmpty()) {
                    throw new AttachmentMgtException(
                        "Attachment not found for the uri:" + attachmentURI);
                  } else if (daoList.size() != 1) {
                    String errorMsg =
                        "There exist more than one attachment for the attachment URI:"
                            + attachmentURI
                            + ". org"
                            + ".wso2.carbon.attachment.mgt.util.URLGeneratorUtil.generateURL method has generated "
                            + "similar uris for different attachments. This has caused a major inconsistency for "
                            + "attachment management.";
                    log.fatal(errorMsg);
                    throw new AttachmentMgtException(errorMsg);
                  } else {
                    return daoList.get(0);
                  }
                }
              });
      return resultantDAO;
    } catch (Exception e) {
      String errorMsg =
          "org.wso2.carbon.attachment.mgt.core.dao.impl.hibernate.AttachmentMgtDAOFactoryImpl.getAttachmentInfoFromURL operation failed. "
              + "Reason: "
              + e.getLocalizedMessage();
      log.error(errorMsg, e);
      throw new AttachmentMgtException(errorMsg, e);
    }
  }
 /**
  * 同步执行一个任务
  *
  * @param jobData
  * @param executor
  * @return
  */
 private JobResult executeJob(JobData jobData, JobExecutor executor) throws Exception {
   JobResult result = null;
   int clientRetries =
       HttpJobUtils.getJobClientRetries(jobData.getData().get(JobData.JOBDATA_DATA_CLIENTRETRIES));
   for (int i = 1; i <= clientRetries + 1; i++) {
     result = executor.execute(jobData);
     if (result.isSuccess()) {
       if (i > 1) {
         result.getData().put(JobResult.JOBRESULT_DATA_CLIENTRETRYCOUNT, String.valueOf(i));
       }
       break;
     }
     try {
       Thread.sleep(5000);
     } catch (InterruptedException e1) {
     }
     if (i > 1 && i == clientRetries + 1) {
       result.getData().put(JobResult.JOBRESULT_DATA_CLIENTRETRYCOUNT, String.valueOf(i));
     }
   }
   return result;
 }
  public void run() {
    log.info("starting...");
    currentIdleInterval = jobExecutor.getIdleMillis();
    try {
      while (isActive) {
        try {
          // checkForNewJobs is set to true in jobWasAdded() below
          checkForNewJobs = false;

          // try to acquire jobs
          Collection<Long> acquiredJobDbids = acquireJobs();

          // no exception so resetting the currentIdleInterval
          currentIdleInterval = jobExecutor.getIdleMillis();
          if ((acquiredJobDbids != null) && (!acquiredJobDbids.isEmpty())) {
            putAcquiredJobDbidsOnQueue(acquiredJobDbids);
            log.debug("added jobs " + acquiredJobDbids + " to the queue");

          } else if (isActive) {
            long waitPeriod = getWaitPeriod();
            if (waitPeriod > 0) {
              synchronized (semaphore) {
                if (!checkForNewJobs) {
                  log.debug(
                      getName() + " will wait for max " + waitPeriod + "ms on " + jobExecutor);
                  semaphore.wait(waitPeriod);
                  log.debug(getName() + " woke up");
                } else {
                  log.debug("skipped wait because new message arrived");
                }
              }
            }
          }

        } catch (InterruptedException e) {
          log.info(
              (isActive ? "active" : "inactivated")
                  + " job dispatcher thread '"
                  + getName()
                  + "' got interrupted");
        } catch (Exception e) {
          log.error(
              "exception in job executor thread. waiting " + currentIdleInterval + " milliseconds",
              e);
          try {
            synchronized (semaphore) {
              semaphore.wait(currentIdleInterval);
            }
          } catch (InterruptedException e2) {
            log.trace("delay after exception got interrupted", e2);
          }
          // after an exception, the current idle interval is doubled to prevent
          // continuous exception generation when e.g. the db is unreachable
          currentIdleInterval = currentIdleInterval * 2;
        }
      }
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
      log.info(getName() + " leaves cyberspace");
    }
  }
 protected Date getNextDueDate() {
   CommandService commandService = jobExecutor.getCommandExecutor();
   Command<Date> getNextDueDate = jobExecutor.getNextDueDateCommand();
   return commandService.execute(getNextDueDate);
 }
 protected Collection<Long> acquireJobs() {
   CommandService commandService = jobExecutor.getCommandExecutor();
   Command<Collection<Long>> acquireJobsCommand = jobExecutor.getAcquireJobsCommand();
   return commandService.execute(acquireJobsCommand);
 }