Java tutorial
/** * 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 uk.co.sdev.async.http; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.Test; import uk.co.sdev.async.HandOff; import uk.co.sdev.async.Tuple2; import uk.co.sdev.async.Tuple3; import uk.co.sdev.async.http.model.Offer; import uk.co.sdev.async.http.model.Profile; import uk.co.sdev.async.http.model.User; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static uk.co.sdev.async.Futures.immediate; import static uk.co.sdev.async.Futures.sequential; public class CompositionTest extends CompletableFutureClientTestSupport { private CompletableFuture<User> user(String name) { return completableFutureClient.get("http://localhost:9101/user/" + name, User.class); } private CompletableFuture<Profile> profile(int id) { return completableFutureClient.get("http://localhost:9101/profile/" + id, Profile.class); } private CompletableFuture<List<Offer>> offers(Profile profile) { return completableFutureClient.get( "http://localhost:9101/offers/" + profile.getSpending().name().toLowerCase(), new TypeReference<List<Offer>>() { }); } @Test public void shouldBeAbleToCaptureIntermediateResultsUsingInlineComposition() throws Exception { stubGet("/user/barney", new User(123456, "barneyrubble@bedrock.org")); stubGet("/profile/123456", new Profile(Profile.Spending.LUXURY)); stubGet("/offers/luxury", Arrays.asList(new Offer("offer1", "description1", "image1"), new Offer("offer2", "description2", "image2"))); HandOff<Tuple3<User, Profile, List<Offer>>> handOff = new HandOff<>(); sequential(user("barney"), user -> profile(user.getId()) .thenCompose(profile -> immediate(new Tuple2<User, Profile>(user, profile))), profileAndUser -> offers(profileAndUser.b()).thenCompose(offers -> immediate( new Tuple3<User, Profile, List<Offer>>(profileAndUser.a(), profileAndUser.b(), offers)))) .whenComplete((tuple, t) -> { handOff.put(tuple); }); Tuple3<User, Profile, List<Offer>> tuple = handOff.get(2); assertThat(tuple.a().getId(), is(123456)); assertThat(tuple.b().getSpending(), is(Profile.Spending.LUXURY)); assertThat(tuple.c().size(), is(2)); } }