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:net.naijatek.myalumni.framework.struts.MyAlumniExceptionHandler.java

/**
 * This method handles any java.lang.Exceptions that are not caught in
 * previous classes. It will loop through and get all the causes (exception
 * chain), create ActionErrors, add them to_email the request and then
 * forward to_email the input./*www .  j  a  v  a2  s  .  com*/
 * 
 * @see org.apache.struts.action.ExceptionHandler#execute()
 *      java.lang.Exception, org.apache.struts.config.ExceptionConfig,
 *      org.apache.struts.action.ActionMapping,
 *      org.apache.struts.action.ActionForm,
 *      javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse )
 * 
 * @param ex
 *            Exception
 * @param ae
 *            ExceptionConfig
 * @param mapping
 *            ActionMapping
 * @param form
 *            ActionForm
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @throws ServletException
 * @return ActionForward
 */
public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws ServletException {

    ActionMessages messages = new ActionMessages();

    // This is where it was suppose to forward to in the first place.
    ActionForward forward = super.execute(ex, ae, mapping, form, request, response);

    ServletContext sCtx = request.getSession().getServletContext();
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sCtx);
    IErrorLogService loggerService = (IErrorLogService) wac.getBean(BaseConstants.SERVICE_ERRORLOGGER_LOOKUP);

    String forwardKey = new String();
    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");

    Throwable thr = (Throwable) request.getAttribute("javax.servlet.error.exception");
    StringBuffer strBuffer = new StringBuffer();

    if (thr != null) {
        StackTraceElement[] stack = thr.getStackTrace();
        for (int n = 0; n < stack.length; n++) {
            strBuffer.append(stack[n].toString());
            strBuffer.append("\n");
        }
    }

    //String messg = (String) request.getAttribute("javax.servlet.error.message");
    String messg = (String) ex.getMessage();
    messg = (messg != null && messg.length() >= 4000) ? messg.substring(0, 3999) : messg;

    String trace = strBuffer.toString();
    trace = (trace != null && trace.length() >= 4000) ? trace.substring(0, 3999) : trace;

    //String cause = (String) request.getAttribute("javax.servlet.error.request_uri");
    String cause = new String();
    if (ex.getCause() != null)
        cause = ex.getCause().toString();

    String userName = new String();

    try {
        MyAlumniUserContainer sessionObj = null;
        HttpSession session = request.getSession(false);
        if (session != null) {
            sessionObj = (MyAlumniUserContainer) session.getAttribute(BaseConstants.USER_CONTAINER);
            userName = sessionObj.getToken().getMemberUserName();
        }
    } catch (Exception npe) {
        // do nothing
        userName = "";
    }

    ErrorLogVO errorLog = new ErrorLogVO();
    errorLog.setErrorDate(new Date());
    errorLog.setLoggedBy(userName);
    errorLog.setLastModifiedBy(userName);
    errorLog.setErrorMessage(messg);
    errorLog.setCause(cause);
    errorLog.setTrace(trace);

    loggerService.addErrorLog(errorLog);

    // 700: Insufficient Priviledges
    // 701: Session Timed Out

    if (statusCode != null) {
        int sc = ((Integer) statusCode).intValue();

        switch (sc) {
        case 700:
            forwardKey = BaseConstants.SC_INSURFICIENT_PRIV_700;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00701"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00701"),
                    forward);
            break;

        case 701:
            forwardKey = BaseConstants.SC_SESSION_EXPIRED_701;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00702"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00702"),
                    forward);
            break;

        }
    }

    if (forwardKey != null && forwardKey.length() == 0) {
        String requestPathInfo = request.getPathInfo(); // request path info.

        if (requestPathInfo != null && requestPathInfo.startsWith("/admin/")) {
            forwardKey = BaseConstants.FWD_ADMIN;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00703"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00703"),
                    forward);
        } else if (requestPathInfo != null && requestPathInfo.startsWith("/member/")) {
            forwardKey = BaseConstants.FWD_MEMBER;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00704"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00704"),
                    forward);
        } else {
            forwardKey = BaseConstants.FWD_MEMBER;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00703"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00703"),
                    forward);
        }
    }

    return mapping.findForward(forwardKey);
}

From source file:org.glassfish.jersey.server.spring.SpringComponentProvider.java

