Example usage for org.springframework.web.context WebApplicationContext getBean

List of usage examples for org.springframework.web.context WebApplicationContext getBean

Introduction

In this page you can find the example usage for org.springframework.web.context WebApplicationContext getBean.

Prototype

Object getBean(String name) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

From source file:de.ingrid.interfaces.csw.admin.IndexDriver.java

/**
 * @param args/*w  ww .ja  v  a2  s . c o  m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    if (!System.getProperties().containsKey("jetty.webapp"))
        log.warn("Property 'jetty.webapp' not defined! Using default webapp directory, which is '"
                + DEFAULT_WEBAPP_DIR + "'.");
    if (!System.getProperties().containsKey("jetty.port"))
        log.warn("Property 'jetty.port' not defined! Using default port, which is '" + DEFAULT_JETTY_PORT
                + "'.");

    WebAppContext webAppContext = new WebAppContext(System.getProperty("jetty.webapp", DEFAULT_WEBAPP_DIR),
            "/");

    Server server = new Server(Integer.getInteger("jetty.port", DEFAULT_JETTY_PORT));
    // fix slow startup time on virtual machine env.
    HashSessionIdManager hsim = new HashSessionIdManager();
    hsim.setRandom(new Random());
    server.setSessionIdManager(hsim);
    server.setHandler(webAppContext);
    server.start();
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(
            webAppContext.getServletContext(),
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.springapp");
    IndexRunnable r = (IndexRunnable) wac.getBean("indexRunnable");
    r.run();
    System.out.println("Try to stopping the iPlug...");
    server.stop();
    System.out.println("iPlug is stopped.");
}

From source file:com.art4ul.jcoonsample.Main.java

public static void main(String[] args) throws Exception {
    WebApplicationContext applicationContext = ServerLauncher.getContext(); // Receive Spring Application context
    ServerLauncher serverLauncher = new ServerLauncher(); // Create object of HTTP Server launcher (Jetty server)
    try {//ww  w  .  j  a v  a2  s .  c  o  m
        serverLauncher.startServer(applicationContext); // Start Http server (just to handle our REST requests )

        TestService service = applicationContext.getBean(TestService.class); // Receive test bean
        service.doTest(); // Invoke test method from it
    } finally {
        serverLauncher.stopServer(); // Stop HTTP server
    }
}

From source file:no.kantega.kwashc.server.ServerJettyStarter.java

public static <T> T getSpringBean(Class<T> beanClass) {
    ServletContext servletContext = webAppContext.getServletHandler().getServletContext();
    WebApplicationContext springWebAppContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    return springWebAppContext.getBean(beanClass);
}

From source file:io.lavagna.web.helper.Redirector.java

public static void sendRedirect(HttpServletRequest req, HttpServletResponse resp, String page,
        Map<String, List<String>> params) throws IOException {
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
    String baseApplicationUrl = ctx.getBean(ConfigurationRepository.class).getValue(Key.BASE_APPLICATION_URL);

    UriComponents urlToRedirect = UriComponentsBuilder.fromHttpUrl(baseApplicationUrl).path(page)
            .queryParams(new LinkedMultiValueMap<>(params)).build();

    resp.sendRedirect(urlToRedirect.toUriString());
}

From source file:org.brekka.paveway.web.support.PolicyHelper.java

public static UploadPolicy identifyPolicy(ServletContext servletContext) {
    WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getWebApplicationContext(servletContext);
    UploadPolicyService uploadPolicyService = webApplicationContext.getBean(UploadPolicyService.class);
    return uploadPolicyService.identifyUploadPolicy();
}

From source file:org.gtri.fhir.api.vistaex.rest.service.util.VistaUtil.java

/**
 * Returns an implementation of the VistaExResource interface.
 * @return/*from w w  w  .ja v  a2s  .c o m*/
 */
public static VistaExResource getVistaExResource() {
    WebApplicationContext parentAppCtx = ContextLoaderListener.getCurrentWebApplicationContext();
    return parentAppCtx.getBean(VistaExResource.class);
}

From source file:org.lamsfoundation.lams.admin.service.AdminServiceProxy.java

private static Object getDomainService(ServletContext servletContext, String serviceName) {
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    return wac.getBean(serviceName);
}

From source file:py.una.pol.karaku.util.Util.java

/**
 * Utiliza el servlet del contexto actual de Faces para obtener una
 * instancia del {@link WebApplicationContext} y as obtener los beans que
 * cargo el mismo./*from w  ww  .  j  a v  a2 s. c  o  m*/
 *
 * <p>
 * <b>Uso:</b>
 *
 * <pre>
 *
 * FacesContext fc = getContext(); // o FacesContext.getCurrentInstance();
 * PropertiesUtil pu = Util.getSpringBeanBYJSFContext(fc, PropertiesUtil.class);
 * </pre>
 *
 * En este punto <code>pu</code> es una variable ya instanciada por Spring,
 * es decir ya tiene inyectadas todas las dependencias.
 * </p>
 *
 * @param context
 *            contexto actual, puede ser nulo
 * @param beanType
 *            tipo del bean que se desea, tiene que estar anotado con alguna
 *            herencia de {@link Component}, o estar definido en los
 *            archivos de configuracin.
 * @return bean del tipo especificado
 * @see WebApplicationContext#getBean(Class)
 */
public static <T> T getSpringBeanByJSFContext(FacesContext context, @NotNull Class<T> beanType) {

    FacesContext contexto = context == null ? FacesContext.getCurrentInstance() : context;
    ServletContext sv = (ServletContext) contexto.getExternalContext().getContext();

    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sv);
    return wac.getBean(beanType);
}

From source file:fr.openwide.talendalfresco.rest.server.CommandAuthenticationFilter.java

/**
 * Return the ServiceRegistry helper instance
 * //from www .ja v a 2 s.c  om
 * @param sc      ServletContext
 * @return ServiceRegistry
 */
public static ServiceRegistry getServiceRegistry(ServletContext sc) {
    WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    return (ServiceRegistry) wc.getBean(ServiceRegistry.SERVICE_REGISTRY);
}

From source file:com.exxonmobile.ace.hybris.storefront.servlets.util.FilterSpringUtil.java

/**
 * The same as {@link #getSpringBean(HttpServletRequest, String, Class)} but uses ServletContext as the first
 * parameter. It might be used in places, where HttpServletRequest is not available, but ServletContext is.
 *///from   www. j  a va  2 s  .c  o m
public static <T> T getSpringBean(final ServletContext servletContext, final String beanName,
        final Class<T> beanClass) {
    T ret = null;
    final WebApplicationContext appContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);

    if (StringUtils.isNotBlank(beanName)) {
        try {
            ret = (T) appContext.getBean(beanName);
        } catch (final NoSuchBeanDefinitionException ex) {
            LOG.warn("No bean found with the specified name. Trying to resolve bean using type...");
        }
    }
    if (ret == null) {
        if (beanClass == null) {
            LOG.warn("No bean could be resolved. Reason: No type specified.");
        } else {
            final Map<String, T> beansOfType = appContext.getBeansOfType(beanClass);
            if (beansOfType != null && !beansOfType.isEmpty()) {
                if (beansOfType.size() > 1) {
                    LOG.warn("More than one matching bean found of type " + beanClass.getSimpleName()
                            + ". Returning the first one found.");
                }
                ret = beansOfType.values().iterator().next();
            }
        }
    }
    return ret;
}