001/** 002 * Copyright (C) 2006-2024 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.runtime.manager.reflect.parameterenricher; 017 018import static java.util.Collections.singletonMap; 019import static java.util.Optional.ofNullable; 020 021import java.lang.annotation.Annotation; 022import java.lang.reflect.InvocationTargetException; 023import java.lang.reflect.ParameterizedType; 024import java.lang.reflect.Type; 025import java.util.Collections; 026import java.util.Map; 027import java.util.stream.Stream; 028 029import org.talend.sdk.component.api.configuration.constraint.meta.Validation; 030import org.talend.sdk.component.api.configuration.constraint.meta.Validations; 031 032public class ValidationParameterEnricher extends BaseParameterEnricher { 033 034 public static final String META_PREFIX = "tcomp::validation::"; 035 036 @Override 037 public Map<String, String> onParameterAnnotation(final String parameterName, final Type parameterType, 038 final Annotation annotation) { 039 final Class<?> asClass = toClass(parameterType); 040 return ofNullable(annotation.annotationType().getAnnotation(Validations.class)) 041 .map(v -> Stream.of(v.value())) 042 .orElseGet(() -> ofNullable(annotation.annotationType().getAnnotation(Validation.class)) 043 .map(Stream::of) 044 .orElseGet(Stream::empty)) 045 .filter(v -> Stream.of(v.expectedTypes()).anyMatch(t -> asClass != null && t.isAssignableFrom(asClass))) 046 .findFirst() 047 .map(v -> singletonMap(META_PREFIX + v.name(), getValueString(annotation))) 048 .orElseGet(Collections::emptyMap); 049 } 050 051 private Class<?> toClass(final Type parameterType) { 052 return ParameterizedType.class.isInstance(parameterType) 053 ? toClass(ParameterizedType.class.cast(parameterType).getRawType()) 054 : (Class.class.isInstance(parameterType) ? Class.class.cast(parameterType) : null); 055 } 056 057 private String getValueString(final Annotation annotation) { 058 try { 059 return String.valueOf(annotation.annotationType().getMethod("value").invoke(annotation)); 060 } catch (final IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { 061 return "true"; // no value method means it is a boolean marker 062 } 063 } 064}