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:org.lamsfoundation.lams.admin.web.ToolContentListAction.java

private DataSource getDataSource() {
    if (ToolContentListAction.dataSource == null) {
        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServlet().getServletContext());
        ToolContentListAction.dataSource = (DataSource) ctx.getBean("dataSource");
    }/*w w  w  .  j a v  a  2 s .co m*/
    return ToolContentListAction.dataSource;
}

From source file:com.netpace.cms.sso.filter.AlfrescoFacade.java

public AlfrescoFacade(ServletContext servletContext) {
    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();
    authComponent = (AuthenticationComponent) ctx.getBean("AuthenticationComponent");
    authService = (AuthenticationService) ctx.getBean("AuthenticationService");
    personService = (PersonService) ctx.getBean("personService");
    permissionService = (PermissionService) ctx.getBean("permissionService");
    authenticationService = (AuthenticationService) ctx.getBean("authenticationService");
    authorityService = (AuthorityService) ctx.getBean("authorityService");
    wpService = serviceRegistry.getWebProjectService();
    transactionalHelper = new TransactionalHelper(transactionService);

}

From source file:com.someco.servlets.AuthenticationFilter.java

public void init(FilterConfig config) throws ServletException {
    this.context = config.getServletContext();
    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();

    authComponent = (AuthenticationComponent) ctx.getBean("AuthenticationComponent");
    authService = (AuthenticationService) ctx.getBean("AuthenticationService");
    personService = (PersonService) ctx.getBean("personService");

    // Get a list of the available locales
    ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService");
    LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.getConfig("Languages")
            .getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID);

    m_languages = configElement.getLanguages();

    casUserSessionAttributeName = config.getInitParameter(CAS_USER_INIT_PARAM_NAME);
    if (casUserSessionAttributeName == null) {
        logger.error("CAS : Filter init-param named " + CAS_USER_INIT_PARAM_NAME + " not found in web.xml");
        Enumeration enumNames = context.getInitParameterNames();
        while (enumNames.hasMoreElements()) {
            String name = enumNames.nextElement().toString();
            logger.error("init param " + name + ": " + context.getInitParameter(name));
        }/* w w  w  .  j a va 2  s .  c o  m*/
        // last resort - hack in the default CAS attribute name. At least it prevents 
        // NPEs later.
        casUserSessionAttributeName = "edu.yale.its.tp.cas.client.filter.user";
    }
}

From source file:com.trailmagic.image.ui.ImageTag.java

public int doStartTag() throws JspException {
    StringBuffer html = new StringBuffer();
    ImageManifestation mf;//from  w  w  w.jav  a2  s  .  co m

    try {
        HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
        // XXX: maybe this should be a parameter of the tag instead?

        // XXX: this is sort of a kludge for setting a default label
        String defaultLabel = req.getParameter(DEFAULT_LABEL_ATTR);
        HttpSession session = req.getSession();
        if (defaultLabel != null) {
            session.setAttribute(DEFAULT_LABEL_ATTR, defaultLabel);
        }

        // XXX: end kludge

        String size = req.getParameter(SIZE_ATTR);
        String originalp = req.getParameter("original");
        if (size != null) {
            mf = WebSupport.getMFBySize(m_image, Integer.parseInt(size), Boolean.parseBoolean(originalp));
        } else {
            // get label by precedence: req param, tag spec, sess attr
            String label = req.getParameter(LABEL_ATTR);
            if (label == null) {
                label = m_sizeLabel;
            }
            if (label == null) {
                label = (String) session.getAttribute(DEFAULT_LABEL_ATTR);
            }
            if (label != null) {
                mf = WebSupport.getMFByLabel(m_image, label);
            } else {
                mf = WebSupport.getDefaultMF((User) pageContext.findAttribute(USER_ATTR), m_image);
            }
        }

        if (mf != null) {
            // XXX: resume kludge
            pageContext.setAttribute("currentLabel", getLabel(mf));
            // XXX: end kludge
            // XXX: end kludge
            html.append("<img src=\"");

            //XXX: yeek?
            /*
            LinkHelper helper =
            new LinkHelper((HttpServletRequest)pageContext.getRequest());
            */
            WebApplicationContext ctx = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(pageContext.getServletContext());
            LinkHelper helper = (LinkHelper) ctx.getBean("linkHelper");

            html.append(helper.getImageMFUrl((HttpServletRequest) pageContext.getRequest(), mf));
            html.append("\" height=\"");
            html.append(mf.getHeight());
            html.append("\" width=\"");
            html.append(mf.getWidth());
            html.append("\" alt=\"");
            if (m_alt != null) {
                html.append(m_alt);
            } else if (m_image.getCaption() != null) {
                html.append(Util.escapeXml(m_image.getCaption()));
            } else {
                html.append(Util.escapeXml(m_image.getDisplayName()));
            }

            html.append("\" class=\"");
            if (mf.getWidth() > mf.getHeight()) {
                html.append("landscape");
            } else {
                html.append("portrait");
            }
            if (m_cssClass != null) {
                html.append(" ");
                html.append(m_cssClass);
            }

            html.append("\"/>");
        } else {
            html.append("No manifestations found for the specified " + "image.");
        }
        pageContext.getOut().write(html.toString());
        return SKIP_BODY;
    } catch (IOException e) {
        throw new JspException(e);
    }
}

