Example usage for org.springframework.context ConfigurableApplicationContext close

List of usage examples for org.springframework.context ConfigurableApplicationContext close

Introduction

In this page you can find the example usage for org.springframework.context ConfigurableApplicationContext close.

Prototype

@Override
void close();

Source Link

Document

Close this application context, releasing all resources and locks that the implementation might hold.

Usage

From source file:org.openspaces.pu.container.jee.jetty.JettyProcessingUnitContainer.java

/**
 * Closes the processing unit container by destroying the web application and the Spring
 * application context./*from   w  w  w . ja va2  s  .  c  om*/
 */
@Override
public void close() throws CannotCloseContainerException {

    for (FreePortGenerator.PortHandle portHandle : portHandels) {
        portHandle.release();
    }
    portHandels.clear();

    if (webAppContext.isRunning()) {
        try {
            webAppContext.stop();
            webAppContext.destroy();
        } catch (Exception e) {
            logger.warn("Failed to stop/destroy web context", e);
        } finally {
            webAppContext.setClassLoader(null);
        }

        if (contextHandlerCollection != null) {
            contextHandlerCollection.removeHandler(webAppContext);
        }
    }

    // close the application context anyhow (it might be closed by the webapp context, but it
    // might not if it is not a pure Spring application).
    ConfigurableApplicationContext confAppContext = (ConfigurableApplicationContext) applicationContext;
    confAppContext.close();

    try {
        jettyHolder.stop();
    } catch (Exception e) {
        logger.warn("Failed to stop jetty server", e);
    }

    super.close();
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdminTests.java

@Test
public void testMultiEntities() {
    ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    template.convertAndSend("e1", "k1", "foo");
    template.convertAndSend("e2", "k2", "bar");
    template.convertAndSend("e3", "k3", "baz");
    template.convertAndSend("e4", "k4", "qux");
    assertEquals("foo", template.receiveAndConvert("q1"));
    assertEquals("bar", template.receiveAndConvert("q2"));
    assertEquals("baz", template.receiveAndConvert("q3"));
    assertEquals("qux", template.receiveAndConvert("q4"));
    RabbitAdmin admin = ctx.getBean(RabbitAdmin.class);
    admin.deleteQueue("q1");
    admin.deleteQueue("q2");
    admin.deleteQueue("q3");
    admin.deleteQueue("q4");
    admin.deleteExchange("e1");
    admin.deleteExchange("e2");
    admin.deleteExchange("e3");
    admin.deleteExchange("e4");
    assertNull(admin.getQueueProperties(ctx.getBean(Config.class).protypeQueueName));
    ctx.close();
}

From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java

@SuppressWarnings("rawtypes")
@Test/* w  ww.j  ava 2 s .c  o  m*/
public void testWithNoId() throws Exception {
    // 2 messages; each retried once by missing id interceptor
    this.latch = new CountDownLatch(4);
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml",
            this.getClass());
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setStatefulRetryFatalWithNullMessageId(false);
    container.setMessageListener(new MessageListenerAdapter(new POJO()));
    container.setQueueNames("retry.test.queue");

    StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean();

    // use an external template so we can share his cache
    RetryTemplate retryTemplate = new RetryTemplate();
    RetryContextCache cache = spy(new MapRetryContextCache());
    retryTemplate.setRetryContextCache(cache);
    fb.setRetryOperations(retryTemplate);

    Advice retryInterceptor = fb.getObject();
    container.setAdviceChain(retryInterceptor);
    container.start();

    template.convertAndSend("retry.test.exchange", "retry.test.binding", "Hello, world!");
    template.convertAndSend("retry.test.exchange", "retry.test.binding", "Hello, world!");
    try {
        assertTrue(latch.await(30, TimeUnit.SECONDS));
        Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map");
        int n = 0;
        while (n++ < 100 && map.size() != 0) {
            Thread.sleep(100);
        }
        verify(cache, never()).put(any(), any(RetryContext.class));
        verify(cache, never()).remove(any());
        assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size());
    } finally {
        container.stop();
        ctx.close();
    }
}

From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java

@SuppressWarnings("rawtypes")
@Test//from  ww  w . ja v  a 2s. c  om
public void testWithId() throws Exception {
    // 2 messages; each retried twice by retry interceptor
    this.latch = new CountDownLatch(6);
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml",
            this.getClass());
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setMessageListener(new MessageListenerAdapter(new POJO()));
    container.setQueueNames("retry.test.queue");

    StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean();

    // use an external template so we can share his cache
    RetryTemplate retryTemplate = new RetryTemplate();
    RetryContextCache cache = spy(new MapRetryContextCache());
    retryTemplate.setRetryContextCache(cache);
    fb.setRetryOperations(retryTemplate);
    fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer());

    Advice retryInterceptor = fb.getObject();
    container.setAdviceChain(retryInterceptor);
    container.start();

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("text/plain");
    messageProperties.setMessageId("foo");
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    template.send("retry.test.exchange", "retry.test.binding", message);
    template.send("retry.test.exchange", "retry.test.binding", message);
    try {
        assertTrue(latch.await(30, TimeUnit.SECONDS));
        Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map");
        int n = 0;
        while (n++ < 100 && map.size() != 0) {
            Thread.sleep(100);
        }
        ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class);
        verify(cache, times(6)).put(putCaptor.capture(), any(RetryContext.class));
        verify(cache, times(6)).get(getCaptor.capture());
        verify(cache, atLeast(2)).remove(removeCaptor.capture());
        verify(cache, atMost(4)).remove(removeCaptor.capture());
        logger.debug("puts:" + putCaptor.getAllValues());
        logger.debug("gets:" + putCaptor.getAllValues());
        logger.debug("removes:" + removeCaptor.getAllValues());
        assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size());
    } finally {
        container.stop();
        ctx.close();
    }
}

