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

Java tutorial

Introduction

Here is the source code for spring.travel.site.services.OffersService.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.Offer;
import spring.travel.site.model.user.Loyalty;
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 OffersService {

    @Autowired
    private HttpClient client;

    @Value("${offers.service.url}")
    private String offersServiceUrl;

    public CompletableFuture<Optional<List<Offer>>> offers(Optional<Profile> profile, Optional<Loyalty> loyalty) {
        return client.get(url(profile, loyalty), new TypeReference<Optional<List<Offer>>>() {
        }).handle(withFallback(Optional.<List<Offer>>empty()));
    }

    private String url(Optional<Profile> profile, Optional<Loyalty> loyalty) {
        return new StringBuilder(offersServiceUrl).append(queryString(profile, loyalty)).toString();
    }

    private String queryString(Optional<Profile> profile, Optional<Loyalty> loyalty) {
        StringBuilder builder = new StringBuilder();

        profile.ifPresent(p -> builder.append("?lifecycle=").append(p.getLifecycle().toString().toLowerCase())
                .append("&spending=").append(p.getSpending().toString().toLowerCase()).append("&gender=")
                .append(p.getGender().toString().toLowerCase()));

        loyalty.ifPresent(l -> builder.append(profile.isPresent() ? "&" : "?").append("loyalty=")
                .append(l.getGroup().toString().toLowerCase()));

        return builder.toString();
    }
}