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:cn.vpclub.spring.boot.kafka.demo1.Application.java

public static void main(String[] args) throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(Application.class).web(false)
            .run(args);//w  ww.  j  a v a 2 s .  co  m

    KafkaMessageQueue mq = new KafkaMessageQueue(context);

    String message = null;
    String response = null;
    for (int i = 0; i < 10; i++) {
        message = "the message a from demo1 to demo2, count: " + i;
        response = mq.send("demo1.to.demo2", "demo2.to.demo1", "test.key", message, 0);
        logger.info(message);
        if (null != response) {
            logger.info("received from demo2: " + response);
        }
        sleep(10L);

        message = "the message b from demo1 to demo3, count: " + i;
        response = mq.send("demo1.to.demo3", "demo3.to.demo1", "test.key", message, 0);
        logger.info(message);
        if (null != response) {
            logger.info("received from demo3: " + response);
        }
        sleep(10L);
    }

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

From source file:com.fantasy.Application.java

public static void main(String[] args) throws ParseException, Exception {
    ConfigurableApplicationContext context;
    context = SpringApplication.run(AggregatorConfig.class);

    SpaceDelimitedCommandLineParser<YearFlag, YearContainer> argParser;
    argParser = context.getBean(SpaceDelimitedCommandLineParser.class);
    YearContainer container = argParser.parseFor(YearFlag.class, args);

    String packageName = container.getPackageName();
    String className = container.getClassName();
    int year = container.getYear();

    List<Class> taskRunners = findTypes(packageName);
    Class runner = null;/* www.  j  a  va2 s .  c om*/

    if (Objects.nonNull(taskRunners)) {
        for (Class cl : taskRunners) {
            if (cl.getSimpleName().equalsIgnoreCase(className)) {
                runner = cl;
                break;
            }
        }

        if (Objects.nonNull(runner)) {
            Task task = (Task) context.getBean(runner);

            if (Objects.nonNull(task)) {
                if (task instanceof ContextUser) {
                    ((ContextUser) task).haveContext(context);
                }
                if (task instanceof YearlyTask) {
                    ((YearlyTask) task).setYear(year);
                }

                try {
                    task.run();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    if (Objects.nonNull(context)) {
                        context.close();
                    }
                }
            }
        }
    }
}

From source file:com.vitco.Main.java

public static void main(String[] args) throws Exception {
    // display version number on splash screen
    final SplashScreen splash = SplashScreen.getSplashScreen();
    if (splash != null) {
        Graphics2D g = splash.createGraphics();
        if (g != null) {
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            Font font = Font
                    .createFont(Font.TRUETYPE_FONT,
                            new SaveResourceLoader("resource/font/arcade.ttf").asInputStream())
                    .deriveFont(Font.PLAIN, 42f);
            g.setFont(font);//from  w  w  w .j a v a2  s .  com
            //g.setFont(g.getFont().deriveFont(9f));
            g.setColor(VitcoSettings.SPLASH_SCREEN_OVERLAY_TEXT_COLOR);
            int width = g.getFontMetrics().stringWidth(VitcoSettings.VERSION_ID);
            g.drawString(VitcoSettings.VERSION_ID, 400 - 20 - width, 110);
            splash.update();
            g.dispose();
        }
    }

    // the JIDE license
    SaveResourceLoader saveResourceLoader = new SaveResourceLoader("resource/jidelicense.txt");
    if (!saveResourceLoader.error) {
        String[] jidelicense = saveResourceLoader.asLines();
        if (jidelicense.length == 3) {
            com.jidesoft.utils.Lm.verifyLicense(jidelicense[0], jidelicense[1], jidelicense[2]);
        }
    }

    // check if we are in debug mode
    if ((args.length > 0) && args[0].equals("debug")) {
        ErrorHandler.setDebugMode();
        debug = true;
    }

    // build the application
    final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "com/vitco/glue/config.xml");

    // for debugging
    if (debug) {
        ((ActionManager) context.getBean("ActionManager")).performValidityCheck();
        ((ComplexActionManager) context.getBean("ComplexActionManager")).performValidityCheck();
    }

    // open vsd file when program is started with "open with"
    MainMenuLogic mainMenuLogic = ((MainMenuLogic) context.getBean("MainMenuLogic"));
    for (String arg : args) {
        if (arg.endsWith(".vsd")) {
            File file = new File(arg);
            if (file.exists() && !file.isDirectory()) {
                mainMenuLogic.openFile(file);
                break;
            }
        }
    }

    // perform shortcut check
    ((ShortcutManager) context.getBean("ShortcutManager")).doSanityCheck(debug);
    //        // test console
    //        final Console console = ((Console) context.getBean("Console"));
    //        new Thread() {
    //            public void run() {
    //                while (true) {
    //                    console.addLine("text");
    //                    try {
    //                        sleep(2000);
    //                    } catch (InterruptedException e) {
    //                       //e.printStackTrace();
    //                    }
    //                }
    //            }
    //        }.start();

    // add a shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            // make reference so Preferences object doesn't get destroyed
            Preferences pref = ((Preferences) context.getBean("Preferences"));
            // trigger @PreDestroy
            context.close();
            // store the preferences (this needs to be done here, b/c
            // some PreDestroys are used to store preferences!)
            pref.save();
        }
    });
}

From source file:things.Application.java

