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.trust.datacollection.thread.DataCollectionThread.java

public void run() {
    if (log.isDebugEnabled())
        log.debug("" + interFetchConfigName + "");

    //Spring//  ww w  . j  a  va2  s .  c  o m
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    DataSource dataSource = (DataSource) context.getBean("sqlServerDataSource"); //SqlServer
    baseSqlMapDAO = (BaseSqlMapDAO) context.getBean("baseSqlMapDAO"); //MySqlIbatis

    try {
        Connection conn = dataSource.getConnection();
        Statement stem = conn.createStatement();
        if (log.isDebugEnabled())
            log.debug(interSelectSql);
        ResultSet rs = stem.executeQuery(interSelectSql);

        boolean localSelectFlag = false, localInsertFlag = false, localUpdateFlag = false;

        //MySqlSQL 
        if (null != localSelectSql && !"".equals(localSelectSql)) {
            localSelectFlag = true;
        } //if
          //MySqlInsertSQL
        if (null != localInsertSql && !"".equals(localInsertSql)) {
            localInsertFlag = true;
        } //if
          //MySqlUpdateSQL
        if (null != localUpdateSql && !"".equals(localUpdateSql)) {
            localUpdateFlag = true;
        } //if

        if (localSelectFlag) { //select
            List selectField = createField(localSelectSql);

            if (localInsertFlag) { //insert
                List insertField = createField(localInsertSql);

                if (localUpdateFlag) { //update
                    List updateField = createField(localUpdateSql);

                    while (rs.next()) {
                        if (findIsExistIbatisSql(localSelectSql, selectField, rs) == 0) {//insertupdate
                            executeIbatisSql(localInsertSql, insertField, rs); //insert
                        } else {
                            executeIbatisSql(localUpdateSql, updateField, rs); //update
                        } //if
                    }

                } else {
                    while (rs.next()) {
                        if (findIsExistIbatisSql(localSelectSql, selectField, rs) > 0) {//
                            executeIbatisSql(localInsertSql, insertField, rs); //insert
                        }
                    }

                } //if

            } else if (localUpdateFlag) {
                List updateField = createField(localUpdateSql);
                while (rs.next()) {
                    executeIbatisSql(localUpdateSql, updateField, rs); //update
                }
            } //if

        } else {
            if (localInsertFlag) { //insert
                List insertField = createField(localInsertSql);
                while (rs.next()) {
                    executeIbatisSql(localInsertSql, insertField, rs); //insert
                }

            } else if (localUpdateFlag) {
                List updateField = createField(localUpdateSql);
                while (rs.next()) {
                    executeIbatisSql(localUpdateSql, updateField, rs); //update
                }
            } //if
        } //if

        if (log.isDebugEnabled())
            log.debug("" + interFetchConfigName + "");

    } catch (SQLException e) {
        e.printStackTrace();
    } //try
}

From source file:nl.strohalm.cyclos.http.LifecycleListener.java

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 *//*from   w  ww  . j  a va 2s.c  o  m*/
@Override
public void contextInitialized(final ServletContextEvent event) {
    LoggedUser.runAsSystem(new Callable<Void>() {
        @Override
        public Void call() {
            try {
                final ServletContext context = event.getServletContext();

                final WebApplicationContext applicationContext = WebApplicationContextUtils
                        .getWebApplicationContext(context);
                SpringHelper.injectBeans(applicationContext, LifecycleListener.this);

                applicationService.initialize();

                context.setAttribute("systemOnline", applicationService.isOnline());
                context.setAttribute("cyclosVersion", applicationService.getCyclosVersion());

                // Run web initializations
                final Collection<LocalWebInitialization> initializations = applicationContext
                        .getBeansOfType(LocalWebInitialization.class).values();
                runAll(initializations);

                final LocalSettings settings = settingsService.getLocalSettings();
                context.log(settings.getApplicationName() + " initialized");

                // Suggest a GC in order to keep the heap low right after a startup
                System.gc();
            } catch (final Throwable e) {
                LOG.error("Error on LifecycleListener.contextInitialized()", e);
                throw new RuntimeException(e);
            }
            return null; // required by compiler
        }
    });
}

From source file:nl.strohalm.cyclos.utils.SpringHelper.java

/**
 * Retrieves a bean from the factory bound to the given servlet context, casting it
 *//*from   w  w  w. ja  v a2 s . c o m*/
public static <T> T bean(final ServletContext context, final Class<T> requiredType) {
    return bean(WebApplicationContextUtils.getWebApplicationContext(context), requiredType);
}

From source file:nl.strohalm.cyclos.utils.SpringHelper.java

/**
 * Injects beans on setters using the Inject annotation
 *//*from  www.ja v  a 2s .  c  o m*/
public static void injectBeans(final ServletContext context, final Object target) {
    final WebApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(context);
    injectBeans(applicationContext, target);
}

From source file:no.kantega.publishing.api.taglibs.security.GetUserTag.java

