Example usage for org.springframework.context.annotation AnnotationConfigApplicationContext registerShutdownHook

List of usage examples for org.springframework.context.annotation AnnotationConfigApplicationContext registerShutdownHook

Introduction

In this page you can find the example usage for org.springframework.context.annotation AnnotationConfigApplicationContext registerShutdownHook.

Prototype

@Override
public void registerShutdownHook() 

Source Link

Document

Register a shutdown hook with the JVM runtime, closing this context on JVM shutdown unless it has already been closed at that time.

Usage

From source file:io.gravitee.gateway.platforms.jetty.bootstrap.Bootstrap.java

public static void main(String[] args) {
    Thread t = Thread.currentThread();
    t.setName("graviteeio-gateway");

    final AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(JettyConfiguration.class);
    ctx.registerShutdownHook();
    ctx.refresh();//from   w  w  w.j  av a 2s . c om

    try {
        final Node node = ctx.getBean(Node.class);
        node.start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                LoggerFactory.getLogger(Bootstrap.class).info("Shutting-down Gravitee Gateway...");
                node.stop();
                ctx.close();
            }
        });
    } catch (Exception ex) {
        LOGGER.error("Unable to start Gravitee Gateway", ex);
    }
}

From source file:uk.ac.kcl.Main.java

public static void main(String[] args) {
    File folder = new File(args[0]);
    File[] listOfFiles = folder.listFiles();
    assert listOfFiles != null;
    for (File listOfFile : listOfFiles) {
        if (listOfFile.isFile()) {
            if (listOfFile.getName().endsWith(".properties")) {
                System.out.println("Properties sile found:" + listOfFile.getName()
                        + ". Attempting to launch application context");
                Properties properties = new Properties();
                InputStream input;
                try {
                    input = new FileInputStream(listOfFile);
                    properties.load(input);
                    if (properties.getProperty("globalSocketTimeout") != null) {
                        TcpHelper.setSocketTimeout(
                                Integer.valueOf(properties.getProperty("globalSocketTimeout")));
                    }/*from   w w  w  . j av a  2 s .  c o m*/
                    Map<String, Object> map = new HashMap<>();
                    properties.forEach((k, v) -> {
                        map.put(k.toString(), v);
                    });
                    ConfigurableEnvironment environment = new StandardEnvironment();
                    MutablePropertySources propertySources = environment.getPropertySources();
                    propertySources.addFirst(new MapPropertySource(listOfFile.getName(), map));
                    @SuppressWarnings("resource")
                    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
                    ctx.registerShutdownHook();
                    ctx.setEnvironment(environment);
                    String scheduling;
                    try {
                        scheduling = properties.getProperty("scheduler.useScheduling");
                        if (scheduling.equalsIgnoreCase("true")) {
                            ctx.register(ScheduledJobLauncher.class);
                            ctx.refresh();
                        } else if (scheduling.equalsIgnoreCase("false")) {
                            ctx.register(SingleJobLauncher.class);
                            ctx.refresh();
                            SingleJobLauncher launcher = ctx.getBean(SingleJobLauncher.class);
                            launcher.launchJob();
                        } else if (scheduling.equalsIgnoreCase("slave")) {
                            ctx.register(JobConfiguration.class);
                            ctx.refresh();
                        } else {
                            throw new RuntimeException(
                                    "useScheduling not configured. Must be true, false or slave");
                        }
                    } catch (NullPointerException ex) {
                        throw new RuntimeException(
                                "useScheduling not configured. Must be true, false or slave");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:se.ivankrizsan.messagecowboy.MessageCowboy.java

/**
 * Starts the Message Cowboy.//from  ww w. j  a va 2 s .c  o  m
 * 
 * @param args Command line arguments. Not used.
 */
public static void main(final String[] args) {
    LOGGER.debug("Loading Spring context...");

    logProcessIdAndHost();

    @SuppressWarnings("resource")
    final AnnotationConfigApplicationContext theSpringContext = new AnnotationConfigApplicationContext(
            MessageCowboyConfiguration.class, ProductionPropertyOverrides.class);
    theSpringContext.registerShutdownHook();

    LOGGER.debug("Spring context loaded.");
    LOGGER.info("Hit [ENTER] in console to stop Message Cowboy.");

    waitForKeyboardEnter();

    System.exit(0);
}

From source file:ca.unx.template.Main.java

public static void main(String[] args) throws Exception {

    final Logger logger = LoggerFactory.getLogger("main");

    try {/*from   w  w  w  .j  a  v  a2s.c o  m*/
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        /*
         * One problem with SpringMVC is it creates its own application
         * context, and so it can end up failing but our application will
         * keep running.
         * 
         * To detect the case where the SpringMVC's web application context
         * fails we'll listen for ContextRefreshEvents and set a flag when
         * we see the web application context refresh.
         */
        applicationContext.addApplicationListener(new ApplicationListener<ContextRefreshedEvent>() {
            @Override
            public void onApplicationEvent(ContextRefreshedEvent event) {
                ApplicationContext ctx = event.getApplicationContext();
                if (ctx instanceof GenericWebApplicationContext) {
                    webApplicationContextInitialized = true;
                }
            }
        });

        applicationContext.registerShutdownHook();
        applicationContext.register(RootConfiguration.class);
        applicationContext.refresh();

        if (!webApplicationContextInitialized) {
            logger.error("Failed to initialize web application.  Exiting.");
            System.exit(1);
        }

        logger.info("Running.");
    } catch (Exception e) {
        logger.error("Error starting application", e);
        System.exit(1);
    }
}

From source file:com.tcloud.bee.key.server.jetty.SpringJettyServer.java

/**
 * @param args/*from  ww w  .ja  v  a  2  s.co m*/
 */
public static void main(String[] args) {

    logger.info("Start Spring Jetty Server.....");

    try {

        @SuppressWarnings("resource")
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        /*
         * One problem with SpringMVC is it creates its own application
         * context, and so it can end up failing but our application will
         * keep running.
         * 
         * To detect the case where the SpringMVC's web application context
         * fails we'll listen for ContextRefreshEvents and set a flag when
         * we see one.
         */
        applicationContext.addApplicationListener(new ApplicationListener<ContextRefreshedEvent>() {
            @Override
            public void onApplicationEvent(ContextRefreshedEvent event) {
                ApplicationContext ctx = event.getApplicationContext();
                if (ctx instanceof AnnotationConfigWebApplicationContext) {
                    webApplicationContextInitialized = true;
                }
            }
        });

        logger.info("Start register JettyConfiguration.....");
        applicationContext.registerShutdownHook();
        applicationContext.register(RootConfiguration.class);
        applicationContext.refresh();

        if (!webApplicationContextInitialized) {
            logger.error("Web application context not initialized. Exiting.");
            System.exit(1);
        }

        logger.info("Running.");
    } catch (Exception e) {
        logger.error("Error starting application", e);
        System.exit(1);
    }
}

From source file:org.geosdi.geoplatform.experimental.dropwizard.app.CoreServiceApp.java

@Override
public void run(CoreServiceConfig t, Environment e) throws Exception {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(CoreOAuth2ServiceLoader.class);
    ctx.refresh();// www  .ja  v a2s . co  m
    ctx.registerShutdownHook();
    ctx.start();

    e.jersey().register(
            new JacksonMessageBodyProvider(new GPJacksonSupport().getDefaultMapper(), e.getValidator()));
    e.jersey().register(new OAuth2ExceptionProvider());
    e.jersey().register(new OAuthProvider<>(new CoreOAuthAuthenticator(t), "protected-resources"));
    e.healthChecks().register("service-health-check", new CoreServiceHealthCheck());

    Map<String, Object> resources = ctx.getBeansWithAnnotation(Path.class);

    for (Map.Entry<String, Object> entry : resources.entrySet()) {
        e.jersey().register(entry.getValue());
    }
}

From source file:org.jbr.commons.container.java.JavaSpringContainer.java

/**
 * Constructs the application context used by this container.
 * /*from  w ww . j  a  v a2 s  . c o  m*/
 * @return this container's new application context
 * @throws SpringContainerException
 */
@Override
protected AbstractApplicationContext createApplicationContext() throws SpringContainerException {
    final Class<?> contextConfigClass = getContextConfigClass();
    final String profile = System.getProperty(JVM_PARM_PROFILE, getDefaultProfile());
    log.info("Configuring Java SpringContainer using registered class [" + contextConfigClass
            + "] under profile [" + profile + "]");
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.getEnvironment().setActiveProfiles(profile);
    context.register(contextConfigClass);
    context.registerShutdownHook();
    return context;
}

From source file:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

public AnnotationConfigApplicationContext createAnnotationConfigApplicationContext() {
    final AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    if (ArrayUtils.isNotEmpty(springProfiles)) {
        ctx.getEnvironment().setActiveProfiles(springProfiles);
    }/*from   w w w . jav a  2  s. co  m*/

    if (ArrayUtils.isNotEmpty(configurationClasses)) {
        for (final Class<?> c : configurationClasses) {
            ctx.register(c);
        }
    }

    ctx.refresh();
    ctx.registerShutdownHook();
    return ctx;
}

From source file:org.jacpfx.vertx.spring.SpringVerticleFactory.java

private Verticle createSpringVerticle(final Class<?> currentVerticleClass, ClassLoader classLoader) {
    final SpringVerticle annotation = currentVerticleClass.getAnnotation(SpringVerticle.class);
    final Class<?> springConfigClass = annotation.springConfig();

    // Create the parent context  
    final GenericApplicationContext genericApplicationContext = new GenericApplicationContext();
    genericApplicationContext.setClassLoader(classLoader);
    if (parentContext != null) {
        genericApplicationContext.setParent(parentContext);
    }//from  w  w  w . j  a  v  a2s  . c o m
    genericApplicationContext.refresh();
    genericApplicationContext.start();

    // 1. Create a new context for each verticle and use the specified spring configuration class if possible
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.setParent(genericApplicationContext);
    annotationConfigApplicationContext.register(SpringContextConfiguration.class, springConfigClass);

    // 2. Register a bean definition for this verticle
    annotationConfigApplicationContext.registerBeanDefinition(currentVerticleClass.getSimpleName(),
            new VerticleBeanDefinition(currentVerticleClass));

    // 3. Add a bean factory post processor to avoid configuration issues
    annotationConfigApplicationContext
            .addBeanFactoryPostProcessor(new SpringSingleVerticleConfiguration(currentVerticleClass));
    annotationConfigApplicationContext.refresh();
    annotationConfigApplicationContext.start();
    annotationConfigApplicationContext.registerShutdownHook();

    // 5. Return the verticle by fetching the bean from the context
    return (Verticle) annotationConfigApplicationContext.getBeanFactory()
            .getBean(currentVerticleClass.getSimpleName());
}