public static void main(String[] args) {

    ConfigurableApplicationContext context = SpringApplication.run(Application.class);
    ThingRepository repository = context.getBean(ThingRepository.class);

    // save a couple of things
    repository.save(new Thing("Jack", "Bauer"));
    repository.save(new Thing("Chloe", "O'Brian"));
    repository.save(new Thing("Kim", "Bauer"));
    repository.save(new Thing("David", "Palmer"));
    repository.save(new Thing("Michelle", "Dessler"));

    // fetch things by last name
    Iterable<Thing<?>> bauers = repository.findByKey("Dessler");
    System.out.println("Customer found with findByLastName('Bauer'):");
    System.out.println("--------------------------------------------");
    for (Thing bauer : bauers) {
        System.out.println(bauer);
    }//from ww  w . ja v  a 2 s . co  m
    Thing dessler = bauers.iterator().next();

    // fetch all things
    Iterable<Thing<?>> things = repository.findAll();
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Thing customer : things) {
        System.out.println(customer);
        customer.getParents().add(dessler.getId());
        customer.setValue("AAAAA");
        repository.save(customer);
    }
    System.out.println();

    things = repository.findAll();
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Thing customer : things) {
        customer.getParents().add(dessler.getId());
        repository.save(customer);
        System.out.println(customer);
    }
    System.out.println();

    //        //fetch an individual customer by ID
    //        Thing thing = repository.findOne(1L);
    //        System.out.println("Customer found with findOne(1L):");
    //        System.out.println("--------------------------------");
    //        System.out.println(thing);
    //        System.out.println();

    context.close();
}

From source file:org.jasig.portlet.announcements.spring.PortletApplicationContextLocator.java

/**
 * If the ApplicationContext returned by {@link #getApplicationContext()} is 'portal managed' the shutdown hook
 * for the context is called, closing and cleaning up all spring managed resources.
 *
 * If the ApplicationContext returned by {@link #getApplicationContext()} is actually a WebApplicationContext
 * this method does nothing but log an error message.
 *//*from   ww  w .  j a  va2  s .  co  m*/
public static void shutdown() {
    if (applicationContextCreator.isCreated()) {
        final ConfigurableApplicationContext applicationContext = applicationContextCreator.get();
        applicationContext.close();
    } else {
        final IllegalStateException createException = new IllegalStateException(
                "No portal managed ApplicationContext has been created, there is nothing to shutdown.");
        LOGGER.error(createException, createException);
    }
}

From source file:com.github.mrstampy.gameboot.GameBoot.java

private static void generatePropertyFiles(ConfigurableApplicationContext ctx) throws IOException {
    GameBootDependencyWriter writer = ctx.getBean(GameBootDependencyWriter.class);

    writer.writeDependencies(ctx);// www .  ja v  a 2s. co  m

    ctx.close();
}

From source file:org.fcrepo.migration.handlers.BasicObjectVersionHandlerIT.java

@BeforeClass
public static void migrateTestData() throws XMLStreamException {
    final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring/it-setup.xml");

    ((Migrator) context.getBean("f3Migrator")).run();
    ((Migrator) context.getBean("f2Migrator")).run();

    client = (Fedora4Client) context.getBean("fedora4Client");
    idMapper = (MigrationIDMapper) context.getBean("idMapper");
    context.close();
}

From source file:org.cbioportal.database.DatabaseAnnotator.java

private static void launchJob(String[] args, String isoform, String studies) throws Exception {
    SpringApplication app = new SpringApplication(DatabaseAnnotator.class);

    ConfigurableApplicationContext ctx = app.run(args);
    JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
    JobParameters jobParameters = new JobParametersBuilder().addString("isoform", isoform)
            .addString("studies", studies).toJobParameters();
    Job databaseAnnotatorJob = ctx.getBean(BatchConfiguration.DATABASE_ANNOTATOR_JOB, Job.class);
    JobExecution jobExecution = jobLauncher.run(databaseAnnotatorJob, jobParameters);
    ctx.close();
}

From source file:com.wandrell.example.swss.client.console.ConsoleClient.java

/**
 * Returns a client generated from the Spring context defined in the
 * specified file.// w ww .j a v  a  2  s  . c o m
 *
 * @param contextPath
 *            path to the Spring context file
 * @return a client loaded from the specified context
 */
private static final EntityClient getEntityClient(final String contextPath) {
    final ConfigurableApplicationContext context; // Context
    final EntityClient client; // Client

    context = new ClassPathXmlApplicationContext(contextPath);

    client = context.getBean(EntityClient.class);

    context.close();

    return client;
}

From source file:org.cbio.portal.pipelines.FoundationPipeline.java

private static void launchJob(String[] args, String sourceDirectory, String outputDirectory,
        String cancerStudyId, boolean generateXmlDocument) throws Exception {
    // set up application context and job launcher
    SpringApplication app = new SpringApplication(FoundationPipeline.class);
    ConfigurableApplicationContext ctx = app.run(args);
    JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);

    // get the appropriate job name
    String jobName = generateXmlDocument ? BatchConfiguration.FOUNDATION_XML_DOCUMENT_JOB
            : BatchConfiguration.FOUNDATION_JOB;

    // configure job parameters and launch job
    Job foundationJob = ctx.getBean(jobName, Job.class);
    JobParameters jobParameters = new JobParametersBuilder().addString("sourceDirectory", sourceDirectory)
            .addString("outputDirectory", outputDirectory).addString("cancerStudyId", cancerStudyId)
            .toJobParameters();/*w  w w.  j  a  v a2s . c  om*/
    JobExecution jobExecution = jobLauncher.run(foundationJob, jobParameters);

    // close job after completion 
    LOG.info("Closing FoundationPipeline.");
    ctx.close();
}