Example usage for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext

List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext

Introduction

In this page you can find the example usage for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext.

Prototype

@Nullable
public static WebApplicationContext getWebApplicationContext(ServletContext sc) 

Source Link

Document

Find the root WebApplicationContext for this web app, typically loaded via org.springframework.web.context.ContextLoaderListener .

Usage

From source file:ar.com.cema.methodology.analyzer.ui.servlet.DependencyInjectionHttpServlet.java

/**
 * Devuelve el {@link ApplicationContext} asociado al contexto web de este servlet.
 * @return El {@link ApplicationContext} asociado al contexto web de este servlet
 *//*w  ww .j  av  a 2s. com*/
protected ApplicationContext getApplicationContext() {
    return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}

From source file:com.tecapro.inventory.common.servlet.BaseServlet.java

@Override
protected void process(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {/*from   w w  w .  ja va2 s  . c o m*/
        super.process(request, response);
    } catch (Throwable e) {
        System.out.println("RequestURL: " + request.getRequestURL());
        e.printStackTrace();

        LogUtil logUtil = (LogUtil) WebApplicationContextUtils.getWebApplicationContext(getServletContext())
                .getBean(BEAN_NAME_LOG_UTIL);
        logUtil.errorLog(LOG, BaseServlet.class.getSimpleName(), "process", null,
                "RequestURL: " + request.getRequestURL());

        BaseForm zform = (BaseForm) request.getAttribute(BaseForm.class.getSimpleName());
        if (zform != null) {
            errorLog(zform, request, e, "process");

            // process error
            ErrorInfoValue errorValue = new ErrorInfoValue();
            List<String> idList = new ArrayList<String>();
            idList.add(Constants.SYSTEM_ERROR_CODE);
            errorValue.setIdList(idList);
            MessageUtil msgUtil = (MessageUtil) WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext()).getBean(BEAN_NAME_MESSAGE_UTIL);
            errorValue.setErrorMessage(msgUtil.getMessage(Constants.SYSTEM_ERROR_CODE, new String[] {}));

            // check request ajax
            if (Constants.REQUEST_AJAX.equals(zform.getType())) {
                request.setAttribute("type", Constants.REQUEST_AJAX);

                // Set header info
                response.setContentType(Constants.CONTENT_TYPE_AJAX);
                response.setCharacterEncoding(Constants.Text.UTF_8);
                PrintWriter out = response.getWriter();
                Gson gson = new Gson();

                // create data JSON to response
                Map<String, Object> mapData = new HashMap<String, Object>();

                // check error
                mapData.put("value", errorValue);

                out.print(gson.toJson(mapData));
                out.flush();
                out.close();
            } else {

                zform.setError(errorValue);

                // forward error screen
                getServletContext().getRequestDispatcher("/WEB-INF/pages/common/system-error.jsp")
                        .forward(request, response);
            }
        }
    }
}

From source file:com.zenika.stripes.contrib.spring.SpringRuntimeConfiguration.java

/**
 * Splits a comma-separated list of class names and maps each {@link LifecycleStage} to the
 * interceptors in the list that intercept it. Also automatically finds Interceptors in
 * packages listed in {@link BootstrapPropertyResolver#PACKAGES} if searchExtensionPackages is true.
 * //from w  ww.  j a v  a  2s .  c  om
 * Interceptors are instancied from the Spring factory AutowireCapableBeanFactory.
 * @see <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.springframework/spring-beans/3.0.2.RELEASE/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java#AbstractAutowireCapableBeanFactory.createBean%28java.lang.Class%29">createBean code</a>
 * 
 * @return a Map of {@link LifecycleStage} to Collection of {@link Interceptor}
 */
@Override
protected Map<LifecycleStage, Collection<Interceptor>> initInterceptors(List classes) {

    Map<LifecycleStage, Collection<Interceptor>> map = new HashMap<LifecycleStage, Collection<Interceptor>>();

    for (Object type : classes) {
        try {
            ServletContext servletContext = getServletContext();
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(servletContext);

            AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
            Interceptor interceptor = (Interceptor) beanFactory.createBean((Class) type,
                    AutowireCapableBeanFactory.AUTOWIRE_NO, false);
            addInterceptor(map, interceptor);
        } catch (Exception e) {
            throw new StripesRuntimeException(
                    "Could not instantiate configured Interceptor [" + type.getClass().getName() + "].", e);
        }
    }

    return map;
}

