spring.travel.site.services.AdvertService.java Source code

Java tutorial

Introduction

Here is the source code for spring.travel.site.services.AdvertService.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;

import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import spring.travel.site.model.Advert;
import spring.travel.site.model.user.Profile;

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

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

@Service
public class AdvertService {

    @Autowired
    private HttpClient client;

    @Value("${advert.service.url}")
    private String advertServiceUrl;

    public CompletableFuture<Optional<List<Advert>>> adverts(int count, Optional<Profile> profile) {
        return client.get(url(count, profile), new TypeReference<Optional<List<Advert>>>() {
        }).handle(withFallback(Optional.<List<Advert>>empty()));
    }

    private String url(int count, Optional<Profile> profile) {
        StringBuilder builder = new StringBuilder(advertServiceUrl).append("?count=").append(count);
        profile.ifPresent(p -> builder.append("&target=").append(target(p)));
        return builder.toString();
    }

    private String target(Profile profile) {
        switch (profile.getSpending()) {
        case Economy:
            return "low";
        case Standard:
            return "middle";
        case Luxury:
            return "high";
        }
        throw new IllegalStateException("Unexpected Spending value '" + profile.getSpending() + "'");
    }
}