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:de.u808.simpleinquest.web.SimpleInquestServlet.java

private void initQuarz() {
    try {// w w  w  .j  ava2 s  .  c  om
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        Scheduler scheduler = (Scheduler) context.getBean("quarz");

        //            scheduler = StdSchedulerFactory.getDefaultScheduler();
        //         // and start it off
        //            scheduler.start();

        //FileIndexer Task
        //for testing
        //            CronTrigger cronTrigger = new CronTrigger("FileIndexerTrigger", "IndexerGroup");
        //            cronTrigger.setCronExpression("0 29 1 ? * *");
        //            cronTrigger.setName(FILE_INDEXER_TRIGGER);
        //            cronTrigger.setGroup(INDEXER_GROUP);

        //Trigger trigger = TriggerUtils.makeSecondlyTrigger(5);
        Trigger trigger = TriggerUtils.makeDailyTrigger(SchedulerManager.FILE_INDEXER_TRIGGER, 01, 00);
        trigger.setName(SchedulerManager.FILE_INDEXER_TRIGGER);
        trigger.setGroup(SchedulerManager.INDEXER_GROUP);

        JobDetail jobDetail = new JobDetail("FileIndexerJob", SchedulerManager.INDEXER_GROUP,
                FileIndexerJob.class);
        scheduler.scheduleJob(jobDetail, trigger);
        // schedulerFactoryBean.setJobDetails(jobs);

    } catch (SchedulerException e) {
        log.error("Error during quarz start", e);
    }

}

From source file:info.jtrac.wicket.JtracApplication.java

@Override
public void init() {

    super.init();

    // get hold of spring managed service layer (see BasePage, BasePanel etc for how it is used)
    ServletContext sc = getServletContext();
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
    jtrac = (Jtrac) applicationContext.getBean("jtrac");

    // check if acegi-cas authentication is being used, get reference to object to be used
    // by wicket authentication to redirect to right pages for login / logout        
    try {/*from  w ww  .  j  a  v a2  s .  co m*/
        jtracCasProxyTicketValidator = (JtracCasProxyTicketValidator) applicationContext
                .getBean("casProxyTicketValidator");
        logger.info(
                "casProxyTicketValidator retrieved from application context: " + jtracCasProxyTicketValidator);
    } catch (NoSuchBeanDefinitionException nsbde) {
        logger.info(
                "casProxyTicketValidator not found in application context, CAS single-sign-on is not being used");
    }

    // delegate wicket i18n support to spring i18n
    getResourceSettings().addStringResourceLoader(new IStringResourceLoader() {
        public String loadStringResource(Class clazz, String key, Locale locale, String style) {
            try {
                return applicationContext.getMessage(key, null, locale);
            } catch (Exception e) {
                // have to return null so that wicket can try to resolve again
                // e.g. without prefixing component id etc.
                if (logger.isDebugEnabled()) {
                    logger.debug("i18n failed for key: '" + key + "', Class: " + clazz + ", Style: " + style
                            + ", Exception: " + e);
                }
                return null;
            }
        }

        public String loadStringResource(Component component, String key) {
            Class clazz = component == null ? null : component.getClass();
            Locale locale = component == null ? Session.get().getLocale() : component.getLocale();
            return loadStringResource(clazz, key, locale, null);
        }
    });

    getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy() {
        public boolean isActionAuthorized(Component c, Action a) {
            return true;
        }

        public boolean isInstantiationAuthorized(Class clazz) {
            if (BasePage.class.isAssignableFrom(clazz)) {
                if (((JtracSession) Session.get()).isAuthenticated()) {
                    return true;
                }
                if (jtracCasProxyTicketValidator != null) {
                    // attempt CAS authentication ==========================
                    logger.debug("checking if context contains CAS authentication");
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                    if (authentication != null && authentication.isAuthenticated()) {
                        logger.debug("security context contains CAS authentication, initializing session");
                        ((JtracSession) Session.get()).setUser((User) authentication.getPrincipal());
                        return true;
                    }
                }
                // attempt remember-me auto login ==========================
                if (attemptRememberMeAutoLogin()) {
                    return true;
                }
                // attempt guest access if there are "public" spaces =======
                List<Space> spaces = getJtrac().findSpacesWhereGuestAllowed();
                if (spaces.size() > 0) {
                    logger.debug(spaces.size() + " public space(s) available, initializing guest user");
                    User guestUser = new User();
                    guestUser.setLoginName("guest");
                    guestUser.setName("Guest");
                    guestUser.addSpaceWithRole(null, "ROLE_GUEST");
                    for (Space space : spaces) {
                        guestUser.addSpaceWithRole(space, "ROLE_GUEST");
                    }
                    ((JtracSession) Session.get()).setUser(guestUser);
                    // and proceed
                    return true;
                }
                // not authenticated, go to login page
                logger.debug("not authenticated, forcing login, page requested was " + clazz.getName());
                if (jtracCasProxyTicketValidator != null) {
                    String serviceUrl = jtracCasProxyTicketValidator.getServiceProperties().getService();
                    String loginUrl = jtracCasProxyTicketValidator.getLoginUrl();
                    logger.debug("cas authentication: service URL: " + serviceUrl);
                    String redirectUrl = loginUrl + "?service=" + serviceUrl;
                    logger.debug("attempting to redirect to: " + redirectUrl);
                    throw new RestartResponseAtInterceptPageException(new RedirectPage(redirectUrl));
                } else {
                    throw new RestartResponseAtInterceptPageException(LoginPage.class);
                }
            }
            return true;
        }
    });

    // friendly urls for selected pages
    if (jtracCasProxyTicketValidator != null) {
        mountBookmarkablePage("/login", CasLoginPage.class);
    } else {
        mountBookmarkablePage("/login", LoginPage.class);
    }
    mountBookmarkablePage("/logout", LogoutPage.class);
    mountBookmarkablePage("/svn", SvnStatsPage.class);
    mountBookmarkablePage("/test", TestPage.class);
    mountBookmarkablePage("/casError", CasLoginErrorPage.class);
    // bookmarkable url for viewing items
    mount(new IndexedParamUrlCodingStrategy("/item", ItemViewPage.class));
}