@Override
public void initialize(ServiceLocator locator) {
    this.locator = locator;

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(LocalizationMessages.CTX_LOOKUP_STARTED());
    }// w  ww  .j ava2s.  co  m

    ServletContext sc = locator.getService(ServletContext.class);

    if (sc != null) {
        // servlet container
        ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
    } else {
        // non-servlet container
        ApplicationHandler applicationHandler = locator.getService(ApplicationHandler.class);
        ApplicationContext springContext = (ApplicationContext) applicationHandler.getConfiguration()
                .getProperty(PARAM_SPRING_CONTEXT);
        if (springContext != null) {
            ctx = springContext;
        } else {
            String contextConfigLocation = (String) applicationHandler.getConfiguration()
                    .getProperty(PARAM_CONTEXT_CONFIG_LOCATION);
            ctx = createXmlSpringConfiguration(contextConfigLocation);
        }
    }
    if (ctx == null) {
        LOGGER.severe(LocalizationMessages.CTX_LOOKUP_FAILED());
        return;
    }
    LOGGER.config(LocalizationMessages.CTX_LOOKUP_SUCESSFUL());

    // initialize HK2 spring-bridge
    SpringBridge.getSpringBridge().initializeSpringBridge(locator);
    SpringIntoHK2Bridge springBridge = locator.getService(SpringIntoHK2Bridge.class);
    springBridge.bridgeSpringBeanFactory(ctx);

    // register Spring @Autowired annotation handler with HK2 ServiceLocator
    ServiceLocatorUtilities.addOneConstant(locator, new AutowiredInjectResolver(ctx));
    ServiceLocatorUtilities.addOneConstant(locator, ctx, "SpringContext", ApplicationContext.class);
    LOGGER.config(LocalizationMessages.SPRING_COMPONENT_PROVIDER_INITIALIZED());
}

From source file:ee.pri.rl.blog.web.filter.BlogPageCachingFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    synchronized (this.getClass()) {
        ApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(filterConfig.getServletContext());
        // Use the cache administrator created by Spring context.
        cacheAdministrator = (GeneralCacheAdministrator) context.getBean("cacheManager");
        blogService = (BlogService) context.getBean("blogService");
    }/*from w  w w .  j av  a 2s .  co  m*/
}

From source file:com.mtgi.analytics.servlet.BehaviorTrackingListener.java

private synchronized void checkInit(ServletRequestEvent event) {
    if (!initialized) {

        ServletContext context = event.getServletContext();
        boolean hasFilter = BehaviorTrackingFilter.isFiltered(context);
        ArrayList<ServletRequestBehaviorTrackingAdapter> beans = new ArrayList<ServletRequestBehaviorTrackingAdapter>();

        //find registered request adapters in all mvc servlet contexts.
        for (Enumeration<?> atts = context.getAttributeNames(); atts.hasMoreElements();) {
            String name = (String) atts.nextElement();
            if (name.startsWith(FrameworkServlet.SERVLET_CONTEXT_PREFIX)) {
                Object value = context.getAttribute(name);
                if (value instanceof ListableBeanFactory)
                    addRequestAdapters(beans, (ListableBeanFactory) value, hasFilter);
            }//  w w w .ja v a  2 s .c  om
        }

        //look for shared application context, loaded by ContextLoaderListener.
        ListableBeanFactory parent = WebApplicationContextUtils.getWebApplicationContext(context);
        if (parent != null)
            addRequestAdapters(beans, parent, hasFilter);

        if (!beans.isEmpty()) {
            adapters = beans.toArray(new ServletRequestBehaviorTrackingAdapter[beans.size()]);
            log.info("BehaviorTracking for HTTP servlet requests started");
        }

        initialized = true;
    }
}

From source file:org.brutusin.rpc.RpcWebInitializer.java

