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:pl.chilldev.web.spring.context.SpringBeansJspPageMetaModelResolver.java

/**
 * {@inheritDoc}//from   w w  w .  j  ava 2  s  .c  o m
 * @since 0.0.1
 */
@Override
public PageMetaModel getPageMetaModel(JspContext context) throws PageMetaModelContextException {
    WebApplicationContext applicationContext;

    // try to get web context
    if (context instanceof PageContext) {
        applicationContext = WebApplicationContextUtils
                .getWebApplicationContext(((PageContext) context).getServletContext());
    } else {
        this.logger.error("Could not acquire appplication context.");
        throw new PageMetaModelContextException(
                "SpringBeansJspPageMetaModelResolver requires JSP to be run with PageContenxt implmentation.");
    }

    try {
        this.logger.debug("Taking PageMetaModel from Spring context.");
        return applicationContext.getBean(PageMetaModel.class);
    } catch (BeansException error) {
        this.logger.error("Error while fethcing page model from Spring context.", error);
        throw new PageMetaModelContextException("Error fetching page meta model from Spring context.", error);
    }
}

From source file:org.wallride.web.controller.admin.page.PagePreviewController.java

@RequestMapping
public void preview(@PathVariable String language, @Valid @ModelAttribute("form") PagePreviewForm form,
        BindingResult result, AuthorizedUser authorizedUser, Model model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Page page = new Page();
    page.setLanguage(language);//from  ww  w .j  a  v  a  2s  .c o m
    page.setCover(form.getCoverId() != null ? mediaService.getMedia(form.getCoverId()) : null);
    page.setTitle(form.getTitle());
    page.setBody(form.getBody());
    page.setDate(form.getDate() != null ? form.getDate() : LocalDateTime.now());
    List<CustomFieldValue> fieldValues = new ArrayList<>();
    for (CustomFieldValueEditForm valueForm : form.getCustomFieldValues()) {
        CustomFieldValue value = new CustomFieldValue();
        value.setCustomField(customFieldService.getCustomFieldById(valueForm.getCustomFieldId(), language));
        if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)
                && !ArrayUtils.isEmpty(valueForm.getTextValues())) {
            value.setTextValue(String.join(",", valueForm.getTextValues()));
        } else {
            value.setTextValue(valueForm.getTextValue());
        }
        value.setStringValue(valueForm.getStringValue());
        value.setNumberValue(valueForm.getNumberValue());
        value.setDateValue(valueForm.getDateValue());
        value.setDatetimeValue(valueForm.getDatetimeValue());
        fieldValues.add(value);
    }
    page.setCustomFieldValues(new TreeSet<>(fieldValues));
    page.setAuthor(authorizedUser);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        throw new ServiceException("GuestServlet is not ready yet");
    }

    Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    BlogLanguage blogLanguage = blog.getLanguage(language);
    request.setAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE, blogLanguage);

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

    final WebContext ctx = new WebContext(request, response, servletContext, LocaleContextHolder.getLocale(),
            mv.getModelMap());
    ctx.setVariable("page", page);

    ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(context, null);
    ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
            evaluationContext);

    SpringTemplateEngine templateEngine = context.getBean("templateEngine", SpringTemplateEngine.class);
    String html = templateEngine.process("page/describe", ctx);

    response.setContentType("text/html;charset=UTF-8");
    response.setContentLength(html.getBytes("UTF-8").length);
    response.getWriter().write(html);
}

From source file:org.wallride.web.controller.admin.article.ArticlePreviewController.java

