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

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

Introduction

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

Prototype

public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc)
        throws IllegalStateException 

Source Link

Document

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

Usage

From source file:com.enonic.cms.server.service.servlet.CmsDispatcherServlet.java

private ApplicationContext startContextIfNeeded() {
    WebApplicationContext appContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServletContext());
    if (appContext instanceof ConfigurableWebApplicationContext) {
        startContextIfNeeded((ConfigurableWebApplicationContext) appContext);
    }// w  ww.  j  a v  a  2 s.  c  om
    return appContext;
}

From source file:flex.contrib.services.SpringAutowiringBootstrapService.java

@Override
public void initialize(String id, ConfigMap properties) {

    MessageBroker mb = getMessageBroker();

    // get the application context
    ServletContext servletContext = mb.getInitServletContext();
    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    // loop over all registered bean definitions
    String[] beanNames = ctx.getBeanDefinitionNames();
    for (int i = 0; i < beanNames.length; i++) {
        String beanName = beanNames[i];
        try {/* w  ww .  j ava2  s .  c om*/
            Object bean = ctx.getBean(beanName);
            // if the bean is a remoting destination bean, create the remoting destination
            if (FlexUtils.hasRemotingDestinationAnnotation(bean)) {
                FlexUtils.createRemotingDestination(bean, beanName, mb);
            }
        } catch (BeanIsAbstractException e) {
            // do nothing... abstract beans aren't going to be remote destination beans
        } catch (ConfigurationException e) {
            log.error("Unable to configure remoting destination for Spring service named '" + beanName + "'.",
                    e);
        } catch (RuntimeException e) {
            log.error("Unable to create remoting destination for Spring service named '" + beanName + "'.", e);
        }
    }
}

From source file:net.siegmar.japtproxy.JaptProxyServlet.java

/**
 * Initializes the Japt-Proxy configuration.
 *
 * @throws ServletException is thrown if the initialization fails.
 *//*from  w ww.  jav a2s  . c  om*/
@Override
public void init() throws ServletException {
    LOG.info("Starting Japt-Proxy servlet {}", Util.VERSION);

    if (japtProxy == null) {
        final WebApplicationContext appCtx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServletContext());
        japtProxy = appCtx.getBean("japtProxy", JaptProxy.class);
    }

    LOG.info("Japt-Proxy servlet initialization complete");
}

From source file:org.openxdata.server.servlet.ResetPasswordServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    mailSender = (org.springframework.mail.javamail.JavaMailSenderImpl) ctx.getBean("mailSender");
    userService = (UserService) ctx.getBean("userService");
    userDetailsService = (UserDetailsService) ctx.getBean("userDetailsService");
    messageSource = (ResourceBundleMessageSource) ctx.getBean("messageSource");
    userLocale = new Locale((String) request.getSession().getAttribute("locale")); //new AcceptHeaderLocaleResolver().resolveLocale(request);
    log.debug("userLocale=" + userLocale.getLanguage());

    String email = request.getParameter("email");
    if (email == null) {
        //ajax response reference text
        out.println("noEmailSuppliedError");
    }/*from ww w. j ava  2  s  .  c  o m*/

    try {
        User user = userService.findUserByEmail(email);
        /*
          * Valid User with the correct e-mail.
          */
        insertUserInSecurityContext(user); // this is so that it is possible to reset their password (security checks)

        Properties props = propertyPlaceholder.getResolvedProps();
        String from = props.getProperty("mailSender.from");

        try {
            //Reset the User password and send an email
            userService.resetPassword(user, 6);
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setTo(email);
            msg.setSubject(messageSource.getMessage("resetPasswordEmailSubject",
                    new Object[] { user.getFullName() }, userLocale));
            msg.setText(messageSource.getMessage("resetPasswordEmail",
                    new Object[] { user.getName(), user.getClearTextPassword() }, userLocale));
            msg.setFrom(from);

            try {
                mailSender.send(msg);
                //ajax response reference text
                out.println("passwordResetSuccessful");
            } catch (MailException ex) {
                log.error("Error while sending an email to the user " + user.getName()
                        + " in order to reset their password.", ex);
                log.error("Password reset email:" + msg.toString());
                //ajax response reference text
                out.println("emailSendError");
            }
        } catch (Exception e) {
            log.error("Error while resetting the user " + user.getName() + "'s password", e);
            //ajax response reference text
            out.println("passwordResetError");
        }
    } catch (UserNotFoundException userNotFound) {
        /*
        * Invalid User or incorrect Email.
        */
        //ajax response reference text
        out.println("validationError");
    }
}

From source file:org.brushingbits.jnap.struts2.config.RestControllerConfigBuilder.java