From source file:org.wallride.web.controller.admin.system.SystemIndexController.java

@Transactional(propagation = Propagation.REQUIRED)
@RequestMapping(value = "/clear-cache", method = RequestMethod.POST)
public String clearCache(@PathVariable String language, RedirectAttributes redirectAttributes,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        throw new ServiceException("GuestServlet is not ready yet");
    }/*from  w ww .ja v  a 2 s  . com*/

    DefaultModelAttributeInterceptor interceptor = context.getBean(DefaultModelAttributeInterceptor.class);
    ModelAndView mv = new ModelAndView("dummy");
    interceptor.postHandle(request, response, this, mv);

    SpringTemplateEngine templateEngine = context.getBean("templateEngine", SpringTemplateEngine.class);
    logger.info("Clear cache started");
    templateEngine.clearTemplateCache();
    logger.info("Clear cache finished");

    redirectAttributes.addFlashAttribute("clearCache", true);
    redirectAttributes.addAttribute("language", language);
    return "redirect:/_admin/{language}/system";
}

From source file:org.lamsfoundation.lams.admin.web.ToolContentListAction.java

private ILearningDesignService getLearningDesignService() {
    if (ToolContentListAction.learningDesignService == null) {
        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServlet().getServletContext());
        ToolContentListAction.learningDesignService = (ILearningDesignService) ctx
                .getBean("learningDesignService");
    }/*from   w  ww  .  jav a  2 s .c om*/
    return ToolContentListAction.learningDesignService;
}

From source file:org.lamsfoundation.lams.admin.web.ToolContentListAction.java

private IUserManagementService getUserManagementService() {
    if (ToolContentListAction.userManagementService == null) {
        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServlet().getServletContext());
        ToolContentListAction.userManagementService = (IUserManagementService) ctx
                .getBean("userManagementService");
    }/* ww w .  jav a  2  s  .  co m*/
    return ToolContentListAction.userManagementService;
}

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  w w  w .  j a  v  a 2 s  .c om
 *
 * @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: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.//from  w  w  w . j ava 2  s  .c  om
 * 
 * @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:com.ibm.asset.trails.form.ReportDownload.java

@Override
public void doGet(HttpServletRequest pHttpServletRequest, HttpServletResponse pHttpServletResponse)
        throws ServletException, IOException {
    String lsName = this.getParameter(pHttpServletRequest, "name");
    String lsCode = this.getParameter(pHttpServletRequest, "code");
    UserSession lUserSession = ((UserSession) pHttpServletRequest.getSession().getAttribute("userSession"));

    if (lUserSession != null || lsName.equalsIgnoreCase(REPORT_NAME_NON_WORKSTATION_ACCOUNTS)
            || lsName.equalsIgnoreCase(REPORT_NAME_WORKSTATION_ACCOUNTS)) {
        Account lAccount = null;//  w w  w. j a va  2  s. c  om
        String remoteUser = null;
        ReportBase lReportBase = null;
        ServletContext lServletContext = getServletContext();
        WebApplicationContext lWebApplicationContext = WebApplicationContextUtils
                .getRequiredWebApplicationContext(lServletContext);
        ReportService lReportService = (ReportService) lWebApplicationContext.getBean("reportService");

        if (lUserSession != null) {
            lAccount = ((UserSession) pHttpServletRequest.getSession().getAttribute("userSession"))
                    .getAccount();
            remoteUser = ((UserSession) pHttpServletRequest.getSession().getAttribute("userSession"))
                    .getRemoteUser();
        }

        try {
            pHttpServletResponse.setContentType("application/vnd.ms-excel");
            HSSFWorkbook hwb = new HSSFWorkbook();
            if (lsCode != null) {
                pHttpServletResponse.setHeader("Content-Disposition",
                        new StringBuffer("filename=").append(lsName).append(lsCode)
                                .append(lAccount != null ? lAccount.getAccount().toString() : "").append(".xls")
                                .toString());
            } else {
                pHttpServletResponse.setHeader("Content-Disposition",
                        new StringBuffer("filename=").append(lsName)
                                .append(lAccount != null ? lAccount.getAccount().toString() : "").append(".xls")
                                .toString());
            }
            lReportBase = getReport(lsName, lsCode, lReportService, pHttpServletResponse.getOutputStream(),
                    pHttpServletRequest, hwb);

            if (lReportBase != null) {
                lReportBase.execute(pHttpServletRequest, lAccount, remoteUser, lsName);
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    } else {
        pHttpServletResponse.sendRedirect("/TRAILS");
    }
}