001/*
002 * Copyright 2012-2018 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.origin;
018
019/**
020 * An interface that may be implemented by an object that can lookup {@link Origin}
021 * information from a given key. Can be used to add origin support to existing classes.
022 *
023 * @param <K> the lookup key type
024 * @author Phillip Webb
025 * @since 2.0.0
026 */
027@FunctionalInterface
028public interface OriginLookup<K> {
029
030        /**
031         * Return the origin of the given key or {@code null} if the origin cannot be
032         * determined.
033         * @param key the key to lookup
034         * @return the origin of the key or {@code null}
035         */
036        Origin getOrigin(K key);
037
038        /**
039         * Attempt to lookup the origin from the given source. If the source is not a
040         * {@link OriginLookup} or if an exception occurs during lookup then {@code null} is
041         * returned.
042         * @param source the source object
043         * @param key the key to lookup
044         * @param <K> the key type
045         * @return an {@link Origin} or {@code null}
046         */
047        @SuppressWarnings("unchecked")
048        static <K> Origin getOrigin(Object source, K key) {
049                if (!(source instanceof OriginLookup)) {
050                        return null;
051                }
052                try {
053                        return ((OriginLookup<K>) source).getOrigin(key);
054                }
055                catch (Throwable ex) {
056                        return null;
057                }
058        }
059
060}