spring.travel.site.services.news.NewsService.java Source code

Java tutorial

Introduction

Here is the source code for spring.travel.site.services.news.NewsService.java

Source

/**
 * Copyright 2014 Andy Godwin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package spring.travel.site.services.news;

import com.google.common.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import spring.travel.site.model.NewsItem;
import spring.travel.site.services.HttpClient;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

import static uk.co.sdev.async.Futures.some;
import static uk.co.sdev.async.Futures.withFallback;

@Service
public class NewsService {

    @Autowired
    private HttpClient client;

    @Autowired
    private Cache<String, List<NewsItem>> newsCache;

    @Autowired
    private NewsDigester newsDigester;

    @Value("${news.service.url}")
    private String newsServiceUrl;

    public CompletableFuture<Optional<List<NewsItem>>> news() {
        List<NewsItem> newsItems = newsCache.getIfPresent(newsServiceUrl);
        if (newsItems != null) {
            return some(newsItems);
        }
        return client
                .get(newsServiceUrl, request -> request.getHeaders().add("Accept", "text/xml"),
                        response -> Optional.of(newsDigester.from(response.getResponseBodyAsStream())))
                .handle(withFallback(Optional.<List<NewsItem>>empty()))
                .whenComplete((items, t) -> items.ifPresent(it -> {
                    if (it.size() > 0) {
                        newsCache.put(newsServiceUrl, it);
                    }
                }));
    }
}