@RequestMapping
public void preview(@PathVariable String language, @Valid @ModelAttribute("form") ArticlePreviewForm form,
        BindingResult result, AuthorizedUser authorizedUser, Model model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Article article = new Article();
    article.setLanguage(language);//ww  w.j  av a  2s. c  o m
    article.setCover(form.getCoverId() != null ? mediaService.getMedia(form.getCoverId()) : null);
    article.setTitle(form.getTitle());
    article.setBody(form.getBody());
    article.setDate(form.getDate() != null ? form.getDate() : LocalDateTime.now());

    List<CustomFieldValue> fieldValues = new ArrayList<>();
    for (CustomFieldValueEditForm valueForm : form.getCustomFieldValues()) {
        CustomFieldValue value = new CustomFieldValue();
        value.setCustomField(customFieldService.getCustomFieldById(valueForm.getCustomFieldId(), language));
        if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)
                && !ArrayUtils.isEmpty(valueForm.getTextValues())) {
            value.setTextValue(String.join(",", valueForm.getTextValues()));
        } else {
            value.setTextValue(valueForm.getTextValue());
        }
        value.setStringValue(valueForm.getStringValue());
        value.setNumberValue(valueForm.getNumberValue());
        value.setDateValue(valueForm.getDateValue());
        value.setDatetimeValue(valueForm.getDatetimeValue());
        fieldValues.add(value);
    }
    article.setCustomFieldValues(new TreeSet<>(fieldValues));
    article.setAuthor(authorizedUser);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        throw new ServiceException("GuestServlet is not ready yet");
    }

    Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    BlogLanguage blogLanguage = blog.getLanguage(language);
    request.setAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE, blogLanguage);

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

    final WebContext ctx = new WebContext(request, response, servletContext, LocaleContextHolder.getLocale(),
            mv.getModelMap());
    ctx.setVariable("article", article);

    ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(context, null);
    ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
            evaluationContext);

    SpringTemplateEngine templateEngine = context.getBean("templateEngine", SpringTemplateEngine.class);
    String html = templateEngine.process("article/describe", ctx);

    response.setContentType("text/html;charset=UTF-8");
    response.setContentLength(html.getBytes("UTF-8").length);
    response.getWriter().write(html);
}

From source file:hudson.security.SecurityRealm.java

/**
 * Creates {@link Filter} that all the incoming HTTP requests will go through
 * for authentication.// w w  w .j  a  v a2 s.c o  m
 *
 * <p>
 * The default implementation uses {@link #getSecurityComponents()} and builds
 * a standard filter chain from /WEB-INF/security/SecurityFilters.groovy.
 * But subclasses can override this to completely change the filter sequence.
 *
 * <p>
 * For other plugins that want to contribute {@link Filter}, see
 * {@link PluginServletFilter}.
 *
 * @since 1.271
 */
public Filter createFilter(FilterConfig filterConfig) {
    LOGGER.entering(SecurityRealm.class.getName(), "createFilter");

    Binding binding = new Binding();
    SecurityComponents sc = getSecurityComponents();
    binding.setVariable("securityComponents", sc);
    binding.setVariable("securityRealm", this);
    BeanBuilder builder = new BeanBuilder();
    builder.parse(
            filterConfig.getServletContext().getResourceAsStream("/WEB-INF/security/SecurityFilters.groovy"),
            binding);
    WebApplicationContext context = builder.createApplicationContext();
    return (Filter) context.getBean("filter");
}

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();/*from   w  w  w.  j  a  v a  2s . co m*/
        }

        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:org.intalio.tempo.web.AlfrescoFacesPortlet.java

private void setAuthenticatedUser(PortletRequest req, String userName) {

    WebApplicationContext ctx = (WebApplicationContext) getPortletContext()
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    TransactionService transactionService = serviceRegistry.getTransactionService();
    NodeService nodeService = serviceRegistry.getNodeService();

    AuthenticationComponent authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    AuthenticationService authService = (AuthenticationService) ctx.getBean("authenticationService");
    PersonService 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();

    // Set up the user information
    UserTransaction tx = transactionService.getUserTransaction();
    NodeRef homeSpaceRef = null;/*from w ww.  j ava 2 s.  c  o m*/
    User user;
    try {
        tx.begin();
        // Set the authentication
        authComponent.setCurrentUser(userName);
        user = new User(userName, authService.getCurrentTicket(), personService.getPerson(userName));
        homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName),
                ContentModel.PROP_HOMEFOLDER);
        if (homeSpaceRef == null) {
            logger.warn("Home Folder is null for user '" + userName + "', using company_home.");
            homeSpaceRef = (NodeRef) nodeService.getRootNode(Repository.getStoreRef());
        }
        user.setHomeSpaceId(homeSpaceRef.getId());
        tx.commit();
    } catch (Throwable ex) {
        logger.error(ex);

        try {
            tx.rollback();
        } catch (Exception ex2) {
            logger.error("Failed to rollback transaction", ex2);
        }

        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException("Failed to set authenticated user", ex);
        }
    }

    // Store the user
    req.getPortletSession().setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user);
    req.getPortletSession().setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE);

    logger.debug("...authenticated user is: " + user.getUserName() + user.getTicket());
}

