Example usage for java.time LocalDate minusMonths

List of usage examples for java.time LocalDate minusMonths

Introduction

In this page you can find the example usage for java.time LocalDate minusMonths.

Prototype

public LocalDate minusMonths(long monthsToSubtract) 

Source Link

Document

Returns a copy of this LocalDate with the specified number of months subtracted.

Usage

From source file:Main.java

public static void main(String[] args) {
    LocalDate a = LocalDate.of(2014, 6, 30);
    LocalDate b = a.minusMonths(6);
    System.out.println(b);// ww  w .  j  a  v a 2 s  .c o m
}

From source file:Main.java

public static void main(String[] args) {
    LocalDate today = LocalDate.now();

    // plus and minus operations
    System.out.println("10 days after today will be " + today.plusDays(10));
    System.out.println("3 weeks after today will be " + today.plusWeeks(3));
    System.out.println("20 months after today will be " + today.plusMonths(20));

    System.out.println("10 days before today will be " + today.minusDays(10));
    System.out.println("3 weeks before today will be " + today.minusWeeks(3));
    System.out.println("20 months before today will be " + today.minusMonths(20));

}

From source file:com.romeikat.datamessie.core.base.ui.page.StatisticsPage.java

private LocalDate getFromDate() {
    final LocalDate toDate = getToDate();
    if (toDate == null) {
        return LocalDate.now();
    }//from   w w w.  j  a  v  a  2  s.  c o m

    Integer statisticsPeriod = DataMessieSession.get().getStatisticsPeriodModel().getObject();
    if (statisticsPeriod == null) {
        return LocalDate.now();
    }

    final StatisticsInterval statisticsInterval = DataMessieSession.get().getStatisticsIntervalModel()
            .getObject();
    if (statisticsInterval == null) {
        return LocalDate.now();
    }

    // Minimum value is 1
    statisticsPeriod = Math.max(statisticsPeriod, 1);

    // Calculate
    final LocalDate fromDate = toDate.plusDays(1);
    switch (statisticsInterval) {
    case DAY:
        return fromDate.minusDays(statisticsPeriod);
    case WEEK:
        return fromDate.minusWeeks(statisticsPeriod);
    case MONTH:
        return fromDate.minusMonths(statisticsPeriod);
    case YEAR:
        return fromDate.minusYears(statisticsPeriod);
    default:
        return LocalDate.now();
    }
}

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

/**
 *
 * @param blogLanguage//from  w  w  w  .  j av  a2  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");
}