@Test
  public void testValidSubscription() {
    // add configuration
    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // check ngsiClient.unsubscribe() is never called
    verify(ngsiClient, never()).unsubscribeContext(any(), any(), any());
    subscriptionManager.validateSubscriptionId("12345678", "http://iotAgent");
  }
  /**
   * Make sure we can kill the job init task on job finished event for the job.
   *
   * @throws GenieException on error
   */
  @Test
  public void canStopJobTask() throws GenieException {
    final String jobId = UUID.randomUUID().toString();
    final ScheduledFuture task = Mockito.mock(ScheduledFuture.class);
    final JobFinishedEvent jobFinishedEvent =
        new JobFinishedEvent(jobId, JobFinishedReason.FAILED_TO_INIT, "something", this);
    Mockito.when(task.isDone()).thenReturn(true).thenReturn(false).thenReturn(false);
    Mockito.when(task.cancel(true)).thenReturn(true).thenReturn(false);
    Mockito.when(scheduler.schedule(Mockito.any(), Mockito.any(Date.class))).thenReturn(task);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));
    coordinator.init(jobId);
    coordinator.schedule(jobId, null, null, null, null, 1024);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024));
    this.coordinator.onJobFinished(jobFinishedEvent);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));
    coordinator.init(jobId);
    coordinator.schedule(jobId, null, null, null, null, 1024);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024));
    this.coordinator.onJobFinished(jobFinishedEvent);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));
    coordinator.init(jobId);
    coordinator.schedule(jobId, null, null, null, null, 1024);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024));
    this.coordinator.onJobFinished(jobFinishedEvent);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));

    Mockito.verify(this.unableToCancel, Mockito.times(1)).increment();
  }
예제 #3
0
 public void init() {
   LOG.info("Configuring cpromo job scheduler");
   for (Map.Entry<String, PortalJob> entry : schedulerMap.entrySet()) {
     String cronExpression = dbSystemProperties.getProperty(entry.getKey() + "_SCHEDULE");
     if (cronExpression != null) {
       LOG.info(
           "scheduling the job {} to run according to the cron expression: {}",
           entry.getValue().getClass(),
           cronExpression);
       try {
         entry.getValue().init();
         taskScheduler.schedule(entry.getValue(), new CronTrigger(cronExpression));
       } catch (RuntimeException e) {
         jobExecutionLogger.errorInit(entry.getKey(), e.getLocalizedMessage());
         continue;
       }
       jobExecutionLogger.successInit(entry.getKey());
     } else {
       jobExecutionLogger.errorInit(
           entry.getKey(),
           "not found cron-expression entry in the system_property table for the job "
               + entry.getKey());
     }
   }
 }
 @Override
 protected void doStart() {
   synchronized (this.monitor) {
     if (this.running.get()) {
       // already running
       return;
     }
     this.running.set(true);
     StreamReadingTask task = new StreamReadingTask();
     TaskScheduler scheduler = getTaskScheduler();
     if (scheduler != null) {
       scheduler.schedule(task, new Date());
     } else {
       Executor executor = Executors.newSingleThreadExecutor();
       executor.execute(task);
     }
   }
 }
 @Before
 @SuppressWarnings("unchecked")
 public void setUp() throws UnknownHostException {
   RepoMdGenerator repoMdGenerator = new RepoMdGenerator(context.gridFs());
   MetadataService metadataService = context.metadataService();
   MongoPrimaryDetector primaryDetector = new MongoPrimaryDetector(context.getMongo());
   ScheduledFuture<Void> scheduledFuture = mock(ScheduledFuture.class);
   TaskScheduler taskScheduler = mock(TaskScheduler.class);
   when(taskScheduler.scheduleWithFixedDelay(any(Runnable.class), anyLong()))
       .thenReturn(scheduledFuture);
   schedulerJob =
       new RepoMetadataSchedulerJob(
           context.repoEntriesRepository(),
           metadataService,
           primaryDetector,
           taskScheduler,
           DELAY);
 }
 @SuppressWarnings("unchecked")
 public RepoMetadataGeneratorJob(
     String name,
     MetadataService metadataService,
     MongoPrimaryDetector primaryDetector,
     TaskScheduler taskScheduler,
     int delayInSec) {
   this.name = name;
   this.metadataService = metadataService;
   this.primaryDetector = primaryDetector;
   this.scheduledFuture = taskScheduler.scheduleWithFixedDelay(this, delayInSec * 1000);
 }
 protected void schedule(Task task, Pair<String, Trigger> triggerAndExpression) {
   if (triggerAndExpression == null) {
     throw new IllegalArgumentException("Must specify a Trigger and its expression");
   }
   LOGGER.info(
       "Scheduling task [{}] with trigger expression [{}]",
       task.id,
       triggerAndExpression.getFirst());
   task.execution = taskScheduler.schedule(task.runnable, triggerAndExpression.getSecond());
   task.executingTriggerExpression = triggerAndExpression.getFirst();
   task.executingTrigger = triggerAndExpression.getSecond();
 }
  private void scheduleRequestLogCleanupTask() {
    String cronExpression = settings.getRequestLogCleanupCronExpression();
    LOGGER.info("Scheduling request log cleanup task with cron '{}'", cronExpression);

    scheduler.schedule(
        new Runnable() {
          @Override
          public void run() {
            cleanupRequestLogTable();
          }
        },
        new CronTrigger(cronExpression));
  }
  @Test
  public void setConfigurationOK() throws Exception {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    SubscribeContext subscribeContext = subscribeContextArg.getValue();
    assertEquals("S.*", subscribeContext.getEntityIdList().get(0).getId());
    assertEquals("TempSensor", subscribeContext.getEntityIdList().get(0).getType());
    assertEquals(true, subscribeContext.getEntityIdList().get(0).getIsPattern());
    assertEquals("temp", subscribeContext.getAttributeList().get(0));
    assertEquals("PT1H", subscribeContext.getDuration());
    assertEquals("http://iotAgent", urlProviderArg.getValue());

    Set<Provider> providers = configuration.getEventTypeIns().get(0).getProviders();
    for (Provider provider : providers) {
      assertEquals("12345678", provider.getSubscriptionId());
      assertNotNull(provider.getSubscriptionDate());
    }
  }
  /** Starts session validation by creating a spring PeriodicTrigger. */
  public void enableSessionValidation() {

    enabled = true;

    if (log.isDebugEnabled()) {
      log.debug(
          "Scheduling session validation job using Spring Scheduler with "
              + "session validation interval of ["
              + sessionValidationInterval
              + "]ms...");
    }

    try {

      PeriodicTrigger trigger =
          new PeriodicTrigger(sessionValidationInterval, TimeUnit.MILLISECONDS);
      trigger.setInitialDelay(sessionValidationInterval);

      scheduler.schedule(
          new Runnable() {
            @Override
            public void run() {
              if (enabled) {
                sessionManager.validateSessions();
              }
            }
          },
          trigger);

      this.enabled = true;

      if (log.isDebugEnabled()) {
        log.debug("Session validation job successfully scheduled with Spring Scheduler.");
      }

    } catch (Exception e) {
      if (log.isErrorEnabled()) {
        log.error(
            "Error starting the Spring Scheduler session validation job.  Session validation may not occur.",
            e);
      }
    }
  }
  @Test
  public void testUnsubscribeOnProviderRemoval() {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    // Return the mocked future on subscription
    when(ngsiClient.subscribeContext(any(), any(), any())).thenReturn(responseFuture);

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // Mock future for unsubscribeContext
    ListenableFuture<UnsubscribeContextResponse> responseFuture2 =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture2).addCallback(successArg.capture(), any());
    when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("12345678")))
        .thenReturn(responseFuture2);

    // Reset conf should trigger unsubsribeContext
    Configuration emptyConfiguration = getBasicConf();
    emptyConfiguration.getEventTypeIns().get(0).setProviders(Collections.emptySet());
    subscriptionManager.setConfiguration(emptyConfiguration);

    // Check that unsubsribe is called
    Assert.notNull(successArg.getValue());
  }
