001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.concurrent;
016    
017    import java.util.concurrent.ExecutionException;
018    import java.util.concurrent.Future;
019    import java.util.concurrent.TimeUnit;
020    import java.util.concurrent.TimeoutException;
021    
022    /**
023     * @author Shuyang Zhou
024     */
025    public abstract class FutureConverter<T, V> implements Future<T> {
026    
027            public FutureConverter(Future<V> future) {
028                    _future = future;
029            }
030    
031            @Override
032            public boolean cancel(boolean mayInterruptIfRunning) {
033                    return _future.cancel(mayInterruptIfRunning);
034            }
035    
036            @Override
037            public T get() throws ExecutionException, InterruptedException {
038                    V v = _future.get();
039    
040                    try {
041                            return convert(v);
042                    }
043                    catch (Throwable t) {
044                            throw new ExecutionException(t);
045                    }
046            }
047    
048            @Override
049            public T get(long timeout, TimeUnit timeUnit)
050                    throws ExecutionException, InterruptedException, TimeoutException {
051    
052                    V v = _future.get(timeout, timeUnit);
053    
054                    try {
055                            return convert(v);
056                    }
057                    catch (Throwable t) {
058                            throw new ExecutionException(t);
059                    }
060            }
061    
062            @Override
063            public boolean isCancelled() {
064                    return _future.isCancelled();
065            }
066    
067            @Override
068            public boolean isDone() {
069                    return _future.isDone();
070            }
071    
072            protected abstract T convert(V v) throws Throwable;
073    
074            private final Future<V> _future;
075    
076    }