@Async
  public void runJob(JobDetails jobDetails, Scheduler scheduler)
      throws JobExecutionAlreadyRunningException, JobRestartException,
          JobInstanceAlreadyCompleteException, JobParametersInvalidException,
          SpartanPersistenceException, SchedulerException, ClassNotFoundException {
    Map<String, JobParameter> jobMapParams = new HashMap<String, JobParameter>();
    JobParameter paramMonth = new JobParameter(1l);
    jobMapParams.put("salForMonth", paramMonth);

    JobParameter paramDateTime = new JobParameter(new Date(System.currentTimeMillis()));
    jobMapParams.put("myCurrentTime", paramDateTime);

    JobParameters defaultParams = new JobParameters(jobMapParams);

    JobDataMap newJobData = new JobDataMap(jobMapParams);

    // Creating Job and link to our Job class
    Class jobClass = Class.forName(jobDetails.getBeanName());
    List<String> listOfJob = scheduler.getJobGroupNames();
    if (listOfJob.size() == 0) {
      schdeuleJob(jobClass, scheduler, jobDetails, newJobData);
    } else {
      for (String groupName : scheduler.getJobGroupNames()) {

        for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {

          String jobName = jobKey.getName();
          String jobGroup = jobKey.getGroup();

          // get job's trigger
          List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
          CronTrigger nextFireTime = (CronTrigger) triggers.get(0);
          if (jobDetails.getJobName().equalsIgnoreCase(jobName)
              && !jobDetails
                  .getScheduler()
                  .getSchedulerExpression()
                  .equalsIgnoreCase(nextFireTime.getCronExpression())) {
            scheduler.deleteJob(jobKey);
            schdeuleJob(jobClass, scheduler, jobDetails, newJobData);
          } else if (listOfJob.contains(jobDetails.getJobName())) {

          } else {
            schdeuleJob(jobClass, scheduler, jobDetails, newJobData);
          }
        }
      }
    }
  }
 public void removeAllJobs() throws SchedulerException {
   for (String groupName : quartzScheduler.getJobGroupNames()) {
     for (JobKey jobKey : quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
       quartzScheduler.deleteJob(jobKey);
     }
   }
 }
 public List<RunTimeJobDetail> listAllJobs() throws SchedulerException {
   List<RunTimeJobDetail> jobs = new ArrayList<RunTimeJobDetail>();
   for (String groupName : quartzScheduler.getJobGroupNames()) {
     for (JobKey jobKey : quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
       jobs.add(getJobDetails(groupName, jobKey.getName()));
     }
   }
   return jobs;
 }
 public List<String> getTaskNames() throws TaskSystemException {
   try {
     List<String> taskNames = new ArrayList<String>();
     String[] groupNames = scheduler.getJobGroupNames();
     for (String group : groupNames) {
       Collections.addAll(taskNames, scheduler.getJobNames(group));
     }
     return taskNames;
   } catch (SchedulerException e) {
     throw new TaskSystemException(e);
   }
 }
