Java Code Examples for org.springframework.scheduling.TaskScheduler

The following examples show how to use org.springframework.scheduling.TaskScheduler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void standaloneEventRegistryWithCustomTaskScheduler() {
    contextRunner
        .withBean(ThreadPoolTaskScheduler.class)
        .withPropertyValues("flowable.eventregistry.enable-change-detection:true")
        .run(context -> {

        EventRegistryEngine eventRegistryEngine = context.getBean(EventRegistryEngine.class);
        assertThat(eventRegistryEngine).as("Event registry engine").isNotNull();
        assertAllServicesPresent(context, eventRegistryEngine);

        assertThat(eventRegistryEngine.getEventRegistryEngineConfiguration().getEventRegistryChangeDetectionManager())
            .isInstanceOf(DefaultEventRegistryChangeDetectionManager.class);
            assertThat(eventRegistryEngine.getEventRegistryEngineConfiguration().getEventRegistryChangeDetectionExecutor())
                .isInstanceOf(DefaultSpringEventRegistryChangeDetectionExecutor.class);

        DefaultSpringEventRegistryChangeDetectionExecutor executor = (DefaultSpringEventRegistryChangeDetectionExecutor)
            eventRegistryEngine.getEventRegistryEngineConfiguration().getEventRegistryChangeDetectionExecutor();
        assertThat(executor.getTaskScheduler()).isEqualTo(context.getBean(TaskScheduler.class));
    });
}
 
Example 2
@Test
public void receiptReceived() throws Exception {

	this.session.afterConnected(this.connection);
	this.session.setTaskScheduler(mock(TaskScheduler.class));

	AtomicReference<Boolean> received = new AtomicReference<>();

	StompHeaders headers = new StompHeaders();
	headers.setDestination("/topic/foo");
	headers.setReceipt("my-receipt");
	Subscription subscription = this.session.subscribe(headers, mock(StompFrameHandler.class));
	subscription.addReceiptTask(() -> received.set(true));

	assertNull(received.get());

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
	accessor.setReceiptId("my-receipt");
	accessor.setLeaveMutable(true);
	this.session.handleMessage(MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()));

	assertNotNull(received.get());
	assertTrue(received.get());
}
 
Example 3
Source Project: genie   Source File: JobMonitoringCoordinator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param genieHostInfo         Information about the host the Genie process is currently running on
 * @param dataServices          The {@link DataServices} instance to use
 * @param genieEventBus         The Genie event bus to use for publishing events
 * @param scheduler             The task scheduler to use to register scheduling of job checkers
 * @param registry              The metrics registry
 * @param jobsDir               The directory where job output is stored
 * @param jobsProperties        The properties pertaining to jobs
 * @param jobSubmitterService   implementation of the job submitter service
 * @param processCheckerFactory The factory of process checkers
 * @throws IOException on error with the filesystem
 */
@Autowired
public JobMonitoringCoordinator(
    final GenieHostInfo genieHostInfo,
    final DataServices dataServices,
    final GenieEventBus genieEventBus,
    @Qualifier("genieTaskScheduler") final TaskScheduler scheduler,
    final MeterRegistry registry,
    final Resource jobsDir,
    final JobsProperties jobsProperties,
    final JobSubmitterService jobSubmitterService,
    final ProcessChecker.Factory processCheckerFactory
) throws IOException {
    super(jobSubmitterService, scheduler, genieEventBus, registry);
    this.hostname = genieHostInfo.getHostname();
    this.persistenceService = dataServices.getPersistenceService();
    this.jobsDir = jobsDir.getFile();
    this.jobsProperties = jobsProperties;
    this.processCheckerFactory = processCheckerFactory;

    // Automatically track the number of jobs running on this node
    this.unableToReAttach = registry.counter("genie.jobs.unableToReAttach.rate");
}
 
Example 4
Source Project: spring-analysis-note   Source File: DefaultStompSessionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void sendWithReceipt() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	this.session.setTaskScheduler(mock(TaskScheduler.class));
	this.session.setAutoReceipt(true);
	this.session.send("/topic/foo", "sample payload");

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertNotNull(accessor.getReceipt());

	StompHeaders stompHeaders = new StompHeaders();
	stompHeaders.setDestination("/topic/foo");
	stompHeaders.setReceipt("my-receipt");
	this.session.send(stompHeaders, "sample payload");

	message = this.messageCaptor.getValue();
	accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals("my-receipt", accessor.getReceipt());
}
 