From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java

public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    // get the context of the servlet
    context = getServletContext();/*  w  w w .j  a v a 2s . com*/

    // get the context of the application
    WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);

    // the the strabon wrapper
    strabonWrapper = (StrabonBeanWrapper) applicationContext.getBean("strabonBean");

    // get the name of this web application
    appName = context.getContextPath().replace("/", "");

}

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

public GenerateImage getGenerateImage() {
    try {//  w  w w . java 2s .  c  om
        if (ScopeApplicationAdapter.initComplete) {
            ApplicationContext context = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            return (GenerateImage) context.getBean("generateImage");
        }
    } catch (Exception err) {
        log.error("[getGenerateImage]", err);
    }
    return null;
}

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

public Organisationmanagement getOrganisationmanagement() {
    try {//w  ww  .j a  v  a2 s .c om
        if (ScopeApplicationAdapter.initComplete) {
            ApplicationContext context = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            return (Organisationmanagement) context.getBean("organisationmanagement");
        }
    } catch (Exception err) {
        log.error("[getOrganisationmanagement]", err);
    }
    return null;
}

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

public Configurationmanagement getCfgManagement() {
    try {// ww w . ja va  2s  . c  o  m
        if (ScopeApplicationAdapter.initComplete) {
            ApplicationContext context = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            return (Configurationmanagement) context.getBean("cfgManagement");
        }
    } catch (Exception err) {
        log.error("[getCfgManagement]", err);
    }
    return null;
}

