Example usage for org.springframework.context.support GenericXmlApplicationContext close

List of usage examples for org.springframework.context.support GenericXmlApplicationContext close

Introduction

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

Prototype

@Override
public void close() 

Source Link

Document

Close this application context, destroying all beans in its bean factory.

Usage

From source file:org.resthub.rpc.example.EchoClient.java

public static void main(String[] args) throws Exception {
    //        CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost", 5672);
    //        connectionFactory.setUsername("guest");
    //        connectionFactory.setPassword("guest");
    //        /*from   w w w.  ja  v a  2s  .c  om*/
    //        AMQPProxyFactory factory = new AMQPProxyFactory();
    //        factory.setConnectionFactory(connectionFactory);
    //        factory.setReadTimeout(3000);
    //        EchoService service = factory.create(EchoService.class);
    //        
    //        System.out.println(service.echo("Hello AMQP!"));
    //        connectionFactory.destroy();

    GenericXmlApplicationContext context = new GenericXmlApplicationContext(
            "classpath:/applicationContext-client.xml");

    EchoService service = (EchoService) context.getBean("echoService");
    System.out.println(service.echo("Hello AMQP!"));

    context.close();

}

From source file:org.bitcoinrt.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/*from  www  . ja  v  a 2 s .  c o m*/
 */
public static void main(final String... args) {

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration Bitcoin-rt Sample! "
            + "\n                                                         "
            + "\n=========================================================");

    System.out.println("Which WebSocket Client would you like to use? <enter>: ");
    System.out.println("\t1. Use Sonatype's Async HTTP Client implementation");
    System.out.println("\t2. Use Jetty's WebSocket client implementation");
    System.out.println("\t3. Use a Dummy client");

    System.out.println("\tq. Quit the application");
    System.out.print("Enter you choice: ");

    final GenericXmlApplicationContext context = new GenericXmlApplicationContext();

    while (true) {
        final String input = scanner.nextLine();

        if ("1".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("default");
            break;
        } else if ("2".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("jetty");
            break;
        } else if ("3".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("dummy");
            break;
        } else if ("q".equals(input.trim())) {
            System.out.println("Exiting application...bye.");
            System.exit(0);
        } else {
            System.out.println("Invalid choice\n\n");
            System.out.print("Enter you choice: ");
        }
    }

    context.load("classpath:META-INF/spring/integration/*-context.xml");
    context.registerShutdownHook();
    context.refresh();

    final ConnectionBroker connectionBroker = context.getBean(ConnectionBroker.class);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n    Please press 'q + Enter' to quit the application.    "
                + "\n    For statistical information press 'i + Enter'.       "
                + "\n                                                         "
                + "\n    In your browser open:                                "
                + "\n    file:///.../src/main/webapp/index.html               "
                + "\n=========================================================");
    }

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        } else if ("i".equals(input.trim())) {
            LOGGER.info("\n========================================================="
                    + "\n                                                         "
                    + "\n Number of connected clients: " + connectionBroker.connectedClients()
                    + "\n                                                         "
                    + "\n=========================================================");
        }

    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Exiting application...bye.");
    }

    context.close();
    System.exit(0);

}

From source file:org.cloudfoundry.identity.api.BootstrapTests.java

@Test
public void testRootContext() throws Exception {
    GenericXmlApplicationContext context = new GenericXmlApplicationContext(
            new FileSystemResource("src/main/webapp/WEB-INF/spring-servlet.xml"));
    context.close();
}

From source file:edu.colorado.orcid.TestSpringContext.java

@Test
public void testLoadContext() throws Exception {
    GenericXmlApplicationContext context = new GenericXmlApplicationContext(
            new FileSystemResource("src/main/webapp/WEB-INF/spring-servlet.xml"));
    context.close();
}

From source file:org.apache.cxf.fediz.service.idp.service.jpa.DBLoaderSpring.java