Example 5
Source Project: spring-analysis-note   Source File: DefaultStompSessionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void receiptReceived() {
	this.session.afterConnected(this.connection);
	this.session.setTaskScheduler(mock(TaskScheduler.class));

	AtomicReference<Boolean> received = new AtomicReference<>();

	StompHeaders headers = new StompHeaders();
	headers.setDestination("/topic/foo");
	headers.setReceipt("my-receipt");
	Subscription subscription = this.session.subscribe(headers, mock(StompFrameHandler.class));
	subscription.addReceiptTask(() -> received.set(true));

	assertNull(received.get());

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
	accessor.setReceiptId("my-receipt");
	accessor.setLeaveMutable(true);
	this.session.handleMessage(MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()));

	assertNotNull(received.get());
	assertTrue(received.get());
}
 
Example 6
Source Project: spring-analysis-note   Source File: DefaultStompSessionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void receiptReceivedBeforeTaskAdded() {
	this.session.afterConnected(this.connection);
	this.session.setTaskScheduler(mock(TaskScheduler.class));

	AtomicReference<Boolean> received = new AtomicReference<>();

	StompHeaders headers = new StompHeaders();
	headers.setDestination("/topic/foo");
	headers.setReceipt("my-receipt");
	Subscription subscription = this.session.subscribe(headers, mock(StompFrameHandler.class));

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
	accessor.setReceiptId("my-receipt");
	accessor.setLeaveMutable(true);
	this.session.handleMessage(MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()));

	subscription.addReceiptTask(() -> received.set(true));

	assertNotNull(received.get());
	assertTrue(received.get());
}
 
Example 7
@Test
public void postProcessAfterInitialization() throws Exception {
    assertThat(processor.postProcessAfterInitialization(mock(Executor.class), toBeExcluded).getClass(),
            not(equalTo(ContextAwareExecutor.class)));
    //concurrent
    assertThat(processor.postProcessAfterInitialization(mock(Executor.class), beanName).getClass(),
            equalTo(ContextAwareExecutor.class));
    assertThat(processor.postProcessAfterInitialization(mock(ExecutorService.class), beanName).getClass(),
            equalTo(ContextAwareExecutorService.class));
    assertThat(processor.postProcessAfterInitialization(mock(ScheduledExecutorService.class), beanName).getClass(),
            equalTo(ContextAwareScheduledExecutorService.class));

    //spring
    assertThat(processor.postProcessAfterInitialization(mock(TaskScheduler.class), beanName).getClass(),
            equalTo(ContextAwareTaskScheduler.class));
    assertThat(processor.postProcessAfterInitialization(new ThreadPoolTaskExecutor(), beanName).getClass(),
            equalTo(ContextAwareThreadPoolTaskExecutor.class));
    assertThat(processor.postProcessAfterInitialization(new ThreadPoolTaskScheduler(), beanName).getClass(),
            equalTo(ContextAwareThreadPoolTaskScheduler.class));
    assertThat(processor.postProcessAfterInitialization(mock(AsyncListenableTaskExecutor.class), beanName).getClass(),
            equalTo(ContextAwareAsyncListenableTaskExecutor.class));
    assertThat(processor.postProcessAfterInitialization(mock(AsyncTaskExecutor.class), beanName).getClass(),
            equalTo(ContextAwareAsyncTaskExecutor.class));
    assertThat(processor.postProcessAfterInitialization(mock(SchedulingTaskExecutor.class), beanName).getClass(),
            equalTo(ContextAwareSchedulingTaskExecutor.class));
}
 
Example 8
Source Project: bugsnag-java   Source File: ScheduledTaskConfiguration.java    License: MIT License 6 votes vote down vote up
/**
 * If a task scheduler has been defined by the application, get it so that
 * bugsnag error handling can be added.
 * <p>
 * Reflection is the simplest way to get and set an error handler
 * because the error handler setter is only defined in the concrete classes,
 * not the TaskScheduler interface.
 *
 * @param taskScheduler the task scheduler
 */