예제 #12
0
  public void rebuildFullWallInformations(final Wall wall) {
    taskScheduler.schedule(
        new Runnable() {
          @Override
          public void run() {
            // TODO prevent wall hiding (exception causing wall not added to wall list) if software
            // not found
            rebuildConnectionPluginsInSoftwareAccess(wall);
            for (SoftwareAccess softwareAccess : wall.getSoftwareAccesses()) {
              if (softwareAccess.getConnection() instanceof BuildCapability) {
                Runnable task = getDiscoverBuildProjectsRunner(wall, softwareAccess);
                task.run();
                // TODO skip first immediate schedule run as called by hand upper
                @SuppressWarnings("unchecked")
                ScheduledFuture<Object> futur =
                    taskScheduler.scheduleWithFixedDelay(
                        task, softwareAccess.getProjectFinderDelaySecond() * 1000);
                softwareAccess.setProjectFinderTask(futur);
              }
            }

            // here as task war run ones without schedule, projects exists, we need that for first
            // run
            // to add other software without waiting for the second project discover
            for (SoftwareAccess softwareAccess : wall.getSoftwareAccesses()) {
              if (!(softwareAccess.getConnection() instanceof BuildCapability)) {
                Runnable task = getDiscoverOtherProjectsRunner(wall, softwareAccess);
                task.run();
                // TODO skip first immediate schedule run as called by hand upper
                @SuppressWarnings("unchecked")
                ScheduledFuture<Object> futur =
                    taskScheduler.scheduleWithFixedDelay(
                        task, softwareAccess.getProjectFinderDelaySecond() * 1000);
                softwareAccess.setProjectFinderTask(futur);
              }
            }
          }
        },
        new Date());
  }
예제 #13
0
 public void run() {
   final long start = System.currentTimeMillis();
   registeredTriggerManager.initializeTriggers();
   final long finish = System.currentTimeMillis();
   triggersHaveInitialized.set(true);
   float elapsed = (finish - start) / 1000 / 60;
   log.info("Trigger initialization completed in " + elapsed + " minutes");
   // Schedule backfill after triggers have been initialized
   if (backfillTask == null) {
     MethodInvokingRunnable backfill = new MethodInvokingRunnable();
     backfill.setTargetObject(availabilityCheckService);
     backfill.setTargetMethod("backfillPlatformAvailability");
     try {
       backfill.prepare();
       final long twoMins = 2 * MeasurementConstants.MINUTE;
       backfillTask =
           scheduler.scheduleWithFixedDelay(
               backfill, new Date(System.currentTimeMillis() + twoMins), twoMins);
     } catch (Exception e) {
       log.error("Unable to schedule availability backfill.", e);
     }
   }
 }