From source file:org.fao.fenix.wds.web.rest.WDSRESTService.java

public String formatOutput(List<List<String>> table, String filename) {
    String output = "";
    ServletContext servletContext = this.getServletConfig().getServletContext();
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    Wrapper wrapper = (Wrapper) wac.getBean("wrapper");
    WrapperConfigurations c = new WrapperConfigurations(fwds.getCss());
    switch (fwds.getOutput()) {
    case HTML:
        output = wrapper.wrapAsHTML(table, true, c).toString();
        break;// w  ww  .jav a2s.  com
    case JSON:
        output = Wrapper.wrapAsJSON(table).toString();
        break;
    case OLAPJSON:
        //            output = OLAPWrapper.wrapAsOLAPJSON(table, fwds.isShowNullValues(), fwds.isAddFlags()).toString(); 
        output = OLAPWrapper.gsonWrapper(table).toString();
        break;
    case CSV:
        output = wrapper.wrapAsCSV(table, c).toString();
        break;
    case EXCEL:
        filename += ".xls";
        output = wrapper.wrapAsExcel(table, filename).toString();
        break;
    case XML2:
        output = Wrapper.wrapAsXML2(table).toString();
        break;
    default:
        output = Wrapper.wrapAsXML(table).toString();
        break;
    }
    return output;
}

From source file:at.gv.egovernment.moa.id.auth.servlet.AuthServlet.java

/**
 * Returns the underlying process engine instance.
 * /*from ww  w.ja  v a  2s  .co  m*/
 * @return The process engine (never {@code null}).
 * @throws NoSuchBeanDefinitionException
 *             if no {@link ProcessEngine} bean was found.
 * @throws NoUniqueBeanDefinitionException
 *             if more than one {@link ProcessEngine} bean was found.
 * @throws BeansException
 *             if a problem getting the {@link ProcessEngine} bean occurred.
 * @throws IllegalStateException
 *             if the Spring WebApplicationContext was not found, which means that the servlet is used outside a
 *             Spring web environment.
 */
public synchronized ProcessEngine getProcessEngine() {
    if (processEngine == null) {
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        if (ctx == null) {
            throw new IllegalStateException(
                    "Unable to find Spring WebApplicationContext. Servlet needs to be executed within a Spring web environment.");
        }
        processEngine = ctx.getBean(ProcessEngine.class);
    }
    return processEngine;
}

From source file:org.wallride.service.PostService.java

/**
 *
 * @param blogLanguage/*from   w  w  w  .  jav a  2s.co m*/
 * @param type
 * @param maxRank
 * @see PostService#getPopularPosts(String, PopularPost.Type)
 */