private void configureExistingTaskScheduler(TaskScheduler taskScheduler,
                                            BugsnagScheduledTaskExceptionHandler errorHandler) {
    try {
        Field errorHandlerField =
                taskScheduler.getClass().getDeclaredField("errorHandler");
        errorHandlerField.setAccessible(true);
        Object existingErrorHandler = errorHandlerField.get(taskScheduler);

        // If an error handler has already been defined then make the Bugsnag handler
        // call this afterwards
        if (existingErrorHandler instanceof ErrorHandler) {
            errorHandler.setExistingErrorHandler((ErrorHandler) existingErrorHandler);
        }

        // Add the bugsnag error handler to the scheduler.
        errorHandlerField.set(taskScheduler, errorHandler);
    } catch (Throwable ex) {
        LOGGER.warn("Bugsnag scheduled task exception handler could not be configured");
    }
}
 
Example 9
Source Project: genie   Source File: GRpcAgentFileStreamServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private TransferManager(
    final ControlStreamManager controlStreamsManager,
    final TaskScheduler taskScheduler,
    final AgentFileStreamProperties properties,
    final MeterRegistry registry
) {
    this.controlStreamsManager = controlStreamsManager;
    this.taskScheduler = taskScheduler;
    this.properties = properties;
    this.registry = registry;
    this.transferTimeOutCounter = registry.counter(TRANSFER_TIMEOUT_COUNTER);
    this.transferSizeDistribution = registry.summary(TRANSFER_SIZE_DISTRIBUTION);

    this.taskScheduler.scheduleAtFixedRate(
        this::reapStalledTransfers,
        this.properties.getStalledTransferCheckInterval()
    );
}
 
Example 10
/**
 * Create a TransportHandlingSockJsService with given {@link TransportHandler handler} types.
 * @param scheduler a task scheduler for heart-beat messages and removing timed-out sessions;
 * the provided TaskScheduler should be declared as a Spring bean to ensure it gets
 * initialized at start-up and shuts down when the application stops
 * @param handlers one or more {@link TransportHandler} implementations to use
 */
public TransportHandlingSockJsService(TaskScheduler scheduler, Collection<TransportHandler> handlers) {
	super(scheduler);

	if (CollectionUtils.isEmpty(handlers)) {
		logger.warn("No transport handlers specified for TransportHandlingSockJsService");
	}
	else {
		for (TransportHandler handler : handlers) {
			handler.initialize(this);
			this.handlers.put(handler.getTransportType(), handler);
		}
	}

	if (jackson2Present) {
		this.messageCodec = new Jackson2SockJsMessageCodec();
	}
}
 
Example 11
Source Project: blackduck-alert   Source File: ProcessingTaskTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRead() {
    TaskManager taskManager = Mockito.mock(TaskManager.class);
    TaskScheduler taskScheduler = Mockito.mock(TaskScheduler.class);
    DefaultNotificationManager notificationManager = Mockito.mock(DefaultNotificationManager.class);
    NotificationProcessor notificationProcessor = Mockito.mock(NotificationProcessor.class);
    Mockito.when(notificationProcessor.processNotifications(FrequencyType.DAILY, modelList)).thenReturn(eventList);
    ChannelEventManager eventManager = Mockito.mock(ChannelEventManager.class);
    ProcessingTask task = createTask(taskScheduler, notificationManager, notificationProcessor, eventManager, taskManager);
    DateRange dateRange = task.getDateRange();
    Mockito.when(notificationManager.findByCreatedAtBetween(dateRange.getStart(), dateRange.getEnd())).thenReturn(modelList);
    ProcessingTask processingTask = Mockito.spy(task);
    List<AlertNotificationModel> actualModelList = processingTask.read(dateRange);
    Mockito.verify(notificationManager).findByCreatedAtBetween(dateRange.getStart(), dateRange.getEnd());
    assertEquals(modelList, actualModelList);
}
 
