001/*
002 * Copyright 2012-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.boot.diagnostics;
018
019import org.springframework.core.ResolvableType;
020
021/**
022 * Abstract base class for most {@code FailureAnalyzer} implementations.
023 *
024 * @param <T> the type of exception to analyze
025 * @author Andy Wilkinson
026 * @author Phillip Webb
027 * @since 1.4.0
028 */
029public abstract class AbstractFailureAnalyzer<T extends Throwable>
030                implements FailureAnalyzer {
031
032        @Override
033        public FailureAnalysis analyze(Throwable failure) {
034                T cause = findCause(failure, getCauseType());
035                if (cause != null) {
036                        return analyze(failure, cause);
037                }
038                return null;
039        }
040
041        /**
042         * Returns an analysis of the given {@code rootFailure}, or {@code null} if no
043         * analysis was possible.
044         * @param rootFailure the root failure passed to the analyzer
045         * @param cause the actual found cause
046         * @return the analysis or {@code null}
047         */
048        protected abstract FailureAnalysis analyze(Throwable rootFailure, T cause);
049
050        /**
051         * Return the cause type being handled by the analyzer. By default the class generic
052         * is used.
053         * @return the cause type
054         */
055        @SuppressWarnings("unchecked")
056        protected Class<? extends T> getCauseType() {
057                return (Class<? extends T>) ResolvableType
058                                .forClass(AbstractFailureAnalyzer.class, getClass()).resolveGeneric();
059        }
060
061        @SuppressWarnings("unchecked")
062        protected final <E extends Throwable> E findCause(Throwable failure, Class<E> type) {
063                while (failure != null) {
064                        if (type.isInstance(failure)) {
065                                return (E) failure;
066                        }
067                        failure = failure.getCause();
068                }
069                return null;
070        }
071
072}