jamesnetherton commented on code in PR #5123:
URL: https://github.com/apache/camel-quarkus/pull/5123#discussion_r1275928307


##########
extensions/mapstruct/deployment/src/main/java/org/apache/camel/quarkus/component/mapstruct/deployment/MapStructProcessor.java:
##########
@@ -0,0 +1,372 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.quarkus.component.mapstruct.deployment;
+
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Stream;
+
+import io.quarkus.arc.deployment.BeanContainerBuildItem;
+import io.quarkus.arc.deployment.GeneratedBeanBuildItem;
+import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor;
+import io.quarkus.arc.deployment.UnremovableBeanBuildItem;
+import io.quarkus.deployment.GeneratedClassGizmoAdaptor;
+import io.quarkus.deployment.annotations.BuildProducer;
+import io.quarkus.deployment.annotations.BuildStep;
+import io.quarkus.deployment.annotations.ExecutionTime;
+import io.quarkus.deployment.annotations.Record;
+import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
+import io.quarkus.deployment.builditem.FeatureBuildItem;
+import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
+import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
+import io.quarkus.deployment.builditem.nativeimage.ServiceProviderBuildItem;
+import io.quarkus.gizmo.ClassCreator;
+import io.quarkus.gizmo.ClassOutput;
+import io.quarkus.gizmo.FieldCreator;
+import io.quarkus.gizmo.FieldDescriptor;
+import io.quarkus.gizmo.MethodCreator;
+import io.quarkus.gizmo.MethodDescriptor;
+import io.quarkus.gizmo.ResultHandle;
+import io.quarkus.runtime.RuntimeValue;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.inject.Named;
+import jakarta.inject.Singleton;
+import org.apache.camel.Exchange;
+import org.apache.camel.component.mapstruct.MapstructComponent;
+import org.apache.camel.quarkus.component.mapstruct.ConversionMethodInfo;
+import org.apache.camel.quarkus.component.mapstruct.MapStructRecorder;
+import org.apache.camel.quarkus.core.deployment.spi.CamelBeanBuildItem;
+import 
org.apache.camel.quarkus.core.deployment.spi.CamelTypeConverterRegistryBuildItem;
+import org.apache.camel.support.SimpleTypeConverter.ConversionMethod;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.ReflectionHelper;
+import org.apache.camel.util.StringHelper;
+import org.eclipse.microprofile.config.ConfigProvider;
+import org.jboss.jandex.AnnotationInstance;
+import org.jboss.jandex.AnnotationTarget;
+import org.jboss.jandex.AnnotationValue;
+import org.jboss.jandex.ClassInfo;
+import org.jboss.jandex.DotName;
+import org.jboss.jandex.FieldInfo;
+import org.jboss.jandex.IndexView;
+import org.mapstruct.Mapper;
+
+class MapStructProcessor {
+
+    private static final String FEATURE = "camel-mapstruct";
+
+    @BuildStep
+    FeatureBuildItem feature() {
+        return new FeatureBuildItem(FEATURE);
+    }
+
+    @BuildStep
+    MapStructMapperPackagesBuildItem getMapperPackages(CombinedIndexBuildItem 
combinedIndex) {
+        final Set<String> mapperPackages = new HashSet<>();
+
+        Optional<String> mapperPackageName = ConfigProvider.getConfig()
+                
.getOptionalValue("camel.component.mapstruct.mapper-package-name", 
String.class);
+
+        if (mapperPackageName.isPresent()) {
+            
mapperPackages.addAll(Arrays.asList(mapperPackageName.get().split(",")));
+        } else {
+            // Fallback on auto discovery
+            combinedIndex.getIndex()
+                    .getAnnotations(Mapper.class)
+                    .stream()
+                    .map(AnnotationInstance::target)
+                    .map(AnnotationTarget::asClass)
+                    .map(ClassInfo::name)
+                    .map(DotName::packagePrefix)
+                    .forEach(mapperPackages::add);
+        }
+
+        return new MapStructMapperPackagesBuildItem(mapperPackages);
+    }
+
+    @Record(ExecutionTime.STATIC_INIT)
+    @BuildStep
+    CamelBeanBuildItem mapStructComponentBean(
+            MapStructMapperPackagesBuildItem mapperPackages,
+            ConversionMethodInfoRuntimeValuesBuildItem conversionMethodInfos,
+            MapStructRecorder recorder) {
+        return new CamelBeanBuildItem("mapstruct", 
MapstructComponent.class.getName(),
+                
recorder.createMapStructComponent(mapperPackages.getMapperPackages(),
+                        
conversionMethodInfos.getConversionMethodInfoRuntimeValues()));
+    }
+
+    @Record(ExecutionTime.STATIC_INIT)
+    @BuildStep
+    void generateMapStructTypeConverters(
+            BuildProducer<GeneratedBeanBuildItem> generatedBean,
+            BuildProducer<GeneratedClassBuildItem> generatedClass,
+            BuildProducer<UnremovableBeanBuildItem> unremovableBean,
+            BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
+            BuildProducer<ConversionMethodInfoRuntimeValuesBuildItem> 
conversionMethodInfos,
+            CombinedIndexBuildItem combinedIndex,
+            MapStructMapperPackagesBuildItem mapperPackages,
+            MapStructRecorder recorder) {
+
+        // The logic that follows mimics dynamic TypeConverter logic in 
DefaultMapStructFinder.discoverMappings
+        Set<String> packages = mapperPackages.getMapperPackages();
+        AtomicInteger methodCount = new AtomicInteger();
+        Map<String, RuntimeValue<ConversionMethodInfo>> conversionMethods = 
new HashMap<>();
+        IndexView index = combinedIndex.getIndex();
+
+        // Find implementations of Mapper annotated interfaces or abstract 
classes
+        index.getAnnotations(Mapper.class)
+                .stream()
+                .map(AnnotationInstance::target)
+                .map(AnnotationTarget::asClass)
+                .filter(classInfo -> 
packages.contains(classInfo.name().packagePrefix()))
+                .filter(classInfo -> classInfo.isInterface() || 
Modifier.isAbstract(classInfo.flags()))
+                .flatMap(classInfo -> 
Stream.concat(index.getAllKnownImplementors(classInfo.name()).stream(),
+                        
index.getAllKnownSubclasses(classInfo.name()).stream()))
+                .forEach(classInfo -> {
+                    AtomicReference<RuntimeValue<?>> mapperRuntimeValue = new 
AtomicReference<>();
+                    String mapperClassName = classInfo.name().toString();
+                    String mapperDefinitionClassName = 
getMapperDefinitionClassName(classInfo);
+                    if (ObjectHelper.isEmpty(mapperDefinitionClassName)) {
+                        return;
+                    }
+
+                    // Check if there's a static instance field defined for 
the Mapper
+                    ClassInfo mapperDefinitionClassInfo = 
index.getClassByName(mapperDefinitionClassName);
+                    Optional<FieldInfo> mapperInstanceField = 
mapperDefinitionClassInfo
+                            .fields()
+                            .stream()
+                            .filter(fieldInfo -> 
Modifier.isStatic(fieldInfo.flags()))
+                            .filter(fieldInfo -> 
fieldInfo.type().name().toString().equals(mapperDefinitionClassName))
+                            .findFirst();
+
+                    // Check of the Mapper is a CDI bean with one of the 
supported MapStruct annotations
+                    boolean mapperBeanExists = 
classInfo.hasDeclaredAnnotation(ApplicationScoped.class)
+                            || classInfo.hasDeclaredAnnotation(Named.class);
+                    if (mapperInstanceField.isEmpty()) {
+                        if (mapperBeanExists) {
+                            unremovableBean
+                                    .produce(new 
UnremovableBeanBuildItem(beanInfo -> beanInfo.hasType(classInfo.name())));
+                        } else {
+                            // Create the Mapper ourselves
+                            
mapperRuntimeValue.set(recorder.createMapper(mapperClassName));
+                        }
+                    }
+
+                    /*
+                     * Generate SimpleTypeConverter.ConversionMethod 
implementations for each candidate Mapper method.
+                     *
+                     * ReflectionHelper is used to resolve the mapper methods 
for simplicity, compared to Jandex where
+                     * we potentially have to iterate over the type hierarchy 
(E.g for multiple interfaces,
+                     * interface / class inheritance etc).
+                     *
+                     * public final class FooConversionMethod implements 
ConversionMethod {
+                     *    private final CarMapperImpl mapper;
+                     *
+                     *    // Generated only if a Mapper instance is a CDI bean
+                     *    public ToCarConversionMethod() {
+                     *    }
+                     *
+                     *    // Generated only if a Mapper instance was declared 
on the Mapper interface
+                     *    public ToCarConversionMethod() {
+                     *        this(CarMapper.INSTANCE);
+                     *    }
+                     *
+                     *    public ToCarConversionMethod(CarMapperImpl mapper) {
+                     *        this.mapper = mapper;
+                     *    }
+                     *
+                     *    @Override
+                     *    public Object doConvert(Class<?> type, Exchange 
exchange, Object value) throws Exception {
+                     *        return mapper.stringToInt(value);
+                     *    }
+                     * }
+                     */

Review Comment:
   Just noticed a few copy / paste errors that make it confusing (constructor 
method names) so I will correct that.



##########
extensions/mapstruct/runtime/src/main/java/org/apache/camel/quarkus/component/mapstruct/CamelQuarkusMapStructMapperFinder.java:
##########
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.quarkus.component.mapstruct;
+
+import org.apache.camel.component.mapstruct.MapStructMapperFinder;
+import org.apache.camel.support.service.ServiceSupport;
+import org.apache.camel.util.ObjectHelper;
+import org.jboss.logging.Logger;
+
+/**
+ * Custom {@link MapStructMapperFinder} that is effectively a noop 
implementation, as the work of discovering
+ * mappings is done at build time.
+ */
+public class CamelQuarkusMapStructMapperFinder extends ServiceSupport 
implements MapStructMapperFinder {
+    private static final Logger LOG = 
Logger.getLogger(CamelQuarkusMapStructMapperFinder.class);
+
+    private final int mappingsCount;
+    private String mapperPackageName;
+
+    public CamelQuarkusMapStructMapperFinder(String mapperPackageName, int 
mappingsCount) {
+        setMapperPackageName(mapperPackageName);
+        this.mappingsCount = mappingsCount;
+    }
+
+    @Override
+    public void setMapperPackageName(String mapperPackageName) {
+        this.mapperPackageName = mapperPackageName;
+    }
+
+    @Override
+    public String getMapperPackageName() {
+        return this.mapperPackageName;
+    }
+
+    @Override
+    public int discoverMappings(Class<?> clazz) {
+        // Discovery is done at build time so just return the count
+        return mappingsCount;
+    }
+
+    @Override
+    protected void doInit() throws Exception {
+        if (ObjectHelper.isNotEmpty(mapperPackageName)) {
+            LOG.infof("Discovered %d MapStruct type converters from classpath 
scanning: %s", mappingsCount, mapperPackageName);

Review Comment:
   Yeah, I can change it. It was a copy / paste from the default impl that 
Camel uses.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@camel.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to