@Inject
public RestControllerConfigBuilder(Configuration configuration, Container container,
        ObjectFactory objectFactory, @Inject("struts.convention.redirect.to.slash") String redirectToSlash,
        @Inject("struts.convention.default.parent.package") String defaultParentPackage,
        @Inject ServletContext servletContext) {

    super(configuration, container, objectFactory, redirectToSlash, defaultParentPackage);
    setAlwaysMapExecute(Boolean.toString(false));

    // finding the web application context
    try {//from   w  ww.  j  a  v  a  2 s. c  o m
        this.applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    } catch (IllegalStateException e) {
        // TODO
    }

}

From source file:com.gisgraphy.webapp.listener.StartupListener.java

@SuppressWarnings({ "unchecked" })
public void contextInitialized(ServletContextEvent event) {
    log.debug("initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }/*w ww . j a v  a2s  . c o m*/

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    boolean encryptPassword = true;

    try {
        ProviderManager provider = (ProviderManager) ctx
                .getBean(ctx.getBeanNamesForType(ProviderManager.class)[0]);
        for (Object o : provider.getProviders()) {
            AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            }
            config.put(Constants.ENCRYPT_PASSWORD, Boolean.TRUE);
            config.put(Constants.ENC_ALGORITHM, "SHA");
        }
    } catch (NoSuchBeanDefinitionException n) {
        log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
        log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        log.debug("Encrypt Passwords? " + encryptPassword);
        if (encryptPassword) {
            log.debug("Encryption Algorithm: " + config.get(Constants.ENC_ALGORITHM));
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);
}

From source file:ejportal.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}// w  ww. j a va  2 s .  co  m
 */
@SuppressWarnings("unchecked")
public void contextInitialized(final ServletContextEvent event) {
    StartupListener.log.debug("Initializing context...");

    final ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*
     * String[] beans = ctx.getBeanDefinitionNames(); for (String bean :
     * beans) { log.debug(bean); }
     */

    PasswordEncoder passwordEncoder = null;
    try {
        final ProviderManager provider = (ProviderManager) ctx.getBean("_authenticationManager");
        for (final Object o : provider.getProviders()) {
            final AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (final NoSuchBeanDefinitionException n) {
        StartupListener.log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (StartupListener.log.isDebugEnabled()) {
        StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        StartupListener.log.debug("Populating drop-downs...");
    }

    StartupListener.setupContext(context);
}

From source file:net.mojodna.sprout.support.SpringBodyTagSupport.java

/**
 * Fetch ContextLoaderPlugIn's WebApplicationContext from the ServletContext,
 * falling back to the root WebApplicationContext (the usual case).
 * @return the WebApplicationContext/*from  ww  w  . jav  a  2s  .c om*/
 * @throws IllegalStateException if no WebApplicationContext could be found
 * @see ContextLoaderPlugIn#SERVLET_CONTEXT_PREFIX
 * @see WebApplicationContextUtils#getWebApplicationContext
 */
protected WebApplicationContext initWebApplicationContext(final PageContext pageContext)
        throws IllegalStateException {
    final ServletContext sc = pageContext.getServletContext();
    WebApplicationContext wac = (WebApplicationContext) sc
            .getAttribute(ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX);
    if (null == wac) {
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    }
    return wac;
}

From source file:org.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override//from w  w  w .ja v  a  2s  .c  o m
public void init(final ServletConfig config) throws ServletException {
    super.init(config);

    final WebApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServletContext());

    final String param = config.getInitParameter(TRUST_ENGINE_PARAM);
    if (param != null) {
        log.debug("Looking up TrustEngine bean: {}", param);
        final Object bean = springContext.getBean(param);
        if (bean instanceof TrustEngine) {
            trustEngine = (TrustEngine) bean;
        } else {
            throw new ServletException("Bean " + param + " was missing, or not a TrustManager");
        }
    }
}

From source file:it.geosolutions.servicebox.ServiceBoxActionServlet.java

/**
 * Init method of the servlet. Don't forgot override it on the actions and
 * change the action name/*from   w  w  w .j  av a 2 s .c  o m*/
 */
public void init(ServletConfig servletConfig) throws ServletException {
    this.actionName = this.getClass().getSimpleName();
    super.init(servletConfig);
    String appPropertyFile = getServletContext().getInitParameter(PROPERTY_FILE_PARAM);
    InputStream inputStream = ServiceBoxActionServlet.class.getResourceAsStream(appPropertyFile);
    try {
        properties.load(inputStream);
        ServletContext context = getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        String actionHandler = DEFAULT_ACTION_HANDLER;
        if (actionName != null && properties != null
                && properties.containsKey(actionName + "." + DEFAULT_ACTION_HANDLER)) {
            actionHandler = properties.getProperty(actionName + "." + DEFAULT_ACTION_HANDLER);
        }
        serviceBoxActionHandler = (ServiceBoxActionHandler) wac.getBean(actionHandler);
        initTemporalFolder();
    } catch (IOException e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Error encountered while processing properties file", e);
        }
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error building the action configuration ", e);
            throw new ServletException(e.getMessage());
        }
    }
}