001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *        http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 */
019
020package org.apache.isis.core.metamodel.specloader.classsubstitutor;
021
022import java.util.Arrays;
023import java.util.List;
024
025import com.google.common.collect.Lists;
026
027public class ClassSubstitutorComposite implements ClassSubstitutor {
028
029    private final List<ClassSubstitutor> substitutors = Lists.newArrayList();
030
031    public ClassSubstitutorComposite(final List<ClassSubstitutor> substitutors) {
032        this.substitutors.addAll(substitutors);
033    }
034
035    public ClassSubstitutorComposite(final ClassSubstitutor... substitutors) {
036        this(Arrays.asList(substitutors));
037    }
038
039    @Override
040    public void init() {
041        for (final ClassSubstitutor classSubstitutor : substitutors) {
042            classSubstitutor.init();
043        }
044    }
045
046    @Override
047    public void shutdown() {
048        for (final ClassSubstitutor classSubstitutor : substitutors) {
049            classSubstitutor.shutdown();
050        }
051    }
052
053    @Override
054    public Class<?> getClass(Class<?> cls) {
055        Class<?> clsBefore;
056        do {
057            clsBefore = cls;
058            for (final ClassSubstitutor substitutor : substitutors) {
059                cls = substitutor.getClass(cls);
060                if (cls == null) {
061                    return null;
062                }
063            }
064        } while (clsBefore != cls);
065        return cls;
066    }
067
068    @Override
069    public void injectInto(final Object candidate) {
070        if (ClassSubstitutorAware.class.isAssignableFrom(candidate.getClass())) {
071            final ClassSubstitutorAware cast = ClassSubstitutorAware.class.cast(candidate);
072            cast.setClassSubstitutor(this);
073        }
074    }
075
076}