Esempio n. 1
0
 /**
  * Get a task scheduler.
  *
  * @param poolSize The initial size of the thread pool that should be allocated
  * @return The task scheduler
  */
 @Bean
 public TaskScheduler taskScheduler(
     @Value("${genie.tasks.scheduler.pool.size:1}") final int poolSize) {
   final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
   scheduler.setPoolSize(poolSize);
   return scheduler;
 }
 public static ThreadPoolTaskScheduler createTaskScheduler(int poolSize) {
   ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
   scheduler.setPoolSize(poolSize);
   scheduler.setRejectedExecutionHandler(new CallerRunsPolicy());
   scheduler.afterPropertiesSet();
   return scheduler;
 }
Esempio n. 3
0
  @Bean(destroyMethod = "shutdown")
  public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(10);

    return scheduler;
  }
 public static TestApplicationContext createTestApplicationContext() {
   TestApplicationContext context = new TestApplicationContext();
   ErrorHandler errorHandler =
       new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(context));
   ThreadPoolTaskScheduler scheduler = createTaskScheduler(10);
   scheduler.setErrorHandler(errorHandler);
   registerBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, scheduler, context);
   return context;
 }
  @Test
  public void testContainerWithDestNameNoCorrelation() throws Exception {
    BeanFactory beanFactory = mock(BeanFactory.class);
    when(beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME))
        .thenReturn(true);
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    when(beanFactory.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class))
        .thenReturn(scheduler);
    final JmsOutboundGateway gateway = new JmsOutboundGateway();
    gateway.setBeanFactory(beanFactory);
    gateway.setConnectionFactory(getConnectionFactory());
    gateway.setRequestDestination(requestQueue4);
    gateway.setReplyDestinationName("reply4");
    gateway.setUseReplyContainer(true);
    gateway.afterPropertiesSet();
    gateway.start();
    final AtomicReference<Object> reply = new AtomicReference<Object>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    Executors.newSingleThreadExecutor()
        .execute(
            () -> {
              latch1.countDown();
              try {
                reply.set(gateway.handleRequestMessage(new GenericMessage<String>("foo")));
              } finally {
                latch2.countDown();
              }
            });
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    JmsTemplate template = new JmsTemplate();
    template.setConnectionFactory(getConnectionFactory());
    template.setReceiveTimeout(10000);
    javax.jms.Message request = template.receive(requestQueue4);
    assertNotNull(request);
    final javax.jms.Message jmsReply = request;
    template.send(
        request.getJMSReplyTo(),
        (MessageCreator)
            session -> {
              jmsReply.setJMSCorrelationID(jmsReply.getJMSMessageID());
              return jmsReply;
            });
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertNotNull(reply.get());

    gateway.stop();
    scheduler.destroy();
  }
 public void executeCooldown(String nsr_id, String vnfr_id, long cooldown) {
   log.info("[EXECUTOR] START_COOLDOWN " + new Date().getTime());
   if (actionMonitor.isTerminating(vnfr_id)) {
     actionMonitor.finishedAction(vnfr_id, Action.TERMINATED);
     return;
   }
   log.info("Starting CooldownTask for VNFR with id: " + vnfr_id);
   if (actionMonitor.requestAction(vnfr_id, Action.COOLDOWN)) {
     log.debug("Creating new CooldownTask for VNFR with id: " + vnfr_id);
     CooldownTask cooldownTask =
         new CooldownTask(nsr_id, vnfr_id, cooldown, executionEngine, actionMonitor);
     taskScheduler.execute(cooldownTask);
   } else {
     if (actionMonitor.getAction(vnfr_id) == Action.COOLDOWN) {
       log.debug(
           "Waiting already for Cooldown for VNFR with id: "
               + vnfr_id
               + ". Cannot create another ExecutionTask for VNFR with id: "
               + vnfr_id);
     } else if (actionMonitor.getAction(vnfr_id) == Action.SCALE) {
       log.debug("VNFR with id: " + vnfr_id + " is still in Scaling.");
     } else {
       log.debug(actionMonitor.toString());
     }
   }
 }