From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java

@SuppressWarnings("rawtypes")
@Test/*from   w  ww. jav  a 2s  .  c om*/
public void testWithIdAndSuccess() throws Exception {
    // 2 messages; each retried twice by retry interceptor
    this.latch = new CountDownLatch(6);
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml",
            this.getClass());
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    final Set<String> processed = new HashSet<>();
    final CountDownLatch latch = new CountDownLatch(4);
    container.setMessageListener(m -> {
        latch.countDown();
        if (!processed.contains(m.getMessageProperties().getMessageId())) {
            processed.add(m.getMessageProperties().getMessageId());
            throw new RuntimeException("fail");
        }
    });
    container.setQueueNames("retry.test.queue");

    StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean();

    // use an external template so we can share his cache
    RetryTemplate retryTemplate = new RetryTemplate();
    RetryContextCache cache = spy(new MapRetryContextCache());
    retryTemplate.setRetryContextCache(cache);
    fb.setRetryOperations(retryTemplate);
    fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer());

    Advice retryInterceptor = fb.getObject();
    container.setAdviceChain(retryInterceptor);
    container.start();

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("text/plain");
    messageProperties.setMessageId("foo");
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    template.send("retry.test.exchange", "retry.test.binding", message);
    messageProperties.setMessageId("bar");
    template.send("retry.test.exchange", "retry.test.binding", message);
    try {
        assertTrue(latch.await(30, TimeUnit.SECONDS));
        Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map");
        int n = 0;
        while (n++ < 100 && map.size() != 0) {
            Thread.sleep(100);
        }
        ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class);
        verify(cache, times(2)).put(putCaptor.capture(), any(RetryContext.class));
        verify(cache, times(2)).get(getCaptor.capture());
        verify(cache, atLeast(2)).remove(removeCaptor.capture());
        verify(cache, atMost(4)).remove(removeCaptor.capture());
        logger.debug("puts:" + putCaptor.getAllValues());
        logger.debug("gets:" + putCaptor.getAllValues());
        logger.debug("removes:" + removeCaptor.getAllValues());
        assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size());
    } finally {
        container.stop();
        ctx.close();
    }
}

From source file:org.springframework.amqp.samples.log4j2.SpringBootAmqpAppenderApplication.java

public static void main(String[] args) throws IOException {
    ConfigurableApplicationContext ctx = SpringApplication.run(SpringBootAmqpAppenderApplication.class, args);
    System.out.println("Hit 'Enter' to terminate");
    System.in.read();/*  w  w w  .  j av a 2s.  co  m*/
    ctx.close();
}

From source file:org.springframework.batch.core.configuration.support.DefaultJobLoader.java

/**
 * Unregister all the jobs and close all the contexts created by this
 * loader./*from   w ww.  j a  va2 s. c  om*/
 *
 * @see JobLoader#clear()
 */
@Override
public void clear() {
    for (ConfigurableApplicationContext context : contexts.values()) {
        if (context.isActive()) {
            context.close();
        }
    }
    for (String jobName : jobRegistry.getJobNames()) {
        doUnregister(jobName);
    }
    contexts.clear();
    contextToJobNames.clear();
}

From source file:org.springframework.batch.core.configuration.support.DefaultJobLoader.java

@Override
public Collection<Job> reload(ApplicationContextFactory factory) {

    // If the same factory is loaded twice the context can be closed
    if (contexts.containsKey(factory)) {
        ConfigurableApplicationContext context = contexts.get(factory);
        for (String name : contextToJobNames.get(context)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Unregistering job: " + name + " from context: " + context.getDisplayName());
            }/*from www .j  a v  a 2  s. c  o m*/
            doUnregister(name);
        }
        context.close();
    }

    try {
        return doLoad(factory, true);
    } catch (DuplicateJobException e) {
        throw new IllegalStateException("Found duplicate job in reload (it should have been unregistered "
                + "if it was previously registered in this loader)", e);
    }
}

From source file:org.springframework.batch.core.launch.support.CommandLineJobRunner.java

@SuppressWarnings("resource")
int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {/*  www  .  j  a v  a2  s.com*/
        try {
            context = new AnnotationConfigApplicationContext(Class.forName(jobPath));
        } catch (ClassNotFoundException cnfe) {
            context = new ClassPathXmlApplicationContext(jobPath);
        }

        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        String jobName = jobIdentifier;

        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job = null;
        if (jobLocator != null) {
            try {
                job = jobLocator.getJob(jobName);
            } catch (NoSuchJobException e) {
            }
        }
        if (job == null) {
            job = (Job) context.getBean(jobName);
        }

        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        JobExecution jobExecution = launcher.run(job, jobParameters);
        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());

    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        CommandLineJobRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:org.springframework.boot.SpringApplication.java

/**
 * Run the Spring application, creating and refreshing a new
 * {@link ApplicationContext}./*from ww w. ja va  2s. co m*/
 * @param args the application arguments (usually passed from a Java main method)
 * @return a running {@link ApplicationContext}
 */
public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    configureHeadlessProperty();
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.started();
    try {
        context = doRun(listeners, args);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        return context;
    } catch (Throwable ex) {
        try {
            listeners.finished(context, ex);
            this.log.error("Application startup failed", ex);
        } finally {
            if (context != null) {
                context.close();
            }
        }
        ReflectionUtils.rethrowRuntimeException(ex);
        return context;
    }
}