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:org.egov.egf.web.actions.voucher.CommonAction.java

@SuppressWarnings("unchecked")
@Action(value = "/voucher/common-ajaxLoadEntites")
public String ajaxLoadEntites() throws ClassNotFoundException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting ajaxLoadEntites...");
    if (accountDetailType == null)
        entitiesList = new ArrayList<EntityType>();
    else {//from   w  w w.  jav  a  2 s  .  co m
        final Accountdetailtype detailType = (Accountdetailtype) persistenceService
                .find("from Accountdetailtype where id=? order by name", accountDetailType);
        final String table = detailType.getFullQualifiedName();
        final Class<?> service = Class.forName(table);
        String simpleName = service.getSimpleName();
        simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1) + "Service";

        final WebApplicationContext wac = WebApplicationContextUtils
                .getWebApplicationContext(ServletActionContext.getServletContext());
        final EntityTypeService entityService = (EntityTypeService) wac.getBean(simpleName);
        entitiesList = (List<EntityType>) entityService.getAllActiveEntities(accountDetailType);
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed ajaxLoadEntites.");
    return "entities";
}

From source file:org.egov.egf.web.actions.voucher.CommonAction.java

@SuppressWarnings("unchecked")
@Action(value = "/voucher/common-ajaxLoadEntitesBy20")
public String ajaxLoadEntitesBy20() throws ClassNotFoundException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting ajaxLoadEntitesBy20...");
    if (accountDetailType == null || accountDetailType == 0)
        entitiesList = new ArrayList<EntityType>();
    else {/*w w  w .ja  v a 2s.  com*/
        final Accountdetailtype detailType = (Accountdetailtype) persistenceService
                .find("from Accountdetailtype where id=? order by name", accountDetailType);
        final String table = detailType.getFullQualifiedName();
        final Class<?> service = Class.forName(table);
        String simpleName = service.getSimpleName();
        simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1) + "Service";

        final WebApplicationContext wac = WebApplicationContextUtils
                .getWebApplicationContext(ServletActionContext.getServletContext());
        final EntityTypeService entityService = (EntityTypeService) wac.getBean(simpleName);
        entitiesList = (List<EntityType>) entityService.filterActiveEntities(startsWith, 20,
                detailType.getId());
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed ajaxLoadEntitesBy20.");
    return "entities";
}

From source file:org.egov.egf.web.actions.voucher.CommonAction.java

@SuppressWarnings("unchecked")
@Action(value = "/voucher/common-searchEntites")
public String searchEntites() throws ClassNotFoundException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting searchEntites...");
    searchType = "EntitySearch";
    if (accountDetailType == null)
        entitiesList = new ArrayList<EntityType>();
    else {// w  ww  .  j av a 2 s  .  c o  m
        final Accountdetailtype detailType = (Accountdetailtype) persistenceService
                .find("from Accountdetailtype where id=? order by name", accountDetailType);
        final String table = detailType.getFullQualifiedName();
        accountDetailTypeName = detailType.getName();
        try {
            final Class<?> service = Class.forName(table);
            String simpleName = service.getSimpleName();
            simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1) + "Service";

            final WebApplicationContext wac = WebApplicationContextUtils
                    .getWebApplicationContext(ServletActionContext.getServletContext());
            EntityTypeService entityService = null;

            entityService = (EntityTypeService) wac.getBean(simpleName);
            entitiesList = (List<EntityType>) entityService.getAllActiveEntities(accountDetailType);
        } catch (final Exception e) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Service Not Available Exception : " + e.getMessage());
            entitiesList = new ArrayList<EntityType>();
        }
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed searchEntites.");
    return "searchResult";
}

From source file:org.encuestame.init.EnMeContext.java

/**
 * On start application.//  w  ww.  j  a va  2 s  .  c o  m
 */