@CacheEvict(value = WallRideCacheConfiguration.POPULAR_POST_CACHE, key = "'list.type.' + #blogLanguage.language + '.' + #type")
public void updatePopularPosts(BlogLanguage blogLanguage, PopularPost.Type type, int maxRank) {
    logger.info("Start update of the popular posts");

    GoogleAnalytics googleAnalytics = blogLanguage.getBlog().getGoogleAnalytics();
    if (googleAnalytics == null) {
        logger.info("Configuration of Google Analytics can not be found");
        return;
    }

    Analytics analytics = GoogleAnalyticsUtils.buildClient(googleAnalytics);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        logger.info("GuestServlet is not ready yet");
        return;
    }

    final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);

    Map<Post, Long> posts = new LinkedHashMap<>();

    int startIndex = 1;
    int currentRetry = 0;
    int totalResults = 0;

    do {
        try {
            LocalDate now = LocalDate.now();
            LocalDate startDate;
            switch (type) {
            case DAILY:
                startDate = now.minusDays(1);
                break;
            case WEEKLY:
                startDate = now.minusWeeks(1);
                break;
            case MONTHLY:
                startDate = now.minusMonths(1);
                break;
            default:
                throw new ServiceException();
            }

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Analytics.Data.Ga.Get get = analytics.data().ga()
                    .get(googleAnalytics.getProfileId(), startDate.format(dateTimeFormatter),
                            now.format(dateTimeFormatter), "ga:sessions")
                    .setDimensions(String.format("ga:pagePath", googleAnalytics.getCustomDimensionIndex()))
                    .setSort(String.format("-ga:sessions", googleAnalytics.getCustomDimensionIndex()))
                    .setStartIndex(startIndex).setMaxResults(GoogleAnalyticsUtils.MAX_RESULTS);
            if (blogLanguage.getBlog().isMultiLanguage()) {
                get.setFilters("ga:pagePath=~/" + blogLanguage.getLanguage() + "/");
            }

            logger.info(get.toString());
            final GaData gaData = get.execute();
            if (CollectionUtils.isEmpty(gaData.getRows())) {
                break;
            }

            for (List row : gaData.getRows()) {
                UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) row.get(0)).build();

                MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
                request.setRequestURI(uriComponents.getPath());
                request.setQueryString(uriComponents.getQuery());
                MockHttpServletResponse response = new MockHttpServletResponse();

                BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService);
                BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request,
                        response);
                try {
                    rewriteMatch.execute(request, response);
                } catch (ServletException e) {
                    throw new ServiceException(e);
                } catch (IOException e) {
                    throw new ServiceException(e);
                }

                request.setRequestURI(rewriteMatch.getMatchingUrl());

                HandlerExecutionChain handler;
                try {
                    handler = mapping.getHandler(request);
                } catch (Exception e) {
                    throw new ServiceException(e);
                }

                if (!(handler.getHandler() instanceof HandlerMethod)) {
                    continue;
                }

                HandlerMethod method = (HandlerMethod) handler.getHandler();
                if (!method.getBeanType().equals(ArticleDescribeController.class)
                        && !method.getBeanType().equals(PageDescribeController.class)) {
                    continue;
                }

                // Last path mean code of post
                String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1);
                Post post = postRepository.findOneByCodeAndLanguage(code,
                        rewriteMatch.getBlogLanguage().getLanguage());
                if (post == null) {
                    logger.debug("Post not found [{}]", code);
                    continue;
                }

                if (!posts.containsKey(post)) {
                    posts.put(post, Long.parseLong((String) row.get(1)));
                }
                if (posts.size() >= maxRank) {
                    break;
                }
            }

            if (posts.size() >= maxRank) {
                break;
            }

            startIndex += GoogleAnalyticsUtils.MAX_RESULTS;
            totalResults = gaData.getTotalResults();
        } catch (IOException e) {
            logger.warn("Failed to synchronize with Google Analytics", e);
            if (currentRetry >= GoogleAnalyticsUtils.MAX_RETRY) {
                throw new GoogleAnalyticsException(e);
            }

            currentRetry++;
            logger.info("{} ms to sleep...", GoogleAnalyticsUtils.RETRY_INTERVAL);
            try {
                Thread.sleep(GoogleAnalyticsUtils.RETRY_INTERVAL);
            } catch (InterruptedException ie) {
                throw new GoogleAnalyticsException(e);
            }
            logger.info("Retry for the {} time", currentRetry);
        }
    } while (startIndex <= totalResults);

    popularPostRepository.deleteByType(blogLanguage.getLanguage(), type);

    int rank = 1;
    for (Map.Entry<Post, Long> entry : posts.entrySet()) {
        PopularPost popularPost = new PopularPost();
        popularPost.setLanguage(blogLanguage.getLanguage());
        popularPost.setType(type);
        popularPost.setRank(rank);
        popularPost.setViews(entry.getValue());
        popularPost.setPost(entry.getKey());
        popularPostRepository.saveAndFlush(popularPost);
        rank++;
    }

    logger.info("Complete the update of popular posts");
}