Example 12
@Test
public void receiptReceivedBeforeTaskAdded() throws Exception {

	this.session.afterConnected(this.connection);
	this.session.setTaskScheduler(mock(TaskScheduler.class));

	AtomicReference<Boolean> received = new AtomicReference<>();

	StompHeaders headers = new StompHeaders();
	headers.setDestination("/topic/foo");
	headers.setReceipt("my-receipt");
	Subscription subscription = this.session.subscribe(headers, mock(StompFrameHandler.class));

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.RECEIPT);
	accessor.setReceiptId("my-receipt");
	accessor.setLeaveMutable(true);
	this.session.handleMessage(MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders()));

	subscription.addReceiptTask(() -> received.set(true));

	assertNotNull(received.get());
	assertTrue(received.get());
}
 
Example 13
Source Project: genie   Source File: DiskCleanupTask.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor. Schedules this task to be run by the task scheduler.
 *
 * @param properties      The disk cleanup properties to use.
 * @param scheduler       The scheduler to use to schedule the cron trigger.
 * @param jobsDir         The resource representing the location of the job directory
 * @param dataServices    The {@link DataServices} instance to use
 * @param jobsProperties  The jobs properties to use
 * @param processExecutor The process executor to use to delete directories
 * @param registry        The metrics registry
 * @throws IOException When it is unable to open a file reference to the job directory
 */
public DiskCleanupTask(
    @NotNull final DiskCleanupProperties properties,
    @NotNull final TaskScheduler scheduler,
    @NotNull final Resource jobsDir,
    @NotNull final DataServices dataServices,
    @NotNull final JobsProperties jobsProperties,
    @NotNull final Executor processExecutor,
    @NotNull final MeterRegistry registry
) throws IOException {
    // Job Directory is guaranteed to exist by the MvcConfig bean creation but just in case someone overrides
    if (!jobsDir.exists()) {
        throw new IOException("Jobs dir " + jobsDir + " doesn't exist. Unable to create task to cleanup.");
    }

    this.properties = properties;
    this.jobsDir = jobsDir.getFile();
    this.persistenceService = dataServices.getPersistenceService();
    this.runAsUser = jobsProperties.getUsers().isRunAsUserEnabled();
    this.processExecutor = processExecutor;

    this.numberOfDeletedJobDirs = registry.gauge(
        "genie.tasks.diskCleanup.numberDeletedJobDirs.gauge",
        new AtomicLong()
    );
    this.numberOfDirsUnableToDelete = registry.gauge(
        "genie.tasks.diskCleanup.numberDirsUnableToDelete.gauge",
        new AtomicLong()
    );
    this.unableToGetJobCounter = registry.counter("genie.tasks.diskCleanup.unableToGetJobs.rate");
    this.unableToDeleteJobDirCounter = registry.counter("genie.tasks.diskCleanup.unableToDeleteJobsDir.rate");

    // Only schedule the task if we don't need sudo while on a non-unix system
    if (this.runAsUser && !SystemUtils.IS_OS_UNIX) {
        log.error("System is not UNIX like. Unable to schedule disk cleanup due to needing Unix commands");
    } else {
        final CronTrigger trigger = new CronTrigger(properties.getExpression(), JobConstants.UTC);
        scheduler.schedule(this, trigger);
    }
}
 
Example 14
Source Project: genie   Source File: GenieCpuHealthIndicator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param healthProperties The maximum physical memory threshold
 * @param registry         Registry
 * @param taskScheduler    task scheduler
 */