public void onStartup(final ServletContext ctx) throws ServletException {
    final RpcServlet rpcServlet = registerRpcServlet(ctx);
    final WebsocketFilter websocketFilter = new WebsocketFilter();
    FilterRegistration.Dynamic dynamic = ctx.addFilter(WebsocketFilter.class.getName(), websocketFilter);
    dynamic.addMappingForUrlPatterns(null, false, RpcConfig.getInstance().getPath() + "/wskt");
    JsonCodec.getInstance().registerStringFormat(MetaDataInputStream.class, "inputstream");
    final Bean<RpcSpringContext> rpcCtxBean = new Bean<RpcSpringContext>();
    ctx.addListener(new ServletRequestListener() {

        public void requestDestroyed(ServletRequestEvent sre) {
            GlobalThreadLocal.clear();/*w w w.ja  v  a 2 s . c om*/
        }

        public void requestInitialized(ServletRequestEvent sre) {
            GlobalThreadLocal.set(new GlobalThreadLocal((HttpServletRequest) sre.getServletRequest(), null));
        }
    });
    ctx.addListener(new ServletContextListener() {

        public void contextInitialized(ServletContextEvent sce) {
            RpcSpringContext rpcCtx = createRpcSpringContext(ctx);
            rpcCtxBean.setValue(rpcCtx);
            rpcServlet.setRpcCtx(rpcCtx);
            initWebsocketRpcRuntime(ctx, rpcCtx);
            ctx.setAttribute(RpcSpringContext.class.getName(), rpcCtx);
        }

        public void contextDestroyed(ServletContextEvent sce) {
            LOGGER.info("Destroying RPC context");
            if (rpcCtxBean.getValue() != null) {
                rpcCtxBean.getValue().destroy();
            }
        }
    });
    ctx.addListener(new ServletContextAttributeListener() {
        public void attributeAdded(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        public void attributeRemoved(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        public void attributeReplaced(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        private void updateRootContext() {
            WebApplicationContext rootCtx = WebApplicationContextUtils.getWebApplicationContext(ctx);
            if (rootCtx != null) {
                if (rpcCtxBean.getValue() != null) {
                    rpcCtxBean.getValue().setParent(rootCtx);
                }
                if (rootCtx.containsBean("springSecurityFilterChain")) {
                    LOGGER.info("Moving WebsocketFilter behind springSecurityFilterChain");
                    websocketFilter.disable();
                    FilterChainProxy fcp = (FilterChainProxy) rootCtx.getBean("springSecurityFilterChain");
                    fcp.getFilterChains().get(0).getFilters().add(new WebsocketFilter());
                }
            }
        }
    });
}

From source file:net.webpasswordsafe.server.report.JasperReportServlet.java

private void processRequest(HttpServletRequest req, HttpServletResponse res) {
    OutputStream outputStream = null;
    Connection jdbcConnection = null;
    try {//from  ww  w.j  a v a2s  . co  m
        String reportName = req.getParameter(Constants.NAME);
        String type = req.getParameter(Constants.TYPE).trim().toLowerCase();
        String locale = req.getParameter("locale");
        setNoCache(res);
        if (isAuthorizedReport(req, reportName)) {
            JasperDesign jasperDesign = JRXmlLoader.load(getServletConfig().getServletContext()
                    .getResourceAsStream("/WEB-INF/reports/" + reportName + ".jrxml"));
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            jasperReport.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);
            Map<String, Object> parameters = new HashMap<String, Object>();
            if (null != locale)
                parameters.put(JRParameter.REPORT_LOCALE, new Locale(locale));
            parameters.put(Constants.SESSION_KEY_USERNAME,
                    (String) req.getSession().getAttribute(Constants.SESSION_KEY_USERNAME));
            parameters.put(Constants.Function.BYPASS_PASSWORD_PERMISSIONS.name(),
                    isAuthorized(req, Constants.Function.BYPASS_PASSWORD_PERMISSIONS.name()) ? "1" : "0");
            ReportConfig reportConfig = (ReportConfig) WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext()).getBean("reportConfig");
            @SuppressWarnings("unchecked")
            Enumeration<String> e = req.getParameterNames();
            while (e.hasMoreElements()) {
                String param = e.nextElement();
                if (param.startsWith(Constants.REPORT_PARAM_PREFIX)) {
                    String pKey = param.substring(Constants.REPORT_PARAM_PREFIX.length());
                    String pValue = Utils.safeString(req.getParameter(param));
                    if (reportConfig.isDateParam(reportName, pKey)) {
                        parameters.put(pKey, convertToDateTime(pValue));
                    } else {
                        parameters.put(pKey, pValue);
                    }
                }
            }
            encryptorRef.set((Encryptor) WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext()).getBean("encryptor"));
            DataSource dataSource = (DataSource) WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext()).getBean("dataSource");
            jdbcConnection = dataSource.getConnection();
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jdbcConnection);
            JRExporter exporter = null;

            if (type.equals(Constants.REPORT_TYPE_PDF)) {
                res.setContentType("application/pdf");
                exporter = new JRPdfExporter();
            } else if (type.equals("rtf")) {
                res.setContentType("application/rtf");
                exporter = new JRRtfExporter();
            } else if (type.equals(Constants.REPORT_TYPE_CSV)) {
                res.setContentType("text/csv");
                exporter = new JRCsvExporter();
            } else if (type.equals("xml")) {
                res.setContentType("text/xml");
                exporter = new JRXmlExporter();
            }

            if (exporter != null) {
                DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                res.setHeader("Content-Disposition", "attachment; filename=" + reportName
                        + dateFormat.format(System.currentTimeMillis()) + "." + type);

                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                outputStream = res.getOutputStream();
                exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
                exporter.exportReport();
            } else {
                throw new RuntimeException("Invalid report type: " + type);
            }
        }
    } catch (Exception e) {
        LOG.error("JasperReportServlet Error " + e.getMessage(), e);
    } finally {
        // close the output stream
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException io) {
                LOG.error("JasperReportServlet Error " + io.getMessage(), io);
            }
        }
        // close the db connection
        if (jdbcConnection != null) {
            try {
                jdbcConnection.close();
            } catch (SQLException sql) {
                LOG.error("JasperReportServlet Error " + sql.getMessage(), sql);
            } finally {
                jdbcConnection = null;
            }
        }
    }
}

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