Esempio n. 7
0
 /** IUNI UC 第三方用户登陆日志文件定时扫描线程 */
 protected void scanOloginLogOnTime() {
   scheduler.scheduleWithFixedDelay(
       new IuniUserOloginLogProcessTask(appCtx), IUNI_UC_OLOGINLOG_SCAN_INTERVAL);
   logger.info(
       "IuniLogDataManager.scanLoginLogOnTime start scheduled task With Fixed Delay, task type: "
           + IuniLogDataConstant.IUNI_UC_OLOGIN_DATA);
 }
  @Test
  public void testLazyContainerWithDest() throws Exception {
    BeanFactory beanFactory = mock(BeanFactory.class);
    when(beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME))
        .thenReturn(true);
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    when(beanFactory.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class))
        .thenReturn(scheduler);
    final JmsOutboundGateway gateway = new JmsOutboundGateway();
    gateway.setBeanFactory(beanFactory);
    gateway.setConnectionFactory(getConnectionFactory());
    gateway.setRequestDestination(requestQueue7);
    gateway.setReplyDestination(replyQueue7);
    gateway.setCorrelationKey("JMSCorrelationID");
    gateway.setUseReplyContainer(true);
    gateway.setIdleReplyContainerTimeout(1, TimeUnit.SECONDS);
    gateway.setRequiresReply(true);
    gateway.setReceiveTimeout(20000);
    gateway.afterPropertiesSet();
    gateway.start();
    Executors.newSingleThreadExecutor()
        .execute(
            () -> {
              JmsTemplate template = new JmsTemplate();
              template.setConnectionFactory(getConnectionFactory());
              template.setReceiveTimeout(20000);
              receiveAndSend(template);
              receiveAndSend(template);
            });

    assertNotNull(gateway.handleRequestMessage(new GenericMessage<String>("foo")));
    DefaultMessageListenerContainer container =
        TestUtils.getPropertyValue(
            gateway, "replyContainer", DefaultMessageListenerContainer.class);
    int n = 0;
    while (n++ < 100 && container.isRunning()) {
      Thread.sleep(100);
    }
    assertFalse(container.isRunning());
    assertNotNull(gateway.handleRequestMessage(new GenericMessage<String>("foo")));
    assertTrue(container.isRunning());

    gateway.stop();
    assertFalse(container.isRunning());
    scheduler.destroy();
  }
 public RabbitTestMessageBus(ConnectionFactory connectionFactory, Codec codec) {
   RabbitMessageBus messageBus = new RabbitMessageBus(connectionFactory, codec);
   GenericApplicationContext context = new GenericApplicationContext();
   ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
   scheduler.setPoolSize(1);
   scheduler.afterPropertiesSet();
   context
       .getBeanFactory()
       .registerSingleton(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, scheduler);
   context.refresh();
   messageBus.setApplicationContext(context);
   messageBus.setLongStringLimit(8193);
   this.setMessageBus(messageBus);
   assertEquals(
       8193,
       TestUtils.getPropertyValue(
           messageBus, "inboundMessagePropertiesConverter.longStringLimit"));
   this.rabbitAdmin = new RabbitAdmin(connectionFactory);
 }
 @ManagedOperation
 public void stopSchedulers() {
   if (logger.isDebugEnabled()) {
     logger.debug("Stopping schedulers " + (this.shutdownForced ? "(force)" : ""));
   }
   List<ExecutorService> executorServices = new ArrayList<ExecutorService>();
   Map<String, ThreadPoolTaskScheduler> schedulers =
       this.applicationContext.getBeansOfType(ThreadPoolTaskScheduler.class);
   for (Entry<String, ThreadPoolTaskScheduler> entry : schedulers.entrySet()) {
     ThreadPoolTaskScheduler scheduler = entry.getValue();
     if (logger.isInfoEnabled()) {
       logger.info("Stopping scheduler " + scheduler.getThreadNamePrefix());
     }
     ExecutorService executorService = scheduler.getScheduledExecutor();
     executorServices.add(executorService);
     doShutdownExecutorService(executorService);
   }
   waitForExecutors(executorServices);
   logger.debug("Stopped schedulers");
 }
  @PostConstruct
  public void setup() {
    _outputQueueResolver = new DNSResolver(getQueueHost());
    final OutputQueueCheckThread outputQueueCheckThread = new OutputQueueCheckThread();
    // every 10 seconds
    _taskScheduler.scheduleWithFixedDelay(outputQueueCheckThread, 10 * 1000);

    if (getPrimaryHostname() != null && getPrimaryHostname().length() > 0) {
      _primaryResolver = new DNSResolver(getPrimaryHostname());
      _log.warn(
          "Primary Inference instance configured to be "
              + getPrimaryHostname()
              + " on "
              + _primaryResolver.getLocalHostString());
      final PrimaryCheckThread primaryCheckThread = new PrimaryCheckThread();
      _taskScheduler.scheduleWithFixedDelay(primaryCheckThread, 10 * 1000);
    }
    _executorService = Executors.newFixedThreadPool(1);
    _heartbeatService = Executors.newFixedThreadPool(1);
    startListenerThread();
  }
 @Override
 public void onApplicationEvent(EurekaRegistryAvailableEvent event) {
   System.out.println("registered");
   y();
   ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
   threadPoolTaskScheduler.initialize();
   threadPoolTaskScheduler.scheduleAtFixedRate(
       () -> {
         PeerAwareInstanceRegistry.getInstance().renew("TESTOPENAM", "openam1", false);
         InstanceInfo s1 =
             PeerAwareInstanceRegistry.getInstance()
                 .getInstanceByAppAndId("SAMPLE-SERVICE", "marek-pc");
         InstanceInfo s2 =
             PeerAwareInstanceRegistry.getInstance()
                 .getInstanceByAppAndId("TESTOPENAM", "openam1");
         String reflectionToString1 = ToStringBuilder.reflectionToString(s1);
         String reflectionToString2 = ToStringBuilder.reflectionToString(s2);
         System.out.println(reflectionToString1);
         System.out.println(reflectionToString2);
       },
       30000);
 }
