/* * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.util.concurrent; import com.google.common.base.Function; import com.google.common.base.Preconditions; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; /** * Utility exception mapper which translates an Exception to a specified type of Exception. * * This mapper is intended to be used with {@link com.google.common.util.concurrent.Futures#makeChecked(com.google.common.util.concurrent.ListenableFuture, Function)} * * * @author Thomas Pantelis * * @param the exception type */ public abstract class ExceptionMapper implements Function { private final Class exceptionType; private final String opName; /** * Constructor. * * @param opName the String prefix for exception messages. * @param exceptionType the exception type to which to translate. */ public ExceptionMapper(final String opName, final Class exceptionType) { this.exceptionType = Preconditions.checkNotNull(exceptionType); this.opName = Preconditions.checkNotNull(opName); } /** * Return the exception class produced by this instance. * * @return Exception class. */ protected final Class getExceptionType() { return exceptionType; } /** * Invoked to create a new exception instance of the specified type. * * @param message the message for the new exception. * @param cause the cause for the new exception. * * @return an instance of the exception type. */ protected abstract X newWithCause(String message, Throwable cause); @SuppressWarnings("unchecked") @Override public X apply(final Exception e) { // If exception is of the specified type,return it. if (exceptionType.isAssignableFrom( e.getClass())) { return (X) e; } // If exception is ExecutionException whose cause is of the specified // type, return the cause. if (e instanceof ExecutionException && e.getCause() != null) { if (exceptionType.isAssignableFrom( e.getCause().getClass())) { return (X) e.getCause(); } else { return newWithCause(opName + " execution failed", e.getCause()); } } // Otherwise return an instance of the specified type with the original // cause. if (e instanceof InterruptedException) { return newWithCause( opName + " was interupted.", e); } if (e instanceof CancellationException ) { return newWithCause( opName + " was cancelled.", e); } // We really shouldn't get here but need to cover it anyway for completeness. return newWithCause(opName + " encountered an unexpected failure", e); } }