List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext
@Nullable public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName)
From source file:de.ingrid.interfaces.csw.admin.IndexDriver.java
/** * @param args// ww w.jav a 2 s . c o m * @throws Exception */ public static void main(String[] args) throws Exception { if (!System.getProperties().containsKey("jetty.webapp")) log.warn("Property 'jetty.webapp' not defined! Using default webapp directory, which is '" + DEFAULT_WEBAPP_DIR + "'."); if (!System.getProperties().containsKey("jetty.port")) log.warn("Property 'jetty.port' not defined! Using default port, which is '" + DEFAULT_JETTY_PORT + "'."); WebAppContext webAppContext = new WebAppContext(System.getProperty("jetty.webapp", DEFAULT_WEBAPP_DIR), "/"); Server server = new Server(Integer.getInteger("jetty.port", DEFAULT_JETTY_PORT)); // fix slow startup time on virtual machine env. HashSessionIdManager hsim = new HashSessionIdManager(); hsim.setRandom(new Random()); server.setSessionIdManager(hsim); server.setHandler(webAppContext); server.start(); WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext( webAppContext.getServletContext(), "org.springframework.web.servlet.FrameworkServlet.CONTEXT.springapp"); IndexRunnable r = (IndexRunnable) wac.getBean("indexRunnable"); r.run(); System.out.println("Try to stopping the iPlug..."); server.stop(); System.out.println("iPlug is stopped."); }
From source file:jetx.ext.springmvc.SpringMvcFunctions.java
/** * ?Spring ROOT //from ww w .j a va 2 s .c om */ public static WebApplicationContext getWebApplicationContext(JetPageContext ctx) { return WebApplicationContextUtils.getWebApplicationContext(ExtendUtils.getServletContext(ctx), WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); }
From source file:de.ingrid.interfaces.csw.admin.JettyStarter.java
private static void init() throws Exception { WebAppContext webAppContext = new WebAppContext(System.getProperty("jetty.webapp", DEFAULT_WEBAPP_DIR), "/"); Server server = new Server(Integer.getInteger("jetty.port", ApplicationProperties.getInteger(ConfigurationKeys.SERVER_PORT, DEFAULT_JETTY_PORT))); // fix slow startup time on virtual machine env. HashSessionIdManager hsim = new HashSessionIdManager(); hsim.setRandom(new Random()); server.setSessionIdManager(hsim);//from ww w . ja v a 2 s . c om Handler[] handlers = new Handler[2]; handlers[0] = basicSecurityHandler(); handlers[1] = webAppContext; server.setHandlers(handlers); server.start(); WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext( webAppContext.getServletContext(), "org.springframework.web.servlet.FrameworkServlet.CONTEXT.springapp"); CSWServlet cswServlet = (CSWServlet) wac.getBean("CSWServlet"); CSWTServlet cswtServlet = (CSWTServlet) wac.getBean("CSWTServlet"); webAppContext.addServlet(new ServletHolder(cswServlet), "/csw"); webAppContext.addServlet(new ServletHolder(cswtServlet), "/csw-t"); server.join(); }
From source file:org.wallride.job.UpdatePostViewsItemWriter.java
@Override public void write(List<? extends List> items) 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 .j a v a 2 s. com*/ final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class); for (List item : items) { UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) item.get(0)).build(); logger.info("Processing [{}]", uriComponents.toString()); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); 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; } logger.info("Update the PageView. Post ID [{}]: {} -> {}", post.getId(), post.getViews(), item.get(1)); post.setViews(Long.parseLong((String) item.get(1))); postRepository.saveAndFlush(post); } }
From source file:net.sf.jabb.stdr.jsp.SetTag.java
/** * Find the Spring bean from WebApplicationContext in servlet context. * @param beanName/*from ww w . j a v a2s .com*/ * @return the bean or null */ private Object findSpringBean(String beanName) { ServletContext servletContext = this.pageContext.getServletContext(); Enumeration<String> attrNames = servletContext.getAttributeNames(); while (attrNames.hasMoreElements()) { String attrName = attrNames.nextElement(); if (attrName.startsWith("org.springframework")) { try { WebApplicationContext springContext = WebApplicationContextUtils .getWebApplicationContext(servletContext, attrName); Object bean = springContext.getBean(beanName); return bean; } catch (Exception e) { // continue if the bean cannot be found. } } } return null; }
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"); }// w w w .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.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);//from w w w . j a v a 2 s . co 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: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 w ww . ja v a 2 s . c om*/ 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.service.PostService.java
/** * * @param blogLanguage/*from w ww. j a v 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"); }
From source file:org.bibsonomy.webapp.util.tags.JabrefLayoutRendererTag.java
/** * @return the configured jabref layout renderer in bibsonomy2-servlet.xml * this requires the {@link ContextLoader} configured in web.xml */// ww w . j a v a 2s .co m private JabrefLayoutRenderer getJabRefLayoutRenderer() { final ServletContext servletContext = this.pageContext.getServletContext(); final WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext, SERVLET_CONTEXT_PATH); final Map<String, JabrefLayoutRenderer> renderer = ctx.getBeansOfType(JabrefLayoutRenderer.class); return renderer.values().iterator().next(); }