Example usage for org.springframework.context Lifecycle isRunning

List of usage examples for org.springframework.context Lifecycle isRunning

Introduction

In this page you can find the example usage for org.springframework.context Lifecycle isRunning.

Prototype

boolean isRunning();

Source Link

Document

Check whether this component is currently running.

Usage

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testConsumerProperties() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    properties.getExtension().setRequeueRejected(true);
    properties.getExtension().setTransacted(true);
    properties.getExtension().setExclusive(true);
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("props.0", null,
            createBindableChannel("input", new BindingProperties()), properties);
    Lifecycle endpoint = extractEndpoint(consumerBinding);
    SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer",
            SimpleMessageListenerContainer.class);
    assertThat(container.getAcknowledgeMode()).isEqualTo(AcknowledgeMode.AUTO);
    assertThat(container.getQueueNames()[0]).startsWith(properties.getExtension().getPrefix());
    assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)).isTrue();
    assertThat(TestUtils.getPropertyValue(container, "exclusive", Boolean.class)).isTrue();
    assertThat(TestUtils.getPropertyValue(container, "concurrentConsumers")).isEqualTo(1);
    assertThat(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")).isNull();
    assertThat(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class)).isTrue();
    assertThat(TestUtils.getPropertyValue(container, "prefetchCount")).isEqualTo(1);
    assertThat(TestUtils.getPropertyValue(container, "txSize")).isEqualTo(1);
    RetryTemplate retry = TestUtils.getPropertyValue(endpoint, "retryTemplate", RetryTemplate.class);
    assertThat(TestUtils.getPropertyValue(retry, "retryPolicy.maxAttempts")).isEqualTo(3);
    assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.initialInterval")).isEqualTo(1000L);
    assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.maxInterval")).isEqualTo(10000L);
    assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.multiplier")).isEqualTo(2.0);
    consumerBinding.unbind();//w ww . j  av a  2 s  .co  m
    assertThat(endpoint.isRunning()).isFalse();

    properties = createConsumerProperties();
    properties.getExtension().setAcknowledgeMode(AcknowledgeMode.NONE);
    properties.setBackOffInitialInterval(2000);
    properties.setBackOffMaxInterval(20000);
    properties.setBackOffMultiplier(5.0);
    properties.setConcurrency(2);
    properties.setMaxAttempts(23);
    properties.getExtension().setMaxConcurrency(3);
    properties.getExtension().setPrefix("foo.");
    properties.getExtension().setPrefetch(20);
    properties.getExtension().setHeaderPatterns(new String[] { "foo" });
    properties.getExtension().setTxSize(10);
    properties.setInstanceIndex(0);
    consumerBinding = binder.bindConsumer("props.0", "test",
            createBindableChannel("input", new BindingProperties()), properties);

    endpoint = extractEndpoint(consumerBinding);
    container = verifyContainer(endpoint);

    assertThat(container.getQueueNames()[0]).isEqualTo("foo.props.0.test");

    consumerBinding.unbind();
    assertThat(endpoint.isRunning()).isFalse();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testProducerProperties() throws Exception {
    RabbitTestBinder binder = getBinder();
    Binding<MessageChannel> producerBinding = binder.bindProducer("props.0",
            createBindableChannel("input", new BindingProperties()), createProducerProperties());
    Lifecycle endpoint = extractEndpoint(producerBinding);
    MessageDeliveryMode mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode",
            MessageDeliveryMode.class);
    assertThat(mode).isEqualTo(MessageDeliveryMode.PERSISTENT);
    List<?> requestHeaders = TestUtils.getPropertyValue(endpoint, "headerMapper.requestHeaderMatcher.matchers",
            List.class);
    assertThat(requestHeaders).hasSize(2);
    producerBinding.unbind();//from  www.j  a va2 s .c om
    assertThat(endpoint.isRunning()).isFalse();
    assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)).isFalse();

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("foo.");
    producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
    producerProperties.getExtension().setHeaderPatterns(new String[] { "foo" });
    producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("'foo'"));
    producerProperties.setPartitionKeyExtractorClass(TestPartitionKeyExtractorClass.class);
    producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("0"));
    producerProperties.setPartitionSelectorClass(TestPartitionSelectorClass.class);
    producerProperties.setPartitionCount(1);
    producerProperties.getExtension().setTransacted(true);
    producerProperties.getExtension().setDelayExpression("42");
    producerProperties.setRequiredGroups("prodPropsRequired");

    BindingProperties producerBindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel channel = createBindableChannel("output", producerBindingProperties);
    producerBinding = binder.bindProducer("props.0", channel, producerProperties);
    endpoint = extractEndpoint(producerBinding);
    assertThat(getEndpointRouting(endpoint))
            .isEqualTo("'props.0-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
    assertThat(
            TestUtils.getPropertyValue(endpoint, "delayExpression", SpelExpression.class).getExpressionString())
                    .isEqualTo("42");
    mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode", MessageDeliveryMode.class);
    assertThat(mode).isEqualTo(MessageDeliveryMode.NON_PERSISTENT);
    assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)).isTrue();
    verifyFooRequestProducer(endpoint);
    channel.send(new GenericMessage<>("foo"));
    org.springframework.amqp.core.Message received = new RabbitTemplate(this.rabbitAvailableRule.getResource())
            .receive("foo.props.0.prodPropsRequired-0", 10_000);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedDelay()).isEqualTo(42);

    producerBinding.unbind();
    assertThat(endpoint.isRunning()).isFalse();
}

