001/**
002 * Copyright (C) 2006-2022 Talend Inc. - www.talend.com
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 */
016package org.talend.sdk.component.junit.environment;
017
018import static java.util.Optional.ofNullable;
019
020import java.lang.annotation.Annotation;
021import java.net.URL;
022import java.net.URLClassLoader;
023import java.util.stream.Stream;
024
025import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency;
026
027import lombok.extern.slf4j.Slf4j;
028
029@Slf4j
030public abstract class ClassLoaderEnvironment extends BaseEnvironmentProvider {
031
032    protected abstract MavenDependency[] rootDependencies();
033
034    @Override
035    protected AutoCloseable doStart(final Class<?> clazz, final Annotation[] annotations) {
036        try {
037            ofNullable(Thread.currentThread().getContextClassLoader())
038                    .orElseGet(ClassLoader::getSystemClassLoader)
039                    .loadClass("org.jboss.shrinkwrap.resolver.api.maven.Maven");
040        } catch (final ClassNotFoundException e) {
041            throw new IllegalStateException("Don't forget to add to your dependencies:\n"
042                    + "  org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-impl-maven:3.1.4");
043        }
044        final Thread thread = Thread.currentThread();
045        final URLClassLoader classLoader = new URLClassLoader(Stream
046                .of(rootDependencies())
047                .peek(dep -> log.info("Resolving " + dep + "..."))
048                .flatMap(dep -> Stream.of(Dependencies.resolve(dep)))
049                .toArray(URL[]::new), Thread.currentThread().getContextClassLoader());
050        final ClassLoader original = thread.getContextClassLoader();
051        thread.setContextClassLoader(classLoader);
052        return () -> {
053            thread.setContextClassLoader(original);
054            classLoader.close();
055        };
056    }
057}