/* * Copyright 2002-2013 the original author or authors. * * 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 org.springframework.messaging.support.tcp; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.springframework.util.Assert; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; import org.springframework.util.concurrent.ListenableFutureCallbackRegistry; import reactor.core.composable.Promise; import reactor.function.Consumer; /** * Adapts a reactor {@link Promise} to {@link ListenableFuture} optionally converting * the result Object type {@code } to the expected target type {@code }. * * @param the type of object expected from the {@link Promise} * @param the type of object expected from the {@link ListenableFuture} * * @author Rossen Stoyanchev * @since 4.0 */ abstract class PromiseToListenableFutureAdapter implements ListenableFuture { private final Promise promise; private final ListenableFutureCallbackRegistry registry = new ListenableFutureCallbackRegistry(); protected PromiseToListenableFutureAdapter(Promise promise) { Assert.notNull(promise, "promise is required"); this.promise = promise; this.promise.onSuccess(new Consumer() { @Override public void accept(S result) { try { registry.success(adapt(result)); } catch (Throwable t) { registry.failure(t); } } }); this.promise.onError(new Consumer() { @Override public void accept(Throwable t) { registry.failure(t); } }); } protected abstract T adapt(S adapteeResult); @Override public T get() { S result = this.promise.get(); return adapt(result); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { S result = this.promise.await(timeout, unit); if (result == null) { throw new TimeoutException(); } return adapt(result); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return this.promise.isComplete(); } @Override public void addCallback(ListenableFutureCallback callback) { this.registry.addCallback(callback); } }