public GenieCpuHealthIndicator(
    @NotNull final HealthProperties healthProperties,
    @NotNull final MeterRegistry registry,
    @NotNull final TaskScheduler taskScheduler
) {
    this(
        healthProperties.getMaxCpuLoadPercent(),
        healthProperties.getMaxCpuLoadConsecutiveOccurrences(),
        (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(),
        registry.summary("genie.cpuLoad"),
        taskScheduler
    );
}
 
Example 15
Source Project: front50   Source File: Front50WebConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public TaskScheduler taskScheduler() {
  ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
  scheduler.setThreadNamePrefix("scheduler-");
  scheduler.setPoolSize(10);

  return scheduler;
}
 
Example 16
public PerConnectionApolloHandler(GraphQL graphQL, GraphQLWebSocketExecutor executor,
                                  TaskScheduler taskScheduler, int keepAliveInterval) {
    this.graphQL = graphQL;
    this.executor = executor;
    this.taskScheduler = taskScheduler;
    this.keepAliveInterval = keepAliveInterval;
    this.handlers = new ConcurrentHashMap<>();
}
 
Example 17
Source Project: genie   Source File: AgentAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Provide a lazy {@link TaskScheduler} to be used by the Agent process if one isn't already defined.
 *
 * @return A {@link ThreadPoolTaskScheduler} instance
 */
@Bean
@Lazy
@ConditionalOnMissingBean(name = "sharedAgentTaskScheduler")
public TaskScheduler sharedAgentTaskScheduler() {
    final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(5); // Big enough?
    scheduler.setThreadNamePrefix("agent-task-scheduler-");
    return scheduler;
}
 
Example 18
Source Project: blackduck-alert   Source File: PhoneHomeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void runTest() throws AlertDatabaseConstraintException {
    AuditUtility auditUtility = Mockito.mock(AuditUtility.class);
    Mockito.when(auditUtility.findFirstByJobId(Mockito.any())).thenReturn(Optional.empty());
    TaskScheduler taskScheduler = Mockito.mock(TaskScheduler.class);
    ProxyManager proxyManager = Mockito.mock(ProxyManager.class);
    Mockito.when(proxyManager.createProxyInfo()).thenReturn(ProxyInfo.NO_PROXY_INFO);
    TestBlackDuckProperties blackDuckProperties = new TestBlackDuckProperties(new Gson(), new TestAlertProperties(), new TestProperties(), proxyManager);

    AboutReader aboutReader = Mockito.mock(AboutReader.class);
    Mockito.when(aboutReader.getProductVersion()).thenReturn(TEST_VERSION);

    DefaultConfigurationAccessor configurationAccessor = Mockito.mock(DefaultConfigurationAccessor.class);
    ConfigurationModel config = Mockito.mock(ConfigurationModel.class);
    Mockito.when(configurationAccessor.getConfigurationsByDescriptorKey(Mockito.any(DescriptorKey.class))).thenReturn(List.of(config));

    DescriptorMap descriptorMap = Mockito.mock(DescriptorMap.class);
    Descriptor descriptor = Mockito.mock(Descriptor.class);
    DescriptorKey descriptorKey = Mockito.mock(DescriptorKey.class);
    Mockito.when(descriptorKey.getUniversalKey()).thenReturn(TEST_DESCRIPTOR_NAME);

    Mockito.when(descriptorMap.getDescriptorMap()).thenReturn(Collections.singletonMap(descriptorKey, descriptor));
    List<ProviderPhoneHomeHandler> providerHandlers = List.of();
    PhoneHomeTask phoneHomeTask = new PhoneHomeTask(taskScheduler, aboutReader, configurationAccessor, null, proxyManager, new Gson(), auditUtility, providerHandlers);

    try {
        phoneHomeTask.run();
    } catch (Exception e) {
        fail("Unexpected exception");
    }
}
 
Example 19
Source Project: spring-cloud-gcp   Source File: BigQueryTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the {@link BigQuery} template.
 *
 * @param bigQuery the underlying client object used to interface with BigQuery
 * @param datasetName the name of the dataset in which all operations will take place
 * @param taskScheduler the {@link TaskScheduler} used to poll for the status of
 *     long-running BigQuery operations
 */
public BigQueryTemplate(BigQuery bigQuery, String datasetName, TaskScheduler taskScheduler) {
	Assert.notNull(bigQuery, "BigQuery client object must not be null.");
	Assert.notNull(datasetName, "Dataset name must not be null");
	Assert.notNull(taskScheduler, "TaskScheduler must not be null");

	this.bigQuery = bigQuery;
	this.datasetName = datasetName;
	this.taskScheduler = taskScheduler;
}
 
Example 20
Source Project: distributed-lock   Source File: DistributedLockConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public LockBeanPostProcessor lockBeanPostProcessor(final KeyGenerator keyGenerator,
                                                   final ConfigurableBeanFactory configurableBeanFactory,
                                                   final IntervalConverter intervalConverter,
                                                   final RetriableLockFactory retriableLockFactory,
                                                   @Autowired(required = false) final TaskScheduler taskScheduler) {
  final var processor = new LockBeanPostProcessor(keyGenerator, configurableBeanFactory::getBean, intervalConverter, retriableLockFactory, taskScheduler);
  processor.setBeforeExistingAdvisors(true);
  return processor;
}
 
Example 21
Source Project: genie   Source File: GRpcServicesAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Provide a lazy gRPC agent heart beat service if one isn't already defined.
 *
 * @param heartBeatServiceStub The heart beat service stub to use
 * @param taskScheduler        The task scheduler to use
 * @param agentProperties      The agent properties
 * @return A {@link GrpcAgentHeartBeatServiceImpl} instance
 */
@Bean
@Lazy
@ConditionalOnMissingBean(AgentHeartBeatService.class)
public AgentHeartBeatService agentHeartBeatService(
    final HeartBeatServiceGrpc.HeartBeatServiceStub heartBeatServiceStub,
    @Qualifier("heartBeatServiceTaskScheduler") final TaskScheduler taskScheduler,
    final AgentProperties agentProperties
) {
    return new GrpcAgentHeartBeatServiceImpl(
        heartBeatServiceStub,
        taskScheduler,
        agentProperties.getHeartBeatService()
    );
}
 
Example 22
/**
 * {@inheritDoc}
 */
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (bean instanceof Executor || bean instanceof TaskScheduler) {
        if (properties.getExecutor().accept(beanName)) {
            if (bean instanceof AsyncListenableTaskExecutor && bean instanceof SchedulingTaskExecutor && bean instanceof TaskScheduler) {
                log.info("Context propagation enabled for ~ThreadPoolTaskScheduler [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareThreadPoolTaskScheduler((AsyncListenableTaskExecutor) bean, (SchedulingTaskExecutor) bean, (TaskScheduler) bean);
            } else if (bean instanceof AsyncListenableTaskExecutor && bean instanceof SchedulingTaskExecutor) {
                log.info("Context propagation enabled for ~ThreadPoolTaskExecutor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareThreadPoolTaskExecutor((AsyncListenableTaskExecutor) bean, (SchedulingTaskExecutor) bean);
            } else if (bean instanceof TaskScheduler) {
                log.info("Context propagation enabled for TaskScheduler [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareTaskScheduler((TaskScheduler) bean);
            } else if (bean instanceof SchedulingTaskExecutor) {
                log.info("Context propagation enabled for SchedulingTaskExecutor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareSchedulingTaskExecutor((SchedulingTaskExecutor) bean);
            } else if (bean instanceof AsyncListenableTaskExecutor) {
                log.info("Context propagation enabled for AsyncListenableTaskExecutor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareAsyncListenableTaskExecutor((AsyncListenableTaskExecutor) bean);
            } else if (bean instanceof AsyncTaskExecutor) {
                log.info("Context propagation enabled for AsyncTaskExecutor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareAsyncTaskExecutor((AsyncTaskExecutor) bean);
            } else if (bean instanceof ScheduledExecutorService) {
                log.info("Context propagation enabled for ScheduledExecutorService [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareScheduledExecutorService((ScheduledExecutorService) bean);
            } else if (bean instanceof ExecutorService) {
                log.info("Context propagation enabled for ExecutorService [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareExecutorService((ExecutorService) bean);
            } else {
                log.info("Context propagation enabled for Executor [{}]:[{}].", beanName, bean.getClass().getName());
                return new ContextAwareExecutor((Executor) bean);
            }
        } else {
            log.debug("Context propagation disabled for Executor [{}]", beanName);
        }
    }
    return bean;
}
 
Example 23
@Test
public void getSubProtocols() throws Exception {
	SubscribableChannel channel = mock(SubscribableChannel.class);
	SubProtocolWebSocketHandler handler = new SubProtocolWebSocketHandler(channel, channel);
	StompSubProtocolHandler stompHandler = new StompSubProtocolHandler();
	handler.addProtocolHandler(stompHandler);

	TaskScheduler scheduler = mock(TaskScheduler.class);
	DefaultSockJsService service = new DefaultSockJsService(scheduler);
	WebSocketServerSockJsSession session = new WebSocketServerSockJsSession("1", service, handler, null);
	SockJsWebSocketHandler sockJsHandler = new SockJsWebSocketHandler(service, handler, session);

	assertEquals(stompHandler.getSupportedProtocols(), sockJsHandler.getSubProtocols());
}
 
Example 24
Source Project: front50   Source File: PluginVersioningConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
PluginVersionCleanupAgent pluginVersionCleanupAgent(
    PluginVersionPinningRepository repository,
    PluginVersionCleanupProperties properties,
    Namer<?> namer,
    TaskScheduler taskScheduler) {
  return new PluginVersionCleanupAgent(repository, properties, namer, taskScheduler);
}
 
Example 25
/**
 * Provide the TaskScheduler to use for SockJS endpoints for which a task
 * scheduler has not been explicitly registered. This method must be called
 * prior to {@link #getHandlerMapping()}.
 */
protected void setTaskScheduler(TaskScheduler scheduler) {
	this.registrations.stream()
			.map(ServletWebSocketHandlerRegistration::getSockJsServiceRegistration)
			.filter(Objects::nonNull)
			.filter(r -> r.getTaskScheduler() == null)
			.forEach(registration -> registration.setTaskScheduler(scheduler));
}
 
Example 26
@Test
public void getSubProtocols() throws Exception {
	SubscribableChannel channel = mock(SubscribableChannel.class);
	SubProtocolWebSocketHandler handler = new SubProtocolWebSocketHandler(channel, channel);
	StompSubProtocolHandler stompHandler = new StompSubProtocolHandler();
	handler.addProtocolHandler(stompHandler);

	TaskScheduler scheduler = mock(TaskScheduler.class);
	DefaultSockJsService service = new DefaultSockJsService(scheduler);
	WebSocketServerSockJsSession session = new WebSocketServerSockJsSession("1", service, handler, null);
	SockJsWebSocketHandler sockJsHandler = new SockJsWebSocketHandler(service, handler, session);

	assertEquals(stompHandler.getSupportedProtocols(), sockJsHandler.getSubProtocols());
}
 
Example 27
@Test
public void getSubProtocolsNone() throws Exception {
	WebSocketHandler handler = new TextWebSocketHandler();
	TaskScheduler scheduler = mock(TaskScheduler.class);
	DefaultSockJsService service = new DefaultSockJsService(scheduler);
	WebSocketServerSockJsSession session = new WebSocketServerSockJsSession("1", service, handler, null);
	SockJsWebSocketHandler sockJsHandler = new SockJsWebSocketHandler(service, handler, session);

	assertNull(sockJsHandler.getSubProtocols());
}
 
Example 28
/**
 * {@inheritDoc}
 * <p>Also automatically sets the {@link #setDefaultHeartbeat defaultHeartbeat}
 * property to "10000,10000" if it is currently set to "0,0".
 */
@Override
public void setTaskScheduler(TaskScheduler taskScheduler) {
	if (taskScheduler != null && !isDefaultHeartbeatEnabled()) {
		setDefaultHeartbeat(new long[] {10000, 10000});
	}
	super.setTaskScheduler(taskScheduler);
}
 
Example 29
Source Project: SpringBootBucket   Source File: HttpClientConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setThreadNamePrefix("poolScheduler");
    scheduler.setPoolSize(50);
    return scheduler;
}
 
Example 30
Source Project: blackduck-alert   Source File: ProcessingTask.java    License: Apache License 2.0 5 votes vote down vote up
public ProcessingTask(TaskScheduler taskScheduler, NotificationManager notificationManager, NotificationProcessor notificationProcessor, ChannelEventManager eventManager, TaskManager taskManager) {
    super(taskScheduler, taskManager);
    this.notificationManager = notificationManager;
    this.notificationProcessor = notificationProcessor;
    this.eventManager = eventManager;
    lastRunTime = DateUtils.createCurrentDateTimestamp();
}