Esempio n. 13
0
 public static void sendMail(
     final String emailAddr,
     final String mailTitle,
     final String mailContent,
     final String[] fileNames,
     final String[] filePaths) {
   EmailJob job = new EmailJob();
   job.setEmailAddr(emailAddr);
   job.setMailTitle(mailTitle);
   job.setMailContent(mailContent);
   job.setFileNames(fileNames);
   job.setFilePaths(filePaths);
   Calendar calendar = Calendar.getInstance();
   calendar.add(Calendar.SECOND, 1);
   scheduler.schedule(job, calendar.getTime());
 }
 public void executeActions(
     String nsr_id, String vnfr_id, Set<ScalingAction> actions, long cooldown) {
   log.info("[EXECUTOR] RECEIVED_ACTION " + new Date().getTime());
   log.info(
       "Processing execution request of ScalingActions: "
           + actions
           + " for VNFR with id: "
           + vnfr_id);
   if (actionMonitor.requestAction(vnfr_id, Action.SCALE)) {
     log.debug(
         "Creating new ExecutionTask of ScalingActions: "
             + actions
             + " for VNFR with id: "
             + vnfr_id);
     ExecutionTask executionTask =
         new ExecutionTask(nsr_id, vnfr_id, actions, cooldown, executionEngine, actionMonitor);
     taskScheduler.execute(executionTask);
   } else {
     if (actionMonitor.getAction(vnfr_id) == Action.SCALE) {
       log.debug(
           "Processing already an execution request for VNFR with id: "
               + vnfr_id
               + ". Cannot create another ExecutionTask for VNFR with id: "
               + vnfr_id);
     } else if (actionMonitor.getAction(vnfr_id) == Action.COOLDOWN) {
       log.debug(
           "Waiting for Cooldown for VNFR with id: "
               + vnfr_id
               + ". Cannot create another ExecutionTask for VNFR with id: "
               + vnfr_id);
     } else {
       log.warn(
           "Problem while starting ExecutionThread. Internal Status is: "
               + actionMonitor.getAction(vnfr_id));
     }
   }
 }
  public void testObtainConnectionIds(AbstractServerConnectionFactory serverFactory)
      throws Exception {
    final List<IpIntegrationEvent> events =
        Collections.synchronizedList(new ArrayList<IpIntegrationEvent>());
    int expectedEvents =
        serverFactory instanceof TcpNetServerConnectionFactory
            ? 7 // Listening, + OPEN, CLOSE, EXCEPTION for each side
            : 5; // Listening, + OPEN, CLOSE (but we *might* get exceptions, depending on timing).
    final CountDownLatch serverListeningLatch = new CountDownLatch(1);
    final CountDownLatch eventLatch = new CountDownLatch(expectedEvents);
    ApplicationEventPublisher publisher =
        new ApplicationEventPublisher() {

          @Override
          public void publishEvent(ApplicationEvent event) {
            LogFactory.getLog(this.getClass()).trace("Received: " + event);
            events.add((IpIntegrationEvent) event);
            if (event instanceof TcpConnectionServerListeningEvent) {
              serverListeningLatch.countDown();
            }
            eventLatch.countDown();
          }

          @Override
          public void publishEvent(Object event) {}
        };
    serverFactory.setBeanName("serverFactory");
    serverFactory.setApplicationEventPublisher(publisher);
    serverFactory = spy(serverFactory);
    final CountDownLatch serverConnectionInitLatch = new CountDownLatch(1);
    doAnswer(
            invocation -> {
              Object result = invocation.callRealMethod();
              serverConnectionInitLatch.countDown();
              return result;
            })
        .when(serverFactory)
        .wrapConnection(any(TcpConnectionSupport.class));
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(10);
    scheduler.afterPropertiesSet();
    BeanFactory bf = mock(BeanFactory.class);
    when(bf.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    when(bf.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class))
        .thenReturn(scheduler);
    serverFactory.setBeanFactory(bf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setOutputChannel(new NullChannel());
    adapter.setConnectionFactory(serverFactory);
    adapter.start();
    assertTrue("Listening event not received", serverListeningLatch.await(10, TimeUnit.SECONDS));
    assertThat(events.get(0), instanceOf(TcpConnectionServerListeningEvent.class));
    assertThat(
        ((TcpConnectionServerListeningEvent) events.get(0)).getPort(),
        equalTo(serverFactory.getPort()));
    int port = serverFactory.getPort();
    TcpNetClientConnectionFactory clientFactory =
        new TcpNetClientConnectionFactory("localhost", port);
    clientFactory.registerListener(message -> false);
    clientFactory.setBeanName("clientFactory");
    clientFactory.setApplicationEventPublisher(publisher);
    clientFactory.start();
    TcpConnectionSupport client = clientFactory.getConnection();
    List<String> clients = clientFactory.getOpenConnectionIds();
    assertEquals(1, clients.size());
    assertTrue(clients.contains(client.getConnectionId()));
    assertTrue(
        "Server connection failed to register",
        serverConnectionInitLatch.await(1, TimeUnit.SECONDS));
    List<String> servers = serverFactory.getOpenConnectionIds();
    assertEquals(1, servers.size());
    assertTrue(serverFactory.closeConnection(servers.get(0)));
    servers = serverFactory.getOpenConnectionIds();
    assertEquals(0, servers.size());
    int n = 0;
    clients = clientFactory.getOpenConnectionIds();
    while (n++ < 100 && clients.size() > 0) {
      Thread.sleep(100);
      clients = clientFactory.getOpenConnectionIds();
    }
    assertEquals(0, clients.size());
    assertTrue(eventLatch.await(10, TimeUnit.SECONDS));
    assertThat(
        "Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events,
        events.size(),
        greaterThanOrEqualTo(expectedEvents));

    FooEvent event = new FooEvent(client, "foo");
    client.publishEvent(event);
    assertThat(
        "Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events,
        events.size(),
        greaterThanOrEqualTo(expectedEvents + 1));

    try {
      event = new FooEvent(mock(TcpConnectionSupport.class), "foo");
      client.publishEvent(event);
      fail("Expected exception");
    } catch (IllegalArgumentException e) {
      assertTrue("Can only publish events with this as the source".equals(e.getMessage()));
    }

    SocketAddress address = serverFactory.getServerSocketAddress();
    if (address instanceof InetSocketAddress) {
      InetSocketAddress inetAddress = (InetSocketAddress) address;
      assertEquals(port, inetAddress.getPort());
    }
    serverFactory.stop();
    scheduler.shutdown();
  }
  @Test
  public void simpleBroker() {
    loadBeanDefinitions("websocket-config-broker-simple.xml");

    HandlerMapping hm = this.appContext.getBean(HandlerMapping.class);
    assertThat(hm, Matchers.instanceOf(SimpleUrlHandlerMapping.class));
    SimpleUrlHandlerMapping suhm = (SimpleUrlHandlerMapping) hm;
    assertThat(suhm.getUrlMap().keySet(), Matchers.hasSize(4));
    assertThat(suhm.getUrlMap().values(), Matchers.hasSize(4));

    HttpRequestHandler httpRequestHandler = (HttpRequestHandler) suhm.getUrlMap().get("/foo");
    assertNotNull(httpRequestHandler);
    assertThat(httpRequestHandler, Matchers.instanceOf(WebSocketHttpRequestHandler.class));

    WebSocketHttpRequestHandler wsHttpRequestHandler =
        (WebSocketHttpRequestHandler) httpRequestHandler;
    HandshakeHandler handshakeHandler = wsHttpRequestHandler.getHandshakeHandler();
    assertNotNull(handshakeHandler);
    assertTrue(handshakeHandler instanceof TestHandshakeHandler);
    List<HandshakeInterceptor> interceptors = wsHttpRequestHandler.getHandshakeInterceptors();
    assertThat(
        interceptors,
        contains(instanceOf(FooTestInterceptor.class), instanceOf(BarTestInterceptor.class)));

    WebSocketHandler wsHandler = unwrapWebSocketHandler(wsHttpRequestHandler.getWebSocketHandler());
    assertNotNull(wsHandler);
    assertThat(wsHandler, Matchers.instanceOf(SubProtocolWebSocketHandler.class));

    SubProtocolWebSocketHandler subProtocolWsHandler = (SubProtocolWebSocketHandler) wsHandler;
    assertEquals(
        Arrays.asList("v10.stomp", "v11.stomp", "v12.stomp"),
        subProtocolWsHandler.getSubProtocols());
    assertEquals(25 * 1000, subProtocolWsHandler.getSendTimeLimit());
    assertEquals(1024 * 1024, subProtocolWsHandler.getSendBufferSizeLimit());

    StompSubProtocolHandler stompHandler =
        (StompSubProtocolHandler) subProtocolWsHandler.getProtocolHandlerMap().get("v12.stomp");
    assertNotNull(stompHandler);
    assertEquals(128 * 1024, stompHandler.getMessageSizeLimit());

    assertNotNull(new DirectFieldAccessor(stompHandler).getPropertyValue("eventPublisher"));

    httpRequestHandler = (HttpRequestHandler) suhm.getUrlMap().get("/test/**");
    assertNotNull(httpRequestHandler);
    assertThat(httpRequestHandler, Matchers.instanceOf(SockJsHttpRequestHandler.class));

    SockJsHttpRequestHandler sockJsHttpRequestHandler =
        (SockJsHttpRequestHandler) httpRequestHandler;
    wsHandler = unwrapWebSocketHandler(sockJsHttpRequestHandler.getWebSocketHandler());
    assertNotNull(wsHandler);
    assertThat(wsHandler, Matchers.instanceOf(SubProtocolWebSocketHandler.class));
    assertNotNull(sockJsHttpRequestHandler.getSockJsService());
    assertThat(
        sockJsHttpRequestHandler.getSockJsService(),
        Matchers.instanceOf(DefaultSockJsService.class));

    DefaultSockJsService defaultSockJsService =
        (DefaultSockJsService) sockJsHttpRequestHandler.getSockJsService();
    WebSocketTransportHandler wsTransportHandler =
        (WebSocketTransportHandler)
            defaultSockJsService.getTransportHandlers().get(TransportType.WEBSOCKET);
    assertNotNull(wsTransportHandler.getHandshakeHandler());
    assertThat(
        wsTransportHandler.getHandshakeHandler(), Matchers.instanceOf(TestHandshakeHandler.class));

    ThreadPoolTaskScheduler scheduler =
        (ThreadPoolTaskScheduler) defaultSockJsService.getTaskScheduler();
    assertEquals(
        Runtime.getRuntime().availableProcessors(),
        scheduler.getScheduledThreadPoolExecutor().getCorePoolSize());
    assertTrue(scheduler.getScheduledThreadPoolExecutor().getRemoveOnCancelPolicy());

    interceptors = defaultSockJsService.getHandshakeInterceptors();
    assertThat(
        interceptors,
        contains(instanceOf(FooTestInterceptor.class), instanceOf(BarTestInterceptor.class)));

    UserSessionRegistry userSessionRegistry = this.appContext.getBean(UserSessionRegistry.class);
    assertNotNull(userSessionRegistry);

    UserDestinationResolver userDestResolver =
        this.appContext.getBean(UserDestinationResolver.class);
    assertNotNull(userDestResolver);
    assertThat(userDestResolver, Matchers.instanceOf(DefaultUserDestinationResolver.class));
    DefaultUserDestinationResolver defaultUserDestResolver =
        (DefaultUserDestinationResolver) userDestResolver;
    assertEquals("/personal/", defaultUserDestResolver.getDestinationPrefix());
    assertSame(
        stompHandler.getUserSessionRegistry(), defaultUserDestResolver.getUserSessionRegistry());

    UserDestinationMessageHandler userDestHandler =
        this.appContext.getBean(UserDestinationMessageHandler.class);
    assertNotNull(userDestHandler);

    SimpleBrokerMessageHandler brokerMessageHandler =
        this.appContext.getBean(SimpleBrokerMessageHandler.class);
    assertNotNull(brokerMessageHandler);
    assertEquals(
        Arrays.asList("/topic", "/queue"),
        new ArrayList<String>(brokerMessageHandler.getDestinationPrefixes()));

    List<Class<? extends MessageHandler>> subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(
            SimpAnnotationMethodMessageHandler.class,
            UserDestinationMessageHandler.class,
            SimpleBrokerMessageHandler.class);
    testChannel("clientInboundChannel", subscriberTypes, 0);
    testExecutor(
        "clientInboundChannel",
        Runtime.getRuntime().availableProcessors() * 2,
        Integer.MAX_VALUE,
        60);

    subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(SubProtocolWebSocketHandler.class);
    testChannel("clientOutboundChannel", subscriberTypes, 0);
    testExecutor(
        "clientOutboundChannel",
        Runtime.getRuntime().availableProcessors() * 2,
        Integer.MAX_VALUE,
        60);

    subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(
            SimpleBrokerMessageHandler.class, UserDestinationMessageHandler.class);
    testChannel("brokerChannel", subscriberTypes, 0);
    try {
      this.appContext.getBean("brokerChannelExecutor", ThreadPoolTaskExecutor.class);
      fail("expected exception");
    } catch (NoSuchBeanDefinitionException ex) {
      // expected
    }

    assertNotNull(this.appContext.getBean("webSocketScopeConfigurer", CustomScopeConfigurer.class));

    DirectFieldAccessor subscriptionRegistryAccessor =
        new DirectFieldAccessor(brokerMessageHandler.getSubscriptionRegistry());
    String pathSeparator =
        (String)
            new DirectFieldAccessor(subscriptionRegistryAccessor.getPropertyValue("pathMatcher"))
                .getPropertyValue("pathSeparator");
    assertEquals(".", pathSeparator);
  }
Esempio n. 17
0
 public void onApplicationEvent(ContextClosedEvent event) {
   System.out.println("==================Spring Context is shutting down==============");
   scheduler.shutdown();
   executor.shutdown();
 }
  @Test
  @RedisAvailable
  public void testDelayerHandlerRescheduleWithRedisMessageStore() throws Exception {
    AbstractApplicationContext context =
        new ClassPathXmlApplicationContext(
            "DelayerHandlerRescheduleIntegrationTests-context.xml", this.getClass());
    MessageChannel input = context.getBean("input", MessageChannel.class);
    MessageGroupStore messageStore = context.getBean("messageStore", MessageGroupStore.class);

    String delayerMessageGroupId = DELAYER_ID + ".messageGroupId";

    messageStore.removeMessageGroup(delayerMessageGroupId);

    Message<String> message1 = MessageBuilder.withPayload("test1").build();
    input.send(message1);
    input.send(MessageBuilder.withPayload("test2").build());

    // Emulate restart and check DB state before next start
    // Interrupt taskScheduler as quickly as possible
    ThreadPoolTaskScheduler taskScheduler =
        (ThreadPoolTaskScheduler) IntegrationContextUtils.getTaskScheduler(context);
    taskScheduler.shutdown();
    taskScheduler.getScheduledExecutor().awaitTermination(10, TimeUnit.SECONDS);
    context.destroy();

    try {
      context.getBean("input", MessageChannel.class);
      fail("IllegalStateException expected");
    } catch (Exception e) {
      assertTrue(e instanceof IllegalStateException);
      assertTrue(
          e.getMessage()
              .contains("BeanFactory not initialized or already closed - call 'refresh'"));
    }

    assertEquals(1, messageStore.getMessageGroupCount());
    assertEquals(delayerMessageGroupId, messageStore.iterator().next().getGroupId());
    assertEquals(2, messageStore.messageGroupSize(delayerMessageGroupId));
    assertEquals(2, messageStore.getMessageCountForAllMessageGroups());
    MessageGroup messageGroup = messageStore.getMessageGroup(delayerMessageGroupId);
    Message<?> messageInStore = messageGroup.getMessages().iterator().next();
    Object payload = messageInStore.getPayload();

    // INT-3049
    assertTrue(payload instanceof DelayHandler.DelayedMessageWrapper);
    assertEquals(message1, ((DelayHandler.DelayedMessageWrapper) payload).getOriginal());

    context.refresh();

    PollableChannel output = context.getBean("output", PollableChannel.class);

    Message<?> message = output.receive(20000);
    assertNotNull(message);

    Object payload1 = message.getPayload();

    message = output.receive(20000);
    assertNotNull(message);
    Object payload2 = message.getPayload();
    assertNotSame(payload1, payload2);

    assertEquals(1, messageStore.getMessageGroupCount());
    assertEquals(0, messageStore.messageGroupSize(delayerMessageGroupId));

    messageStore.removeMessageGroup(delayerMessageGroupId);
  }
 @Bean
 public ThreadPoolTaskScheduler sockJsTaskScheduler() {
   ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
   taskScheduler.setThreadNamePrefix("SockJS-");
   return taskScheduler;
 }
  @Test
  public void testReplyContainerRecovery() throws Exception {
    JmsOutboundGateway gateway = new JmsOutboundGateway();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestDestinationName("foo");
    gateway.setUseReplyContainer(true);
    ReplyContainerProperties replyContainerProperties = new ReplyContainerProperties();
    final List<Throwable> errors = new ArrayList<Throwable>();
    ErrorHandlingTaskExecutor errorHandlingTaskExecutor =
        new ErrorHandlingTaskExecutor(
            Executors.newFixedThreadPool(10),
            new ErrorHandler() {

              @Override
              public void handleError(Throwable t) {
                logger.info("Error:", t);
                errors.add(t);
                throw new RuntimeException(t);
              }
            });
    replyContainerProperties.setTaskExecutor(errorHandlingTaskExecutor);
    replyContainerProperties.setRecoveryInterval(100L);
    gateway.setReplyContainerProperties(replyContainerProperties);
    final Connection connection = mock(Connection.class);
    final AtomicInteger connectionAttempts = new AtomicInteger();
    doAnswer(
            new Answer<Connection>() {

              @SuppressWarnings("serial")
              @Override
              public Connection answer(InvocationOnMock invocation) throws Throwable {
                int theCount = connectionAttempts.incrementAndGet();
                if (theCount > 1 && theCount < 4) {
                  throw new JmsException("bar") {};
                }
                return connection;
              }
            })
        .when(connectionFactory)
        .createConnection();
    Session session = mock(Session.class);
    when(connection.createSession(false, 1)).thenReturn(session);
    MessageConsumer consumer = mock(MessageConsumer.class);
    when(session.createConsumer(any(Destination.class), anyString())).thenReturn(consumer);
    when(session.createTemporaryQueue()).thenReturn(mock(TemporaryQueue.class));
    final Message message = mock(Message.class);
    final AtomicInteger count = new AtomicInteger();
    doAnswer(
            new Answer<Message>() {

              @SuppressWarnings("serial")
              @Override
              public Message answer(InvocationOnMock invocation) throws Throwable {
                int theCount = count.incrementAndGet();
                if (theCount > 1 && theCount < 4) {
                  throw new JmsException("foo") {};
                }
                if (theCount > 4) {
                  Thread.sleep(100);
                  return null;
                }
                return message;
              }
            })
        .when(consumer)
        .receive(anyLong());
    when(message.getJMSCorrelationID()).thenReturn("foo");
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    beanFactory.registerSingleton("taskScheduler", taskScheduler);
    gateway.setBeanFactory(beanFactory);
    gateway.afterPropertiesSet();
    gateway.start();
    try {
      int n = 0;
      while (n++ < 100 && count.get() < 5) {
        Thread.sleep(100);
      }
      assertTrue(count.get() > 4);
      assertEquals(0, errors.size());
    } finally {
      gateway.stop();
    }
  }
  public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
      host = args[0];
    }

    int port = 37232;
    if (args.length > 1) {
      port = Integer.valueOf(args[1]);
    }

    String homeUrl = "http://{host}:{port}/home";
    logger.debug("Sending warm-up HTTP request to " + homeUrl);
    HttpStatus status =
        new RestTemplate().getForEntity(homeUrl, Void.class, host, port).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StandardWebSocketClient webSocketClient = new StandardWebSocketClient();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
      ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
      taskScheduler.afterPropertiesSet();

      String stompUrl = "ws://{host}:{port}/stomp";
      WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
      stompClient.setMessageConverter(new StringMessageConverter());
      stompClient.setTaskScheduler(taskScheduler);
      stompClient.setDefaultHeartbeat(new long[] {0, 0});

      logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
      StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
      stopWatch.start();

      List<ConsumerStompSessionHandler> consumers = new ArrayList<>();
      for (int i = 0; i < NUMBER_OF_USERS; i++) {
        consumers.add(
            new ConsumerStompSessionHandler(
                BROADCAST_MESSAGE_COUNT,
                connectLatch,
                subscribeLatch,
                messageLatch,
                disconnectLatch,
                failure));
        stompClient.connect(stompUrl, consumers.get(i), host, port);
      }

      if (failure.get() != null) {
        throw new AssertionError("Test failed", failure.get());
      }
      if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all users connected, remaining: " + connectLatch.getCount());
      }
      if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all users subscribed, remaining: " + subscribeLatch.getCount());
      }

      stopWatch.stop();
      logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

      logger.debug(
          "Broadcasting "
              + BROADCAST_MESSAGE_COUNT
              + " messages to "
              + NUMBER_OF_USERS
              + " users ");
      stopWatch.start();

      ProducerStompSessionHandler producer =
          new ProducerStompSessionHandler(BROADCAST_MESSAGE_COUNT, failure);
      stompClient.connect(stompUrl, producer, host, port);
      stompClient.setTaskScheduler(taskScheduler);

      if (failure.get() != null) {
        throw new AssertionError("Test failed", failure.get());
      }
      if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
        for (ConsumerStompSessionHandler consumer : consumers) {
          if (consumer.messageCount.get() < consumer.expectedMessageCount) {
            logger.debug(consumer);
          }
        }
      }
      if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
        fail("Not all handlers received every message, remaining: " + messageLatch.getCount());
      }

      producer.session.disconnect();
      if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
      }

      stopWatch.stop();
      logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

      System.out.println("\nPress any key to exit...");
      System.in.read();
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
      jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
  }