@Override
public void contextInitialized(final ServletContextEvent sce) {
    EnMeContext.servletContext = sce.getServletContext();
    super.contextInitialized(sce);
    boolean existHomeDirectory = DirectorySetupOperations.isHomeDirectoryValid();
    if (!existHomeDirectory) {
        log.fatal("**********************************************");
        log.fatal("*           ENCUESTAME HOME IS MISSING");
        log.fatal("*           Troubles ?? Visit the wiki a get your answer.");
        log.fatal("*  http://www.encuestame.org/wiki/display/DOC/Troubleshooting+Guides");
        log.fatal("**********************************************");
        throw new IllegalStateException("home not valid, please set a home property in the configuration file");
    } else {
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        //servletContext.setInitParameter("spring.profiles.active", "live");
        final StartupProcess startup = (StartupProcess) ctx.getBean("applicationStartup");
        try {
            startup.startProcess();
            log.info("**********************************************");
            log.info("*     ENCUESTAME IS RUNNING SUCCESSFULLY      *");
            log.info("*        http://www.encuestame.org           *");
            log.info("**********************************************");
        } catch (Exception e) {
            log.fatal("EnMe: Error on start encuestame context: " + e.getMessage());
            this.closeWebApplicationContext(servletContext);
            throw new IllegalStateException("EnMe: Error on stat encuestame context : " + e.getMessage());
        }
    }
}

From source file:org.eurekastreams.commons.server.ActionRPCServiceImpl.java

/**
 * As a servlet, this class' init() method is called automatically. This is how we get context.
 * /*w w w.  j  a  v  a2s  .  c  om*/
 * @param config
 *            the configuration describing the run-time environment.
 */
@Override
public void init(final ServletConfig config) {
    log.info("ActionRPCServiceImpl::init()");

    try {
        super.init(config);
    } catch (ServletException e) {
        log.error("Caught a ServletException during initialization: " + e.getMessage(), e);
    }

    springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    actionExecutorFactory = (ActionExecutorFactory) springContext.getBean("actionExecutorFactory");
}

From source file:org.eurekastreams.server.service.filters.FilterInitializer.java

/**
 * //from w  w  w.  ja v  a  2 s .c  o  m
 * @param theFilter
 *            - the filter to configure
 * @param filterConfig
 *            - filter config params
 */
public static void initializeFilter(final Filter theFilter, final FilterConfig filterConfig) {
    ApplicationContext context = (ApplicationContext) WebApplicationContextUtils
            .getWebApplicationContext(filterConfig.getServletContext());

    if (theFilter instanceof RootOrgCheckFilter) {
        RootOrgCheckFilter rootOrgFilter = (RootOrgCheckFilter) theFilter;

        GetRootOrganizationIdAndShortName getRootOrgIdMapper = (GetRootOrganizationIdAndShortName) context
                .getBean("getRootOrganizationIdAndShortNameMapper");

        rootOrgFilter.setGetRootOrganizationIdMapper(getRootOrgIdMapper);
    }
}

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

/**
 * {@inheritDoc}//from w ww . ja va 2 s .co  m
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    ImageWriter imageWriter = (ImageWriter) springContext.getBean("imageWriter");
    RenderedImage image = imageWriter.read(request.getParameter("img"));

    // show a 404 page
    if (image == null) {
        httpError(NOTFOUND, response);
    } else {
        BufferedOutputStream bos = null;
        ByteArrayOutputStream baos = null;

        try {
            baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);

            bos = new BufferedOutputStream(response.getOutputStream());

            response.setContentType("image/png");
            response.setContentLength(baos.toByteArray().length);

            bos.write(baos.toByteArray());

        } catch (Exception e) {
            // Tell the user there was some internal server error.\
            // 500 - Internal server error.
            httpError(ERROR, response);
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    log.error(e);
                    // To late to do anything about it now, we may have already sent some data to user.
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    log.error(e);
                    // To late to do anything about it now, we may have already sent some data to user.
                }
            }
        }
    }

}

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

/**
 * Uploads the image.//ww  w  . j  a va2s.  c om
 * 
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws ServletException
 *             not expected
 * @throws IOException
 *             not expected
 */
