Example usage for org.springframework.web.servlet.mvc.method.annotation RequestMappingHandlerMapping getHandler

List of usage examples for org.springframework.web.servlet.mvc.method.annotation RequestMappingHandlerMapping getHandler

Introduction

In this page you can find the example usage for org.springframework.web.servlet.mvc.method.annotation RequestMappingHandlerMapping getHandler.

Prototype

@Nullable
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;

Source Link

Document

Return a handler and any interceptors for this request.

Usage

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  w  w .ja v  a 2  s . c  om*/

    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:org.wallride.service.PostService.java

/**
 *
 * @param blogLanguage// w  w  w .java 2 s .c o  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");
}