From source file:io.github.benas.todolist.web.servlet.user.account.ChangePasswordServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    ApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(servletConfig.getServletContext());
    userService = applicationContext.getBean(UserService.class);
    resourceBundle = ResourceBundle.getBundle("todolist");

    //initialize JSR 303 validator
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();/*from ww  w .  j av a 2  s . com*/
}

From source file:net.sf.sail.webapp.presentation.web.filters.PasAuthenticationProcessingFilter.java

/**
 * @see org.acegisecurity.ui.AbstractProcessingFilter#successfulAuthentication(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse,
 *      org.acegisecurity.Authentication)
 *//*from   ww w.j a v a 2 s  . co  m*/
@Override
protected void successfulAuthentication(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response, Authentication authResult)
        throws IOException, ServletException {

    UserDetails userDetails = (UserDetails) authResult.getPrincipal();
    if (LOGGER.isDebugEnabled()) {
        logDebug(userDetails);
    }

    HttpSession session = request.getSession();
    ApplicationContext springContext = WebApplicationContextUtils
            .getWebApplicationContext(session.getServletContext());
    UserService userService = (UserService) springContext.getBean("userService");
    User user = userService.retrieveUser(userDetails);
    session.setAttribute(User.CURRENT_USER_SESSION_KEY, user);

    // add new session in a allLoggedInUsers servletcontext HashMap variable
    String sessionId = session.getId();
    HashMap<String, User> allLoggedInUsers = (HashMap<String, User>) session.getServletContext()
            .getAttribute("allLoggedInUsers");
    if (allLoggedInUsers == null) {
        allLoggedInUsers = new HashMap<String, User>();
        session.getServletContext().setAttribute(PasSessionListener.ALL_LOGGED_IN_USERS, allLoggedInUsers);
    }
    allLoggedInUsers.put(sessionId, user);

    super.successfulAuthentication(request, response, authResult);
}

From source file:com.google.gwt.sample.dynatablemvp.server.loc.ProxyObjectLocator.java

@SuppressWarnings("unchecked")
public ProxyObjectLocator() {
    final Type genericSuperclass2 = getClass().getGenericSuperclass();
    if (genericSuperclass2 instanceof ParameterizedType) {
        ParameterizedType genericSuperclass = (ParameterizedType) genericSuperclass2;
        final Type entityType = genericSuperclass.getActualTypeArguments()[1];
        final Type daoType = genericSuperclass.getActualTypeArguments()[2];
        HttpServletRequest request = RequestFactoryServlet.getThreadLocalRequest();
        ApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(request.getSession().getServletContext());
        objectDao = (D) getTarget(context.getBean((Class<D>) daoType));
        this.keyTypeClass = (Class<K>) entityType;
    } else {//from  ww w.  j a v  a 2 s .c  o m
        this.keyTypeClass = null;
        objectDao = null;
    }
}

From source file:org.openmeetings.servlet.outputhandler.ActivateUser.java

private Usermanagement getUsermanagement() {
    try {//from   w  w  w  . jav a2s  . c o  m
        if (!ScopeApplicationAdapter.initComplete) {
            return null;
        }
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        return (Usermanagement) context.getBean("userManagement");
    } catch (Exception err) {
        log.error("[getUsermanagement]", err);
    }
    return null;
}

From source file:com.kurento.kmf.spring.KurentoApplicationContextUtils.java

/**
 * This class returns the Spring KurentoApplicationContext, which is the
 * parent context for all specific Kurento Servlet contexts. In case a
 * pre-exiting Spring root WebApplicationContext if found, the returned
 * KurentoApplicationContext will be made child of this root context. When
 * necessary, this method creates the KurentoApplicationContext, so it
 * should never return null./*from www. ja  v a2 s  .  c om*/
 * 
 * This method MUST NOT be called in ServletContextListeners, given that at
 * that stage there might not be information about the presence of a root
 * Spring root WebApplicationConext.
 * 
 * @param ctx
 * @return
 * 
 */