@Override
public void load() {

    GenericXmlApplicationContext ctx = null;
    try {/*from w w w.j  a  v a  2s.  c om*/

        if (resource == null) {
            LOG.warn("Resource null for DBLoaderSpring");
        }

        ctx = new GenericXmlApplicationContext();
        ctx.load(resource);
        ctx.refresh();
        ctx.start();

        Collection<EntitlementEntity> entitlements = ctx.getBeansOfType(EntitlementEntity.class, true, true)
                .values();
        for (EntitlementEntity e : entitlements) {
            em.persist(e);
        }
        LOG.info(entitlements.size() + " EntitlementEntity added");

        Collection<RoleEntity> roles = ctx.getBeansOfType(RoleEntity.class, true, true).values();
        for (RoleEntity r : roles) {
            em.persist(r);
        }
        LOG.info(roles.size() + " RoleEntity added");

        Collection<ClaimEntity> claims = ctx.getBeansOfType(ClaimEntity.class, true, true).values();
        for (ClaimEntity c : claims) {
            em.persist(c);
        }
        LOG.info(claims.size() + " ClaimEntity added");

        Collection<TrustedIdpEntity> trustedIdps = ctx.getBeansOfType(TrustedIdpEntity.class).values();
        for (TrustedIdpEntity t : trustedIdps) {
            em.persist(t);
        }
        LOG.info(trustedIdps.size() + " TrustedIdpEntity added");

        Collection<ApplicationEntity> applications = ctx.getBeansOfType(ApplicationEntity.class).values();
        for (ApplicationEntity a : applications) {
            em.persist(a);
        }
        LOG.info(applications.size() + " ApplicationEntity added");

        Collection<IdpEntity> idps = ctx.getBeansOfType(IdpEntity.class).values();
        for (IdpEntity i : idps) {
            em.persist(i);
        }
        LOG.info(idps.size() + " IdpEntity added");

        Collection<ApplicationClaimEntity> applicationClaims = ctx.getBeansOfType(ApplicationClaimEntity.class)
                .values();
        for (ApplicationClaimEntity ac : applicationClaims) {
            em.persist(ac);
        }
        LOG.info(applicationClaims.size() + " ApplicationClaimEntity added");

        em.flush();
    } catch (Exception ex) {
        LOG.warn("Failed to initialize DB with data", ex);
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:com.opensourceagility.springintegration.alerts.AlertsIntegrationTest.java

@SuppressWarnings("unchecked")
@Test/*from   w w  w .  ja v a 2 s.  co m*/
public void testChannelAdapterDemo() throws InterruptedException, ParseException {

    System.setProperty("spring.profiles.active", "testCase");

    final GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext(
            configFilesChannelAdapterDemo);

    final MessageChannel createAlertRequestChannel = applicationContext.getBean("createAlertRequestChannel",
            MessageChannel.class);

    createAlertTestData(createAlertRequestChannel, thisMinuteDate);

    final QueueChannel queueChannel = applicationContext.getBean("queueChannel", QueueChannel.class);

    for (int counter = 1; counter <= 50; counter++) {
        int id = counter * 2;
        Message<String> reply = (Message<String>) queueChannel.receive(10000);
        Assert.assertNotNull(reply);
        String out = reply.getPayload();
        Assert.assertEquals(getExpectedXml(id), out);
        LOGGER.debug("Received expected Alert XML from queue:" + out);
    }
    LOGGER.debug(
            "Asserted that urgent alerts are those 50 alerts with even ids, ranging from 2 up to 100... and that these are received from the queue");

    Message<String> reply = (Message<String>) queueChannel.receive(10000);
    Assert.assertNull(reply);

    LOGGER.debug("Sleeping for 2 minutes until files are expected to have been (mock) uploaded...");
    Thread.sleep(120 * 1000);

    final MockAmazonS3FileUploader mockFileProcessor = applicationContext.getBean("amazonS3FileUploader",
            MockAmazonS3FileUploader.class);
    Assert.assertEquals(2, mockFileProcessor.getLinesByFileName().size());
    LOGGER.debug("Asserted successfully that 2 csv files were expected");

    List<String> minute1Lines = mockFileProcessor.getLinesByFileName().get(thisMinuteString);
    List<String> minute2Lines = mockFileProcessor.getLinesByFileName().get(nextMinuteString);

    // Assert we have the correct 30 entries in the csv file for the 1st minute
    Assert.assertEquals(30, minute1Lines.size());
    LOGGER.debug("Asserted successfully that 30 alerts found in file:" + thisMinuteString);

    // Assert we have 20 correct entries in the csv file for the 2nd minute
    Assert.assertEquals(20, minute2Lines.size());
    LOGGER.debug("Asserted successfully that 20 alerts found in file:" + nextMinuteString);

    // Check that the 1st minute's csv lines are as expected
    for (int counter = 1; counter <= 30; counter++) {
        int id = counter * 2 - 1;
        String line = minute1Lines.get(counter - 1);
        Assert.assertEquals(getExpectedCsvLine(id), line);
        LOGGER.debug("Found expected csv line in file:" + thisMinuteString + ":" + line);

    }

    // Check that the 2nd minute's csv lines are as expected
    for (int counter = 31; counter <= 50; counter++) {
        int id = counter * 2 - 1;
        String line = minute2Lines.get(counter - 31);
        Assert.assertEquals(getExpectedCsvLine(id), line);
        LOGGER.debug("Found expected csv line in file:" + nextMinuteString + " : " + line);

    }

    LOGGER.debug(
            "Asserted that non-urgent alerts are those 50 alerts with odd ids, ranging from 1 up to 99... and that these are written to csv files and uploaded");

    LOGGER.debug("Completed test successfully, closing application context");

    applicationContext.close();
}

From source file:nz.co.jsrsolutions.tideservice.scraper.TideScraper.java

public static void main(String[] args) {

    logger.info("Starting application [ tide scraper ] ...");

    GenericXmlApplicationContext context = null;

    try {/* w ww . j  av a  2 s. c  om*/

        CommandLineParser parser = new GnuParser();

        CommandLine commandLine = parser.parse(CommandLineOptions.Options, args);

        if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) {

            context = new GenericXmlApplicationContext();

            //ConfigurableEnvironment env = ctx.getEnvironment();

            //env.setActiveProfiles("test1");

            context.load(SPRING_CONFIG);

            context.refresh();

            context.registerShutdownHook();

            if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) {

                Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class);
                scheduler.start();

                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }

            } else {
                TideScraperController controller = context.getBean(CONTROLLER_BEAN_ID,
                        TideScraperController.class);
                controller.executeCommandLine(commandLine);
            }

        } else {

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("ts", CommandLineOptions.Options);

        }

    } catch (TideScraperException tse) {
        logger.error("Failed to execute command", tse);
    } catch (ParseException pe) {

        logger.error("Failed to parse command line", pe);

    } catch (Exception e) {

        logger.error("Failed to execute command", e);

    } finally {
        if (context != null) {
            context.close();
        }
    }

    logger.info("Exiting application [ tide scraper ] ...");

}

