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:org.granite.grails.integration.GrailsExternalizer.java

private Externalizer getDelegate() {
    if (delegate == null) {
        GraniteContext context = GraniteContext.getCurrentInstance();
        ServletContext sc = ((HttpGraniteContext) context).getServletContext();
        ApplicationContext springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

        grailsApplication = (GrailsApplication) springContext.getBean("grailsApplication");
        GrailsPluginManager manager = (GrailsPluginManager) springContext.getBean("pluginManager");
        if (manager.hasGrailsPlugin("app-engine"))
            delegate = new GrailsDataNucleusExternalizer(grailsApplication);
        else//from ww w .  j  av  a  2 s. co  m
            delegate = new GrailsHibernateExternalizer(grailsApplication);

        enumExternalizer = new EnumExternalizer();
    }
    return delegate;
}

From source file:org.musicrecital.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}//from   w w w  . jav  a  2s  . c om
 */
@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>();
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    PasswordEncoder passwordEncoder = null;
    try {
        ProviderManager provider = (ProviderManager) ctx
                .getBean("org.springframework.security.authentication.ProviderManager#0");
        for (Object o : provider.getProviders()) {
            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 (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"));
        if (passwordEncoder != null) {
            log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);

    // Determine version number for CSS and JS Assets
    String appVersion = null;
    try {
        InputStream is = context.getResourceAsStream("/META-INF/MANIFEST.MF");
        if (is == null) {
            log.warn("META-INF/MANIFEST.MF not found.");
        } else {
            Manifest mf = new Manifest();
            mf.read(is);
            Attributes atts = mf.getMainAttributes();
            appVersion = atts.getValue("Implementation-Version");
        }
    } catch (IOException e) {
        log.error("I/O Exception reading manifest: " + e.getMessage());
    }

    // If there was a build number defined in the war, then use it for
    // the cache buster. Otherwise, assume we are in development mode
    // and use a random cache buster so developers don't have to clear
    // their browser cache.
    if (appVersion == null || appVersion.contains("SNAPSHOT")) {
        appVersion = "" + new Random().nextInt(100000);
    }

    log.info("Application version set to: " + appVersion);
    context.setAttribute(Constants.ASSETS_VERSION, appVersion);
}

From source file:sg.edu.ntu.hrms.web.action.UploadEmp.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w  . j a  v  a 2s. c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean hasAccess = false;
    response.setContentType("text/html;charset=UTF-8");
    String action = request.getParameter("action");
    System.out.println("action: " + action);
    HttpSession session = request.getSession();
    HashMap accessTab = (HashMap) session.getAttribute("access");
    AccessDTO access = (AccessDTO) accessTab.get("System Log");
    if (access.getAccess() >= 1) {
        hasAccess = true;
    }
    if (!hasAccess) {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/noAccess.jsp");
        dispatcher.forward(request, response);
    } else {
        if (action == null || action.isEmpty()) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            //PriceDAO priceDAO = new PriceDAO();
            WebApplicationContext ctx = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(getServletContext());

            try {
                List<FileItem> fields = upload.parseRequest(request);
                EmployeeEditService svc = (EmployeeEditService) ctx.getBean(EmployeeEditService.class);
                svc.uploadEmp(fields);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

                //System.out.println("redirect to employee");
                response.sendRedirect("employee.action");
                /*
                RequestDispatcher dispatcher = request.getRequestDispatcher("/employee");
                //request.setAttribute(Constants.TITLE, "Home");
                dispatcher.forward(request, response);
                */

            }
        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/uploadEmp.jsp");
            //request.setAttribute(Constants.TITLE, "Home");
            dispatcher.forward(request, response);

        }
    }
}

From source file:de.fhg.igd.vaadin.util.VaadinUtil.java

public static ApplicationContext getSpringApplicationContext(Application app) {
    return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext(app));
}

From source file:com.wtr.ui.action.Login.java

public void prepare() throws Exception {
    logger.debug("Inside Login:prepare()");
    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(ServletActionContext.getServletContext());

    /* COMMENTED FOR FUTURE SERVICE IMPLEMENTATION
    userService = (UserService)context.getBean("userService");
    patientService = (PatientService)context.getBean("patientService");
    doctorService = (DoctorService)context.getBean("doctorService");
            /* w  ww . j a v  a2 s  . c  o  m*/
    auditInfoService = (AuditInfoService)context.getBean("auditInfoService");
    logger.debug("In prepare, userService ="+userService);
            
    */
    //is client behind something?
    ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    logger.debug("client's ipAddress =" + ipAddress);
}

From source file:org.xaloon.wicket.component.application.AbstractWebApplication.java