public static AnnotationConfigApplicationContext createKurentoApplicationContext(ServletContext ctx) {
    Assert.notNull(ctx, "Cannot recover KurentoApplicationContext from a null ServletContext");
    Assert.isNull(kurentoApplicationContextInternalReference,
            "Pre-existing Kurento ApplicationContext found. Cannot create a new instance.");

    kurentoApplicationContextInternalReference = new AnnotationConfigApplicationContext();

    // Add or remove packages when required
    kurentoApplicationContextInternalReference.scan("com.kurento.kmf");

    // Recover root WebApplicationContext context just in case
    // application developer is using Spring
    WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(ctx);
    if (rootContext != null) {
        kurentoApplicationContextInternalReference.setParent(rootContext);
    }

    final String jbossServerConfigDir = System.getProperty("jboss.server.config.dir");
    final String kurentoPropertiesDir = System.getProperty("kurento.properties.dir");
    final String kurentoProperties = "/kurento.properties";
    InputStream inputStream = null;
    try {
        if (jbossServerConfigDir != null && new File(jbossServerConfigDir + kurentoProperties).exists()) {
            // First, look for JVM argument "jboss.server.config.dir"
            inputStream = new FileInputStream(jbossServerConfigDir + kurentoProperties);
            log.info("Found custom properties in 'jboss.server.config.dir': " + jbossServerConfigDir);
        } else if (kurentoPropertiesDir != null
                && new File(kurentoPropertiesDir + kurentoProperties).exists()) {
            // Second, look for JVM argument "kurento.properties.dir"
            log.info("Found custom properties in 'kurento.properties.dir': " + kurentoPropertiesDir);
            inputStream = new FileInputStream(kurentoPropertiesDir + kurentoProperties);
        } else {
            // Third, look for properties in Servlet Context
            ServletContextResource servletContextResource = new ServletContextResource(ctx,
                    "/WEB-INF" + kurentoProperties);
            if (servletContextResource.exists()) {
                log.info("Found custom properties in Servlet Context: /WEB-INF" + kurentoProperties);
                inputStream = servletContextResource.getInputStream();
            }
        }

        if (inputStream != null) {
            Properties properties = new Properties();
            properties.load(inputStream);
            PropertyOverrideConfigurer propertyOverrideConfigurer = new PropertyOverrideConfigurer();
            propertyOverrideConfigurer.setProperties(properties);
            kurentoApplicationContextInternalReference.addBeanFactoryPostProcessor(propertyOverrideConfigurer);
            inputStream.close();
        }

    } catch (IOException e) {
        log.error("Exception loading custom properties", e);
        throw new RuntimeException(e);
    }

    kurentoApplicationContextInternalReference.refresh();
    return kurentoApplicationContextInternalReference;
}

From source file:gov.nih.nci.system.web.HTTPQuery.java

/**
 * Initialize the servlet/*from w  w  w.  j  av  a  2s  . co m*/
 */
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ServletContext context = config.getServletContext();

    ctx = WebApplicationContextUtils.getWebApplicationContext(context);
    Properties systemProperties = (Properties) ctx.getBean("WebSystemProperties");

    cacoreStyleSheet = systemProperties.getProperty("resultOutputFormatter");
    jsonStyleSheet = systemProperties.getProperty("jsonOutputFormatter");
    log.debug("cacoreStylesheet: " + cacoreStyleSheet);
    log.debug("jsonStyleSheet: " + jsonStyleSheet);

    try {
        String pageCount = systemProperties.getProperty("rowCounter");
        log.debug("rowCounter: " + pageCount);
        if (pageCount != null) {
            pageSize = Integer.parseInt(pageCount);
        }
    } catch (Exception ex) {
        log.error("Exception: ", ex);
    }
}

From source file:com.telefonica.euro_iaas.sdc.bootstrap.PropertiesMBeanRegisterBootstrap.java

/**
 * Stores every system properties in BD and show them by JMX
 *//*from w  w w  . ja v  a2 s .c  om*/

public void contextInitialized(ServletContextEvent event) {

    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());

    PropertiesProvider propertiesUtil = new PropertiesProviderFactoryImpl()
            .createPropertiesProvider((EntityManagerFactory) ctx.getBean("entityManagerFactory"));
    try {
        for (String namespace : propertiesUtil.getNamespaces()) {
            PropertiesProviderMBean mbean = new PropertiesProviderMBean(namespace, propertiesUtil);
            log.info("Registering mbean " + namespace);
            MBeanUtils.register(mbean,
                    event.getServletContext().getContextPath() + ":service=SystemConfiguration-" + namespace);
        }
    } catch (Exception e) {
        throw new SdcRuntimeException(e);
    }
}