@Override
public void init() throws ServletException {
    super.init();
    try {/*from   w w w .java  2  s . c o  m*/
        CommonUtil commonUtil = (CommonUtil) WebApplicationContextUtils
                .getWebApplicationContext(getServletContext()).getBean(BEAN_NAME_COMMON_UTIL);
        ItemPropertyUtil itemPropUtil = (ItemPropertyUtil) WebApplicationContextUtils
                .getWebApplicationContext(getServletContext()).getBean(BEAN_NAME_ITEM_PROP_UTIL);
        PropertiesUtil propUtil = (PropertiesUtil) WebApplicationContextUtils
                .getWebApplicationContext(getServletContext()).getBean(BEAN_NAME_PROP_UTIL);
        commonUtil.init();
        itemPropUtil.init();
        propUtil.init();
    } catch (Exception exception) {
        errorLog(null, null, exception, "init");
        throw new ServletException(exception);
    }

}

From source file:org.openlmis.fulfillment.service.JasperReportsViewService.java

/**
 * Get application context from servlet.
 *//* w w w.j a v  a  2 s  .c o  m*/
public WebApplicationContext getApplicationContext(HttpServletRequest servletRequest) {
    ServletContext servletContext = servletRequest.getSession().getServletContext();
    return WebApplicationContextUtils.getWebApplicationContext(servletContext);
}

From source file:co.edu.udea.prestamoDispositivos.server.PrestamoRemoteServiceImpl.java

/**
 * es la implementacion del metodo usado para obtener la lista de dispositivos
 *///from  w ww .  ja v  a 2  s.c om
@Override
public List<DispositivoListado> obtenerDispositivos() throws MyException {

    List<Dispositivo> dispositivos = null;
    List<DispositivoListado> listadoDispositivos = new ArrayList<DispositivoListado>();

    ServletContext sc = getServletContext();
    ApplicationContext webApp = WebApplicationContextUtils.getWebApplicationContext(sc);

    HttpServletRequest req = this.getThreadLocalRequest();
    HttpSession ses = req.getSession();

    try {

        DispositivoBL dispositivoBL = (DispositivoBL) webApp.getBean("dispositivoBL");
        dispositivos = dispositivoBL.obtener();

        for (Dispositivo dispositivo : dispositivos) {
            DispositivoListado dispositivoL = new DispositivoListado();

            dispositivoL.setId_dispositivo(dispositivo.getId_dispositivo());
            dispositivoL.setEstado(dispositivo.getEstado());
            dispositivoL.setDescripcion(dispositivo.getDescripcion());
            listadoDispositivos.add(dispositivoL);
        }
    } catch (PrestamoDispositivoException e) {
        throw new MyException(e.getMessage());
    }
    return listadoDispositivos;
}

From source file:org.opennms.netmgt.ncs.rest.AbstractSpringJerseyRestTestCase.java

@Before
public void setUp() throws Throwable {
    beforeServletStart();/*from  ww w  .j a v a 2 s .c  om*/

    setServletContext(new MockServletContext("file:src/main/webapp"));

    getServletContext().addInitParameter("contextConfigLocation",
            "file:src/main/resources/META-INF/opennms/component-service.xml");

    getServletContext().addInitParameter("parentContextKey", "testDaoContext");

    ServletContextEvent e = new ServletContextEvent(getServletContext());
    setContextListener(new ContextLoaderListener());
    getContextListener().contextInitialized(e);

    getServletContext().setContextPath(contextPath);
    setServletConfig(new MockServletConfig(getServletContext(), "dispatcher"));
    /*
    getServletConfig().addInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
    getServletConfig().addInitParameter("com.sun.jersey.config.property.packages", "org.opennms.netmgt.ncs.rest");
    */
    try {

        MockFilterConfig filterConfig = new MockFilterConfig(getServletContext(), "openSessionInViewFilter");
        setFilter(new OpenSessionInViewFilter());
        getFilter().init(filterConfig);

        setDispatcher(new SpringServlet());
        getDispatcher().init(getServletConfig());

    } catch (ServletException se) {
        throw se.getRootCause();
    }

    setWebAppContext(WebApplicationContextUtils.getWebApplicationContext(getServletContext()));
    afterServletStart();
    System.err.println("------------------------------------------------------------------------------");
}