@Override
protected void init() {
    super.init();
    getResourceSettings().setThrowExceptionOnMissingResource(false);

    getMarkupSettings().setCompressWhitespace(true);
    getMarkupSettings().setStripComments(true);
    getMarkupSettings().setStripWicketTags(true);
    getMarkupSettings().setDefaultMarkupEncoding("UTF-8");
    getRequestCycleSettings().setResponseRequestEncoding("UTF-8");
    addComponentInstantiationListener(new SpringComponentInjector(this));

    context = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
    pluginManager.init(context);//from ww w . j  av  a 2  s  .com

    annotationScannerContainer.addObserver(new MenuPluginObserver(pluginManager));
    annotationScannerContainer.scan(this, context);
}

From source file:com.nec.harvest.servlet.listener.WebApplicationContextLoaderListener.java

/**
 * Close the root web application context
 *//*w w w  . java 2 s.co m*/
@Override
public void contextDestroyed(ServletContextEvent event) {
    super.contextDestroyed(event);

    // Destroying Harvest application.......
    if (logger.isDebugEnabled()) {
        logger.debug("Destroying Harvest application.......");
    }

    /// You can get Servlet Context
    ServletContext servletContext = event.getServletContext();
    WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    String jasperReportPath = getReportPath(webApplicationContext);

    // Delete jasper report folder
    logger.info("Trying to remove storaged folder for all reports", jasperReportPath);

    File folder = new File(jasperReportPath);
    if (folder.exists()) {
        try {
            FileUtil.delete(folder);
        } catch (IOException ex) {
            logger.warn(ex.getMessage());
        }
    }
}

From source file:fr.hoteia.qalingo.core.web.servlet.DispatcherServlet.java

private void initPlatformTheme(HttpServletRequest request) {
    final ServletContext context = getServletContext();
    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    final RequestUtil requestUtil = (RequestUtil) ctx.getBean("requestUtil");

    // THEME//from   www  . j ava2s.  c o  m
    try {
        final MarketArea marketArea = requestUtil.getCurrentMarketArea(request);
        if (marketArea != null && StringUtils.isNotEmpty(marketArea.getTheme())) {
            String themeFolder = marketArea.getTheme();
            requestUtil.updateCurrentTheme(request, themeFolder);
        } else {
            final Market market = requestUtil.getCurrentMarket(request);
            if (market != null && StringUtils.isNotEmpty(market.getTheme())) {
                String themeFolder = market.getTheme();
                requestUtil.updateCurrentTheme(request, themeFolder);
            } else {
                final MarketPlace marketPlace = requestUtil.getCurrentMarketPlace(request);
                if (marketPlace != null && StringUtils.isNotEmpty(marketPlace.getTheme())) {
                    String themeFolder = marketPlace.getTheme();
                    requestUtil.updateCurrentTheme(request, themeFolder);
                }
            }
        }

    } catch (Exception e) {
        LOG.error("", e);
    }
}

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

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

From source file:com.qualogy.qafe.web.ContextLoader.java

private static void create(ServletContext servletContext) throws MalformedURLException, URISyntaxException {
    String configLocation = servletContext.getInitParameter(CONFIG_FILE_PARAM);
    String contextPath = getContextPath(servletContext);
    QafeConfigurationManager contextInitialiser = new QafeConfigurationManager(contextPath);
    ApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    contextInitialiser.setSpringContext(springContext);
    qafeContext.putInstance(QafeConfigurationManager.class.getName(), contextInitialiser);

    StopWatch watch = new StopWatch();
    watch.start();//from w  w w. j a  v  a2s.  co m
    ApplicationContextLoader.unload();

    // The default way: works on JBoss/Tomcat/Jetty
    String configFileLocation = servletContext.getRealPath("/WEB-INF/");
    if (configFileLocation != null) {
        configFileLocation += File.separator + configLocation;
        logger.log(Level.INFO, "URL to config file on disk :" + configFileLocation + ")");
        ApplicationContextLoader.load(configFileLocation, true);
    } else {
        // This is how a weblogic explicitly wants the fetching of resources.
        URL url = servletContext.getResource("/WEB-INF/" + configLocation);
        logger.log(Level.INFO, "Fallback scenario" + url.toString());
        if (url != null) {
            logger.log(Level.INFO, "URL to config file " + url.toString());
            ApplicationContextLoader.load(url.toURI(), true);
        } else {
            throw new RuntimeException(
                    "Strange Error: /WEB-INF/ cannot be found. Check the appserver or installation directory.");
        }
    }

    watch.stop();
    logger.log(Level.INFO,
            "Root WebApplicationContext: initialization completed in " + watch.getTime() + " ms");
}