001/** 002 * Copyright (C) 2006-2023 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.stream.Collectors.toList; 019 020import java.lang.reflect.AnnotatedElement; 021import java.lang.reflect.InvocationTargetException; 022import java.util.Collection; 023import java.util.Optional; 024import java.util.stream.Stream; 025 026import org.junit.platform.commons.util.AnnotationUtils; 027 028public class EnvironmentsConfigurationParser { 029 030 private final Collection<EnvironmentProvider> environments; 031 032 private final boolean parallel; 033 034 public EnvironmentsConfigurationParser(final Class<?> clazz) { // backward compatibility 035 this((AnnotatedElement) clazz); 036 } 037 038 public EnvironmentsConfigurationParser(final AnnotatedElement context) { 039 final Optional<Environments> config = AnnotationUtils.findAnnotation(context, Environments.class); 040 environments = Stream 041 .concat(config.map(Environments::value).map(Stream::of).orElseGet(Stream::empty), 042 AnnotationUtils 043 .findAnnotation(context, Environment.class) 044 .map(Stream::of) 045 .orElseGet(Stream::empty)) 046 .distinct() 047 .map(e -> { 048 try { 049 return e.value().getConstructor().newInstance(); 050 } catch (final InstantiationException | IllegalAccessException | NoSuchMethodException ex) { 051 throw new IllegalStateException(ex); 052 } catch (final InvocationTargetException ex) { 053 throw new IllegalStateException(ex.getTargetException()); 054 } 055 }) 056 .map(DecoratingEnvironmentProvider::new) 057 .collect(toList()); 058 parallel = config.map(Environments::parallel).orElse(false); 059 } 060 061 public Stream<EnvironmentProvider> stream() { 062 final Stream<EnvironmentProvider> stream = environments.stream(); 063 if (parallel) { 064 return stream.parallel(); 065 } 066 return stream; 067 } 068}