@Override
@SuppressWarnings("unchecked")
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");

    springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    UserDetails userDetails = getUserDetails();
    T domainEntity = getDomainEntity(userDetails.getUsername(), request);

    HashGeneratorStrategy hasher = new HashGeneratorStrategy();
    String imageId = hasher.hash(String.valueOf(domainEntity.getId()));

    try {
        FileItem uploadItem = getFileItem(request);

        if (uploadItem == null) {
            response.getWriter().write("fail");
            return;
        }

        // Save the File

        Object actionBean = getAction(request);

        T newDomainEntity = null;

        if (actionBean instanceof ServiceAction || actionBean instanceof TaskHandlerServiceAction) {
            SaveImageRequest currentRequest = new SaveImageRequest(uploadItem, domainEntity.getId(), imageId);
            ActionController serviceActionController = (ActionController) springContext
                    .getBean("serviceActionController");
            DefaultPrincipal principal = new DefaultPrincipal(userDetails.getUsername(),
                    ((ExtendedUserDetails) userDetails).getPerson().getOpenSocialId(),
                    ((ExtendedUserDetails) userDetails).getPerson().getId());
            ServiceActionContext currentContext = new ServiceActionContext(currentRequest, principal);

            if (actionBean instanceof ServiceAction) {
                newDomainEntity = (T) serviceActionController.execute(currentContext,
                        (ServiceAction) actionBean);
            } else {
                newDomainEntity = (T) serviceActionController.execute(currentContext,
                        (TaskHandlerServiceAction) actionBean);
            }
        } else {
            throw new Exception("Invalid action call within the UploadImageServlet.");
        }

        // Return the resulting person objects properties to the user.
        response.getWriter().write(imageId + "," + getResponseString(newDomainEntity));

    } catch (Exception e) {
        log.error("Error running UploadImageServlet.", e);

        response.getWriter().write("fail");
    }
}

From source file:org.glimpse.server.ConnectionFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean userOk = false;
    String connectionId = GlimpseUtils.getConnectionId((HttpServletRequest) request);
    if (StringUtils.isNotEmpty(connectionId)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Connection id found : <" + connectionId + ">");
        }// w w  w . ja va  2 s  .c  o m

        UserManager userManager = WebApplicationContextUtils.getWebApplicationContext(servletContext)
                .getBean(UserManager.class);
        String userId = userManager.getUserId(connectionId);
        if (StringUtils.isNotBlank(userId)) {
            if (logger.isDebugEnabled()) {
                logger.debug("User id is : <" + userId + ">");
            }

            request.setAttribute(GlimpseUtils.REQUEST_ATTRIBUTE_USER_ID, userId);
            UserAttributes userAttributes = userManager.getUserAttributes(userId);
            request.setAttribute(GlimpseUtils.REQUEST_ATTRIBUTE_USER_ATTRIBUTES, userAttributes);
            userOk = true;
        }
    }

    if (!userOk) {
        logger.debug("No valid connection id found");
        request.removeAttribute(GlimpseUtils.REQUEST_ATTRIBUTE_USER_ID);
        request.removeAttribute(GlimpseUtils.REQUEST_ATTRIBUTE_USER_ATTRIBUTES);
    }
    chain.doFilter(request, response);
}

From source file:org.glimpse.server.news.NewsIconServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String url = request.getParameter("url");
    int i = url.indexOf(':');
    i = url.indexOf('/', i + 3);
    if (i == -1) {
        i = url.length();//  w  ww .j av a 2s. co  m
    }
    url = url.substring(0, i) + "/favicon.ico";

    CloseableHttpClient client = WebApplicationContextUtils.getWebApplicationContext(getServletContext())
            .getBean(CloseableHttpClient.class);

    HttpGet method = new HttpGet(url);
    CloseableHttpResponse httpresponse = null;
    try {
        httpresponse = client.execute(method);
    } catch (Exception e) {
        logger.error("Unable to get new icon for <" + url + ">", e);
    }

    try {
        if (httpresponse != null && httpresponse.getStatusLine().getStatusCode() == 200) {
            IOUtils.copy(httpresponse.getEntity().getContent(), response.getOutputStream());
        } else {
            File f = new File(getServletContext().getRealPath("images/feed.png"));
            FileInputStream fis = new FileInputStream(f);
            IOUtils.copy(fis, response.getOutputStream());
            fis.close();
        }
    } finally {
        if (httpresponse != null) {
            httpresponse.close();
        }
    }
}