Exemple #5
0
 @SuppressWarnings("unchecked")
 public List<EndpointDTO> list() {
   List<EndpointDTO> endpointDTOs = Lists.newArrayList();
   try {
     for (String groupName : scheduler.getJobGroupNames()) {
       for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
         JobDetail jobDetail = scheduler.getJobDetail(jobKey);
         List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
         endpointDTOs.add(new EndpointDTO(jobDetail, triggers));
       }
     }
   } catch (SchedulerException e) {
   }
   return endpointDTOs;
 }
  public List<RunTimeJobDetail> searchJobs(String groupExp, String nameExp)
      throws SchedulerException {
    Pattern groupPattern = Pattern.compile(groupExp);
    Pattern namePattern = Pattern.compile(nameExp);

    List<RunTimeJobDetail> jobs = new ArrayList<RunTimeJobDetail>();
    for (String groupName : quartzScheduler.getJobGroupNames()) {
      if (groupPattern.matcher(groupName).matches()) {
        for (JobKey jobKey : quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
          if (namePattern.matcher(jobKey.getName()).matches()) {
            jobs.add(getJobDetails(groupName, jobKey.getName()));
          }
        }
      }
    }
    return jobs;
  }
 public void runIndividualTask(String taskName) throws TaskSystemException {
   try {
     String[] scheduledTasksGroups = scheduler.getJobGroupNames();
     OUTER:
     for (String groupName : scheduledTasksGroups) {
       String[] groupsTaskNames = scheduler.getJobNames(groupName);
       for (String groupsTaskName : groupsTaskNames) {
         if (groupsTaskName.equals(taskName)) {
           scheduler.triggerJob(taskName, groupName);
           break OUTER;
         }
       }
     }
   } catch (SchedulerException se) {
     throw new TaskSystemException(se);
   }
 }
  @Override
  public List<SchedulerResponse> getScheduledJobs(StorageType storageType)
      throws SchedulerException {

    try {
      Scheduler scheduler = getScheduler(storageType);

      List<String> groupNames = scheduler.getJobGroupNames();

      List<SchedulerResponse> schedulerResponses = new ArrayList<>();

      for (String groupName : groupNames) {
        schedulerResponses.addAll(getScheduledJobs(scheduler, groupName, storageType));
      }

      return schedulerResponses;
    } catch (Exception e) {
      throw new SchedulerException("Unable to get jobs with type " + storageType, e);
    }
  }
  @Test
  public void testBasicStorageFunctions() throws Exception {
    Scheduler sched = createScheduler("testBasicStorageFunctions", 2);

    // test basic storage functions of scheduler...

    JobDetail job = newJob().ofType(TestJob.class).withIdentity("j1").storeDurably().build();

    assertFalse("Unexpected existence of job named 'j1'.", sched.checkExists(jobKey("j1")));

    sched.addJob(job, false);

    assertTrue(
        "Expected existence of job named 'j1' but checkExists return false.",
        sched.checkExists(jobKey("j1")));

    job = sched.getJobDetail(jobKey("j1"));

    assertNotNull("Stored job not found!", job);

    sched.deleteJob(jobKey("j1"));

    Trigger trigger =
        newTrigger()
            .withIdentity("t1")
            .forJob(job)
            .startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(5))
            .build();

    assertFalse("Unexpected existence of trigger named 't1'.", sched.checkExists(triggerKey("t1")));

    sched.scheduleJob(job, trigger);

    assertTrue(
        "Expected existence of trigger named 't1' but checkExists return false.",
        sched.checkExists(triggerKey("t1")));

    job = sched.getJobDetail(jobKey("j1"));

    assertNotNull("Stored job not found!", job);

    trigger = sched.getTrigger(triggerKey("t1"));

    assertNotNull("Stored trigger not found!", trigger);

    job = newJob().ofType(TestJob.class).withIdentity("j2", "g1").build();

    trigger =
        newTrigger()
            .withIdentity("t2", "g1")
            .forJob(job)
            .startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(5))
            .build();

    sched.scheduleJob(job, trigger);

    job = newJob().ofType(TestJob.class).withIdentity("j3", "g1").build();

    trigger =
        newTrigger()
            .withIdentity("t3", "g1")
            .forJob(job)
            .startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(5))
            .build();

    sched.scheduleJob(job, trigger);

    List<String> jobGroups = sched.getJobGroupNames();
    List<String> triggerGroups = sched.getTriggerGroupNames();

    assertTrue("Job group list size expected to be = 2 ", jobGroups.size() == 2);
    assertTrue("Trigger group list size expected to be = 2 ", triggerGroups.size() == 2);

    Set<JobKey> jobKeys = sched.getJobKeys(GroupMatcher.jobGroupEquals(JobKey.DEFAULT_GROUP));
    Set<TriggerKey> triggerKeys =
        sched.getTriggerKeys(GroupMatcher.triggerGroupEquals(TriggerKey.DEFAULT_GROUP));

    assertTrue("Number of jobs expected in default group was 1 ", jobKeys.size() == 1);
    assertTrue("Number of triggers expected in default group was 1 ", triggerKeys.size() == 1);

    jobKeys = sched.getJobKeys(GroupMatcher.jobGroupEquals("g1"));
    triggerKeys = sched.getTriggerKeys(GroupMatcher.triggerGroupEquals("g1"));

    assertTrue("Number of jobs expected in 'g1' group was 2 ", jobKeys.size() == 2);
    assertTrue("Number of triggers expected in 'g1' group was 2 ", triggerKeys.size() == 2);

    TriggerState s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be NORMAL ", s.equals(TriggerState.NORMAL));

    sched.pauseTrigger(triggerKey("t2", "g1"));
    s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be PAUSED ", s.equals(TriggerState.PAUSED));

    sched.resumeTrigger(triggerKey("t2", "g1"));
    s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be NORMAL ", s.equals(TriggerState.NORMAL));

    Set<String> pausedGroups = sched.getPausedTriggerGroups();
    assertTrue("Size of paused trigger groups list expected to be 0 ", pausedGroups.size() == 0);

    sched.pauseTriggers(GroupMatcher.triggerGroupEquals("g1"));

    // test that adding a trigger to a paused group causes the new trigger to be paused also...
    job = newJob().ofType(TestJob.class).withIdentity("j4", "g1").build();

    trigger =
        newTrigger()
            .withIdentity("t4", "g1")
            .forJob(job)
            .startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(5))
            .build();

    sched.scheduleJob(job, trigger);
    // TODO: nexus hack: JobStoreImpl DOES NOT "remember" paused groups
    sched.pauseJob(jobKey("j4", "g1"));

    pausedGroups = sched.getPausedTriggerGroups();
    assertTrue(
        "Size of paused trigger groups list expected to be 1: " + pausedGroups,
        pausedGroups.size() == 1);

    s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be PAUSED ", s.equals(TriggerState.PAUSED));

    s = sched.getTriggerState(triggerKey("t4", "g1"));
    assertTrue("State of trigger t4 expected to be PAUSED ", s.equals(TriggerState.PAUSED));

    sched.resumeTriggers(GroupMatcher.triggerGroupEquals("g1"));
    s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be NORMAL ", s.equals(TriggerState.NORMAL));
    s = sched.getTriggerState(triggerKey("t4", "g1"));
    assertTrue("State of trigger t4 expected to be NORMAL ", s.equals(TriggerState.NORMAL));
    pausedGroups = sched.getPausedTriggerGroups();
    assertTrue("Size of paused trigger groups list expected to be 0 ", pausedGroups.size() == 0);

    assertFalse(
        "Scheduler should have returned 'false' from attempt to unschedule non-existing trigger. ",
        sched.unscheduleJob(triggerKey("foasldfksajdflk")));

    assertTrue(
        "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ",
        sched.unscheduleJob(triggerKey("t3", "g1")));

    jobKeys = sched.getJobKeys(GroupMatcher.jobGroupEquals("g1"));
    triggerKeys = sched.getTriggerKeys(GroupMatcher.triggerGroupEquals("g1"));

    assertTrue(
        "Number of jobs expected in 'g1' group was 1 ",
        jobKeys.size() == 2); // job should have been deleted also, because it is non-durable
    assertTrue("Number of triggers expected in 'g1' group was 1 ", triggerKeys.size() == 2);

    assertTrue(
        "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ",
        sched.unscheduleJob(triggerKey("t1")));

    jobKeys = sched.getJobKeys(GroupMatcher.jobGroupEquals(JobKey.DEFAULT_GROUP));
    triggerKeys = sched.getTriggerKeys(GroupMatcher.triggerGroupEquals(TriggerKey.DEFAULT_GROUP));

    assertTrue(
        "Number of jobs expected in default group was 1 ",
        jobKeys.size() == 1); // job should have been left in place, because it is non-durable
    assertTrue("Number of triggers expected in default group was 0 ", triggerKeys.size() == 0);

    sched.shutdown(true);
  }
  @Test
  public void testExecuteQuickImport() throws Exception {
    expect(mockBarrier.await(20, TimeUnit.SECONDS)).andReturn(true);

    expect(mockBeanFactory.getInstance(currentUser)).andReturn(new MockI18nHelper()).anyTimes();
    // called during validation!
    expect(mockPermissionManager.hasPermission(Permissions.SYSTEM_ADMIN, currentUser))
        .andReturn(true);

    // This is called during the first parse of the XML file.  At this stage nothing should have
    // been created yet!
    final MockGenericValue mockGv = new MockGenericValue("someentity");
    expect(mockOfBizDelegator.makeValue(EasyMock.<String>anyObject())).andReturn(mockGv).anyTimes();
    expect(mockAttachmentPathManager.getDefaultAttachmentPath())
        .andReturn(directories.get(0).getAbsolutePath())
        .anyTimes();
    expect(mockIndexPathManager.getDefaultIndexRootPath())
        .andReturn(directories.get(1).getAbsolutePath())
        .anyTimes();
    expect(
            mockLicenseStringFactory.create(
                EasyMock.<String>anyObject(), EasyMock.<String>anyObject()))
        .andStubReturn("");

    // after the first parse check the build number.
    expect(mockBuildUtilsInfo.getCurrentBuildNumber()).andStubReturn("99999999");
    expect(mockBuildUtilsInfo.getMinimumUpgradableBuildNumber()).andStubReturn("0");

    // after the first parse we also verify the license is good.
    expect(
            mockJiraLicenseService.validate(
                EasyMock.<I18nHelper>anyObject(), EasyMock.<String>anyObject()))
        .andStubReturn(mockValidationResult);
    expect(mockValidationResult.getLicenseVersion()).andStubReturn(2);
    expect(mockValidationResult.getErrorCollection()).andStubReturn(new SimpleErrorCollection());

    // this gets called during shutdownAndFlushAsyncServices.  After parse and before the import.
    // This shuts down
    // the scheduler
    mockScheduler.standby();
    expect(mockScheduler.getJobGroupNames()).andReturn(new String[] {"group1"});
    expect(mockScheduler.getJobNames("group1")).andReturn(new String[] {"job1", "job2"});
    expect(mockScheduler.deleteJob("job1", "group1")).andReturn(true);
    expect(mockScheduler.deleteJob("job2", "group1")).andReturn(true);
    mockMailQueue.sendBuffer();
    expect(mockTaskManager.awaitUntilActiveTasksComplete(20)).andReturn(true);

    // Expect AO to be cleared.
    backup.clear();

    // Once the import is running one of the first things to do is to clear out the old database
    // values.
    expect(mockOfBizDelegator.getModelReader()).andReturn(mockModelReader);
    expect(mockModelReader.getEntityNames())
        .andReturn(CollectionBuilder.<String>list("Issue", "User"));
    expect(mockModelReader.getModelEntity("Issue")).andReturn(new ModelEntity());
    expect(mockOfBizDelegator.removeByAnd("Issue", Collections.<String, Object>emptyMap()))
        .andReturn(10);
    expect(mockModelReader.getModelEntity("User")).andReturn(new ModelEntity());
    expect(mockOfBizDelegator.removeByAnd("User", Collections.<String, Object>emptyMap()))
        .andReturn(5);

    // then we go through and create all our GVs (already mocked out during the first parse above)

    // once everything's been imported need to refresh the ofbiz sequencer and check for data
    // consistency.
    mockOfBizDelegator.refreshSequencer();
    mockConsistencyChecker.checkDataConsistency();

    // after the consistency check lets do the upgrade
    expect(mockUpgradeManager.doUpgradeIfNeededAndAllowed(null))
        .andReturn(Collections.<String>emptyList());

    // now do a reindex
    mockIndexManager.deactivate();
    expect(mockIndexManager.size()).andReturn(5);
    expect(mockIndexManager.activate((Context) notNull())).andReturn(1L);

    // raise the JiraStartedEvent
    mockPluginEventManager.broadcast(EasyMock.<JiraStartedEvent>anyObject());

    // finally we can restart the scheduler!
    expect(
            mockScheduler.scheduleJob(
                EasyMock.<JobDetail>anyObject(), EasyMock.<Trigger>anyObject()))
        .andReturn(new Date())
        .anyTimes();
    mockScheduler.start();

    final String filePath = getDataFilePath("jira-export-test.xml");
    final DataImportParams params =
        new DataImportParams.Builder(filePath).setQuickImport(true).build();

    // Finally everything's mocked out.  Run the import!
    executeTest(params, true, DataImportService.ImportError.NONE);

    // create() should have been called on our GVs
    assertTrue(mockGv.isCreated());
    // the world should have been rebuilt!
    assertTrue(((MockDataImportDependencies) mockDependencies).globalRefreshCalled);
  }