From source file:com.kagubuzz.servlets.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * // w w  w.j a va 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
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    ApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());

    fileService = (FileService) applicationContext.getBean("fileService");
    JavaFileUtilities fileUtils = new JavaFileUtilities();
    InputStream is = null;
    FileOutputStream os = null;
    Map<String, Object> uploadResult = new HashMap<String, Object>();
    ObjectMapper mapper = new ObjectMapper();

    //TODO:  Mske all these files write to a tmp direcotry for th euploader to be erased when the review button is pushed
    try {
        byte[] buffer = new byte[4096];
        int bytesRead = 0;

        // Make sure image file is less than 4 megs

        if (bytesRead > 1024 * 1024 * 4)
            throw new FileUploadException();

        is = request.getInputStream();

        File tmpFile = File.createTempFile("image-", ".jpg");

        os = new FileOutputStream(tmpFile);

        System.out.println("Saving to " + JavaFileUtilities.getTempFilePath());

        while ((bytesRead = is.read(buffer)) != -1)
            os.write(buffer, 0, bytesRead);

        KaguImage thumbnailImage = new KaguImage(tmpFile);

        thumbnailImage.setWorkingDirectory(JavaFileUtilities.getTempFilePath());
        thumbnailImage.resize(140, 180);

        File thumbnail = thumbnailImage
                .saveAsJPG("thumbnail-" + FilenameUtils.removeExtension(tmpFile.getName()));

        fileService.write(fileUtils.fileToByteArrayOutputStream(tmpFile), tmpFile.getName(),
                fileService.getTempFilePath());
        fileService.write(fileUtils.fileToByteArrayOutputStream(thumbnail), thumbnail.getName(),
                fileService.getTempFilePath());

        response.setStatus(HttpServletResponse.SC_OK);

        uploadResult.put("success", "true");
        uploadResult.put("indexedfilename", fileService.getTempDirectoryURL() + tmpFile.getName());
        uploadResult.put("thumbnailfilename", fileService.getTempDirectoryURL() + thumbnail.getName());
    } catch (FileNotFoundException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        uploadResult.put("success", "false");
        log(UploadServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    } catch (IOException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        uploadResult.put("success", "false");
        log(UploadServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    } catch (FileUploadException e) {
        response.setStatus(HttpServletResponse.SC_OK);
        uploadResult.put("success", "false");
        uploadResult.put("indexedfilename", "filetobig");
    } finally {
        try {
            mapper.writeValue(response.getWriter(), uploadResult);
            os.close();
            is.close();
        }

        catch (IOException ignored) {
        }
    }
}

From source file:org.eurekastreams.server.service.servlets.GetThemeCssServlet.java

/**
 * Initialize object from spring context if needed.
 *///from  ww w  . j a v a 2 s.  c om
@SuppressWarnings("unchecked")
private void initializeSpringObjects() {
    // grab items from spring context if not initialized, 500 error if unable
    if (requestUriToThemeUuIdTransformer == null || getThemeCssByUuidMapper == null) {
        ApplicationContext springContext = WebApplicationContextUtils
                .getWebApplicationContext(getServletContext());

        // Grab needed item from spring context.
        requestUriToThemeUuIdTransformer = (Transformer<String, String>) springContext
                .getBean("requestUriToThemeUuidTransformer");

        getThemeCssByUuidMapper = (DomainMapper<String, String>) springContext.getBean("getThemeCssByUuid");
    }
}

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

public FileExplorerItemDaoImpl getFileExplorerItemDaoImpl() {
    try {//  ww w.j a v  a 2s . c o m
        if (ScopeApplicationAdapter.initComplete) {
            ApplicationContext context = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            return (FileExplorerItemDaoImpl) context.getBean("fileExplorerItemDao");
        }
    } catch (Exception err) {
        log.error("[getUserManagement]", err);
    }
    return null;
}

From source file:org.jbpm.formbuilder.server.ExportTemplateServlet.java

protected TaskDefinitionService createTaskService(HttpServletRequest request) {
    return (TaskDefinitionService) WebApplicationContextUtils
            .getWebApplicationContext(request.getSession().getServletContext()).getBean("guvnorTaskService");
}