From source file:org.springframework.context.support.DefaultLifecycleProcessor.java

/**
 * Start the specified bean as part of the given set of Lifecycle beans,
 * making sure that any beans that it depends on are started first.
 * @param lifecycleBeans Map with bean name as key and Lifecycle instance as value
 * @param beanName the name of the bean to start
 *//*w  ww.  j a  va  2s.c om*/
private void doStart(Map<String, ? extends Lifecycle> lifecycleBeans, String beanName,
        boolean autoStartupOnly) {
    Lifecycle bean = lifecycleBeans.remove(beanName);
    if (bean != null && !this.equals(bean)) {
        String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName);
        for (String dependency : dependenciesForBean) {
            doStart(lifecycleBeans, dependency, autoStartupOnly);
        }
        if (!bean.isRunning() && (!autoStartupOnly || !(bean instanceof SmartLifecycle)
                || ((SmartLifecycle) bean).isAutoStartup())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Starting bean '" + beanName + "' of type [" + bean.getClass() + "]");
            }
            try {
                bean.start();
            } catch (Throwable ex) {
                throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Successfully started bean '" + beanName + "'");
            }
        }
    }
}

From source file:org.springframework.context.support.DefaultLifecycleProcessor.java

/**
 * Stop the specified bean as part of the given set of Lifecycle beans,
 * making sure that any beans that depends on it are stopped first.
 * @param lifecycleBeans Map with bean name as key and Lifecycle instance as value
 * @param beanName the name of the bean to stop
 *///w w  w.ja  v a 2  s.c o  m
private void doStop(Map<String, ? extends Lifecycle> lifecycleBeans, final String beanName,
        final CountDownLatch latch, final Set<String> countDownBeanNames) {

    Lifecycle bean = lifecycleBeans.remove(beanName);
    if (bean != null) {
        String[] dependentBeans = getBeanFactory().getDependentBeans(beanName);
        for (String dependentBean : dependentBeans) {
            doStop(lifecycleBeans, dependentBean, latch, countDownBeanNames);
        }
        try {
            if (bean.isRunning()) {
                if (bean instanceof SmartLifecycle) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "Asking bean '" + beanName + "' of type [" + bean.getClass() + "] to stop");
                    }
                    countDownBeanNames.add(beanName);
                    ((SmartLifecycle) bean).stop(() -> {
                        latch.countDown();
                        countDownBeanNames.remove(beanName);
                        if (logger.isDebugEnabled()) {
                            logger.debug("Bean '" + beanName + "' completed its stop procedure");
                        }
                    });
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Stopping bean '" + beanName + "' of type [" + bean.getClass() + "]");
                    }
                    bean.stop();
                    if (logger.isDebugEnabled()) {
                        logger.debug("Successfully stopped bean '" + beanName + "'");
                    }
                }
            } else if (bean instanceof SmartLifecycle) {
                // don't wait for beans that aren't running
                latch.countDown();
            }
        } catch (Throwable ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to stop bean '" + beanName + "'", ex);
            }
        }
    }
}

From source file:org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.java

public void start() {
    for (Lifecycle lifecycle : this.lifecycles) {
        if (!lifecycle.isRunning()) {
            lifecycle.start();//from   ww w .j  a  v  a  2  s.  co  m
        }
    }
    this.running = true;
}

From source file:org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.java

public void stop() {
    for (Lifecycle lifecycle : this.lifecycles) {
        if (lifecycle.isRunning()) {
            lifecycle.stop();//from www . ja  v a 2  s  .c o  m
        }
    }
    this.running = false;
}

From source file:org.springframework.statemachine.processor.StateMachineAnnotationPostProcessor.java

@Override
public void start() {
    for (Lifecycle lifecycle : this.lifecycles) {
        if (!lifecycle.isRunning()) {
            lifecycle.start();/*from  ww w.  ja  va  2  s.  c  o  m*/
        }
    }
    this.running = true;
}

From source file:org.springframework.statemachine.processor.StateMachineAnnotationPostProcessor.java

@Override
public void stop() {
    for (Lifecycle lifecycle : this.lifecycles) {
        if (lifecycle.isRunning()) {
            lifecycle.stop();//from   w ww. j ava  2 s .c om
        }
    }
    this.running = false;
}