OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
177 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils.cc;
15
 
16
import java.util.concurrent.ExecutionException;
17
import java.util.concurrent.FutureTask;
18
 
19
public class ExceptionFuture<V, X extends Exception, X2 extends Exception> extends FutureTask<V> {
20
 
21
    static public class OneExceptionFuture<V, X extends Exception> extends ExceptionFuture<V, X, RuntimeException> {
22
        public <X2 extends RuntimeException> OneExceptionFuture(final I2ExnFactory<? extends V, ? extends X, ? extends RuntimeException> cl) {
23
            super(cl, RuntimeException.class);
24
        }
25
    }
26
 
27
    private final Class<X2> exnClass;
28
 
29
    public ExceptionFuture(final I2ExnFactory<? extends V, ? extends X, ? extends X2> cl, final Class<X2> exnClass) {
30
        super(cl::createChecked);
31
        this.exnClass = exnClass;
32
    }
33
 
34
    public final V getWithOriginalException() throws InterruptedException, X, X2 {
35
        try {
36
            return this.get();
37
        } catch (ExecutionException e) {
38
            final Throwable cause = e.getCause();
39
            if (cause instanceof Error) {
40
                throw (Error) cause;
41
            } else if (cause instanceof RuntimeException) {
42
                throw (RuntimeException) cause;
43
                // Not strictly necessary but it feels more robust than to cast "cause" to X even
44
                // when it's really X2
45
            } else if (this.exnClass.isInstance(cause)) {
46
                throw this.exnClass.cast(cause);
47
            } else {
48
                // our Callable throws X or X2 but the latter is already handled above.
49
                @SuppressWarnings("unchecked")
50
                final X casted = (X) cause;
51
                throw casted;
52
            }
53
        }
54
    }
55
}