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.springframework.integration.samples.fileprocessing.FileProcessingTest.java

@Test
public void testConcurrentFileProcessing() throws Exception {
    logger.info("\n\n#### Starting Concurrent processing test #### ");
    logger.info("Populating directory with files");
    for (int i = 0; i < fileCount; i++) {
        File file = new File("input/file_" + i + ".txt");
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write("hello " + i);
        out.close();/*from   ww  w  . ja  v  a 2 s .  com*/
    }
    logger.info("Populated directory with files");
    Thread.sleep(2000);
    logger.info("Starting Spring Integration Sequential File processing");
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "/META-INF/spring/integration/concurrentFileProcessing-config.xml");
    PollableChannel filesOutChannel = ac.getBean("filesOutChannel", PollableChannel.class);
    for (int i = 0; i < fileCount; i++) {
        logger.info("Finished processing " + filesOutChannel.receive(10000).getPayload());
    }
    ac.close();
}

From source file:org.springframework.integration.samples.ftp.FtpOutboundChannelAdapterSample.java

@Test
public void runDemo() throws Exception {

    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
            "META-INF/spring/integration/FtpOutboundChannelAdapterSample-context.xml");

    MessageChannel ftpChannel = ctx.getBean("ftpChannel", MessageChannel.class);

    baseFolder.mkdirs();/*from w  w w  . jav  a2s. c  o  m*/

    final File fileToSendA = new File(baseFolder, "a.txt");
    final File fileToSendB = new File(baseFolder, "b.txt");

    final InputStream inputStreamA = FtpOutboundChannelAdapterSample.class
            .getResourceAsStream("/test-files/a.txt");
    final InputStream inputStreamB = FtpOutboundChannelAdapterSample.class
            .getResourceAsStream("/test-files/b.txt");

    FileUtils.copyInputStreamToFile(inputStreamA, fileToSendA);
    FileUtils.copyInputStreamToFile(inputStreamB, fileToSendB);

    assertTrue(fileToSendA.exists());
    assertTrue(fileToSendB.exists());

    final Message<File> messageA = MessageBuilder.withPayload(fileToSendA).build();
    final Message<File> messageB = MessageBuilder.withPayload(fileToSendB).build();

    ftpChannel.send(messageA);
    ftpChannel.send(messageB);

    Thread.sleep(2000);

    assertTrue(new File(TestSuite.FTP_ROOT_DIR + File.separator + "a.txt").exists());
    assertTrue(new File(TestSuite.FTP_ROOT_DIR + File.separator + "b.txt").exists());

    LOGGER.info("Successfully transfered file 'a.txt' and 'b.txt' to a remote FTP location.");
    ctx.close();
}

From source file:org.springframework.integration.samples.http.HttpClientDemo.java

public static void main(String[] args) {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "/META-INF/spring/integration/http-outbound-config.xml");
    RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class);
    String reply = requestGateway.echo("Hello");
    logger.info("\n\n++++++++++++ Replied with: " + reply + " ++++++++++++\n");
    context.close();
}

From source file:org.springframework.integration.samples.loanbroker.demo.LoanBrokerSharkDetectorDemo.java

public static void main(String[] args) {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "META-INF/spring/integration/bootstrap-config/stubbed-loan-broker-multicast.xml");
    LoanBrokerGateway broker = context.getBean("loanBrokerGateway", LoanBrokerGateway.class);
    LoanRequest loanRequest = new LoanRequest();
    loanRequest.setCustomer(new Customer());
    LoanQuote loan = broker.getBestLoanQuote(loanRequest);
    logger.info("\n********* Best Quote: " + loan);
    List<LoanQuote> loanQuotes = broker.getAllLoanQuotes(loanRequest);
    logger.info("\n********* All Quotes: ");
    for (LoanQuote loanQuote : loanQuotes) {
        logger.info(loanQuote);//from   ww w  . j  a  v  a  2  s . c  om
    }
    context.close();
}

From source file:org.springframework.testng.AbstractSpringContextTests.java

/**
 * Set custom locations dirty. This will cause them to be reloaded
 * from the cache before the next test case is executed.
 * <p>Call this method only if you change the state of a singleton
 * bean, potentially affecting future tests.
 *///from   ww  w . java2 s .co m
protected void setDirty(String[] locations) {
    String keyString = contextKeyString(locations);
    ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) contextKeyToContextMap
            .remove(keyString);
    if (ctx != null) {
        ctx.close();
    }
}

From source file:org.springframework.xd.dirt.stream.FileSourceModuleTests.java

@Test
public void testSplitterUsesIterator() throws Exception {
    System.out.println(System.getProperty("user.dir"));
    ConfigurableApplicationContext ctx = new FileSystemXmlApplicationContext(
            new String[] { "../modules/common/file-source-common-context.xml",
                    "classpath:org/springframework/xd/dirt/stream/ppc-context.xml" },
            false);/* w  w  w . ja  v a  2 s  . com*/
    StandardEnvironment env = new StandardEnvironment();
    Properties props = new Properties();
    props.setProperty("fixedDelay", "5");
    props.setProperty("timeUnit", "SECONDS");
    props.setProperty("initialDelay", "0");
    props.setProperty("withMarkers", "false");
    PropertiesPropertySource pps = new PropertiesPropertySource("props", props);
    env.getPropertySources().addLast(pps);
    env.setActiveProfiles("use-contents-with-split");
    ctx.setEnvironment(env);
    ctx.refresh();
    FileSplitter splitter = ctx.getBean(FileSplitter.class);
    File foo = File.createTempFile("foo", ".txt");
    final AtomicReference<Method> splitMessage = new AtomicReference<>();
    ReflectionUtils.doWithMethods(FileSplitter.class, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            method.setAccessible(true);
            splitMessage.set(method);
        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return method.getName().equals("splitMessage");
        }
    });
    Object result = splitMessage.get().invoke(splitter, new GenericMessage<File>(foo));
    assertThat(result, instanceOf(Iterator.class));
    ctx.close();
    foo.delete();
}

