001/**
002 * Copyright (C) 2006-2019 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;
019import static java.util.stream.Collectors.toList;
020
021import java.lang.reflect.InvocationTargetException;
022import java.util.Collection;
023import java.util.Optional;
024import java.util.stream.Stream;
025
026public class EnvironmentsConfigurationParser {
027
028    private final Collection<EnvironmentProvider> environments;
029
030    private final boolean parallel;
031
032    public EnvironmentsConfigurationParser(final Class<?> testClass) {
033        final Optional<Environments> config = ofNullable(testClass.getAnnotation(Environments.class));
034        environments = Stream
035                .concat(config.map(Environments::value).map(Stream::of).orElseGet(Stream::empty),
036                        ofNullable(testClass.getAnnotation(Environment.class)).map(Stream::of).orElseGet(Stream::empty))
037                .map(e -> {
038                    try {
039                        return e.value().getConstructor().newInstance();
040                    } catch (final InstantiationException | IllegalAccessException | NoSuchMethodException ex) {
041                        throw new IllegalStateException(ex);
042                    } catch (final InvocationTargetException ex) {
043                        throw new IllegalStateException(ex.getTargetException());
044                    }
045                })
046                .map(DecoratingEnvironmentProvider::new)
047                .collect(toList());
048        parallel = config.map(Environments::parallel).orElse(false);
049    }
050
051    public Stream<EnvironmentProvider> stream() {
052        final Stream<EnvironmentProvider> stream = environments.stream();
053        if (parallel) {
054            return stream.parallel();
055        }
056        return stream;
057    }
058}