public int doStartTag() throws JspException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

    try {/*w  w w .j a v a2 s .c om*/
        if (webApplicationContext == null) {
            webApplicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(pageContext.getServletContext());
        }
        SecuritySession session = SecuritySession.getInstance(request);
        User user = null;
        if (!isBlank(userid)) {
            try {
                SecurityRealm realm = null;
                Map<String, SecurityRealm> beansOfType = webApplicationContext
                        .getBeansOfType(SecurityRealm.class);
                for (SecurityRealm r : beansOfType.values()) {
                    user = r.lookupUser(userid);
                    if (user != null) {
                        realm = r;
                        break;

                    }
                }

                if (user != null) {
                    if (getRoles || getRoleTopics) {
                        List<Role> roles = realm.lookupRolesForUser(user.getId());
                        for (Role role : roles) {
                            user.addRole(role);
                        }
                        if (getRoleTopics && Aksess.isTopicMapsEnabled()) {
                            // Hent topics for bruker
                            TopicMapService topicService = new TopicMapService(request);

                            if (user.getRoles() != null) {
                                for (Role role : roles) {
                                    List<Topic> tmp = topicService.getTopicsBySID(role);
                                    for (Topic aTmp : tmp) {
                                        user.addTopic(aTmp);
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (SystemException e) {
                user = null;
            }
        } else {
            user = session.getUser();
        }

        if (user != null) {
            request.setAttribute(name, user);
        }
    } catch (Exception e) {
        log.error("Error setting user", e);
        throw new JspTagException(e);
    }

    return SKIP_BODY;
}

From source file:nu.mine.kino.web.JSONICContainer.java

@Override
public void init(HttpServlet servlet) throws ServletException {
    super.init(servlet);
    this.log = LogFactory.getLog(servlet.getClass());
    appContext = WebApplicationContextUtils.getWebApplicationContext(context);

}

From source file:org.acegisecurity.ui.session.HttpSessionEventPublisher.java

ApplicationContext getContext(ServletContext servletContext) {
    return WebApplicationContextUtils.getWebApplicationContext(servletContext);
}

From source file:org.agnitas.web.forms.StrutsFormBase.java

/**
 * Getter for property webApplicationContext.
 *
 * @return Value of property webApplicationContext.
 *///from w ww .j  a va2s .c  o m
public ApplicationContext getWebApplicationContext() {
    return WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
}

From source file:org.agnitas.web.OnePixelCount.java

/**
 * Gets company data from database and stores it in cachedCompany variable.
 * @param companyID//from  w w  w.j a v a  2s .  c  o m
 * @return
 */
protected Company getCompany(int companyID) {
    if (cachedCompany == null) {
        ApplicationContext con = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        CompanyDao cDao = (CompanyDao) con.getBean("CompanyDao");

        cachedCompany = cDao.getCompany(companyID);
    }
    return cachedCompany;
}

From source file:org.agnitas.web.OnePixelCount.java

/**
 * Servlet service-method, is invoked on calling the servlet.
 * Parses data from uid parameter (company id, mailing id and customer id),
 * stores the data from the request in database,
 * writes one pixel gif image into response.
 * Also executes mailing open action, if the mailing has one.
 * Returns nothing if the company is not in status "active" or if some execution error occurs.
 * @param req HTTP request; should contain "uid" parameter with values of company id, mailing id and customer id
 * @param res HTTP response, contains one pixel gif image
 * @throws IOException if an input/output error occurs
 * @throws ServletException if a servlet exception occurs
 *///  w w w .  ja v  a  2s .c om
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    ApplicationContext con = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    String param = null;
    OnepixelDao pixelDao = (OnepixelDao) con.getBean("OnepixelDao");

    ExtensibleUIDService uidService = (ExtensibleUIDService) con
            .getBean(ExtensibleUIDConstants.SERVICE_BEAN_NAME);

    // send gif to Browser.
    res.setContentType("image/gif");
    OutputStream out = res.getOutputStream();
    out.write(onePixelGif);
    out.close();

    param = req.getParameter("uid");
    if (param == null) {
        logger.error("service: no uid set");
        return;
    }

    try {
        // validate uid
        ExtensibleUID uid = null;
        Company company = null;

        try {
            uid = uidService.parse(param);
        } catch (UIDParseException e) {
            logger.warn("Error parsing UID: " + param + " (" + e.getMessage() + ")");
            logger.debug(e);
        }

        if (uid == null || uid.getCompanyID() == 0) {
            return;
        }

        company = getCompany((int) uid.getCompanyID());

        if (company == null) {
            logger.error("Company with ID: " + uid.getCompanyID() + " not found ");
            return;
        }

        /*
        // TODO: Create a separate Helper class to validate the old UIDs
        if(uid.validateUID(company.getSecret())==false) {
           logger.warn("uid invalid: " + param);
           return;
        }
        */

        if (!STATUS_ACTIVE.equals(company.getStatus())) {
            return;
        }

        persistLog(req, pixelDao, uid);
        executeMailingOpenAction(uid, con, req);

    } catch (Exception e) {
        logger.error(e);
        return;
    }
}