From source file:org.springframework.integration.core.MessageIdGenerationTests.java

@Test
public void testCustomIdGenerationWithParentChildIndependentCreation() throws Exception {
    ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext(
            "MessageIdGenerationTests-context-withGenerator.xml", this.getClass());
    GenericXmlApplicationContext child = new GenericXmlApplicationContext();
    child.load("classpath:/org/springframework/integration/core/MessageIdGenerationTests-context.xml");
    child.setParent(parent);/*from   w ww . j  a v  a2 s .c  o m*/
    child.refresh();

    IdGenerator idGenerator = child.getBean("idGenerator", IdGenerator.class);
    MessageChannel inputChannel = child.getBean("input", MessageChannel.class);
    inputChannel.send(new GenericMessage<Integer>(0));
    verify(idGenerator, atLeastOnce()).generateId();
    child.close();
    parent.close();
    this.assertDestroy();
}

From source file:org.springframework.integration.core.MessageIdGenerationTests.java

@Test
public void testCustomIdGenerationWithParentChildIndependentCreationChildrenRegistrarsOneAtTheTime()
        throws Exception {
    ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext(
            "MessageIdGenerationTests-context.xml", this.getClass());

    GenericXmlApplicationContext childA = new GenericXmlApplicationContext();
    childA.load(/*from   w  w w  .  j av a2s  .  c  o m*/
            "classpath:/org/springframework/integration/core/MessageIdGenerationTests-context-withGenerator.xml");
    childA.setParent(parent);
    childA.refresh();

    childA.close();

    GenericXmlApplicationContext childB = new GenericXmlApplicationContext();
    childB.load(
            "classpath:/org/springframework/integration/core/MessageIdGenerationTests-context-withGenerator.xml");
    childB.setParent(parent);
    childB.refresh();

    parent.close();
    childB.close();
    this.assertDestroy();
}

From source file:org.springframework.integration.samples.travel.Main.java

/**
 * @param args Not used./*from  w ww  . j  ava 2s.c o m*/
 */
public static void main(String... args) throws Exception {

    final GenericXmlApplicationContext context = new GenericXmlApplicationContext();

    final ConfigurableEnvironment env = context.getEnvironment();
    boolean mapQuestApiKeyDefined = env.containsProperty("mapquest.apikey");

    if (mapQuestApiKeyDefined) {
        env.setActiveProfiles("mapquest");
    }

    context.load("classpath:META-INF/spring/*.xml");
    context.refresh();

    final TravelGateway travelGateway = context.getBean("travelGateway", TravelGateway.class);

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration Travel App!        "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springintegration.org/                    "
            + "\n                                                         "
            + "\n=========================================================");

    System.out.println(
            "Please select the city, for which you would like to get traffic and weather information:");

    for (City city : City.values()) {
        System.out.println(String.format("\t%s. %s", city.getId(), city.getName()));
    }
    System.out.println("\tq. Quit the application");
    System.out.print("Enter your choice: ");

    while (true) {
        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            System.out.println("Exiting application...bye.");
            break;
        } else {

            final Integer cityId = Integer.valueOf(input);
            final City city = City.getCityForId(cityId);

            final String weatherReply = travelGateway.getWeatherByCity(city);

            System.out.println("\n=========================================================" + "\n    Weather:"
                    + "\n=========================================================");
            System.out.println(weatherReply);

            if (mapQuestApiKeyDefined) {
                final String trafficReply = travelGateway.getTrafficByCity(city);

                System.out.println("\n========================================================="
                        + "\n    Traffic:" + "\n=========================================================");
                System.out.println(trafficReply);
            } else {
                LOGGER.warn("Skipping Traffic Information call. Did you setup your MapQuest API Key? "
                        + "e.g. by calling:\n\n    $ mvn exec:java -Dmapquest.apikey=\"your_mapquest_api_key_url_decoded\"");
            }

            System.out.println("\n=========================================================" + "\n    Done."
                    + "\n=========================================================");
            System.out.print("Enter your choice: ");
        }
    }

    scanner.close();
    context.close();
}