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; 017 018import static java.util.Optional.ofNullable; 019 020import java.util.stream.Stream; 021 022import org.junit.rules.TestRule; 023import org.junit.runner.Description; 024import org.junit.runners.model.Statement; 025import org.talend.sdk.component.api.DecryptedServer; 026import org.talend.sdk.component.base.BaseMavenDecrypter; 027import org.talend.sdk.component.maven.Server; 028 029import lombok.RequiredArgsConstructor; 030 031@RequiredArgsConstructor 032public class MavenDecrypterRule implements TestRule { 033 034 private final Object instance; 035 036 private final BaseMavenDecrypter decrypter = new BaseMavenDecrypter();; 037 038 @Override 039 public Statement apply(final Statement base, final Description description) { 040 return new Statement() { 041 042 @Override 043 public void evaluate() throws Throwable { 044 doInject(instance, instance.getClass()); 045 base.evaluate(); 046 } 047 }; 048 } 049 050 private void doInject(final Object instance, final Class<?> base) { 051 Stream.of(base.getDeclaredFields()).filter(f -> f.isAnnotationPresent(DecryptedServer.class)).forEach(f -> { 052 final DecryptedServer annotation = f.getAnnotation(DecryptedServer.class); 053 final Server server = decrypter.createInstance(annotation); 054 if (!f.isAccessible()) { 055 f.setAccessible(true); 056 } 057 try { 058 f.set(instance, server); 059 } catch (final IllegalAccessException e) { 060 throw new IllegalStateException(e); 061 } 062 }); 063 ofNullable(base.getSuperclass()).filter(s -> s != Object.class).ifPresent(c -> doInject(instance, c)); 064 } 065}