This is an automated email from the ASF dual-hosted git repository.

orpiske pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 712bd3511e16276cf92a4c377e02410f40dbf733
Author: Otavio Rodolfo Piske <[email protected]>
AuthorDate: Thu May 16 06:21:51 2024 +0200

    (chores) camel-jackson: code cleanup
    
    - break large and complex methods
    - cleanup unnecessary explicit types
---
 .../jackson/AbstractJacksonDataFormat.java         | 264 ++++++++++++---------
 .../jackson/converter/JacksonTypeConverters.java   |  42 ++--
 .../jackson/transform/JsonSchemaResolver.java      |  63 +++--
 .../component/jackson/JacksonConcurrentTest.java   |   2 +-
 4 files changed, 212 insertions(+), 159 deletions(-)

diff --git 
a/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/AbstractJacksonDataFormat.java
 
b/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/AbstractJacksonDataFormat.java
index 848e56f4ddb..b58764477ac 100644
--- 
a/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/AbstractJacksonDataFormat.java
+++ 
b/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/AbstractJacksonDataFormat.java
@@ -568,30 +568,7 @@ public abstract class AbstractJacksonDataFormat extends 
ServiceSupport
             setCollectionType(ArrayList.class);
         }
 
-        boolean objectMapperFoundRegistry = false;
-        if (objectMapper == null) {
-            // lookup if there is a single default mapper we can use
-            if (useDefaultObjectMapper && camelContext != null) {
-                if (isAutoDiscoverObjectMapper()) {
-                    Set<? extends ObjectMapper> set = 
camelContext.getRegistry().findByType(getObjectMapperClass());
-                    if (set.size() == 1) {
-                        objectMapper = set.iterator().next();
-                        LOG.debug("Found single ObjectMapper in Registry to 
use: {}", objectMapper);
-                        objectMapperFoundRegistry = true;
-                    } else if (set.size() > 1) {
-                        LOG.debug(
-                                "Found {} ObjectMapper in Registry cannot use 
as default as there are more than one instance.",
-                                set.size());
-                    }
-                } else {
-                    LOG.debug("The option autoDiscoverObjectMapper is set to 
false, Camel won't search in the registry");
-                }
-            }
-            if (objectMapper == null) {
-                objectMapper = createNewObjectMapper();
-                LOG.debug("Creating new ObjectMapper to use: {}", 
objectMapper);
-            }
-        }
+        final boolean objectMapperFoundRegistry = resolveObjectMapper();
 
         if (!objectMapperFoundRegistry) {
             if (include != null) {
@@ -604,120 +581,181 @@ public abstract class AbstractJacksonDataFormat extends 
ServiceSupport
             }
 
             if (enableFeatures != null) {
-                Iterator<?> it = ObjectHelper.createIterator(enableFeatures);
-                while (it.hasNext()) {
-                    String enable = it.next().toString();
-                    // it can be different kind
-                    SerializationFeature sf
-                            = 
getCamelContext().getTypeConverter().tryConvertTo(SerializationFeature.class, 
enable);
-                    if (sf != null) {
-                        objectMapper.enable(sf);
-                        continue;
-                    }
-                    DeserializationFeature df
-                            = 
getCamelContext().getTypeConverter().tryConvertTo(DeserializationFeature.class, 
enable);
-                    if (df != null) {
-                        objectMapper.enable(df);
-                        continue;
-                    }
-                    MapperFeature mf = 
getCamelContext().getTypeConverter().tryConvertTo(MapperFeature.class, enable);
-                    if (mf != null) {
-                        objectMapper.enable(mf);
-                        continue;
-                    }
-                    throw new IllegalArgumentException(
-                            "Enable feature: " + enable
-                                                       + " cannot be converted 
to an accepted enum of types 
[SerializationFeature,DeserializationFeature,MapperFeature]");
-                }
+                doEnableFeaures();
             }
             if (disableFeatures != null) {
-                Iterator<?> it = ObjectHelper.createIterator(disableFeatures);
-                while (it.hasNext()) {
-                    String disable = it.next().toString();
-                    // it can be different kind
-                    SerializationFeature sf
-                            = 
getCamelContext().getTypeConverter().tryConvertTo(SerializationFeature.class, 
disable);
-                    if (sf != null) {
-                        objectMapper.disable(sf);
-                        continue;
-                    }
-                    DeserializationFeature df
-                            = 
getCamelContext().getTypeConverter().tryConvertTo(DeserializationFeature.class, 
disable);
-                    if (df != null) {
-                        objectMapper.disable(df);
-                        continue;
-                    }
-                    MapperFeature mf = 
getCamelContext().getTypeConverter().tryConvertTo(MapperFeature.class, disable);
-                    if (mf != null) {
-                        objectMapper.disable(mf);
-                        continue;
-                    }
-                    throw new IllegalArgumentException(
-                            "Disable feature: " + disable
-                                                       + " cannot be converted 
to an accepted enum of types 
[SerializationFeature,DeserializationFeature,MapperFeature]");
-                }
+                doDisableFeatures();
             }
 
             if (modules != null) {
-                for (Module module : modules) {
-                    LOG.debug("Registering module: {}", module);
-                    objectMapper.registerModules(module);
-                }
+                registerModules();
             }
             if (moduleClassNames != null) {
-                Iterable<?> it = ObjectHelper.createIterable(moduleClassNames);
-                for (Object o : it) {
-                    String name = o.toString();
-                    Class<Module> clazz = 
camelContext.getClassResolver().resolveMandatoryClass(name, Module.class);
-                    Module module = 
camelContext.getInjector().newInstance(clazz);
-                    LOG.debug("Registering module: {} -> {}", name, module);
-                    objectMapper.registerModule(module);
-                }
+                registerModulesByClassNames();
             }
             if (moduleRefs != null) {
-                Iterable<?> it = ObjectHelper.createIterable(moduleRefs);
-                for (Object o : it) {
-                    String name = o.toString();
-                    if (name.startsWith("#")) {
-                        name = name.substring(1);
-                    }
-                    Module module = 
CamelContextHelper.mandatoryLookup(camelContext, name, Module.class);
-                    LOG.debug("Registering module: {} -> {}", name, module);
-                    objectMapper.registerModule(module);
-                }
+                registerModulesByRefs();
             }
             if (org.apache.camel.util.ObjectHelper.isNotEmpty(timezone)) {
-                LOG.debug("Setting timezone to Object Mapper: {}", timezone);
-                objectMapper.setTimeZone(timezone);
+                setTimezone();
             }
 
             if (org.apache.camel.util.ObjectHelper.isNotEmpty(namingStrategy)) 
{
-                PropertyNamingStrategy selectedNamingStrategy = 
determineNamingStrategy(namingStrategy);
-                if 
(org.apache.camel.util.ObjectHelper.isNotEmpty(selectedNamingStrategy)) {
-                    
objectMapper.setPropertyNamingStrategy(selectedNamingStrategy);
-                }
+                setNamingStrategy();
             }
         } else {
             LOG.debug("The objectMapper was already found in the registry, no 
customizations will be applied");
         }
 
         if (schemaResolver == null && isAutoDiscoverSchemaResolver()) {
-            if (camelContext != null) {
-                Set<SchemaResolver> set = 
camelContext.getRegistry().findByType(SchemaResolver.class);
-                if (set.size() == 1) {
-                    schemaResolver = set.iterator().next();
-                    LOG.debug("Found single SchemaResolver in Registry to use: 
{}", schemaResolver);
-                } else if (set.size() > 1) {
-                    LOG.debug(
-                            "Found {} SchemaResolver in Registry cannot use as 
default as there are more than one instance.",
-                            set.size());
-                }
-            }
+            schemaResolverLookuyp();
         } else {
             LOG.debug("The option autoDiscoverSchemaResolver is set to false, 
Camel won't search in the registry");
         }
     }
 
+    private boolean resolveObjectMapper() {
+        boolean objectMapperFoundRegistry = false;
+        if (objectMapper == null) {
+            // lookup if there is a single default mapper we can use
+            if (useDefaultObjectMapper && camelContext != null) {
+                if (isAutoDiscoverObjectMapper()) {
+                    Set<? extends ObjectMapper> set = 
camelContext.getRegistry().findByType(getObjectMapperClass());
+                    if (set.size() == 1) {
+                        objectMapper = set.iterator().next();
+                        LOG.debug("Found single ObjectMapper in Registry to 
use: {}", objectMapper);
+                        objectMapperFoundRegistry = true;
+                    } else if (set.size() > 1) {
+                        LOG.debug(
+                                "Found {} ObjectMapper in Registry cannot use 
as default as there are more than one instance.",
+                                set.size());
+                    }
+                } else {
+                    LOG.debug("The option autoDiscoverObjectMapper is set to 
false, Camel won't search in the registry");
+                }
+            }
+
+            if (objectMapper == null) {
+                objectMapper = createNewObjectMapper();
+                LOG.debug("Creating new ObjectMapper to use: {}", 
objectMapper);
+            }
+        }
+        return objectMapperFoundRegistry;
+    }
+
+    private void doEnableFeaures() {
+        Iterator<?> it = ObjectHelper.createIterator(enableFeatures);
+        while (it.hasNext()) {
+            String enable = it.next().toString();
+            // it can be different kind
+            SerializationFeature sf
+                    = 
getCamelContext().getTypeConverter().tryConvertTo(SerializationFeature.class, 
enable);
+            if (sf != null) {
+                objectMapper.enable(sf);
+                continue;
+            }
+            DeserializationFeature df
+                    = 
getCamelContext().getTypeConverter().tryConvertTo(DeserializationFeature.class, 
enable);
+            if (df != null) {
+                objectMapper.enable(df);
+                continue;
+            }
+            MapperFeature mf = 
getCamelContext().getTypeConverter().tryConvertTo(MapperFeature.class, enable);
+            if (mf != null) {
+                objectMapper.enable(mf);
+                continue;
+            }
+            throw new IllegalArgumentException(
+                    "Enable feature: " + enable
+                                               + " cannot be converted to an 
accepted enum of types 
[SerializationFeature,DeserializationFeature,MapperFeature]");
+        }
+    }
+
+    private void schemaResolverLookuyp() {
+        if (camelContext != null) {
+            Set<SchemaResolver> set = 
camelContext.getRegistry().findByType(SchemaResolver.class);
+            if (set.size() == 1) {
+                schemaResolver = set.iterator().next();
+                LOG.debug("Found single SchemaResolver in Registry to use: 
{}", schemaResolver);
+            } else if (set.size() > 1) {
+                LOG.debug(
+                        "Found {} SchemaResolver in Registry cannot use as 
default as there are more than one instance.",
+                        set.size());
+            }
+        }
+    }
+
+    private void setNamingStrategy() {
+        PropertyNamingStrategy selectedNamingStrategy = 
determineNamingStrategy(namingStrategy);
+        if 
(org.apache.camel.util.ObjectHelper.isNotEmpty(selectedNamingStrategy)) {
+            objectMapper.setPropertyNamingStrategy(selectedNamingStrategy);
+        }
+    }
+
+    private void setTimezone() {
+        LOG.debug("Setting timezone to Object Mapper: {}", timezone);
+        objectMapper.setTimeZone(timezone);
+    }
+
+    private void registerModulesByRefs() {
+        Iterable<?> it = ObjectHelper.createIterable(moduleRefs);
+        for (Object o : it) {
+            String name = o.toString();
+            if (name.startsWith("#")) {
+                name = name.substring(1);
+            }
+            Module module = CamelContextHelper.mandatoryLookup(camelContext, 
name, Module.class);
+            LOG.debug("Registering module: {} -> {}", name, module);
+            objectMapper.registerModule(module);
+        }
+    }
+
+    private void registerModulesByClassNames() throws ClassNotFoundException {
+        Iterable<?> it = ObjectHelper.createIterable(moduleClassNames);
+        for (Object o : it) {
+            String name = o.toString();
+            Class<Module> clazz = 
camelContext.getClassResolver().resolveMandatoryClass(name, Module.class);
+            Module module = camelContext.getInjector().newInstance(clazz);
+            LOG.debug("Registering module: {} -> {}", name, module);
+            objectMapper.registerModule(module);
+        }
+    }
+
+    private void registerModules() {
+        for (Module module : modules) {
+            LOG.debug("Registering module: {}", module);
+            objectMapper.registerModules(module);
+        }
+    }
+
+    private void doDisableFeatures() {
+        Iterator<?> it = ObjectHelper.createIterator(disableFeatures);
+        while (it.hasNext()) {
+            String disable = it.next().toString();
+            // it can be different kind
+            SerializationFeature sf
+                    = 
getCamelContext().getTypeConverter().tryConvertTo(SerializationFeature.class, 
disable);
+            if (sf != null) {
+                objectMapper.disable(sf);
+                continue;
+            }
+            DeserializationFeature df
+                    = 
getCamelContext().getTypeConverter().tryConvertTo(DeserializationFeature.class, 
disable);
+            if (df != null) {
+                objectMapper.disable(df);
+                continue;
+            }
+            MapperFeature mf = 
getCamelContext().getTypeConverter().tryConvertTo(MapperFeature.class, disable);
+            if (mf != null) {
+                objectMapper.disable(mf);
+                continue;
+            }
+            throw new IllegalArgumentException(
+                    "Disable feature: " + disable
+                                               + " cannot be converted to an 
accepted enum of types 
[SerializationFeature,DeserializationFeature,MapperFeature]");
+        }
+    }
+
     private PropertyNamingStrategy determineNamingStrategy(String 
namingStrategy) {
         PropertyNamingStrategy strategy = null;
         switch (namingStrategy) {
diff --git 
a/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/converter/JacksonTypeConverters.java
 
b/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/converter/JacksonTypeConverters.java
index b7f7f648c40..4bd45abb1d1 100644
--- 
a/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/converter/JacksonTypeConverters.java
+++ 
b/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/converter/JacksonTypeConverters.java
@@ -136,7 +136,7 @@ public final class JacksonTypeConverters {
     @Converter
     public Map<String, Object> toMap(JsonNode node, Exchange exchange) throws 
Exception {
         ObjectMapper mapper = resolveObjectMapper(exchange.getContext());
-        return mapper.convertValue(node, new TypeReference<Map<String, 
Object>>() {
+        return mapper.convertValue(node, new TypeReference<>() {
         });
     }
 
@@ -214,24 +214,7 @@ public final class JacksonTypeConverters {
 
         // only do this if enabled (disabled by default)
         if (!init && exchange != null) {
-            Map<String, String> globalOptions = 
exchange.getContext().getGlobalOptions();
-
-            // init to see if this is enabled
-            String text = 
globalOptions.get(JacksonConstants.ENABLE_TYPE_CONVERTER);
-            if (text != null) {
-                text = exchange.getContext().resolvePropertyPlaceholders(text);
-                enabled = Boolean.parseBoolean(text);
-            }
-
-            // pojoOnly is disabled by default
-            text = globalOptions.get(JacksonConstants.TYPE_CONVERTER_TO_POJO);
-            if (text != null) {
-                text = exchange.getContext().resolvePropertyPlaceholders(text);
-                toPojo = Boolean.parseBoolean(text);
-            }
-
-            moduleClassNames = 
globalOptions.get(JacksonConstants.TYPE_CONVERTER_MODULE_CLASS_NAMES);
-            init = true;
+            initialize(exchange);
         }
 
         if (!enabled) {
@@ -283,6 +266,27 @@ public final class JacksonTypeConverters {
         return null;
     }
 
+    private void initialize(Exchange exchange) {
+        Map<String, String> globalOptions = 
exchange.getContext().getGlobalOptions();
+
+        // init to see if this is enabled
+        String text = 
globalOptions.get(JacksonConstants.ENABLE_TYPE_CONVERTER);
+        if (text != null) {
+            text = exchange.getContext().resolvePropertyPlaceholders(text);
+            enabled = Boolean.parseBoolean(text);
+        }
+
+        // pojoOnly is disabled by default
+        text = globalOptions.get(JacksonConstants.TYPE_CONVERTER_TO_POJO);
+        if (text != null) {
+            text = exchange.getContext().resolvePropertyPlaceholders(text);
+            toPojo = Boolean.parseBoolean(text);
+        }
+
+        moduleClassNames = 
globalOptions.get(JacksonConstants.TYPE_CONVERTER_MODULE_CLASS_NAMES);
+        init = true;
+    }
+
     /**
      * Whether the type is NOT a pojo type but only a set of simple types such 
as String and numbers.
      */
diff --git 
a/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/transform/JsonSchemaResolver.java
 
b/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/transform/JsonSchemaResolver.java
index 27a3e5b7dba..afbf0fd14c8 100644
--- 
a/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/transform/JsonSchemaResolver.java
+++ 
b/components/camel-jackson/src/main/java/org/apache/camel/component/jackson/transform/JsonSchemaResolver.java
@@ -19,6 +19,7 @@ package org.apache.camel.component.jackson.transform;
 import java.io.InputStream;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
+import java.util.function.Function;
 
 import com.fasterxml.jackson.core.FormatSchema;
 import com.fasterxml.jackson.core.JsonProcessingException;
@@ -110,37 +111,13 @@ public class JsonSchemaResolver implements 
SchemaResolver, Processor {
         JsonNode answer = exchange.getProperty(SchemaHelper.CONTENT_SCHEMA, 
JsonNode.class);
 
         if (answer == null && 
exchange.getProperties().containsKey(SchemaHelper.SCHEMA)) {
-            String schemaJson = exchange.getProperty(SchemaHelper.SCHEMA, 
String.class);
-            try {
-                answer = Json.mapper().readTree(schemaJson);
-            } catch (JsonProcessingException e) {
-                throw new RuntimeException("Unable to load Json schema", e);
-            }
+            answer = tryLoadingSchema(exchange);
         }
 
         if (answer == null) {
             String contentClass = SchemaHelper.resolveContentClass(exchange, 
this.contentClass);
             if (contentClass != null) {
-                answer = this.schemes.computeIfAbsent(contentClass, t -> {
-                    Resource res = 
PluginHelper.getResourceLoader(exchange.getContext())
-                            .resolveResource(
-                                    "classpath:schemas/" + 
SchemaType.JSON.type() + "/" + t + "." + SchemaType.JSON.type());
-
-                    try {
-                        if (res.exists()) {
-                            try (InputStream is = res.getInputStream()) {
-                                if (is != null) {
-                                    return Json.mapper().readTree(is);
-                                }
-                            }
-                        }
-                    } catch (Exception e) {
-                        throw new RuntimeException(
-                                "Unable to load Json schema for type: " + t + 
", resource: " + res.getLocation(), e);
-                    }
-
-                    return null;
-                });
+                answer = this.schemes.computeIfAbsent(contentClass, 
tryLoadingSchemaFromResourceLoader(exchange));
             }
         }
 
@@ -151,6 +128,40 @@ public class JsonSchemaResolver implements SchemaResolver, 
Processor {
         return answer;
     }
 
+    private static Function<String, JsonNode> 
tryLoadingSchemaFromResourceLoader(Exchange exchange) {
+        return t -> {
+            Resource res = 
PluginHelper.getResourceLoader(exchange.getContext())
+                    .resolveResource(
+                            "classpath:schemas/" + SchemaType.JSON.type() + 
"/" + t + "." + SchemaType.JSON.type());
+
+            try {
+                if (res.exists()) {
+                    try (InputStream is = res.getInputStream()) {
+                        if (is != null) {
+                            return Json.mapper().readTree(is);
+                        }
+                    }
+                }
+            } catch (Exception e) {
+                throw new RuntimeException(
+                        "Unable to load Json schema for type: " + t + ", 
resource: " + res.getLocation(), e);
+            }
+
+            return null;
+        };
+    }
+
+    private static JsonNode tryLoadingSchema(Exchange exchange) {
+        JsonNode answer;
+        String schemaJson = exchange.getProperty(SchemaHelper.SCHEMA, 
String.class);
+        try {
+            answer = Json.mapper().readTree(schemaJson);
+        } catch (JsonProcessingException e) {
+            throw new RuntimeException("Unable to load Json schema", e);
+        }
+        return answer;
+    }
+
     @Override
     public FormatSchema resolve(Exchange exchange) {
         JsonNode answer = exchange.getProperty(SchemaHelper.CONTENT_SCHEMA, 
JsonNode.class);
diff --git 
a/components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonConcurrentTest.java
 
b/components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonConcurrentTest.java
index 53cfe67dc26..da7ef85e42d 100644
--- 
a/components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonConcurrentTest.java
+++ 
b/components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonConcurrentTest.java
@@ -47,7 +47,7 @@ public class JacksonConcurrentTest extends CamelTestSupport {
         ExecutorService executor = Executors.newFixedThreadPool(poolSize);
         for (int i = 0; i < files; i++) {
             final int index = i;
-            executor.submit(new Callable<Object>() {
+            executor.submit(new Callable<>() {
                 public Object call() {
                     TestPojo pojo = new TestPojo();
                     pojo.setName("Hi " + index);

Reply via email to