From source file:org.springframework.yarn.examples.CommonMain.java

public static void main(String args[]) {

    ConfigurableApplicationContext context = null;

    try {/*from w  w w .j a  va 2s.  c o  m*/
        context = new ClassPathXmlApplicationContext("application-context.xml");
        System.out.println("Submitting example");
        YarnClient client = (YarnClient) context.getBean("yarnClient");
        client.submitApplication();
        System.out.println("Submitted example");
    } catch (Throwable e) {
        log.error("Error in main method", e);
    } finally {
        if (context != null) {
            context.close();
        }
    }

}

From source file:org.springframework.yarn.examples.Main.java

public static void main(String args[]) {

    Properties properties = StringUtils.splitArrayElementsIntoProperties(args, "=");
    if (properties == null) {
        properties = new Properties();
    }//from   ww  w.  j av a2s.c  o m

    boolean nokill = Boolean.parseBoolean(properties.getProperty("nokill"));
    String appid = properties.getProperty("appid");

    if (nokill) {
        new Main().doMain(new String[] { YarnSystemConstants.DEFAULT_CONTEXT_FILE_CLIENT,
                YarnSystemConstants.DEFAULT_ID_CLIENT, CommandLineClientRunner.OPT_SUBMIT });
    } else if (appid != null) {
        new Main().doMain(new String[] { YarnSystemConstants.DEFAULT_CONTEXT_FILE_CLIENT,
                YarnSystemConstants.DEFAULT_ID_CLIENT, CommandLineClientRunner.OPT_KILL,
                CommandLineClientRunner.ARG_APPLICATION_ID + "=" + appid });
    } else if (!nokill) {
        ConfigurableApplicationContext context = null;
        try {
            context = new ClassPathXmlApplicationContext("application-context.xml");
            System.out.println("Submitting kill-application example");
            YarnClient client = (YarnClient) context.getBean("yarnClient");
            ApplicationId applicationId = client.submitApplication();
            System.out.println("Submitted kill-application example");
            System.out.println("Waiting 30 seconds before aborting the application");
            Thread.sleep(30000);
            System.out.println(
                    "Asking resource manager to abort application with applicationid=" + applicationId);
            client.killApplication(applicationId);
        } catch (Throwable e) {
            log.error("Error in main method", e);
        } finally {
            if (context != null) {
                context.close();
            }
        }
    }
}

From source file:org.springframework.yarn.launch.AbstractCommandLineRunner.java

/**
 * Builds the Application Context(s) and handles 'execution'
 * of a bean./*from w  w w. j  av a2  s .com*/
 *
 * @param configLocation the main context config location
 * @param masterIdentifier the bean identifier
 * @param childConfigLocation the child context config location
 * @param parameters the parameters
 * @param opts the options
 * @return the status of the execution
 */
protected int start(String configLocation, String masterIdentifier, String childConfigLocation,
        String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    ExitStatus exitStatus = ExitStatus.COMPLETED;
    try {
        context = getApplicationContext(configLocation);
        getChildApplicationContext(childConfigLocation, context);

        @SuppressWarnings("unchecked")
        T bean = (T) context.getBean(masterIdentifier);

        if (log.isDebugEnabled()) {
            log.debug("Passing bean=" + bean + " from context=" + context + " for beanId=" + masterIdentifier);
        }

        exitStatus = handleBeanRun(bean, parameters, opts);

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

From source file:org.wise.WISE.java

/**
 * @param springConfigClassname//from   w  w w . jav a 2  s .co  m
 * @throws ClassNotFoundException
 * @throws IOException 
 */
public static void resetDB(String springConfigClassname) throws ClassNotFoundException, IOException {
    ConfigurableApplicationContext applicationContext = null;
    try {
        File wisePropertiesFile = new File("target/classes/wise.properties");
        String wisePropertiesString = FileUtils.readFileToString(wisePropertiesFile);
        wisePropertiesString = wisePropertiesString.replaceAll("#hibernate.hbm2ddl.auto=create", "");
        wisePropertiesString = wisePropertiesString.replaceAll("hibernate.hbm2ddl.auto=create", "");

        wisePropertiesString = "hibernate.hbm2ddl.auto=create\n\n" + wisePropertiesString;

        FileUtils.writeStringToFile(wisePropertiesFile, wisePropertiesString);

        try {
            Thread.sleep(5000); // give it time to save the file
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SpringConfiguration springConfig = (SpringConfiguration) BeanUtils
                .instantiateClass(Class.forName(springConfigClassname));
        applicationContext = new ClassPathXmlApplicationContext(
                springConfig.getRootApplicationContextConfigLocations());
    } finally {

        if (applicationContext != null) {
            applicationContext.close();
        }
    }
}