From a57aea8e20e30807606eaea8171aed297a14e926 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:15 +0000 Subject: [PATCH 01/14] (chores): fix SonarCloud S6201 in core modules Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../impl/engine/AbstractCamelContext.java | 8 ++-- .../impl/engine/IntrospectionSupport.java | 6 +-- .../camel/language/csimple/CSimpleHelper.java | 4 +- .../apache/camel/model/BeanModelHelper.java | 4 +- .../camel/support/PropertyBindingSupport.java | 40 ++++++++----------- .../apache/camel/support/http/HttpUtil.java | 2 +- .../camel/support/jndi/JndiContext.java | 3 +- .../management/MixinRequiredModelMBean.java | 4 +- .../support/processor/RestBindingAdvice.java | 4 +- .../camel/yaml/LwModelToYAMLDumper.java | 4 +- .../org/apache/camel/yaml/io/YamlWriter.java | 9 ++--- 11 files changed, 38 insertions(+), 50 deletions(-) diff --git a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java index c4be7d561d7f8..79816d6ff1238 100644 --- a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java +++ b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java @@ -2609,16 +2609,16 @@ && getManagementStrategy().getManagementAgent() != null) { } } if (runtimeEndpointRegistry != null) { - if (runtimeEndpointRegistry instanceof EventNotifier && getManagementStrategy() != null) { - getManagementStrategy().addEventNotifier((EventNotifier) runtimeEndpointRegistry); + if (runtimeEndpointRegistry instanceof EventNotifier en && getManagementStrategy() != null) { + getManagementStrategy().addEventNotifier(en); } addService(runtimeEndpointRegistry, true, true); } // register error registry as event notifier so it captures exchange failure events ErrorRegistry errorRegistry = getErrorRegistry(); - if (errorRegistry instanceof EventNotifier && getManagementStrategy() != null) { - getManagementStrategy().addEventNotifier((EventNotifier) errorRegistry); + if (errorRegistry instanceof EventNotifier en && getManagementStrategy() != null) { + getManagementStrategy().addEventNotifier(en); } bindDataFormats(); diff --git a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/IntrospectionSupport.java b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/IntrospectionSupport.java index 25ff026a36011..5b6f514f45a4b 100644 --- a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/IntrospectionSupport.java +++ b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/IntrospectionSupport.java @@ -478,16 +478,14 @@ static boolean setProperty( "Cannot set property: " + name + " as a Map because target bean has no setter method for the Map"); } } - if (obj instanceof Map) { - Map map = (Map) obj; + if (obj instanceof Map map) { if (context != null && refName != null && value == null) { String s = refName.replace("#", ""); value = CamelContextHelper.lookup(context, s); } map.put(lookupKey, value); return true; - } else if (obj instanceof List) { - List list = (List) obj; + } else if (obj instanceof List list) { if (context != null && refName != null && value == null) { String s = refName.replace("#", ""); value = CamelContextHelper.lookup(context, s); diff --git a/core/camel-core-languages/src/main/java/org/apache/camel/language/csimple/CSimpleHelper.java b/core/camel-core-languages/src/main/java/org/apache/camel/language/csimple/CSimpleHelper.java index adf74c990b998..2f3a4c2e44db6 100644 --- a/core/camel-core-languages/src/main/java/org/apache/camel/language/csimple/CSimpleHelper.java +++ b/core/camel-core-languages/src/main/java/org/apache/camel/language/csimple/CSimpleHelper.java @@ -258,8 +258,8 @@ public static String toJsonBody(Exchange exchange, boolean pretty) { if (body == null) { return null; } - if (body instanceof String) { - return (String) body; + if (body instanceof String str) { + return str; } final java.io.StringWriter writer = new java.io.StringWriter(); try { diff --git a/core/camel-core-model/src/main/java/org/apache/camel/model/BeanModelHelper.java b/core/camel-core-model/src/main/java/org/apache/camel/model/BeanModelHelper.java index fe1d11674dfdf..a64aa436cb1ff 100644 --- a/core/camel-core-model/src/main/java/org/apache/camel/model/BeanModelHelper.java +++ b/core/camel-core-model/src/main/java/org/apache/camel/model/BeanModelHelper.java @@ -67,7 +67,7 @@ public static Object newInstance(BeanFactoryDefinition def, CamelContext context String script = resolveScript(context, def); // create bean via the script final Language lan = context.resolveLanguage(def.getScriptLanguage()); - final ScriptingLanguage slan = lan instanceof ScriptingLanguage ? (ScriptingLanguage) lan : null; + final ScriptingLanguage slan = lan instanceof ScriptingLanguage sl ? sl : null; String fqn = def.getType(); if (fqn.startsWith("#class:")) { fqn = fqn.substring(7); @@ -178,7 +178,7 @@ public static void bind(BeanFactoryDefinition def, RouteTemplateContext route clazz = Object.class; } final String script = resolveScript(camelContext, def); - final ScriptingLanguage slan = lan instanceof ScriptingLanguage ? (ScriptingLanguage) lan : null; + final ScriptingLanguage slan = lan instanceof ScriptingLanguage sl ? sl : null; if (slan != null) { // scripting language should be evaluated with route template context as binding // and memorize so the script is only evaluated once and the local bean is the same diff --git a/core/camel-support/src/main/java/org/apache/camel/support/PropertyBindingSupport.java b/core/camel-support/src/main/java/org/apache/camel/support/PropertyBindingSupport.java index fa8d07ca3608f..6d6f1e4ce3e2a 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/PropertyBindingSupport.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/PropertyBindingSupport.java @@ -571,17 +571,17 @@ private static boolean doSetPropertyValue( } // if the target value is a map type, then we can skip reflection // and set the entry - if (!bound && target instanceof Map) { - ((Map) target).put(key, value); + if (!bound && target instanceof Map map) { + map.put(key, value); bound = true; } // if the target value is a list type (and key is digit), // then we can skip reflection and set the entry - if (!bound && target instanceof List && StringHelper.isDigit(key)) { + if (!bound && target instanceof List list && StringHelper.isDigit(key)) { try { // key must be digit int idx = Integer.parseInt(key); - org.apache.camel.util.ObjectHelper.addListByIndex((List) target, idx, value); + org.apache.camel.util.ObjectHelper.addListByIndex(list, idx, value); bound = true; } catch (NumberFormatException e) { // ignore @@ -659,13 +659,11 @@ private static boolean setPropertyCollectionViaReflection( } } - if (obj instanceof Map) { + if (obj instanceof Map map) { // this supports both Map and Properties - Map map = (Map) obj; map.put(lookupKey, value); return true; - } else if (obj instanceof List) { - List list = (List) obj; + } else if (obj instanceof List list) { if (isNotEmpty(lookupKey)) { int idx = Integer.parseInt(lookupKey); org.apache.camel.util.ObjectHelper.addListByIndex(list, idx, value); @@ -745,13 +743,11 @@ private static boolean setPropertyCollectionViaConfigurer( return false; } - if (obj instanceof Map) { + if (obj instanceof Map map) { // this supports both Map and Properties - Map map = (Map) obj; map.put(lookupKey, value); return true; - } else if (obj instanceof List) { - List list = (List) obj; + } else if (obj instanceof List list) { if (isNotEmpty(lookupKey)) { int idx = Integer.parseInt(lookupKey); if (idx < list.size()) { @@ -972,8 +968,7 @@ private static Object getOrCreatePropertyOgnlPathViaConfigurer( } } - if (answer instanceof Map && lookupKey != null) { - Map map = (Map) answer; + if (answer instanceof Map map && lookupKey != null) { answer = map.get(lookupKey); if (answer == null) { // okay there was no element in the list, so create a new empty instance if we can know its parameter type @@ -987,8 +982,7 @@ private static Object getOrCreatePropertyOgnlPathViaConfigurer( answer = instance; } } - } else if (answer instanceof List) { - List list = (List) answer; + } else if (answer instanceof List list) { if (isNotEmpty(lookupKey)) { int idx = Integer.parseInt(lookupKey); answer = list.size() > idx ? list.get(idx) : null; @@ -1092,8 +1086,7 @@ private static Object getOrCreatePropertyOgnlPathViaReflection( } } - if (answer instanceof Map && lookupKey != null) { - Map map = (Map) answer; + if (answer instanceof Map map && lookupKey != null) { answer = map.get(lookupKey); if (answer == null) { Class parameterType = null; @@ -1120,8 +1113,7 @@ private static Object getOrCreatePropertyOgnlPathViaReflection( answer = instance; } } - } else if (answer instanceof List) { - List list = (List) answer; + } else if (answer instanceof List list) { if (isNotEmpty(lookupKey)) { int idx = Integer.parseInt(lookupKey); answer = list.size() > idx ? list.get(idx) : null; @@ -2106,8 +2098,8 @@ public Object remove(Object key) { Object obj = map.get(part); if (i == parts.length - 1) { map.remove(part); - } else if (obj instanceof Map) { - map = (Map) obj; + } else if (obj instanceof Map m) { + map = m; } } @@ -2145,8 +2137,8 @@ public int compare(String o1, String o2) { // 2) sort by reference (as it may refer to other beans in the OGNL graph) Object v1 = map.get(o1); Object v2 = map.get(o2); - boolean ref1 = v1 instanceof String && ((String) v1).startsWith("#"); - boolean ref2 = v2 instanceof String && ((String) v2).startsWith("#"); + boolean ref1 = v1 instanceof String s1 && s1.startsWith("#"); + boolean ref2 = v2 instanceof String s2 && s2.startsWith("#"); if (ref1 != ref2) { return Boolean.compare(ref1, ref2); } diff --git a/core/camel-support/src/main/java/org/apache/camel/support/http/HttpUtil.java b/core/camel-support/src/main/java/org/apache/camel/support/http/HttpUtil.java index 7d3e9e3bd02c9..952334d9f0316 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/http/HttpUtil.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/http/HttpUtil.java @@ -56,7 +56,7 @@ public static int determineResponseCode(Exchange camelExchange, Object body) { int codeToUse = currentCode == null ? defaultCode : currentCode; if (codeToUse != INTERNAL_SERVER_ERROR) { - if (body == null || body instanceof String && ((String) body).isBlank()) { + if (body == null || body instanceof String str && str.isBlank()) { // no content codeToUse = currentCode == null ? NO_CONTENT : currentCode; } diff --git a/core/camel-support/src/main/java/org/apache/camel/support/jndi/JndiContext.java b/core/camel-support/src/main/java/org/apache/camel/support/jndi/JndiContext.java index 40cfd27fe8baf..e8c621ecf0fb9 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/jndi/JndiContext.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/jndi/JndiContext.java @@ -198,8 +198,7 @@ public Object lookup(String name) throws NamingException { Object value = bindings.get(first); if (value == null) { throw new NameNotFoundException(name); - } else if (value instanceof Context && path.size() > 1) { - Context subContext = (Context) value; + } else if (value instanceof Context subContext && path.size() > 1) { value = subContext.lookup(path.getSuffix(1)); } return value; diff --git a/core/camel-support/src/main/java/org/apache/camel/support/management/MixinRequiredModelMBean.java b/core/camel-support/src/main/java/org/apache/camel/support/management/MixinRequiredModelMBean.java index f78e13162e2a2..fc81731408a7d 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/management/MixinRequiredModelMBean.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/management/MixinRequiredModelMBean.java @@ -72,8 +72,8 @@ public Object invoke(String opName, Object[] opArgs, String[] sig) throws MBeanE answer = super.invoke(opName, opArgs, sig); } // mask the answer if enabled and it was a String type (we cannot mask other types) - if (mask && answer instanceof String && ObjectHelper.isNotEmpty(answer) && isMaskOperation(opName)) { - answer = mask(opName, (String) answer); + if (mask && answer instanceof String str && ObjectHelper.isNotEmpty(answer) && isMaskOperation(opName)) { + answer = mask(opName, str); } return answer; } diff --git a/core/camel-support/src/main/java/org/apache/camel/support/processor/RestBindingAdvice.java b/core/camel-support/src/main/java/org/apache/camel/support/processor/RestBindingAdvice.java index be337a4e71316..073743b90f5d8 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/processor/RestBindingAdvice.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/processor/RestBindingAdvice.java @@ -203,8 +203,8 @@ private void unmarshal(Exchange exchange, Map state) { // set data type if in use if (exchange.getContext().isUseDataType()) { - if (exchange.getIn() instanceof DataTypeAware && (isJson || isXml)) { - ((DataTypeAware) exchange.getIn()).setDataType(new DataType(isJson ? "json" : "xml")); + if (exchange.getIn() instanceof DataTypeAware dataTypeAware && (isJson || isXml)) { + dataTypeAware.setDataType(new DataType(isJson ? "json" : "xml")); } } diff --git a/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java b/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java index 5ac6e9f880a82..cb58001322c69 100644 --- a/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java +++ b/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java @@ -98,8 +98,8 @@ protected void doWriteOptionalIdentifiedDefinitionAttributes(OptionalIdentifiedD } // write location information if (sourceLocation || context.isDebugging()) { - String loc = (def instanceof RouteDefinition ? ((RouteDefinition) def).getInput() : def).getLocation(); - int line = (def instanceof RouteDefinition ? ((RouteDefinition) def).getInput() : def).getLineNumber(); + String loc = (def instanceof RouteDefinition rd1 ? rd1.getInput() : def).getLocation(); + int line = (def instanceof RouteDefinition rd2 ? rd2.getInput() : def).getLineNumber(); if (line != -1) { writer.addAttribute("sourceLineNumber", Integer.toString(line)); writer.addAttribute("sourceLocation", loc); diff --git a/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/io/YamlWriter.java b/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/io/YamlWriter.java index 9a962617f86d5..e9cf741459467 100644 --- a/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/io/YamlWriter.java +++ b/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/io/YamlWriter.java @@ -373,10 +373,10 @@ private void doAsNode(EipModel model, EipNode node) { node.addOutput(asNode(other)); } else if ("choice".equals(node.getName()) && "when".equals(key)) { Object v = entry.getValue(); - if (v instanceof List) { + if (v instanceof List list) { // can be a list in choice - List list = (List) v; - for (EipModel m : list) { + for (Object item : list) { + EipModel m = (EipModel) item; node.addOutput(asNode(m)); } } else { @@ -470,8 +470,7 @@ private JsonObject asJSonNode(EipModel model) { } Object value = entry.getValue(); if (value != null) { - if (value instanceof Collection) { - Collection col = (Collection) value; + if (value instanceof Collection col) { List list = new ArrayList<>(); for (Object v : col) { Object r = v; From 2ab2338a56598f61fcf17b6161008642e9de2c89 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:18 +0000 Subject: [PATCH 02/14] (chores): fix SonarCloud S6201 in camel-pqc Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../camel/component/pqc/PQCProducer.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCProducer.java b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCProducer.java index f684ad8a359f7..baa64ffe401bf 100644 --- a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCProducer.java +++ b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCProducer.java @@ -938,12 +938,12 @@ private void persistStatefulKeyStateAfterSign(Exchange exchange) throws Exceptio * Returns the remaining signatures for a stateful private key, or -1 if the key is not stateful. */ static long getStatefulKeyRemaining(PrivateKey privateKey) { - if (privateKey instanceof XMSSPrivateKey) { - return ((XMSSPrivateKey) privateKey).getUsagesRemaining(); - } else if (privateKey instanceof XMSSMTPrivateKey) { - return ((XMSSMTPrivateKey) privateKey).getUsagesRemaining(); - } else if (privateKey instanceof LMSPrivateKey) { - return ((LMSPrivateKey) privateKey).getUsagesRemaining(); + if (privateKey instanceof XMSSPrivateKey xmssPrivateKey) { + return xmssPrivateKey.getUsagesRemaining(); + } else if (privateKey instanceof XMSSMTPrivateKey xmssmtPrivateKey) { + return xmssmtPrivateKey.getUsagesRemaining(); + } else if (privateKey instanceof LMSPrivateKey lmsPrivateKey) { + return lmsPrivateKey.getUsagesRemaining(); } return -1; } @@ -953,12 +953,12 @@ static long getStatefulKeyRemaining(PrivateKey privateKey) { * not stateful. */ static long getStatefulKeyIndex(PrivateKey privateKey) { - if (privateKey instanceof XMSSPrivateKey) { - return ((XMSSPrivateKey) privateKey).getIndex(); - } else if (privateKey instanceof XMSSMTPrivateKey) { - return ((XMSSMTPrivateKey) privateKey).getIndex(); - } else if (privateKey instanceof LMSPrivateKey) { - return ((LMSPrivateKey) privateKey).getIndex(); + if (privateKey instanceof XMSSPrivateKey xmssPrivateKey) { + return xmssPrivateKey.getIndex(); + } else if (privateKey instanceof XMSSMTPrivateKey xmssmtPrivateKey) { + return xmssmtPrivateKey.getIndex(); + } else if (privateKey instanceof LMSPrivateKey lmsPrivateKey) { + return lmsPrivateKey.getIndex(); } return 0; } From 0eb83634bfe8161a7f9784a9c13fbbc999c34400 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:28 +0000 Subject: [PATCH 03/14] (chores): fix SonarCloud S6201 in camel-jackson3 Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../AvroBinaryDataTypeTransformer.java | 4 ++-- .../ProtobufBinaryDataTypeTransformer.java | 4 ++-- .../converter/JacksonTypeConverters.java | 21 +++++++------------ .../component/jackson3/transform/Json.java | 4 ++-- 4 files changed, 13 insertions(+), 20 deletions(-) diff --git a/components/camel-jackson3-avro/src/main/java/org/apache/camel/component/jackson3/avro/transform/AvroBinaryDataTypeTransformer.java b/components/camel-jackson3-avro/src/main/java/org/apache/camel/component/jackson3/avro/transform/AvroBinaryDataTypeTransformer.java index 88b2dc3a7a578..c4452f4214b78 100644 --- a/components/camel-jackson3-avro/src/main/java/org/apache/camel/component/jackson3/avro/transform/AvroBinaryDataTypeTransformer.java +++ b/components/camel-jackson3-avro/src/main/java/org/apache/camel/component/jackson3/avro/transform/AvroBinaryDataTypeTransformer.java @@ -76,8 +76,8 @@ public void transform(Message message, DataType fromType, DataType toType) { private JsonNode getBodyAsJsonNode(Message message, AvroSchema schema) throws InvalidPayloadException, IOException, ClassNotFoundException { - if (message.getBody() instanceof JsonNode) { - return (JsonNode) message.getBody(); + if (message.getBody() instanceof JsonNode jsonNode) { + return jsonNode; } if (message.getBody() instanceof String jsonString && Json.isJson(jsonString)) { diff --git a/components/camel-jackson3-protobuf/src/main/java/org/apache/camel/component/jackson3/protobuf/transform/ProtobufBinaryDataTypeTransformer.java b/components/camel-jackson3-protobuf/src/main/java/org/apache/camel/component/jackson3/protobuf/transform/ProtobufBinaryDataTypeTransformer.java index 9e8472efb876a..22861f8c70fde 100644 --- a/components/camel-jackson3-protobuf/src/main/java/org/apache/camel/component/jackson3/protobuf/transform/ProtobufBinaryDataTypeTransformer.java +++ b/components/camel-jackson3-protobuf/src/main/java/org/apache/camel/component/jackson3/protobuf/transform/ProtobufBinaryDataTypeTransformer.java @@ -76,8 +76,8 @@ public void transform(Message message, DataType fromType, DataType toType) { private JsonNode getBodyAsJsonNode(Message message, ProtobufSchema schema) throws InvalidPayloadException, IOException, ClassNotFoundException { - if (message.getBody() instanceof JsonNode) { - return (JsonNode) message.getBody(); + if (message.getBody() instanceof JsonNode jsonNode) { + return jsonNode; } if (message.getBody() instanceof String jsonString && Json.isJson(jsonString)) { diff --git a/components/camel-jackson3/src/main/java/org/apache/camel/component/jackson3/converter/JacksonTypeConverters.java b/components/camel-jackson3/src/main/java/org/apache/camel/component/jackson3/converter/JacksonTypeConverters.java index 2ffbeedb8799d..1caf70f76f9f6 100644 --- a/components/camel-jackson3/src/main/java/org/apache/camel/component/jackson3/converter/JacksonTypeConverters.java +++ b/components/camel-jackson3/src/main/java/org/apache/camel/component/jackson3/converter/JacksonTypeConverters.java @@ -110,8 +110,7 @@ public JsonNode toJsonNode(Map map, Exchange exchange) throws Exception { @Converter public String toString(JsonNode node, Exchange exchange) throws Exception { - if (node instanceof StringNode) { - StringNode tn = (StringNode) node; + if (node instanceof StringNode tn) { return tn.textValue(); } ObjectMapper mapper = resolveObjectMapper(exchange.getContext()); @@ -121,8 +120,7 @@ public String toString(JsonNode node, Exchange exchange) throws Exception { @Converter public byte[] toByteArray(JsonNode node, Exchange exchange) throws Exception { - if (node instanceof StringNode) { - StringNode tn = (StringNode) node; + if (node instanceof StringNode tn) { return tn.textValue().getBytes(StandardCharsets.UTF_8); } @@ -151,8 +149,7 @@ public Reader toReader(JsonNode node, Exchange exchange) throws Exception { @Converter public Integer toInteger(JsonNode node, Exchange exchange) throws Exception { - if (node instanceof NumericNode) { - NumericNode nn = (NumericNode) node; + if (node instanceof NumericNode nn) { if (nn.canConvertToInt()) { return nn.asInt(); } @@ -163,8 +160,7 @@ public Integer toInteger(JsonNode node, Exchange exchange) throws Exception { @Converter public Long toLong(JsonNode node, Exchange exchange) throws Exception { - if (node instanceof NumericNode) { - NumericNode nn = (NumericNode) node; + if (node instanceof NumericNode nn) { if (nn.canConvertToLong()) { return nn.asLong(); } @@ -180,8 +176,7 @@ public Boolean toBoolean(BooleanNode node, Exchange exchange) throws Exception { @Converter public Boolean toBoolean(JsonNode node, Exchange exchange) throws Exception { - if (node instanceof BooleanNode) { - BooleanNode bn = (BooleanNode) node; + if (node instanceof BooleanNode bn) { return bn.asBoolean(); } String text = node.asText(); @@ -190,8 +185,7 @@ public Boolean toBoolean(JsonNode node, Exchange exchange) throws Exception { @Converter public Double toDouble(JsonNode node, Exchange exchange) throws Exception { - if (node instanceof NumericNode) { - NumericNode nn = (NumericNode) node; + if (node instanceof NumericNode nn) { if (nn.isFloatingPointNumber()) { return nn.asDouble(); } @@ -202,8 +196,7 @@ public Double toDouble(JsonNode node, Exchange exchange) throws Exception { @Converter public Float toFloat(JsonNode node, Exchange exchange) throws Exception { - if (node instanceof NumericNode) { - NumericNode nn = (NumericNode) node; + if (node instanceof NumericNode nn) { if (nn.isFloat()) { return nn.floatValue(); } diff --git a/components/camel-jackson3/src/main/java/org/apache/camel/component/jackson3/transform/Json.java b/components/camel-jackson3/src/main/java/org/apache/camel/component/jackson3/transform/Json.java index 9d61f140737c1..6444e7944db62 100644 --- a/components/camel-jackson3/src/main/java/org/apache/camel/component/jackson3/transform/Json.java +++ b/components/camel-jackson3/src/main/java/org/apache/camel/component/jackson3/transform/Json.java @@ -120,8 +120,8 @@ public static List arrayToJsonBeans(JsonNode json) throws JacksonExcepti Iterator it = json.iterator(); while (it.hasNext()) { Object item = it.next(); - if (item instanceof StringNode) { - jsonBeans.add(StringHelper.removeLeadingAndEndingQuotes(((StringNode) item).asText())); + if (item instanceof StringNode stringNode) { + jsonBeans.add(StringHelper.removeLeadingAndEndingQuotes(stringNode.asText())); } else { jsonBeans.add(mapper().writeValueAsString(item)); } From 80a445152cf23071e590e9eb619028cb60066d28 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:28 +0000 Subject: [PATCH 04/14] (chores): fix SonarCloud S6201 in camel-elasticsearch Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../ElasticsearchActionRequestConverter.java | 131 +++++++++--------- 1 file changed, 63 insertions(+), 68 deletions(-) diff --git a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/converter/ElasticsearchActionRequestConverter.java b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/converter/ElasticsearchActionRequestConverter.java index 4ae90a194dfa9..90b2fc8ff76e5 100644 --- a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/converter/ElasticsearchActionRequestConverter.java +++ b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/converter/ElasticsearchActionRequestConverter.java @@ -21,7 +21,6 @@ import java.io.InputStream; import java.io.Reader; import java.io.StringReader; -import java.util.List; import java.util.Map; import co.elastic.clients.elasticsearch._types.WaitForActiveShards; @@ -61,18 +60,18 @@ private ElasticsearchActionRequestConverter() { // Index requests private static IndexOperation.Builder createIndexOperationBuilder(Object document, Exchange exchange) throws IOException { - if (document instanceof IndexOperation.Builder) { - return (IndexOperation.Builder) document; + if (document instanceof IndexOperation.Builder indexOpBuilder) { + return indexOpBuilder; } IndexOperation.Builder builder = new IndexOperation.Builder<>(); - if (document instanceof byte[]) { - builder.document(JsonData.from(new ByteArrayInputStream((byte[]) document))); - } else if (document instanceof InputStream) { - builder.document(JsonData.from((InputStream) document)); - } else if (document instanceof String) { - builder.document(JsonData.from(new StringReader((String) document))); - } else if (document instanceof Reader) { - builder.document(JsonData.from((Reader) document)); + if (document instanceof byte[] byteArray) { + builder.document(JsonData.from(new ByteArrayInputStream(byteArray))); + } else if (document instanceof InputStream inputStream) { + builder.document(JsonData.from(inputStream)); + } else if (document instanceof String string) { + builder.document(JsonData.from(new StringReader(string))); + } else if (document instanceof Reader reader) { + builder.document(JsonData.from(reader)); } else if (document instanceof Map) { ObjectMapper objectMapper = new ObjectMapper(); builder.document(JsonData.from(new StringReader(objectMapper.writeValueAsString(document)))); @@ -85,19 +84,18 @@ private static IndexOperation.Builder createIndexOperationBuilder(Object docu @Converter public static IndexRequest.Builder toIndexRequestBuilder(Object document, Exchange exchange) throws IOException { - if (document instanceof IndexRequest.Builder) { - IndexRequest.Builder builder = (IndexRequest.Builder) document; - return builder.id(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_ID, String.class)); + if (document instanceof IndexRequest.Builder indexReqBuilder) { + return indexReqBuilder.id(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_ID, String.class)); } IndexRequest.Builder builder = new IndexRequest.Builder<>(); - if (document instanceof byte[]) { - builder.withJson(new ByteArrayInputStream((byte[]) document)); - } else if (document instanceof InputStream) { - builder.withJson((InputStream) document); - } else if (document instanceof String) { - builder.withJson(new StringReader((String) document)); - } else if (document instanceof Reader) { - builder.withJson((Reader) document); + if (document instanceof byte[] byteArray) { + builder.withJson(new ByteArrayInputStream(byteArray)); + } else if (document instanceof InputStream inputStream) { + builder.withJson(inputStream); + } else if (document instanceof String string) { + builder.withJson(new StringReader(string)); + } else if (document instanceof Reader reader) { + builder.withJson(reader); } else if (document instanceof Map) { ObjectMapper objectMapper = new ObjectMapper(); builder.withJson(new StringReader(objectMapper.writeValueAsString(document))); @@ -116,22 +114,21 @@ public static IndexRequest.Builder toIndexRequestBuilder(Object document, Exc @Converter public static UpdateRequest.Builder toUpdateRequestBuilder(Object document, Exchange exchange) throws IOException { - if (document instanceof UpdateRequest.Builder) { - UpdateRequest.Builder builder = (UpdateRequest.Builder) document; - return builder.id(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_ID, String.class)); + if (document instanceof UpdateRequest.Builder updateReqBuilder) { + return updateReqBuilder.id(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_ID, String.class)); } UpdateRequest.Builder builder = new UpdateRequest.Builder<>(); Boolean enableDocumentOnlyMode = exchange.getIn().getHeader(ElasticsearchConstants.PARAM_DOCUMENT_MODE, Boolean.FALSE, Boolean.class); Mode mode = enableDocumentOnlyMode == Boolean.TRUE ? Mode.DOCUMENT_ONLY : Mode.DEFAULT; - if (document instanceof byte[]) { - mode.addDocToUpdateRequestBuilder(builder, new ByteArrayInputStream((byte[]) document)); - } else if (document instanceof InputStream) { - mode.addDocToUpdateRequestBuilder(builder, (InputStream) document); - } else if (document instanceof String) { - mode.addDocToUpdateRequestBuilder(builder, new StringReader((String) document)); - } else if (document instanceof Reader) { - mode.addDocToUpdateRequestBuilder(builder, (Reader) document); + if (document instanceof byte[] byteArray) { + mode.addDocToUpdateRequestBuilder(builder, new ByteArrayInputStream(byteArray)); + } else if (document instanceof InputStream inputStream) { + mode.addDocToUpdateRequestBuilder(builder, inputStream); + } else if (document instanceof String string) { + mode.addDocToUpdateRequestBuilder(builder, new StringReader(string)); + } else if (document instanceof Reader reader) { + mode.addDocToUpdateRequestBuilder(builder, reader); } else if (document instanceof Map) { ObjectMapper objectMapper = new ObjectMapper(); mode.addDocToUpdateRequestBuilder(builder, new StringReader(objectMapper.writeValueAsString(document))); @@ -151,34 +148,34 @@ public static IndexRequest.Builder toIndexRequestBuilder(Object document, Exc @Converter public static GetRequest.Builder toGetRequestBuilder(Object document, Exchange exchange) { - if (document instanceof GetRequest.Builder) { - return (GetRequest.Builder) document; + if (document instanceof GetRequest.Builder getReqBuilder) { + return getReqBuilder; } - if (document instanceof String) { + if (document instanceof String string) { return new GetRequest.Builder() .index(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_NAME, String.class)) - .id((String) document); + .id(string); } return null; } @Converter public static DeleteRequest.Builder toDeleteRequestBuilder(Object document, Exchange exchange) { - if (document instanceof DeleteRequest.Builder) { - return (DeleteRequest.Builder) document; + if (document instanceof DeleteRequest.Builder deleteReqBuilder) { + return deleteReqBuilder; } - if (document instanceof String) { + if (document instanceof String string) { return new DeleteRequest.Builder() .index(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_NAME, String.class)) - .id((String) document); + .id(string); } return null; } @Converter public static DeleteIndexRequest.Builder toDeleteIndexRequestBuilder(Object document, Exchange exchange) { - if (document instanceof DeleteIndexRequest.Builder) { - return (DeleteIndexRequest.Builder) document; + if (document instanceof DeleteIndexRequest.Builder deleteIdxReqBuilder) { + return deleteIdxReqBuilder; } if (document instanceof String) { return new DeleteIndexRequest.Builder() @@ -189,15 +186,15 @@ public static DeleteIndexRequest.Builder toDeleteIndexRequestBuilder(Object docu @Converter public static MgetRequest.Builder toMgetRequestBuilder(Object documents, Exchange exchange) { - if (documents instanceof MgetRequest.Builder) { - return (MgetRequest.Builder) documents; + if (documents instanceof MgetRequest.Builder mgetReqBuilder) { + return mgetReqBuilder; } - if (documents instanceof Iterable) { + if (documents instanceof Iterable documentIterable) { MgetRequest.Builder builder = new MgetRequest.Builder(); builder.index(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_NAME, String.class)); - for (Object document : (List) documents) { - if (document instanceof String) { - builder.ids((String) document); + for (Object document : documentIterable) { + if (document instanceof String string) { + builder.ids(string); } else { LOG.warn( "Cannot convert document id of type {} into a String", @@ -214,12 +211,11 @@ public static MgetRequest.Builder toMgetRequestBuilder(Object documents, Exchang public static SearchRequest.Builder toSearchRequestBuilder(Object queryObject, Exchange exchange) throws IOException { String indexName = exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_NAME, String.class); - if (queryObject instanceof SearchRequest.Builder) { - SearchRequest.Builder builder = (SearchRequest.Builder) queryObject; - if (builder.build().index().isEmpty()) { - builder.index(indexName); + if (queryObject instanceof SearchRequest.Builder searchReqBuilder) { + if (searchReqBuilder.build().index().isEmpty()) { + searchReqBuilder.index(indexName); } - return builder; + return searchReqBuilder; } SearchRequest.Builder builder = new SearchRequest.Builder(); @@ -234,8 +230,7 @@ public static SearchRequest.Builder toSearchRequestBuilder(Object queryObject, E String queryText; - if (queryObject instanceof Map) { - Map mapQuery = (Map) queryObject; + if (queryObject instanceof Map mapQuery) { // Remove 'query' prefix from the query object for backward // compatibility if (mapQuery.containsKey(ES_QUERY_DSL_PREFIX)) { @@ -243,8 +238,8 @@ public static SearchRequest.Builder toSearchRequestBuilder(Object queryObject, E } ObjectMapper objectMapper = new ObjectMapper(); queryText = objectMapper.writeValueAsString(mapQuery); - } else if (queryObject instanceof String) { - queryText = (String) queryObject; + } else if (queryObject instanceof String queryString) { + queryText = queryString; ObjectMapper mapper = new ObjectMapper(); JsonNode jsonTextObject = mapper.readValue(queryText, JsonNode.class); JsonNode parentJsonNode = jsonTextObject.get(ES_QUERY_DSL_PREFIX); @@ -271,22 +266,22 @@ public static SearchRequest.Builder toSearchRequestBuilder(Object queryObject, E @Converter public static BulkRequest.Builder toBulkRequestBuilder(Object documents, Exchange exchange) throws IOException { - if (documents instanceof BulkRequest.Builder) { - return (BulkRequest.Builder) documents; + if (documents instanceof BulkRequest.Builder bulkReqBuilder) { + return bulkReqBuilder; } - if (documents instanceof Iterable) { + if (documents instanceof Iterable documentIterable) { BulkRequest.Builder builder = new BulkRequest.Builder(); builder.index(exchange.getIn().getHeader(ElasticsearchConstants.PARAM_INDEX_NAME, String.class)); - for (Object document : (List) documents) { - if (document instanceof DeleteOperation.Builder) { + for (Object document : documentIterable) { + if (document instanceof DeleteOperation.Builder deleteOpBuilder) { builder.operations( - new BulkOperation.Builder().delete(((DeleteOperation.Builder) document).build()).build()); - } else if (document instanceof UpdateOperation.Builder) { + new BulkOperation.Builder().delete(deleteOpBuilder.build()).build()); + } else if (document instanceof UpdateOperation.Builder updateOpBuilder) { builder.operations( - new BulkOperation.Builder().update(((UpdateOperation.Builder) document).build()).build()); - } else if (document instanceof CreateOperation.Builder) { + new BulkOperation.Builder().update(updateOpBuilder.build()).build()); + } else if (document instanceof CreateOperation.Builder createOpBuilder) { builder.operations( - new BulkOperation.Builder().create(((CreateOperation.Builder) document).build()).build()); + new BulkOperation.Builder().create(createOpBuilder.build()).build()); } else { builder.operations( new BulkOperation.Builder().index(createIndexOperationBuilder(document, exchange).build()).build()); From 40c589d168593b0d9fcacd5b070959e93e70ed28 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:29 +0000 Subject: [PATCH 05/14] (chores): fix SonarCloud S6201 in camel-opensearch Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../OpensearchActionRequestConverter.java | 66 +++++++++---------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/components/camel-opensearch/src/main/java/org/apache/camel/component/opensearch/converter/OpensearchActionRequestConverter.java b/components/camel-opensearch/src/main/java/org/apache/camel/component/opensearch/converter/OpensearchActionRequestConverter.java index a5dececfbf04c..1eaca57e00dfc 100644 --- a/components/camel-opensearch/src/main/java/org/apache/camel/component/opensearch/converter/OpensearchActionRequestConverter.java +++ b/components/camel-opensearch/src/main/java/org/apache/camel/component/opensearch/converter/OpensearchActionRequestConverter.java @@ -20,7 +20,6 @@ import java.io.InputStream; import java.io.Reader; import java.io.StringReader; -import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonInclude; @@ -66,8 +65,8 @@ private OpensearchActionRequestConverter() { // Index requests private static IndexOperation.Builder createIndexOperationBuilder(Object document, Exchange exchange) throws IOException { - if (document instanceof IndexOperation.Builder) { - return (IndexOperation.Builder) document; + if (document instanceof IndexOperation.Builder indexOpBuilder) { + return indexOpBuilder; } JacksonJsonpMapper mapper = createMapper(); IndexOperation.Builder builder = new IndexOperation.Builder<>(); @@ -155,34 +154,34 @@ public static IndexRequest.Builder toIndexRequestBuilder(Object document, Exc @Converter public static GetRequest.Builder toGetRequestBuilder(Object document, Exchange exchange) { - if (document instanceof GetRequest.Builder) { - return (GetRequest.Builder) document; + if (document instanceof GetRequest.Builder getReqBuilder) { + return getReqBuilder; } - if (document instanceof String) { + if (document instanceof String string) { return new GetRequest.Builder() .index(exchange.getIn().getHeader(OpensearchConstants.PARAM_INDEX_NAME, String.class)) - .id((String) document); + .id(string); } return null; } @Converter public static DeleteRequest.Builder toDeleteRequestBuilder(Object document, Exchange exchange) { - if (document instanceof DeleteRequest.Builder) { - return (DeleteRequest.Builder) document; + if (document instanceof DeleteRequest.Builder deleteReqBuilder) { + return deleteReqBuilder; } - if (document instanceof String) { + if (document instanceof String string) { return new DeleteRequest.Builder() .index(exchange.getIn().getHeader(OpensearchConstants.PARAM_INDEX_NAME, String.class)) - .id((String) document); + .id(string); } return null; } @Converter public static DeleteIndexRequest.Builder toDeleteIndexRequestBuilder(Object document, Exchange exchange) { - if (document instanceof DeleteIndexRequest.Builder) { - return (DeleteIndexRequest.Builder) document; + if (document instanceof DeleteIndexRequest.Builder deleteIdxReqBuilder) { + return deleteIdxReqBuilder; } if (document instanceof String) { return new DeleteIndexRequest.Builder() @@ -193,15 +192,15 @@ public static DeleteIndexRequest.Builder toDeleteIndexRequestBuilder(Object docu @Converter public static MgetRequest.Builder toMgetRequestBuilder(Object documents, Exchange exchange) { - if (documents instanceof MgetRequest.Builder) { - return (MgetRequest.Builder) documents; + if (documents instanceof MgetRequest.Builder mgetReqBuilder) { + return mgetReqBuilder; } if (documents instanceof Iterable documentIterable) { MgetRequest.Builder builder = new MgetRequest.Builder(); builder.index(exchange.getIn().getHeader(OpensearchConstants.PARAM_INDEX_NAME, String.class)); for (Object document : documentIterable) { - if (document instanceof String) { - builder.ids((String) document); + if (document instanceof String string) { + builder.ids(string); } else { LOG.warn( "Cannot convert document id of type {} into a String", @@ -218,12 +217,11 @@ public static MgetRequest.Builder toMgetRequestBuilder(Object documents, Exchang public static SearchRequest.Builder toSearchRequestBuilder(Object queryObject, Exchange exchange) throws IOException { String indexName = exchange.getIn().getHeader(OpensearchConstants.PARAM_INDEX_NAME, String.class); - if (queryObject instanceof SearchRequest.Builder) { - SearchRequest.Builder builder = (SearchRequest.Builder) queryObject; - if (builder.build().index().isEmpty()) { - builder.index(indexName); + if (queryObject instanceof SearchRequest.Builder searchReqBuilder) { + if (searchReqBuilder.build().index().isEmpty()) { + searchReqBuilder.index(indexName); } - return builder; + return searchReqBuilder; } SearchRequest.Builder builder = new SearchRequest.Builder(); @@ -273,24 +271,24 @@ public static SearchRequest.Builder toSearchRequestBuilder(Object queryObject, E @Converter public static BulkRequest.Builder toBulkRequestBuilder(Object documents, Exchange exchange) throws IOException { - if (documents instanceof BulkRequest.Builder) { - return (BulkRequest.Builder) documents; + if (documents instanceof BulkRequest.Builder bulkReqBuilder) { + return bulkReqBuilder; } - if (documents instanceof Iterable) { + if (documents instanceof Iterable documentIterable) { BulkRequest.Builder builder = new BulkRequest.Builder(); builder.index(exchange.getIn().getHeader(OpensearchConstants.PARAM_INDEX_NAME, String.class)); - for (Object document : (List) documents) { - if (document instanceof BulkOperationVariant) { - builder.operations(((BulkOperationVariant) document)._toBulkOperation()); - } else if (document instanceof DeleteOperation.Builder) { + for (Object document : documentIterable) { + if (document instanceof BulkOperationVariant bulkOpVariant) { + builder.operations(bulkOpVariant._toBulkOperation()); + } else if (document instanceof DeleteOperation.Builder deleteOpBuilder) { builder.operations( - new BulkOperation.Builder().delete(((DeleteOperation.Builder) document).build()).build()); - } else if (document instanceof UpdateOperation.Builder) { + new BulkOperation.Builder().delete(deleteOpBuilder.build()).build()); + } else if (document instanceof UpdateOperation.Builder updateOpBuilder) { builder.operations( - new BulkOperation.Builder().update(((UpdateOperation.Builder) document).build()).build()); - } else if (document instanceof CreateOperation.Builder) { + new BulkOperation.Builder().update(updateOpBuilder.build()).build()); + } else if (document instanceof CreateOperation.Builder createOpBuilder) { builder.operations( - new BulkOperation.Builder().create(((CreateOperation.Builder) document).build()).build()); + new BulkOperation.Builder().create(createOpBuilder.build()).build()); } else { builder.operations( new BulkOperation.Builder().index(createIndexOperationBuilder(document, exchange).build()).build()); From 488d5ec5049dad052ae54c85f471d5e9490a62aa Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:29 +0000 Subject: [PATCH 06/14] (chores): fix SonarCloud S6201 in camel-smpp Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../component/smpp/AbstractSmppCommand.java | 20 ++++----- .../camel/component/smpp/SmppBinding.java | 40 +++++++++--------- .../component/smpp/SmppDataSmCommand.java | 42 +++++++++---------- .../camel/component/smpp/SmppMessage.java | 7 ++-- .../component/smpp/SmppReplaceSmCommand.java | 8 ++-- .../smpp/SmppSubmitMultiCommand.java | 8 ++-- .../component/smpp/SmppSubmitSmCommand.java | 8 ++-- .../camel/component/smpp/SmppUtils.java | 4 +- 8 files changed, 68 insertions(+), 69 deletions(-) diff --git a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/AbstractSmppCommand.java b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/AbstractSmppCommand.java index 36a75bafc9313..81279211825a9 100644 --- a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/AbstractSmppCommand.java +++ b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/AbstractSmppCommand.java @@ -54,16 +54,16 @@ protected List createOptionalParametersByCode(Map createOptionalParameterByName(DeliverSm deliverSm) { try { Tag valueOfTag = OptionalParameter.Tag.valueOf(optPara.tag); if (valueOfTag != null) { - if (optPara instanceof COctetString) { - optParams.put(valueOfTag.toString(), ((COctetString) optPara).getValueAsString()); - } else if (optPara instanceof OctetString) { - optParams.put(valueOfTag.toString(), ((OctetString) optPara).getValueAsString()); - } else if (optPara instanceof OptionalParameter.Byte) { + if (optPara instanceof COctetString cOctetString) { + optParams.put(valueOfTag.toString(), cOctetString.getValueAsString()); + } else if (optPara instanceof OctetString octetString) { + optParams.put(valueOfTag.toString(), octetString.getValueAsString()); + } else if (optPara instanceof OptionalParameter.Byte byteParam) { optParams.put(valueOfTag.toString(), - ((OptionalParameter.Byte) optPara).getValue()); - } else if (optPara instanceof OptionalParameter.Short) { + byteParam.getValue()); + } else if (optPara instanceof OptionalParameter.Short shortParam) { optParams.put(valueOfTag.toString(), - ((OptionalParameter.Short) optPara).getValue()); - } else if (optPara instanceof OptionalParameter.Int) { + shortParam.getValue()); + } else if (optPara instanceof OptionalParameter.Int intParam) { optParams.put(valueOfTag.toString(), - ((OptionalParameter.Int) optPara).getValue()); + intParam.getValue()); } else if (optPara instanceof Null) { optParams.put(valueOfTag.toString(), null); } @@ -188,19 +188,19 @@ private Map createOptionalParameterByName(DeliverSm deliverSm) { private Map createOptionalParameterByCode(DeliverSm deliverSm) { Map optParams = new HashMap<>(); for (OptionalParameter optPara : deliverSm.getOptionalParameters()) { - if (optPara instanceof COctetString) { - optParams.put(optPara.tag, ((COctetString) optPara).getValueAsString()); - } else if (optPara instanceof OctetString) { - optParams.put(optPara.tag, ((OctetString) optPara).getValue()); - } else if (optPara instanceof OptionalParameter.Byte) { + if (optPara instanceof COctetString cOctetString) { + optParams.put(optPara.tag, cOctetString.getValueAsString()); + } else if (optPara instanceof OctetString octetString) { + optParams.put(optPara.tag, octetString.getValue()); + } else if (optPara instanceof OptionalParameter.Byte byteParam) { optParams.put(optPara.tag, - ((OptionalParameter.Byte) optPara).getValue()); - } else if (optPara instanceof OptionalParameter.Short) { + byteParam.getValue()); + } else if (optPara instanceof OptionalParameter.Short shortParam) { optParams.put(optPara.tag, - ((OptionalParameter.Short) optPara).getValue()); - } else if (optPara instanceof OptionalParameter.Int) { + shortParam.getValue()); + } else if (optPara instanceof OptionalParameter.Int intParam) { optParams.put(optPara.tag, - ((OptionalParameter.Int) optPara).getValue()); + intParam.getValue()); } else if (optPara instanceof Null) { optParams.put(optPara.tag, null); } diff --git a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppDataSmCommand.java b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppDataSmCommand.java index a061dc45dc799..2a10fa2d2d57c 100644 --- a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppDataSmCommand.java +++ b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppDataSmCommand.java @@ -92,16 +92,16 @@ protected Map createOptionalParameterByName(OptionalParameter[] for (OptionalParameter optionalParameter : optionalParameters) { String value = null; - if (optionalParameter instanceof COctetString) { - value = ((COctetString) optionalParameter).getValueAsString(); - } else if (optionalParameter instanceof OctetString) { - value = ((OctetString) optionalParameter).getValueAsString(); - } else if (optionalParameter instanceof Int) { - value = String.valueOf(((Int) optionalParameter).getValue()); - } else if (optionalParameter instanceof Short) { - value = String.valueOf(((Short) optionalParameter).getValue()); - } else if (optionalParameter instanceof Byte) { - value = String.valueOf(((Byte) optionalParameter).getValue()); + if (optionalParameter instanceof COctetString cOctetString) { + value = cOctetString.getValueAsString(); + } else if (optionalParameter instanceof OctetString octetString) { + value = octetString.getValueAsString(); + } else if (optionalParameter instanceof Int intParam) { + value = String.valueOf(intParam.getValue()); + } else if (optionalParameter instanceof Short shortParam) { + value = String.valueOf(shortParam.getValue()); + } else if (optionalParameter instanceof Byte byteParam) { + value = String.valueOf(byteParam.getValue()); } else if (optionalParameter instanceof Null) { value = null; } @@ -118,20 +118,20 @@ protected Map createOptionalParameterByCode(OptionalPar Map optParams = new HashMap<>(); for (OptionalParameter optPara : optionalParameters) { - if (COctetString.class.isInstance(optPara)) { - optParams.put(java.lang.Short.valueOf(optPara.tag), ((COctetString) optPara).getValueAsString()); - } else if (org.jsmpp.bean.OptionalParameter.OctetString.class.isInstance(optPara)) { - optParams.put(java.lang.Short.valueOf(optPara.tag), ((OctetString) optPara).getValue()); - } else if (org.jsmpp.bean.OptionalParameter.Byte.class.isInstance(optPara)) { + if (optPara instanceof COctetString cOctetString) { + optParams.put(java.lang.Short.valueOf(optPara.tag), cOctetString.getValueAsString()); + } else if (optPara instanceof OctetString octetString) { + optParams.put(java.lang.Short.valueOf(optPara.tag), octetString.getValue()); + } else if (optPara instanceof Byte byteParam) { optParams.put(java.lang.Short.valueOf(optPara.tag), - java.lang.Byte.valueOf(((org.jsmpp.bean.OptionalParameter.Byte) optPara).getValue())); - } else if (org.jsmpp.bean.OptionalParameter.Short.class.isInstance(optPara)) { + java.lang.Byte.valueOf(byteParam.getValue())); + } else if (optPara instanceof Short shortParam) { optParams.put(java.lang.Short.valueOf(optPara.tag), - java.lang.Short.valueOf(((org.jsmpp.bean.OptionalParameter.Short) optPara).getValue())); - } else if (org.jsmpp.bean.OptionalParameter.Int.class.isInstance(optPara)) { + java.lang.Short.valueOf(shortParam.getValue())); + } else if (optPara instanceof Int intParam) { optParams.put(java.lang.Short.valueOf(optPara.tag), - Integer.valueOf(((org.jsmpp.bean.OptionalParameter.Int) optPara).getValue())); - } else if (Null.class.isInstance(optPara)) { + Integer.valueOf(intParam.getValue())); + } else if (optPara instanceof Null) { optParams.put(java.lang.Short.valueOf(optPara.tag), null); } } diff --git a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppMessage.java b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppMessage.java index dde75b0ef09c1..ab270bf861adf 100644 --- a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppMessage.java +++ b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppMessage.java @@ -60,17 +60,16 @@ public boolean isDataSm() { } public boolean isDeliverSm() { - return command instanceof DeliverSm && !((DeliverSm) command).isSmscDeliveryReceipt(); + return command instanceof DeliverSm deliverSm && !deliverSm.isSmscDeliveryReceipt(); } public boolean isDeliveryReceipt() { - return command instanceof DeliverSm && ((DeliverSm) command).isSmscDeliveryReceipt(); + return command instanceof DeliverSm deliverSm && deliverSm.isSmscDeliveryReceipt(); } @Override protected Object createBody() { - if (command instanceof MessageRequest) { - MessageRequest msgRequest = (MessageRequest) command; + if (command instanceof MessageRequest msgRequest) { byte[] shortMessage = msgRequest.getShortMessage(); if (shortMessage == null || shortMessage.length == 0) { return null; diff --git a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppReplaceSmCommand.java b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppReplaceSmCommand.java index 9cfad5ccea5cb..1f02d1bd68ca3 100644 --- a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppReplaceSmCommand.java +++ b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppReplaceSmCommand.java @@ -108,10 +108,10 @@ protected ReplaceSm createReplaceSmTempate(Exchange exchange) { if (in.getHeaders().containsKey(SmppConstants.VALIDITY_PERIOD)) { Object validityPeriod = in.getHeader(SmppConstants.VALIDITY_PERIOD); - if (validityPeriod instanceof String) { - replaceSm.setValidityPeriod((String) validityPeriod); - } else if (validityPeriod instanceof Date) { - replaceSm.setValidityPeriod(SmppUtils.formatTime((Date) validityPeriod)); + if (validityPeriod instanceof String validityPeriodString) { + replaceSm.setValidityPeriod(validityPeriodString); + } else if (validityPeriod instanceof Date validityPeriodDate) { + replaceSm.setValidityPeriod(SmppUtils.formatTime(validityPeriodDate)); } } diff --git a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppSubmitMultiCommand.java b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppSubmitMultiCommand.java index 22f06fedf2518..5ea28071d929d 100644 --- a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppSubmitMultiCommand.java +++ b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppSubmitMultiCommand.java @@ -248,10 +248,10 @@ protected SubmitMulti createSubmitMultiTemplate(Exchange exchange) { if (in.getHeaders().containsKey(SmppConstants.VALIDITY_PERIOD)) { Object validityPeriod = in.getHeader(SmppConstants.VALIDITY_PERIOD); - if (validityPeriod instanceof String) { - submitMulti.setValidityPeriod((String) validityPeriod); - } else if (validityPeriod instanceof Date) { - submitMulti.setValidityPeriod(SmppUtils.formatTime((Date) validityPeriod)); + if (validityPeriod instanceof String validityPeriodString) { + submitMulti.setValidityPeriod(validityPeriodString); + } else if (validityPeriod instanceof Date validityPeriodDate) { + submitMulti.setValidityPeriod(SmppUtils.formatTime(validityPeriodDate)); } } diff --git a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppSubmitSmCommand.java b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppSubmitSmCommand.java index d0ff5000bb0a3..8e1484ad8ecb6 100644 --- a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppSubmitSmCommand.java +++ b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppSubmitSmCommand.java @@ -213,10 +213,10 @@ protected SubmitSm createSubmitSmTemplate(Exchange exchange) { if (in.getHeaders().containsKey(SmppConstants.VALIDITY_PERIOD)) { Object validityPeriod = in.getHeader(SmppConstants.VALIDITY_PERIOD); - if (validityPeriod instanceof String) { - submitSm.setValidityPeriod((String) validityPeriod); - } else if (validityPeriod instanceof Date) { - submitSm.setValidityPeriod(SmppUtils.formatTime((Date) validityPeriod)); + if (validityPeriod instanceof String validityPeriodString) { + submitSm.setValidityPeriod(validityPeriodString); + } else if (validityPeriod instanceof Date validityPeriodDate) { + submitSm.setValidityPeriod(SmppUtils.formatTime(validityPeriodDate)); } } diff --git a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppUtils.java b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppUtils.java index 8276d826064f0..d87c59b35808f 100644 --- a/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppUtils.java +++ b/components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppUtils.java @@ -144,8 +144,8 @@ public static byte[] getMessageBody(DeliverSm deliverSm) { byte[] body = deliverSm.getShortMessage(); if (body == null || body.length == 0) { OptionalParameter param = deliverSm.getOptionalParameter(Tag.MESSAGE_PAYLOAD); - if (param instanceof OctetString) { - body = ((OctetString) param).getValue(); + if (param instanceof OctetString octetString) { + body = octetString.getValue(); } } return body; From 7203927d24a720cc03f4257fb590f0b690734a7b Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:29 +0000 Subject: [PATCH 07/14] (chores): fix SonarCloud S6201 in camel-zeebe Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../zeebe/processor/DeploymentProcessor.java | 26 +++++++++---------- .../zeebe/processor/ProcessProcessor.java | 10 +++---- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/components/camel-zeebe/src/main/java/org/apache/camel/component/zeebe/processor/DeploymentProcessor.java b/components/camel-zeebe/src/main/java/org/apache/camel/component/zeebe/processor/DeploymentProcessor.java index daa2f0deeac01..b86fc662e0b31 100644 --- a/components/camel-zeebe/src/main/java/org/apache/camel/component/zeebe/processor/DeploymentProcessor.java +++ b/components/camel-zeebe/src/main/java/org/apache/camel/component/zeebe/processor/DeploymentProcessor.java @@ -43,18 +43,18 @@ public void process(Exchange exchange) throws Exception { if (headerResourceName != null && (body instanceof String || body instanceof byte[] || body instanceof InputStream)) { message = new DeploymentRequest(); message.setName(headerResourceName); - if (body instanceof String) { - message.setContent(((String) body).getBytes()); - } else if (body instanceof byte[]) { - message.setContent((byte[]) body); + if (body instanceof String bodyString) { + message.setContent(bodyString.getBytes()); + } else if (body instanceof byte[] bodyBytes) { + message.setContent(bodyBytes); } else { message.setContent(((InputStream) body).readAllBytes()); } - } else if (body instanceof DeploymentRequest) { - message = (DeploymentRequest) body; - } else if (body instanceof String) { + } else if (body instanceof DeploymentRequest deploymentRequest) { + message = deploymentRequest; + } else if (body instanceof String bodyString) { try { - message = objectMapper.readValue((String) body, DeploymentRequest.class); + message = objectMapper.readValue(bodyString, DeploymentRequest.class); } catch (JsonProcessingException jsonProcessingException) { throw new IllegalArgumentException("Cannot convert body to DeploymentRequestMessage", jsonProcessingException); } @@ -78,15 +78,15 @@ public void process(Exchange exchange) throws Exception { exchange.getMessage().setHeader(ZeebeConstants.IS_SUCCESS, resultMessage.isSuccess()); if (resultMessage.isSuccess()) { - if (resultMessage instanceof ProcessDeploymentResponse) { + if (resultMessage instanceof ProcessDeploymentResponse processDeploymentResponse) { exchange.getMessage().setHeader(ZeebeConstants.RESOURCE_NAME, - ((ProcessDeploymentResponse) resultMessage).getResourceName()); + processDeploymentResponse.getResourceName()); exchange.getMessage().setHeader(ZeebeConstants.BPMN_PROCESS_ID, - ((ProcessDeploymentResponse) resultMessage).getBpmnProcessId()); + processDeploymentResponse.getBpmnProcessId()); exchange.getMessage().setHeader(ZeebeConstants.PROCESS_DEFINITION_KEY, - ((ProcessDeploymentResponse) resultMessage).getProcessDefinitionKey()); + processDeploymentResponse.getProcessDefinitionKey()); exchange.getMessage().setHeader(ZeebeConstants.VERSION, - ((ProcessDeploymentResponse) resultMessage).getVersion()); + processDeploymentResponse.getVersion()); } } else { exchange.getMessage().setHeader(ZeebeConstants.ERROR_MESSAGE, resultMessage.getErrorMessage()); diff --git a/components/camel-zeebe/src/main/java/org/apache/camel/component/zeebe/processor/ProcessProcessor.java b/components/camel-zeebe/src/main/java/org/apache/camel/component/zeebe/processor/ProcessProcessor.java index cf41d42c465cd..6049c06c96616 100644 --- a/components/camel-zeebe/src/main/java/org/apache/camel/component/zeebe/processor/ProcessProcessor.java +++ b/components/camel-zeebe/src/main/java/org/apache/camel/component/zeebe/processor/ProcessProcessor.java @@ -35,12 +35,12 @@ public void process(Exchange exchange) throws Exception { if (exchange.getMessage().getBody() instanceof ProcessRequest) { message = exchange.getMessage().getBody(ProcessRequest.class); - } else if (exchange.getMessage().getBody() instanceof ProcessResponse) { + } else if (exchange.getMessage().getBody() instanceof ProcessResponse processResponse) { message = new ProcessRequest(); - message.setProcessInstanceKey(((ProcessResponse) exchange.getMessage().getBody()).getProcessInstanceKey()); - message.setProcessId(((ProcessResponse) exchange.getMessage().getBody()).getProcessId()); - message.setProcessVersion(((ProcessResponse) exchange.getMessage().getBody()).getProcessVersion()); - message.setProcessKey(((ProcessResponse) exchange.getMessage().getBody()).getProcessKey()); + message.setProcessInstanceKey(processResponse.getProcessInstanceKey()); + message.setProcessId(processResponse.getProcessId()); + message.setProcessVersion(processResponse.getProcessVersion()); + message.setProcessKey(processResponse.getProcessKey()); } else if (exchange.getMessage().getBody() instanceof String) { try { String bodyString = exchange.getMessage().getBody(String.class); From 033668fd925f374699f66465fd52ab7e99b41a01 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:29 +0000 Subject: [PATCH 08/14] (chores): fix SonarCloud S6201 in camel-mail Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../apache/camel/component/mail/MailBinding.java | 4 ++-- .../camel/component/mail/MailComponent.java | 16 ++++++++-------- .../camel/component/mail/MailConsumer.java | 3 +-- .../camel/component/mail/MailConverters.java | 9 ++++----- .../apache/camel/component/mail/MailMessage.java | 11 +++++------ .../camel/component/mail/MailProducer.java | 4 ++-- .../mail/SplitAttachmentsExpression.java | 4 ++-- .../mime/multipart/MimeMultipartDataFormat.java | 4 ++-- 8 files changed, 26 insertions(+), 29 deletions(-) diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java index 2f45d92936f43..2a96fca0606a4 100644 --- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java +++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java @@ -347,8 +347,8 @@ public void extractAttachmentsFromMail(Message message, Map LOG.trace("Extracting attachments +++ start +++"); Object content = message.getContent(); - if (content instanceof Multipart) { - extractAttachmentsFromMultipart((Multipart) content, map); + if (content instanceof Multipart multipart) { + extractAttachmentsFromMultipart(multipart, map); } else if (content != null) { LOG.trace("No attachments to extract as content is not Multipart: {}", content.getClass().getName()); } diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailComponent.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailComponent.java index 83c6cfed08069..1bf321c3c743c 100644 --- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailComponent.java +++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailComponent.java @@ -79,9 +79,9 @@ protected Endpoint createEndpoint(String uri, String remaining, Map 0) { BodyPart part = multipart.getBodyPart(0); content = part.getContent(); @@ -85,11 +84,11 @@ public static String toString(Multipart multipart) throws MessagingException, IO for (int i = 0; i < size; i++) { BodyPart part = multipart.getBodyPart(i); Object content = part.getContent(); - while (content instanceof MimeMultipart) { - if (multipart.getCount() < 1) { + while (content instanceof MimeMultipart mimeMultipart) { + if (mimeMultipart.getCount() < 1) { break; } - part = ((MimeMultipart) content).getBodyPart(0); + part = mimeMultipart.getBodyPart(0); content = part.getContent(); } // Perform a case-insensitive "startsWith" check that works for different locales diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java index f9ab6972dab49..09f2173a71796 100644 --- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java +++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java @@ -117,18 +117,17 @@ protected void populateInitialHeaders(Map map) { @Override public void copyFrom(org.apache.camel.Message that) { // only do a deep copy if we need to (yes when that is not a mail message, or if the mapMailMessage is true) - boolean needCopy = !(that instanceof MailMessage) || (((MailMessage) that).mapMailMessage); + boolean needCopy = !(that instanceof MailMessage thatMail) || thatMail.mapMailMessage; if (needCopy) { super.copyFrom(that); } else { // no deep copy needed, but copy message id setMessageId(that.getMessageId()); } - if (that instanceof MailMessage) { - MailMessage tmpMailMessage = (MailMessage) that; - this.originalMailMessage = tmpMailMessage.originalMailMessage; - this.mailMessage = tmpMailMessage.mailMessage; - this.mapMailMessage = tmpMailMessage.mapMailMessage; + if (that instanceof MailMessage thatMailMessage) { + this.originalMailMessage = thatMailMessage.originalMailMessage; + this.mailMessage = thatMailMessage.mailMessage; + this.mapMailMessage = thatMailMessage.mapMailMessage; } // cover over exchange if none has been assigned if (getExchange() == null) { diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java index f0557eb6a5437..d1ab2f2a5532e 100644 --- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java +++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java @@ -57,9 +57,9 @@ public boolean process(Exchange exchange, AsyncCallback callback) { MimeMessage mimeMessage; final Object body = exchange.getIn().getBody(); - if (body instanceof MimeMessage) { + if (body instanceof MimeMessage mimeMsg) { // Body is directly a MimeMessage - mimeMessage = (MimeMessage) body; + mimeMessage = mimeMsg; } else { // Create a message with exchange data mimeMessage = new MimeMessage(mailSender.getSession()); diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java index 3ec673dbd9479..4c0b7d1c4e1e4 100644 --- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java +++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java @@ -85,8 +85,8 @@ private Message extractAttachment(Attachment attachment, String attachmentName, final Message outMessage = new DefaultMessage(camelContext); outMessage.setHeader(HEADER_NAME, attachmentName); Object obj = attachment.getDataHandler().getContent(); - if (obj instanceof InputStream) { - outMessage.setBody(readMimePart((InputStream) obj)); + if (obj instanceof InputStream inputStream) { + outMessage.setBody(readMimePart(inputStream)); return outMessage; } else if (obj instanceof String || obj instanceof byte[]) { outMessage.setBody(obj); diff --git a/components/camel-mail/src/main/java/org/apache/camel/dataformat/mime/multipart/MimeMultipartDataFormat.java b/components/camel-mail/src/main/java/org/apache/camel/dataformat/mime/multipart/MimeMultipartDataFormat.java index 4f28bf0d0e5d0..116705d1d235d 100644 --- a/components/camel-mail/src/main/java/org/apache/camel/dataformat/mime/multipart/MimeMultipartDataFormat.java +++ b/components/camel-mail/src/main/java/org/apache/camel/dataformat/mime/multipart/MimeMultipartDataFormat.java @@ -397,8 +397,8 @@ private String getAttachmentKey(BodyPart bp) throws MessagingException, Unsuppor // use the filename as key for the map String key = bp.getFileName(); // if there is no file name we use the Content-ID header - if (key == null && bp instanceof MimeBodyPart) { - key = ((MimeBodyPart) bp).getContentID(); + if (key == null && bp instanceof MimeBodyPart mimeBodyPart) { + key = mimeBodyPart.getContentID(); if (key != null && key.startsWith("<") && key.length() > 2) { // strip <> key = key.substring(1, key.length() - 1); From f2ac964ae99f34a2825b61cd5fd42bf3c3a55f53 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:29 +0000 Subject: [PATCH 09/14] (chores): fix SonarCloud S6201 in camel-netty Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../netty/http/DefaultNettyHttpBinding.java | 32 +++++++++---------- .../http/HttpClientInitializerFactory.java | 4 +-- .../http/HttpServerInitializerFactory.java | 12 +++---- .../netty/http/NettyHttpComponent.java | 11 +++---- .../component/netty/http/NettyHttpHelper.java | 4 +-- .../http/SecurityAuthenticatorSupport.java | 6 ++-- .../handlers/HttpClientChannelHandler.java | 3 +- .../handlers/HttpInboundStreamHandler.java | 16 +++++----- .../handlers/HttpOutboundStreamHandler.java | 8 ++--- .../handlers/HttpServerChannelHandler.java | 11 +++---- .../HttpServerMultiplexChannelHandler.java | 7 ++-- .../DefaultClientInitializerFactory.java | 8 ++--- .../DefaultServerInitializerFactory.java | 8 ++--- .../component/netty/NettyConfiguration.java | 4 +-- .../component/netty/NettyPayloadHelper.java | 16 +++++----- .../camel/component/netty/NettyProducer.java | 4 +-- 16 files changed, 74 insertions(+), 80 deletions(-) diff --git a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/DefaultNettyHttpBinding.java b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/DefaultNettyHttpBinding.java index 77ca6f96e5a93..2bdc975b48270 100644 --- a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/DefaultNettyHttpBinding.java +++ b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/DefaultNettyHttpBinding.java @@ -250,11 +250,12 @@ public void populateCamelHeaders( if (request.method().name().equals("POST") && request.headers().get(NettyHttpConstants.CONTENT_TYPE) != null && request.headers().get(NettyHttpConstants.CONTENT_TYPE) .startsWith(NettyHttpConstants.CONTENT_TYPE_WWW_FORM_URLENCODED) - && !configuration.isBridgeEndpoint() && !configuration.isHttpProxy() && request instanceof FullHttpRequest) { + && !configuration.isBridgeEndpoint() && !configuration.isHttpProxy() + && request instanceof FullHttpRequest fullHttpRequest) { // Push POST form params into the headers to retain compatibility with DefaultHttpBinding String body; - ByteBuf buffer = ((FullHttpRequest) request).content().retain(); + ByteBuf buffer = fullHttpRequest.content().retain(); try { body = buffer.toString(StandardCharsets.UTF_8); } finally { @@ -423,8 +424,7 @@ public void populateCamelHeaders( public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toNettyResponse: {}", message); - if (message instanceof NettyHttpMessage) { - final NettyHttpMessage nettyHttpMessage = (NettyHttpMessage) message; + if (message instanceof NettyHttpMessage nettyHttpMessage) { final FullHttpResponse response = nettyHttpMessage.getHttpResponse(); if (response != null && nettyHttpMessage.getBody() == null) { @@ -433,8 +433,8 @@ public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration conf } // the message body may already be a Netty HTTP response - if (message.getBody() instanceof HttpResponse) { - return (HttpResponse) message.getBody(); + if (message.getBody() instanceof HttpResponse httpResponse) { + return httpResponse; } Object body = message.getBody(); @@ -483,15 +483,15 @@ public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration conf HttpResponse response = null; - if (body instanceof InputStream && configuration.isDisableStreamCache()) { + if (body instanceof InputStream inputStream && configuration.isDisableStreamCache()) { response = new OutboundStreamHttpResponse( - (InputStream) body, new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), true)); + inputStream, new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), true)); response.headers().set(TRANSFER_ENCODING, CHUNKED); } if (response == null) { - if (body instanceof ByteBuf) { - buffer = (ByteBuf) body; + if (body instanceof ByteBuf byteBuf) { + buffer = byteBuf; } else { // try to convert to buffer first buffer = message.getBody(ByteBuf.class); @@ -622,10 +622,10 @@ public HttpRequest toNettyRequest(Message message, String fullUri, NettyHttpConf } HttpRequest request = null; - if (message instanceof NettyHttpMessage) { + if (message instanceof NettyHttpMessage nettyHttpMessage) { // if the request is already given we should set the values // from message headers and pass on the same request - final FullHttpRequest givenRequest = ((NettyHttpMessage) message).getHttpRequest(); + final FullHttpRequest givenRequest = nettyHttpMessage.getHttpRequest(); // we need to make sure that the givenRequest is the original // request received by the proxy, only when the body wasn't // modified by a processor on route @@ -637,9 +637,9 @@ public HttpRequest toNettyRequest(Message message, String fullUri, NettyHttpConf } } - if (request == null && body instanceof InputStream && configuration.isDisableStreamCache()) { + if (request == null && body instanceof InputStream inputStream && configuration.isDisableStreamCache()) { request = new OutboundStreamHttpRequest( - (InputStream) body, new DefaultHttpRequest(protocol, httpMethod, uriForRequest)); + inputStream, new DefaultHttpRequest(protocol, httpMethod, uriForRequest)); request.headers().set(TRANSFER_ENCODING, CHUNKED); } @@ -649,8 +649,8 @@ public HttpRequest toNettyRequest(Message message, String fullUri, NettyHttpConf if (body != null) { // support bodies as native Netty ByteBuf buffer; - if (body instanceof ByteBuf) { - buffer = (ByteBuf) body; + if (body instanceof ByteBuf byteBuf) { + buffer = byteBuf; } else { // try to convert to buffer first buffer = message.getBody(ByteBuf.class); diff --git a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpClientInitializerFactory.java b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpClientInitializerFactory.java index 6eb72c7809d35..e3a8648a7048e 100644 --- a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpClientInitializerFactory.java +++ b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpClientInitializerFactory.java @@ -119,9 +119,9 @@ protected void initChannel(Channel ch) throws Exception { private void addToPipeline(List handlers, ChannelPipeline pipeline, String prefix) { for (int x = 0; x < handlers.size(); x++) { ChannelHandler handler = handlers.get(x); - if (handler instanceof ChannelHandlerFactory) { + if (handler instanceof ChannelHandlerFactory channelHandlerFactory) { // use the factory to create a new instance of the channel as it may not be shareable - handler = ((ChannelHandlerFactory) handler).newChannelHandler(); + handler = channelHandlerFactory.newChannelHandler(); } pipeline.addLast(prefix + x, handler); } diff --git a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerInitializerFactory.java b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerInitializerFactory.java index ea071d6e81959..982fad1dcbe87 100644 --- a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerInitializerFactory.java +++ b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerInitializerFactory.java @@ -84,9 +84,9 @@ protected void initChannel(Channel ch) throws Exception { ChannelHandler sslHandler = configureServerSSLOnDemand(); if (sslHandler != null) { - if (sslHandler instanceof ChannelHandlerFactory) { + if (sslHandler instanceof ChannelHandlerFactory channelHandlerFactory) { // use the factory to create a new instance of the channel as it may not be shareable - sslHandler = ((ChannelHandlerFactory) sslHandler).newChannelHandler(); + sslHandler = channelHandlerFactory.newChannelHandler(); } LOG.debug("Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler); @@ -99,9 +99,9 @@ protected void initChannel(Channel ch) throws Exception { List decoders = consumer.getConfiguration().getDecodersAsList(); for (int x = 0; x < decoders.size(); x++) { ChannelHandler decoder = decoders.get(x); - if (decoder instanceof ChannelHandlerFactory) { + if (decoder instanceof ChannelHandlerFactory channelHandlerFactory) { // use the factory to create a new instance of the channel as it may not be shareable - decoder = ((ChannelHandlerFactory) decoder).newChannelHandler(); + decoder = channelHandlerFactory.newChannelHandler(); } pipeline.addLast("decoder-" + x, decoder); } @@ -109,9 +109,9 @@ protected void initChannel(Channel ch) throws Exception { List encoders = consumer.getConfiguration().getEncodersAsList(); for (int x = 0; x < encoders.size(); x++) { ChannelHandler encoder = encoders.get(x); - if (encoder instanceof ChannelHandlerFactory) { + if (encoder instanceof ChannelHandlerFactory channelHandlerFactory) { // use the factory to create a new instance of the channel as it may not be shareable - encoder = ((ChannelHandlerFactory) encoder).newChannelHandler(); + encoder = channelHandlerFactory.newChannelHandler(); } pipeline.addLast("encoder-" + x, encoder); } diff --git a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpComponent.java b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpComponent.java index b1aded8fcac40..ed4b2741cd3a0 100644 --- a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpComponent.java +++ b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpComponent.java @@ -194,11 +194,11 @@ protected Endpoint createEndpoint(String uri, String remaining, Map out) throws Exception { - if (msg instanceof HttpRequest) { - InboundStreamHttpRequest request = new InboundStreamHttpRequest((HttpRequest) msg, is); + if (msg instanceof HttpRequest httpRequest) { + InboundStreamHttpRequest request = new InboundStreamHttpRequest(httpRequest, is); out.add(request); } - if (msg instanceof HttpResponse) { - InboundStreamHttpResponse response = new InboundStreamHttpResponse((HttpResponse) msg, is); + if (msg instanceof HttpResponse httpResponse) { + InboundStreamHttpResponse response = new InboundStreamHttpResponse(httpResponse, is); out.add(response); } - if (msg instanceof HttpContent) { - ByteBuf body = ((HttpContent) msg).content(); + if (msg instanceof HttpContent httpContent) { + ByteBuf body = httpContent.content(); if (body.readableBytes() > 0) { body.readBytes(os, body.readableBytes()); } diff --git a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpOutboundStreamHandler.java b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpOutboundStreamHandler.java index 59130ebba1e24..186c5bd7041a1 100644 --- a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpOutboundStreamHandler.java +++ b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpOutboundStreamHandler.java @@ -28,11 +28,11 @@ public class HttpOutboundStreamHandler extends ChunkedWriteHandler { public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { boolean needNewPromise = false; - if (msg instanceof OutboundStreamHttpRequest) { - super.write(ctx, ((OutboundStreamHttpRequest) msg).getRequest(), promise); + if (msg instanceof OutboundStreamHttpRequest outboundStreamHttpRequest) { + super.write(ctx, outboundStreamHttpRequest.getRequest(), promise); needNewPromise = true; - } else if (msg instanceof OutboundStreamHttpResponse) { - super.write(ctx, ((OutboundStreamHttpResponse) msg).getResponse(), promise); + } else if (msg instanceof OutboundStreamHttpResponse outboundStreamHttpResponse) { + super.write(ctx, outboundStreamHttpResponse.getResponse(), promise); needNewPromise = true; } diff --git a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java index d9df6e10d0270..a0901ff050dcc 100644 --- a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java +++ b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java @@ -82,8 +82,8 @@ public NettyHttpConsumer getConsumer() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { HttpRequest request; - if (msg instanceof HttpRequest) { - request = (HttpRequest) msg; + if (msg instanceof HttpRequest httpReq) { + request = httpReq; } else { request = ((InboundStreamHttpRequest) msg).getHttpRequest(); } @@ -307,8 +307,8 @@ protected void beforeProcess(Exchange exchange, final ChannelHandlerContext ctx, } HttpRequest request; - if (message instanceof HttpRequest) { - request = (HttpRequest) message; + if (message instanceof HttpRequest httpReq) { + request = httpReq; } else { request = ((InboundStreamHttpRequest) message).getHttpRequest(); } @@ -350,8 +350,7 @@ protected Exchange createExchange(ChannelHandlerContext ctx, Object message) thr // create a new IN message as we cannot reuse with netty Message in; - if (message instanceof FullHttpRequest) { - FullHttpRequest request = (FullHttpRequest) message; + if (message instanceof FullHttpRequest request) { in = consumer.getEndpoint().getNettyHttpBinding().toCamelMessage(request, exchange, consumer.getConfiguration()); } else { InboundStreamHttpRequest request = (InboundStreamHttpRequest) message; diff --git a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerMultiplexChannelHandler.java b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerMultiplexChannelHandler.java index c6714be55135d..6b0304a00092b 100644 --- a/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerMultiplexChannelHandler.java +++ b/components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerMultiplexChannelHandler.java @@ -118,8 +118,8 @@ public ChannelHandler getChannelHandler() { protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // store request, as this channel handler is created per pipeline HttpRequest request; - if (msg instanceof HttpRequest) { - request = (HttpRequest) msg; + if (msg instanceof HttpRequest httpReq) { + request = httpReq; } else { request = ((InboundStreamHttpRequest) msg).getHttpRequest(); } @@ -157,9 +157,8 @@ protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Except Attribute attr = ctx.channel().attr(SERVER_HANDLER_KEY); // store handler as attachment attr.set(handler); - if (msg instanceof HttpContent) { + if (msg instanceof HttpContent httpContent) { // need to hold the reference of content - HttpContent httpContent = (HttpContent) msg; httpContent.content().retain(); } handler.channelRead(ctx, msg); diff --git a/components/camel-netty/src/main/java/org/apache/camel/component/netty/DefaultClientInitializerFactory.java b/components/camel-netty/src/main/java/org/apache/camel/component/netty/DefaultClientInitializerFactory.java index 4d42846f0abb0..e47a8b1409ef0 100644 --- a/components/camel-netty/src/main/java/org/apache/camel/component/netty/DefaultClientInitializerFactory.java +++ b/components/camel-netty/src/main/java/org/apache/camel/component/netty/DefaultClientInitializerFactory.java @@ -65,9 +65,9 @@ protected void initChannel(Channel ch) throws Exception { List decoders = producer.getConfiguration().getDecodersAsList(); for (int x = 0; x < decoders.size(); x++) { ChannelHandler decoder = decoders.get(x); - if (decoder instanceof ChannelHandlerFactory) { + if (decoder instanceof ChannelHandlerFactory channelHandlerFactory) { // use the factory to create a new instance of the channel as it may not be shareable - decoder = ((ChannelHandlerFactory) decoder).newChannelHandler(); + decoder = channelHandlerFactory.newChannelHandler(); } addToPipeline("decoder-" + x, channelPipeline, decoder); } @@ -75,9 +75,9 @@ protected void initChannel(Channel ch) throws Exception { List encoders = producer.getConfiguration().getEncodersAsList(); for (int x = 0; x < encoders.size(); x++) { ChannelHandler encoder = encoders.get(x); - if (encoder instanceof ChannelHandlerFactory) { + if (encoder instanceof ChannelHandlerFactory channelHandlerFactory) { // use the factory to create a new instance of the channel as it may not be shareable - encoder = ((ChannelHandlerFactory) encoder).newChannelHandler(); + encoder = channelHandlerFactory.newChannelHandler(); } addToPipeline("encoder-" + x, channelPipeline, encoder); } diff --git a/components/camel-netty/src/main/java/org/apache/camel/component/netty/DefaultServerInitializerFactory.java b/components/camel-netty/src/main/java/org/apache/camel/component/netty/DefaultServerInitializerFactory.java index 78b85af20f9e9..88e347ff8c307 100644 --- a/components/camel-netty/src/main/java/org/apache/camel/component/netty/DefaultServerInitializerFactory.java +++ b/components/camel-netty/src/main/java/org/apache/camel/component/netty/DefaultServerInitializerFactory.java @@ -69,9 +69,9 @@ protected void initChannel(Channel ch) throws Exception { List encoders = consumer.getConfiguration().getEncodersAsList(); for (int x = 0; x < encoders.size(); x++) { ChannelHandler encoder = encoders.get(x); - if (encoder instanceof ChannelHandlerFactory) { + if (encoder instanceof ChannelHandlerFactory channelHandlerFactory) { // use the factory to create a new instance of the channel as it may not be shareable - encoder = ((ChannelHandlerFactory) encoder).newChannelHandler(); + encoder = channelHandlerFactory.newChannelHandler(); } addToPipeline("encoder-" + x, channelPipeline, encoder); } @@ -79,9 +79,9 @@ protected void initChannel(Channel ch) throws Exception { List decoders = consumer.getConfiguration().getDecodersAsList(); for (int x = 0; x < decoders.size(); x++) { ChannelHandler decoder = decoders.get(x); - if (decoder instanceof ChannelHandlerFactory) { + if (decoder instanceof ChannelHandlerFactory channelHandlerFactory) { // use the factory to create a new instance of the channel as it may not be shareable - decoder = ((ChannelHandlerFactory) decoder).newChannelHandler(); + decoder = channelHandlerFactory.newChannelHandler(); } addToPipeline("decoder-" + x, channelPipeline, decoder); } diff --git a/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyConfiguration.java b/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyConfiguration.java index 4cdd8741388ff..8bfabbd1b2d4b 100644 --- a/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyConfiguration.java +++ b/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyConfiguration.java @@ -354,8 +354,8 @@ private String uriRef(NettyComponent component, Map parameters, Object value = parameters.remove(key); if (value == null) { value = defaultValue; - } else if (value instanceof String && EndpointHelper.isReferenceParameter((String) value)) { - String name = ((String) value).replace("#", ""); + } else if (value instanceof String str && EndpointHelper.isReferenceParameter(str)) { + String name = str.replace("#", ""); value = CamelContextHelper.mandatoryLookup(component.getCamelContext(), name); } if (value instanceof File) { diff --git a/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyPayloadHelper.java b/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyPayloadHelper.java index 1f35f507c30de..d09c5d8ae4d51 100644 --- a/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyPayloadHelper.java +++ b/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyPayloadHelper.java @@ -62,14 +62,14 @@ public static Object getOut(NettyEndpoint endpoint, Exchange exchange) { } public static void setIn(Exchange exchange, Object payload) { - if (payload instanceof DefaultExchangeHolder) { - DefaultExchangeHolder.unmarshal(exchange, (DefaultExchangeHolder) payload); + if (payload instanceof DefaultExchangeHolder defaultExchangeHolder) { + DefaultExchangeHolder.unmarshal(exchange, defaultExchangeHolder); } else if (payload instanceof AddressedEnvelope) { @SuppressWarnings("unchecked") AddressedEnvelope dp = (AddressedEnvelope) payload; // need to check if the content is ExchangeHolder - if (dp.content() instanceof DefaultExchangeHolder) { - DefaultExchangeHolder.unmarshal(exchange, (DefaultExchangeHolder) dp.content()); + if (dp.content() instanceof DefaultExchangeHolder defaultExchangeHolder) { + DefaultExchangeHolder.unmarshal(exchange, defaultExchangeHolder); } else { // need to take out the payload here exchange.getIn().setBody(dp.content()); @@ -85,14 +85,14 @@ public static void setIn(Exchange exchange, Object payload) { } public static void setOut(Exchange exchange, Object payload) { - if (payload instanceof DefaultExchangeHolder) { - DefaultExchangeHolder.unmarshal(exchange, (DefaultExchangeHolder) payload); + if (payload instanceof DefaultExchangeHolder defaultExchangeHolder) { + DefaultExchangeHolder.unmarshal(exchange, defaultExchangeHolder); } else if (payload instanceof AddressedEnvelope) { @SuppressWarnings("unchecked") AddressedEnvelope dp = (AddressedEnvelope) payload; // need to check if the content is ExchangeHolder - if (dp.content() instanceof DefaultExchangeHolder) { - DefaultExchangeHolder.unmarshal(exchange, (DefaultExchangeHolder) dp.content()); + if (dp.content() instanceof DefaultExchangeHolder defaultExchangeHolder) { + DefaultExchangeHolder.unmarshal(exchange, defaultExchangeHolder); } else { // need to take out the payload here exchange.getOut().setBody(dp.content()); diff --git a/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java b/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java index 04e7eef6180da..e3fc56afe4e79 100644 --- a/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java +++ b/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java @@ -179,8 +179,8 @@ protected void doStart() throws Exception { } else { correlationManager = new DefaultNettyCamelStateCorrelationManager(); } - if (correlationManager instanceof CamelContextAware) { - ((CamelContextAware) correlationManager).setCamelContext(getContext()); + if (correlationManager instanceof CamelContextAware camelContextAware) { + camelContextAware.setCamelContext(getContext()); } ServiceHelper.startService(correlationManager); From 3bf3bcef0c9b714e713a28e007134e52f6005a15 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:29 +0000 Subject: [PATCH 10/14] (chores): fix SonarCloud S6201 in camel-sjms Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../camel/component/sjms/SjmsMessage.java | 11 +++--- .../camel/component/sjms/SjmsProducer.java | 3 +- .../consumer/EndpointMessageListener.java | 7 ++-- .../SimpleMessageListenerContainer.java | 4 +-- .../camel/component/sjms/jms/JmsBinding.java | 21 +++++------ .../component/sjms/jms/JmsMessageHelper.java | 35 +++++++++---------- .../sjms/reply/ReplyManagerSupport.java | 4 +-- 7 files changed, 39 insertions(+), 46 deletions(-) diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsMessage.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsMessage.java index 0edec65ccd4ab..30d316930fb7b 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsMessage.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsMessage.java @@ -103,8 +103,7 @@ public void copyFrom(org.apache.camel.Message that) { getHeaders().clear(); boolean copyMessageId = true; - if (that instanceof SjmsMessage) { - SjmsMessage thatMessage = (SjmsMessage) that; + if (that instanceof SjmsMessage thatMessage) { this.jmsMessage = thatMessage.jmsMessage; if (this.jmsMessage != null) { // for performance lets not copy the messageID if we are a JMS message @@ -302,10 +301,10 @@ private String getDestinationAsString(Destination destination) throws JMSExcepti String result = null; if (destination == null) { result = "null destination!" + File.separator; - } else if (destination instanceof Topic) { - result = "topic" + File.separator + ((Topic) destination).getTopicName() + File.separator; - } else if (destination instanceof Queue) { - result = "queue" + File.separator + ((Queue) destination).getQueueName() + File.separator; + } else if (destination instanceof Topic topic) { + result = "topic" + File.separator + topic.getTopicName() + File.separator; + } else if (destination instanceof Queue queue) { + result = "queue" + File.separator + queue.getQueueName() + File.separator; } return result; } diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsProducer.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsProducer.java index 6e38956785bf0..8e24ea906c20a 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsProducer.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsProducer.java @@ -389,8 +389,7 @@ public Message createMessage(Session session) throws JMSException { // the reply to is a String, so we need to look up its Destination instance // and if needed create the destination using the session if needed to - if (jmsReplyTo instanceof String) { - String replyTo = (String) jmsReplyTo; + if (jmsReplyTo instanceof String replyTo) { // we need to null it as we use the String to resolve it as a Destination instance jmsReplyTo = resolveOrCreateDestination(replyTo, session); } diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/EndpointMessageListener.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/EndpointMessageListener.java index 63fe3dd1c33ee..382140bf94d16 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/EndpointMessageListener.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/EndpointMessageListener.java @@ -253,8 +253,7 @@ public Exchange createExchange(Message message, Session session, Object replyDes Exchange exchange = consumer.createExchange(false); // reuse existing jms message if pooled org.apache.camel.Message msg = exchange.getIn(); - if (msg instanceof SjmsMessage) { - SjmsMessage jm = (SjmsMessage) msg; + if (msg instanceof SjmsMessage jm) { jm.init(exchange, message, session, endpoint.getBinding()); } else { exchange.setIn(new SjmsMessage(exchange, message, session, endpoint.getBinding())); @@ -442,8 +441,8 @@ public void done(boolean doneSync) { // send back reply if there was no error and we are supposed to send back a reply if (rce == null && sendReply && (body != null || cause != null)) { LOG.trace("onMessage.sendReply START"); - if (replyDestination instanceof Destination) { - sendReply(session, (Destination) replyDestination, message, exchange, body, cause); + if (replyDestination instanceof Destination destination) { + sendReply(session, destination, message, exchange, body, cause); } else { sendReply(session, (String) replyDestination, message, exchange, body, cause); } diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/SimpleMessageListenerContainer.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/SimpleMessageListenerContainer.java index e2271079920e2..886c530c5b7eb 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/SimpleMessageListenerContainer.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/SimpleMessageListenerContainer.java @@ -147,9 +147,9 @@ public void onMessage(Message message) { try { doOnMessage(message); } catch (Exception e) { - if (e instanceof JMSException) { + if (e instanceof JMSException jmsException) { if (endpoint.getExceptionListener() != null) { - endpoint.getExceptionListener().onException((JMSException) e); + endpoint.getExceptionListener().onException(jmsException); } } else { LOG.warn("Execution of JMS message listener failed. This exception is ignored.", e); diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/jms/JmsBinding.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/jms/JmsBinding.java index 52d74816d149c..774d45861219b 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/jms/JmsBinding.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/jms/JmsBinding.java @@ -98,27 +98,24 @@ public Object extractBodyFromJms(Exchange exchange, Message message) { return message; } - if (message instanceof ObjectMessage) { + if (message instanceof ObjectMessage objectMessage) { LOG.trace("Extracting body as a ObjectMessage from JMS message: {}", message); - ObjectMessage objectMessage = (ObjectMessage) message; Object payload = objectMessage.getObject(); - if (payload instanceof DefaultExchangeHolder) { - DefaultExchangeHolder holder = (DefaultExchangeHolder) payload; + if (payload instanceof DefaultExchangeHolder holder) { DefaultExchangeHolder.unmarshal(exchange, holder); // NOSONAR return exchange.getIn().getBody(); } else { return objectMessage.getObject(); } - } else if (message instanceof TextMessage) { + } else if (message instanceof TextMessage textMessage) { LOG.trace("Extracting body as a TextMessage from JMS message: {}", message); - TextMessage textMessage = (TextMessage) message; return textMessage.getText(); - } else if (message instanceof MapMessage) { + } else if (message instanceof MapMessage mapMessage) { LOG.trace("Extracting body as a MapMessage from JMS message: {}", message); - return createMapFromMapMessage((MapMessage) message); - } else if (message instanceof BytesMessage) { + return createMapFromMapMessage(mapMessage); + } else if (message instanceof BytesMessage bytesMessage) { LOG.trace("Extracting body as a BytesMessage from JMS message: {}", message); - return createByteArrayFromBytesMessage((BytesMessage) message); + return createByteArrayFromBytesMessage(bytesMessage); } else if (message instanceof StreamMessage) { LOG.trace("Extracting body as a StreamMessage from JMS message: {}", message); return message; @@ -256,10 +253,10 @@ public void appendJmsProperty(Message jmsMessage, Exchange exchange, String head if (headerName.equals(JmsConstants.JMS_CORRELATION_ID)) { jmsMessage.setJMSCorrelationID(ExchangeHelper.convertToType(exchange, String.class, headerValue)); } else if (headerName.equals(JmsConstants.JMS_REPLY_TO) && headerValue != null) { - if (headerValue instanceof String) { + if (headerValue instanceof String s) { // if the value is a String we must normalize it first, and must include the prefix // as ActiveMQ requires that when converting the String to a jakarta.jms.Destination type - headerValue = normalizeDestinationName((String) headerValue, true); + headerValue = normalizeDestinationName(s, true); } Destination replyTo = ExchangeHelper.convertToType(exchange, Destination.class, headerValue); JmsMessageHelper.setJMSReplyTo(jmsMessage, replyTo); diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/jms/JmsMessageHelper.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/jms/JmsMessageHelper.java index be05e08fbd562..7a67fc2b630f8 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/jms/JmsMessageHelper.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/jms/JmsMessageHelper.java @@ -128,22 +128,22 @@ public static void setProperty(Message jmsMessage, String name, Object value) th if (value == null) { return; } - if (value instanceof Byte) { - jmsMessage.setByteProperty(name, (Byte) value); - } else if (value instanceof Boolean) { - jmsMessage.setBooleanProperty(name, (Boolean) value); - } else if (value instanceof Double) { - jmsMessage.setDoubleProperty(name, (Double) value); - } else if (value instanceof Float) { - jmsMessage.setFloatProperty(name, (Float) value); - } else if (value instanceof Integer) { - jmsMessage.setIntProperty(name, (Integer) value); - } else if (value instanceof Long) { - jmsMessage.setLongProperty(name, (Long) value); - } else if (value instanceof Short) { - jmsMessage.setShortProperty(name, (Short) value); - } else if (value instanceof String) { - jmsMessage.setStringProperty(name, (String) value); + if (value instanceof Byte byteValue) { + jmsMessage.setByteProperty(name, byteValue); + } else if (value instanceof Boolean booleanValue) { + jmsMessage.setBooleanProperty(name, booleanValue); + } else if (value instanceof Double doubleValue) { + jmsMessage.setDoubleProperty(name, doubleValue); + } else if (value instanceof Float floatValue) { + jmsMessage.setFloatProperty(name, floatValue); + } else if (value instanceof Integer intValue) { + jmsMessage.setIntProperty(name, intValue); + } else if (value instanceof Long longValue) { + jmsMessage.setLongProperty(name, longValue); + } else if (value instanceof Short shortValue) { + jmsMessage.setShortProperty(name, shortValue); + } else if (value instanceof String stringValue) { + jmsMessage.setStringProperty(name, stringValue); } else { // fallback to Object jmsMessage.setObjectProperty(name, value); @@ -383,8 +383,7 @@ public static String getJMSMessageID(Message message) { public static void setJMSDeliveryMode(Exchange exchange, Message message, Object deliveryMode) throws JMSException { Integer mode = null; - if (deliveryMode instanceof String) { - String s = (String) deliveryMode; + if (deliveryMode instanceof String s) { if ("PERSISTENT".equalsIgnoreCase(s)) { mode = DeliveryMode.PERSISTENT; } else if ("NON_PERSISTENT".equalsIgnoreCase(s)) { diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/ReplyManagerSupport.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/ReplyManagerSupport.java index 18b05d58fa04b..1b0b37808c181 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/ReplyManagerSupport.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/ReplyManagerSupport.java @@ -172,11 +172,11 @@ public void processReply(ReplyHolder holder) { exchange.setOut(response); Object body = response.getBody(); - if (endpoint.isTransferException() && body instanceof Exception) { + if (endpoint.isTransferException() && body instanceof Exception exception) { log.debug("Reply was an Exception. Setting the Exception on the Exchange: {}", body); // we got an exception back and endpoint was configured to transfer exception // therefore set response as exception - exchange.setException((Exception) body); + exchange.setException(exception); } else { log.debug("Reply received. OUT message body set to reply payload: {}", body); } From 5cb9fad3571af76e917560df1d2fb1f7e5cb9130 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:30 +0000 Subject: [PATCH 11/14] (chores): fix SonarCloud S6201 in camel-spring-rabbitmq Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../springrabbit/DefaultMessageConverter.java | 6 ++-- .../springrabbit/EndpointMessageListener.java | 4 +-- .../springrabbit/SpringRabbitMQEndpoint.java | 32 +++++++++---------- .../springrabbit/SpringRabbitMQProducer.java | 4 +-- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/DefaultMessageConverter.java b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/DefaultMessageConverter.java index 58fbc11caa9df..dc9518da9cc57 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/DefaultMessageConverter.java +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/DefaultMessageConverter.java @@ -46,12 +46,12 @@ public Message createMessage(Object body, MessageProperties messageProperties) t boolean text = body instanceof String; byte[] data; try { - if (body instanceof String) { + if (body instanceof String str) { String encoding = messageProperties.getContentEncoding(); if (encoding != null) { - data = ((String) body).getBytes(encoding); + data = str.getBytes(encoding); } else { - data = ((String) body).getBytes(defaultCharset); + data = str.getBytes(defaultCharset); messageProperties.setContentEncoding(defaultCharset); } } else { diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/EndpointMessageListener.java b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/EndpointMessageListener.java index b16969f2b8e02..bd85fd309ff6a 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/EndpointMessageListener.java +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/EndpointMessageListener.java @@ -273,8 +273,8 @@ private void sendReply(Address replyDestination, Message message, Exchange excha String cid = message.getMessageProperties().getCorrelationId(); Object body = out.getBody(); Message msg; - if (body instanceof Message) { - msg = (Message) body; + if (body instanceof Message bodyMessage) { + msg = bodyMessage; } else { MessageProperties mp = endpoint.getMessagePropertiesConverter().toMessageProperties(exchange); mp.setCorrelationId(cid); diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQEndpoint.java b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQEndpoint.java index 65c3f7d8041ce..3b7befc08c589 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQEndpoint.java +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQEndpoint.java @@ -686,8 +686,8 @@ protected String parseArgsString(Map args, String key, String de } public void declareElements(AbstractMessageListenerContainer container) { - if (container instanceof MessageListenerContainer) { - AmqpAdmin admin = ((MessageListenerContainer) container).getAmqpAdmin(); + if (container instanceof MessageListenerContainer messageListenerContainer) { + AmqpAdmin admin = messageListenerContainer.getAmqpAdmin(); declareElements(container, admin); } } @@ -819,32 +819,32 @@ private void prepareDeadLetterQueueArgs(Map args) { private void prepareArgs(Map args) { // some arguments must be in numeric values so we need to fix this Object arg = args.get(SpringRabbitMQConstants.MAX_LENGTH); - if (arg instanceof String) { - args.put(SpringRabbitMQConstants.MAX_LENGTH, Long.parseLong((String) arg)); + if (arg instanceof String str) { + args.put(SpringRabbitMQConstants.MAX_LENGTH, Long.parseLong(str)); } arg = args.get(SpringRabbitMQConstants.MAX_LENGTH_BYTES); - if (arg instanceof String) { - args.put(SpringRabbitMQConstants.MAX_LENGTH_BYTES, Long.parseLong((String) arg)); + if (arg instanceof String str) { + args.put(SpringRabbitMQConstants.MAX_LENGTH_BYTES, Long.parseLong(str)); } arg = args.get(SpringRabbitMQConstants.MAX_PRIORITY); - if (arg instanceof String) { - args.put(SpringRabbitMQConstants.MAX_PRIORITY, Integer.parseInt((String) arg)); + if (arg instanceof String str) { + args.put(SpringRabbitMQConstants.MAX_PRIORITY, Integer.parseInt(str)); } arg = args.get(SpringRabbitMQConstants.DELIVERY_LIMIT); - if (arg instanceof String) { - args.put(SpringRabbitMQConstants.DELIVERY_LIMIT, Integer.parseInt((String) arg)); + if (arg instanceof String str) { + args.put(SpringRabbitMQConstants.DELIVERY_LIMIT, Integer.parseInt(str)); } arg = args.get(SpringRabbitMQConstants.MESSAGE_TTL); - if (arg instanceof String) { - args.put(SpringRabbitMQConstants.MESSAGE_TTL, Long.parseLong((String) arg)); + if (arg instanceof String str) { + args.put(SpringRabbitMQConstants.MESSAGE_TTL, Long.parseLong(str)); } arg = args.get(SpringRabbitMQConstants.EXPIRES); - if (arg instanceof String) { - args.put(SpringRabbitMQConstants.EXPIRES, Long.parseLong((String) arg)); + if (arg instanceof String str) { + args.put(SpringRabbitMQConstants.EXPIRES, Long.parseLong(str)); } arg = args.get(SpringRabbitMQConstants.SINGLE_ACTIVE_CONSUMER); - if (arg instanceof String) { - args.put(SpringRabbitMQConstants.SINGLE_ACTIVE_CONSUMER, Boolean.parseBoolean((String) arg)); + if (arg instanceof String str) { + args.put(SpringRabbitMQConstants.SINGLE_ACTIVE_CONSUMER, Boolean.parseBoolean(str)); } } diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQProducer.java b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQProducer.java index 78d9bc13477ef..e1252b4dcdc40 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQProducer.java +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQProducer.java @@ -182,8 +182,8 @@ protected boolean processInOut(Exchange exchange, AsyncCallback callback) { private Message getMessage(Exchange exchange) { Object body = exchange.getMessage().getBody(); Message msg; - if (body instanceof Message) { - msg = (Message) body; + if (body instanceof Message bodyMessage) { + msg = bodyMessage; } else { MessageProperties mp = getEndpoint().getMessagePropertiesConverter().toMessageProperties(exchange); msg = getEndpoint().getMessageConverter().toMessage(body, mp); From d5220bcdb4609537becb5a5b99b36ca471af27ee Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:36 +0000 Subject: [PATCH 12/14] (chores): fix SonarCloud S6201 in camel-aws Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../bedrock/agent/BedrockAgentProducer.java | 12 ++--- .../BedrockAgentRuntimeProducer.java | 4 +- .../aws2/bedrock/runtime/BedrockProducer.java | 12 ++--- .../aws/config/AWSConfigProducer.java | 15 ++---- .../aws/secretsmanager/SecretsDevConsole.java | 4 +- .../vault/CloudTrailReloadTriggerTask.java | 4 +- .../camel/component/aws/xray/XRayTracer.java | 9 ++-- .../decorators/TimerSegmentDecorator.java | 2 +- .../http/AbstractHttpSegmentDecorator.java | 12 ++--- .../camel/component/aws2/cw/Cw2Producer.java | 4 +- .../Ddb2JsonDataTypeTransformer.java | 12 ++--- .../component/aws2/ec2/AWS2EC2Producer.java | 52 +++++++++---------- .../aws2/eventbridge/EventbridgeProducer.java | 4 +- .../camel/component/aws2/mq/MQ2Producer.java | 24 ++++----- .../component/aws2/msk/MSK2Producer.java | 16 +++--- .../component/aws2/s3/utils/AWS2S3Utils.java | 4 +- .../component/aws2/sns/Sns2Producer.java | 12 ++--- .../component/aws2/sqs/Sqs2MessageHelper.java | 12 ++--- .../component/aws2/sts/STS2Producer.java | 9 ++-- .../aws2/translate/Translate2Producer.java | 4 +- 20 files changed, 108 insertions(+), 119 deletions(-) diff --git a/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agent/BedrockAgentProducer.java b/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agent/BedrockAgentProducer.java index fdc811365241c..06380c1827f1f 100644 --- a/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agent/BedrockAgentProducer.java +++ b/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agent/BedrockAgentProducer.java @@ -90,10 +90,10 @@ private void startIngestionJob(BedrockAgentClient bedrockAgentClient, Exchange e throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); - if (payload instanceof StartIngestionJobRequest) { + if (payload instanceof StartIngestionJobRequest startIngestionJobRequest) { StartIngestionJobResponse result; try { - result = bedrockAgentClient.startIngestionJob((StartIngestionJobRequest) payload); + result = bedrockAgentClient.startIngestionJob(startIngestionJobRequest); } catch (AwsServiceException ase) { LOG.trace("Start Ingestion Job command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -135,10 +135,10 @@ private void listIngestionJobs(BedrockAgentClient bedrockAgentClient, Exchange e throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); - if (payload instanceof ListIngestionJobsRequest) { + if (payload instanceof ListIngestionJobsRequest listIngestionJobsRequest) { ListIngestionJobsResponse result; try { - result = bedrockAgentClient.listIngestionJobs((ListIngestionJobsRequest) payload); + result = bedrockAgentClient.listIngestionJobs(listIngestionJobsRequest); } catch (AwsServiceException ase) { LOG.trace("Start Ingestion Job command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -180,10 +180,10 @@ private void getIngestionJob(BedrockAgentClient bedrockAgentClient, Exchange exc throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); - if (payload instanceof GetIngestionJobRequest) { + if (payload instanceof GetIngestionJobRequest getIngestionJobRequest) { GetIngestionJobResponse result; try { - result = bedrockAgentClient.getIngestionJob((GetIngestionJobRequest) payload); + result = bedrockAgentClient.getIngestionJob(getIngestionJobRequest); } catch (AwsServiceException ase) { LOG.trace("Get Ingestion Job command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; diff --git a/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agentruntime/BedrockAgentRuntimeProducer.java b/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agentruntime/BedrockAgentRuntimeProducer.java index 10b1796aad58d..ff55017c5f81b 100644 --- a/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agentruntime/BedrockAgentRuntimeProducer.java +++ b/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agentruntime/BedrockAgentRuntimeProducer.java @@ -84,10 +84,10 @@ private void retrieveAndGenerate(BedrockAgentRuntimeClient bedrockAgentRuntimeCl throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); - if (payload instanceof RetrieveAndGenerateRequest) { + if (payload instanceof RetrieveAndGenerateRequest retrieveAndGenerateRequest) { RetrieveAndGenerateResponse result; try { - result = bedrockAgentRuntimeClient.retrieveAndGenerate((RetrieveAndGenerateRequest) payload); + result = bedrockAgentRuntimeClient.retrieveAndGenerate(retrieveAndGenerateRequest); } catch (AwsServiceException ase) { LOG.trace("Retrieve and Generate command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; diff --git a/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/runtime/BedrockProducer.java b/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/runtime/BedrockProducer.java index cac050a892a07..34596b9d242b1 100644 --- a/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/runtime/BedrockProducer.java +++ b/components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/runtime/BedrockProducer.java @@ -122,10 +122,10 @@ public BedrockEndpoint getEndpoint() { private void invokeTextModel(BedrockRuntimeClient bedrockRuntimeClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); - if (payload instanceof InvokeModelRequest) { + if (payload instanceof InvokeModelRequest invokeModelRequest) { InvokeModelResponse result; try { - result = bedrockRuntimeClient.invokeModel((InvokeModelRequest) payload); + result = bedrockRuntimeClient.invokeModel(invokeModelRequest); } catch (AwsServiceException ase) { LOG.trace("Invoke Model command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -166,10 +166,10 @@ private void invokeTextModel(BedrockRuntimeClient bedrockRuntimeClient, Exchange private void invokeImageModel(BedrockRuntimeClient bedrockRuntimeClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); - if (payload instanceof InvokeModelRequest) { + if (payload instanceof InvokeModelRequest invokeModelRequest) { InvokeModelResponse result; try { - result = bedrockRuntimeClient.invokeModel((InvokeModelRequest) payload); + result = bedrockRuntimeClient.invokeModel(invokeModelRequest); } catch (AwsServiceException ase) { LOG.trace("Invoke Image Model command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -215,10 +215,10 @@ private void invokeEmbeddingsModel(BedrockRuntimeClient bedrockRuntimeClient, Ex throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); - if (payload instanceof InvokeModelRequest) { + if (payload instanceof InvokeModelRequest invokeModelRequest) { InvokeModelResponse result; try { - result = bedrockRuntimeClient.invokeModel((InvokeModelRequest) payload); + result = bedrockRuntimeClient.invokeModel(invokeModelRequest); } catch (AwsServiceException ase) { LOG.trace("Invoke Image Model command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; diff --git a/components/camel-aws/camel-aws-config/src/main/java/org/apache/camel/component/aws/config/AWSConfigProducer.java b/components/camel-aws/camel-aws-config/src/main/java/org/apache/camel/component/aws/config/AWSConfigProducer.java index 5d107db63980f..b7a6793caa1eb 100644 --- a/components/camel-aws/camel-aws-config/src/main/java/org/apache/camel/component/aws/config/AWSConfigProducer.java +++ b/components/camel-aws/camel-aws-config/src/main/java/org/apache/camel/component/aws/config/AWSConfigProducer.java @@ -99,10 +99,9 @@ public AWSConfigEndpoint getEndpoint() { private void putConfigRule(ConfigClient configClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof PutConfigRuleRequest) { + if (payload instanceof PutConfigRuleRequest request) { PutConfigRuleResponse result; try { - PutConfigRuleRequest request = (PutConfigRuleRequest) payload; result = configClient.putConfigRule(request); } catch (AwsServiceException ase) { LOG.trace("Put Config rule command returned the error code {}", ase.awsErrorDetails().errorCode()); @@ -146,10 +145,9 @@ private void putConfigRule(ConfigClient configClient, Exchange exchange) throws private void removeConfigRule(ConfigClient configClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof DeleteConfigRuleRequest) { + if (payload instanceof DeleteConfigRuleRequest request) { DeleteConfigRuleResponse result; try { - DeleteConfigRuleRequest request = (DeleteConfigRuleRequest) payload; result = configClient.deleteConfigRule(request); } catch (AwsServiceException ase) { LOG.trace("Delete Config rule command returned the error code {}", ase.awsErrorDetails().errorCode()); @@ -182,10 +180,9 @@ private void removeConfigRule(ConfigClient configClient, Exchange exchange) thro private void describeRuleCompliance(ConfigClient configClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof DescribeComplianceByConfigRuleRequest) { + if (payload instanceof DescribeComplianceByConfigRuleRequest request) { DescribeComplianceByConfigRuleResponse result; try { - DescribeComplianceByConfigRuleRequest request = (DescribeComplianceByConfigRuleRequest) payload; result = configClient.describeComplianceByConfigRule(request); } catch (AwsServiceException ase) { LOG.trace("Describe Compliance by Config rule command returned the error code {}", @@ -218,10 +215,9 @@ private void describeRuleCompliance(ConfigClient configClient, Exchange exchange private void putConformancePack(ConfigClient configClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof PutConformancePackRequest) { + if (payload instanceof PutConformancePackRequest request) { PutConformancePackResponse result; try { - PutConformancePackRequest request = (PutConformancePackRequest) payload; result = configClient.putConformancePack(request); } catch (AwsServiceException ase) { LOG.trace("Put Conformance Pack command returned the error code {}", ase.awsErrorDetails().errorCode()); @@ -269,10 +265,9 @@ private void putConformancePack(ConfigClient configClient, Exchange exchange) th private void removeConformancePack(ConfigClient configClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof DeleteConformancePackRequest) { + if (payload instanceof DeleteConformancePackRequest request) { DeleteConformancePackResponse result; try { - DeleteConformancePackRequest request = (DeleteConformancePackRequest) payload; result = configClient.deleteConformancePack(request); } catch (AwsServiceException ase) { LOG.trace("Remove Conformance Pack rule command returned the error code {}", diff --git a/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/SecretsDevConsole.java b/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/SecretsDevConsole.java index 62316d58e7e0b..29f97661d4389 100644 --- a/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/SecretsDevConsole.java +++ b/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/SecretsDevConsole.java @@ -49,8 +49,8 @@ protected void doStart() throws Exception { if (getCamelContext().getPropertiesComponent().hasPropertiesFunction("aws")) { PropertiesFunction pf = getCamelContext().getPropertiesComponent().getPropertiesFunction("aws"); - if (pf instanceof SecretsManagerPropertiesFunction) { - propertiesFunction = (SecretsManagerPropertiesFunction) pf; + if (pf instanceof SecretsManagerPropertiesFunction secretsManagerPropertiesFunction) { + propertiesFunction = secretsManagerPropertiesFunction; } } AwsVaultConfiguration aws = getCamelContext().getVaultConfiguration().getAwsVaultConfiguration(); diff --git a/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTask.java b/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTask.java index e64edf3623fc5..5c194115f0ea2 100644 --- a/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTask.java +++ b/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTask.java @@ -163,8 +163,8 @@ protected void doStart() throws Exception { // auto-detect secrets in-use PropertiesComponent pc = camelContext.getPropertiesComponent(); PropertiesFunction pf = pc.getPropertiesFunction("aws"); - if (pf instanceof SecretsManagerPropertiesFunction) { - propertiesFunction = (SecretsManagerPropertiesFunction) pf; + if (pf instanceof SecretsManagerPropertiesFunction secretsManagerPropertiesFunction) { + propertiesFunction = secretsManagerPropertiesFunction; LOG.debug("Auto-detecting secrets from properties-function: {}", pf.getName()); } // specific secrets diff --git a/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/XRayTracer.java b/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/XRayTracer.java index eaac2a6921d05..3f93270ff8ba1 100644 --- a/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/XRayTracer.java +++ b/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/XRayTracer.java @@ -264,8 +264,7 @@ private final class XRayEventNotifier extends EventNotifierSupport { @Override public void notify(CamelEvent event) throws Exception { - if (event instanceof ExchangeSendingEvent) { - ExchangeSendingEvent ese = (ExchangeSendingEvent) event; + if (event instanceof ExchangeSendingEvent ese) { if (LOG.isTraceEnabled()) { LOG.trace("-> {} - target: {} (routeId: {})", event.getClass().getSimpleName(), ese.getEndpoint(), @@ -304,19 +303,17 @@ public void notify(CamelEvent event) throws Exception { LOG.trace("Ignoring creation of XRay subsegment as no segment exists in the current thread"); } - } else if (event instanceof ExchangeSentEvent) { - ExchangeSentEvent ese = (ExchangeSentEvent) event; + } else if (event instanceof ExchangeSentEvent ese) { if (LOG.isTraceEnabled()) { LOG.trace("-> {} - target: {} (routeId: {})", event.getClass().getSimpleName(), ese.getEndpoint(), ese.getExchange().getFromRouteId()); } Entity entity = getTraceEntityFromExchange(ese.getExchange()); - if (entity instanceof Subsegment) { + if (entity instanceof Subsegment subsegment) { AWSXRay.setTraceEntity(entity); SegmentDecorator sd = getSegmentDecorator(ese.getEndpoint()); try { - Subsegment subsegment = (Subsegment) entity; sd.post(subsegment, ese.getExchange(), ese.getEndpoint()); subsegment.close(); if (LOG.isTraceEnabled()) { diff --git a/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/TimerSegmentDecorator.java b/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/TimerSegmentDecorator.java index d79ee70196b19..2acf903c163df 100644 --- a/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/TimerSegmentDecorator.java +++ b/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/TimerSegmentDecorator.java @@ -29,6 +29,6 @@ public String getComponent() { @Override public String getOperationName(Exchange exchange, Endpoint endpoint) { Object name = exchange.getProperty(Exchange.TIMER_NAME); - return name instanceof String ? (String) name : super.getOperationName(exchange, endpoint); + return name instanceof String stringName ? stringName : super.getOperationName(exchange, endpoint); } } diff --git a/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/http/AbstractHttpSegmentDecorator.java b/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/http/AbstractHttpSegmentDecorator.java index eac37e5b112ae..03e5d98d89d9a 100644 --- a/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/http/AbstractHttpSegmentDecorator.java +++ b/components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/http/AbstractHttpSegmentDecorator.java @@ -55,8 +55,8 @@ public void post(Entity segment, Exchange exchange, Endpoint endpoint) { protected String getHttpMethod(Exchange exchange, Endpoint endpoint) { // 1. Use method provided in header. Object method = exchange.getIn().getHeader(Exchange.HTTP_METHOD); - if (method instanceof String) { - return (String) method; + if (method instanceof String stringMethod) { + return stringMethod; } // 2. GET if query string is provided in header. @@ -80,12 +80,12 @@ protected String getHttpMethod(Exchange exchange, Endpoint endpoint) { protected String getHttpUrl(Exchange exchange, Endpoint endpoint) { Object url = exchange.getIn().getHeader(Exchange.HTTP_URL); - if (url instanceof String) { - return (String) url; + if (url instanceof String stringUrl) { + return stringUrl; } else { Object uri = exchange.getIn().getHeader(Exchange.HTTP_URI); - if (uri instanceof String) { - return (String) uri; + if (uri instanceof String stringUri) { + return stringUri; } else { // Try to obtain from endpoint int index = endpoint.getEndpointUri().lastIndexOf("http:"); diff --git a/components/camel-aws/camel-aws2-cw/src/main/java/org/apache/camel/component/aws2/cw/Cw2Producer.java b/components/camel-aws/camel-aws2-cw/src/main/java/org/apache/camel/component/aws2/cw/Cw2Producer.java index 6747af3f97d3a..77e14c29008a1 100644 --- a/components/camel-aws/camel-aws2-cw/src/main/java/org/apache/camel/component/aws2/cw/Cw2Producer.java +++ b/components/camel-aws/camel-aws2-cw/src/main/java/org/apache/camel/component/aws2/cw/Cw2Producer.java @@ -216,8 +216,8 @@ private List getMetricData(Exchange exchange) { return CastUtils.cast((List) body); } - if (body instanceof MetricDatum) { - return Arrays.asList((MetricDatum) body); + if (body instanceof MetricDatum metricDatum) { + return Arrays.asList(metricDatum); } MetricDatum.Builder metricDatum = MetricDatum.builder().metricName(determineName(exchange)) diff --git a/components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddb/transform/Ddb2JsonDataTypeTransformer.java b/components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddb/transform/Ddb2JsonDataTypeTransformer.java index 5cb3bdbf4ddf7..123c85a030662 100644 --- a/components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddb/transform/Ddb2JsonDataTypeTransformer.java +++ b/components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddb/transform/Ddb2JsonDataTypeTransformer.java @@ -202,16 +202,16 @@ private static AttributeValue getAttributeValue(Object value) { return AttributeValue.builder().n(value.toString()).build(); } - if (value instanceof Boolean) { - return AttributeValue.builder().bool((Boolean) value).build(); + if (value instanceof Boolean booleanValue) { + return AttributeValue.builder().bool(booleanValue).build(); } - if (value instanceof String[]) { - return AttributeValue.builder().ss((String[]) value).build(); + if (value instanceof String[] stringArray) { + return AttributeValue.builder().ss(stringArray).build(); } - if (value instanceof int[]) { - return AttributeValue.builder().ns(Stream.of((int[]) value).map(Object::toString).collect(Collectors.toList())) + if (value instanceof int[] intArray) { + return AttributeValue.builder().ns(Stream.of(intArray).map(Object::toString).collect(Collectors.toList())) .build(); } diff --git a/components/camel-aws/camel-aws2-ec2/src/main/java/org/apache/camel/component/aws2/ec2/AWS2EC2Producer.java b/components/camel-aws/camel-aws2-ec2/src/main/java/org/apache/camel/component/aws2/ec2/AWS2EC2Producer.java index 83b4d6d6c39bd..f0c99eb95d351 100644 --- a/components/camel-aws/camel-aws2-ec2/src/main/java/org/apache/camel/component/aws2/ec2/AWS2EC2Producer.java +++ b/components/camel-aws/camel-aws2-ec2/src/main/java/org/apache/camel/component/aws2/ec2/AWS2EC2Producer.java @@ -149,10 +149,10 @@ private void createAndRunInstance(Ec2Client ec2Client, Exchange exchange) throws InstanceType instanceType; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof RunInstancesRequest) { + if (payload instanceof RunInstancesRequest runInstancesRequest) { RunInstancesResponse result; try { - result = ec2Client.runInstances((RunInstancesRequest) payload); + result = ec2Client.runInstances(runInstancesRequest); } catch (AwsServiceException ase) { LOG.trace("Run Instances command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -240,15 +240,15 @@ private void startInstances(Ec2Client ec2Client, Exchange exchange) throws Inval Collection instanceIds; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof StartInstancesRequest) { + if (payload instanceof StartInstancesRequest startInstancesRequest) { StartInstancesResponse result; try { - result = ec2Client.startInstances((StartInstancesRequest) payload); + result = ec2Client.startInstances(startInstancesRequest); } catch (AwsServiceException ase) { LOG.trace("Start Instances command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } - LOG.trace("Starting instances with Ids [{}] ", ((StartInstancesRequest) payload).instanceIds()); + LOG.trace("Starting instances with Ids [{}] ", startInstancesRequest.instanceIds()); Message message = getMessageForResponse(exchange); message.setBody(result); } @@ -282,15 +282,15 @@ private void stopInstances(Ec2Client ec2Client, Exchange exchange) throws Invali Collection instanceIds; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof StopInstancesRequest) { + if (payload instanceof StopInstancesRequest stopInstancesRequest) { StopInstancesResponse result; try { - result = ec2Client.stopInstances((StopInstancesRequest) payload); + result = ec2Client.stopInstances(stopInstancesRequest); } catch (AwsServiceException ase) { LOG.trace("Stop Instances command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } - LOG.trace("Stopping instances with Ids [{}] ", ((StopInstancesRequest) payload).instanceIds()); + LOG.trace("Stopping instances with Ids [{}] ", stopInstancesRequest.instanceIds()); Message message = getMessageForResponse(exchange); message.setBody(result); } @@ -324,15 +324,15 @@ private void terminateInstances(Ec2Client ec2Client, Exchange exchange) throws I Collection instanceIds; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof TerminateInstancesRequest) { + if (payload instanceof TerminateInstancesRequest terminateInstancesRequest) { TerminateInstancesResponse result; try { - result = ec2Client.terminateInstances((TerminateInstancesRequest) payload); + result = ec2Client.terminateInstances(terminateInstancesRequest); } catch (AwsServiceException ase) { LOG.trace("Terminate Instances command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } - LOG.trace("Terminating instances with Ids [{}] ", ((TerminateInstancesRequest) payload).instanceIds()); + LOG.trace("Terminating instances with Ids [{}] ", terminateInstancesRequest.instanceIds()); Message message = getMessageForResponse(exchange); message.setBody(result); } @@ -426,10 +426,10 @@ private void rebootInstances(Ec2Client ec2Client, Exchange exchange) throws Inva Collection instanceIds; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof RebootInstancesRequest) { + if (payload instanceof RebootInstancesRequest rebootInstancesRequest) { try { - LOG.trace("Rebooting instances with Ids [{}] ", ((RebootInstancesRequest) payload).instanceIds()); - ec2Client.rebootInstances((RebootInstancesRequest) payload); + LOG.trace("Rebooting instances with Ids [{}] ", rebootInstancesRequest.instanceIds()); + ec2Client.rebootInstances(rebootInstancesRequest); } catch (AwsServiceException ase) { LOG.trace("Reboot Instances command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -461,15 +461,15 @@ private void monitorInstances(Ec2Client ec2Client, Exchange exchange) throws Inv Collection instanceIds; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof MonitorInstancesRequest) { + if (payload instanceof MonitorInstancesRequest monitorInstancesRequest) { MonitorInstancesResponse result; try { - result = ec2Client.monitorInstances((MonitorInstancesRequest) payload); + result = ec2Client.monitorInstances(monitorInstancesRequest); } catch (AwsServiceException ase) { LOG.trace("Monitor Instances command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } - LOG.trace("Start Monitoring instances with Ids [{}] ", ((MonitorInstancesRequest) payload).instanceIds()); + LOG.trace("Start Monitoring instances with Ids [{}] ", monitorInstancesRequest.instanceIds()); Message message = getMessageForResponse(exchange); message.setBody(result); } @@ -503,15 +503,15 @@ private void unmonitorInstances(Ec2Client ec2Client, Exchange exchange) throws I Collection instanceIds; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof UnmonitorInstancesRequest) { + if (payload instanceof UnmonitorInstancesRequest unmonitorInstancesRequest) { UnmonitorInstancesResponse result; try { - result = ec2Client.unmonitorInstances((UnmonitorInstancesRequest) payload); + result = ec2Client.unmonitorInstances(unmonitorInstancesRequest); } catch (AwsServiceException ase) { LOG.trace("Unmonitor Instances command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } - LOG.trace("Stop Monitoring instances with Ids [{}] ", ((UnmonitorInstancesRequest) payload).instanceIds()); + LOG.trace("Stop Monitoring instances with Ids [{}] ", unmonitorInstancesRequest.instanceIds()); Message message = getMessageForResponse(exchange); message.setBody(result); } @@ -545,15 +545,15 @@ private void createTags(Ec2Client ec2Client, Exchange exchange) throws InvalidPa Collection instanceIds; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof CreateTagsRequest) { + if (payload instanceof CreateTagsRequest createTagsRequest) { CreateTagsResponse result; try { - result = ec2Client.createTags((CreateTagsRequest) payload); + result = ec2Client.createTags(createTagsRequest); } catch (AwsServiceException ase) { LOG.trace("Create tags command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } - LOG.trace("Created tags [{}] ", ((CreateTagsRequest) payload).tags()); + LOG.trace("Created tags [{}] ", createTagsRequest.tags()); Message message = getMessageForResponse(exchange); message.setBody(result); } @@ -594,15 +594,15 @@ private void deleteTags(Ec2Client ec2Client, Exchange exchange) throws InvalidPa Collection instanceIds; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof DeleteTagsRequest) { + if (payload instanceof DeleteTagsRequest deleteTagsRequest) { DeleteTagsResponse result; try { - result = ec2Client.deleteTags((DeleteTagsRequest) payload); + result = ec2Client.deleteTags(deleteTagsRequest); } catch (AwsServiceException ase) { LOG.trace("Delete tags command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } - LOG.trace("Delete tags [{}] ", ((DeleteTagsRequest) payload).tags()); + LOG.trace("Delete tags [{}] ", deleteTagsRequest.tags()); Message message = getMessageForResponse(exchange); message.setBody(result); } diff --git a/components/camel-aws/camel-aws2-eventbridge/src/main/java/org/apache/camel/component/aws2/eventbridge/EventbridgeProducer.java b/components/camel-aws/camel-aws2-eventbridge/src/main/java/org/apache/camel/component/aws2/eventbridge/EventbridgeProducer.java index faa1f8654284e..1d4a9b5af4f62 100644 --- a/components/camel-aws/camel-aws2-eventbridge/src/main/java/org/apache/camel/component/aws2/eventbridge/EventbridgeProducer.java +++ b/components/camel-aws/camel-aws2-eventbridge/src/main/java/org/apache/camel/component/aws2/eventbridge/EventbridgeProducer.java @@ -144,10 +144,10 @@ public String toString() { private void putRule(EventBridgeClient eventbridgeClient, Exchange exchange) throws InvalidPayloadException, IOException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof PutRuleRequest) { + if (payload instanceof PutRuleRequest putRuleRequest) { PutRuleResponse result; try { - result = eventbridgeClient.putRule((PutRuleRequest) payload); + result = eventbridgeClient.putRule(putRuleRequest); } catch (AwsServiceException ase) { LOG.trace("PutRule command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; diff --git a/components/camel-aws/camel-aws2-mq/src/main/java/org/apache/camel/component/aws2/mq/MQ2Producer.java b/components/camel-aws/camel-aws2-mq/src/main/java/org/apache/camel/component/aws2/mq/MQ2Producer.java index 44bb421f80dc3..a4a6fa103073c 100644 --- a/components/camel-aws/camel-aws2-mq/src/main/java/org/apache/camel/component/aws2/mq/MQ2Producer.java +++ b/components/camel-aws/camel-aws2-mq/src/main/java/org/apache/camel/component/aws2/mq/MQ2Producer.java @@ -119,10 +119,10 @@ public MQ2Endpoint getEndpoint() { private void listBrokers(MqClient mqClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof ListBrokersRequest) { + if (payload instanceof ListBrokersRequest listBrokersRequest) { ListBrokersResponse result; try { - result = mqClient.listBrokers((ListBrokersRequest) payload); + result = mqClient.listBrokers(listBrokersRequest); } catch (AwsServiceException ase) { LOG.trace("List Brokers command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -167,10 +167,10 @@ private void createBroker(MqClient mqClient, Exchange exchange) throws InvalidPa List users; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof CreateBrokerRequest) { + if (payload instanceof CreateBrokerRequest createBrokerRequest) { CreateBrokerResponse result; try { - result = mqClient.createBroker((CreateBrokerRequest) payload); + result = mqClient.createBroker(createBrokerRequest); } catch (AwsServiceException ase) { LOG.trace("Create Broker command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -240,10 +240,10 @@ private void deleteBroker(MqClient mqClient, Exchange exchange) throws InvalidPa String brokerId; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof DeleteBrokerRequest) { + if (payload instanceof DeleteBrokerRequest deleteBrokerRequest) { DeleteBrokerResponse result; try { - result = mqClient.deleteBroker((DeleteBrokerRequest) payload); + result = mqClient.deleteBroker(deleteBrokerRequest); } catch (AwsServiceException ase) { LOG.trace("Delete Broker command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -275,10 +275,10 @@ private void rebootBroker(MqClient mqClient, Exchange exchange) throws InvalidPa String brokerId; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof RebootBrokerRequest) { + if (payload instanceof RebootBrokerRequest rebootBrokerRequest) { RebootBrokerResponse result; try { - result = mqClient.rebootBroker((RebootBrokerRequest) payload); + result = mqClient.rebootBroker(rebootBrokerRequest); } catch (AwsServiceException ase) { LOG.trace("Reboot Broker command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -311,10 +311,10 @@ private void updateBroker(MqClient mqClient, Exchange exchange) throws InvalidPa ConfigurationId configurationId; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof UpdateBrokerRequest) { + if (payload instanceof UpdateBrokerRequest updateBrokerRequest) { UpdateBrokerResponse result; try { - result = mqClient.updateBroker((UpdateBrokerRequest) payload); + result = mqClient.updateBroker(updateBrokerRequest); } catch (AwsServiceException ase) { LOG.trace("Update Broker command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -352,10 +352,10 @@ private void describeBroker(MqClient mqClient, Exchange exchange) throws Invalid String brokerId; if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof DescribeBrokerRequest) { + if (payload instanceof DescribeBrokerRequest describeBrokerRequest) { DescribeBrokerResponse result; try { - result = mqClient.describeBroker((DescribeBrokerRequest) payload); + result = mqClient.describeBroker(describeBrokerRequest); } catch (AwsServiceException ase) { LOG.trace("Reboot Broker command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; diff --git a/components/camel-aws/camel-aws2-msk/src/main/java/org/apache/camel/component/aws2/msk/MSK2Producer.java b/components/camel-aws/camel-aws2-msk/src/main/java/org/apache/camel/component/aws2/msk/MSK2Producer.java index 73aec28dc6ee3..84edeb597ff39 100644 --- a/components/camel-aws/camel-aws2-msk/src/main/java/org/apache/camel/component/aws2/msk/MSK2Producer.java +++ b/components/camel-aws/camel-aws2-msk/src/main/java/org/apache/camel/component/aws2/msk/MSK2Producer.java @@ -103,10 +103,10 @@ public MSK2Endpoint getEndpoint() { private void listClusters(KafkaClient mskClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof ListClustersRequest) { + if (payload instanceof ListClustersRequest listClustersRequest) { ListClustersResponse result; try { - result = mskClient.listClusters((ListClustersRequest) payload); + result = mskClient.listClusters(listClustersRequest); } catch (AwsServiceException ase) { LOG.trace("List Clusters command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -147,10 +147,10 @@ private void listClusters(KafkaClient mskClient, Exchange exchange) throws Inval private void createCluster(KafkaClient mskClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof CreateClusterRequest) { + if (payload instanceof CreateClusterRequest createClusterRequest) { CreateClusterResponse response; try { - response = mskClient.createCluster((CreateClusterRequest) payload); + response = mskClient.createCluster(createClusterRequest); } catch (AwsServiceException ase) { LOG.trace("Create Cluster command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -202,10 +202,10 @@ private void createCluster(KafkaClient mskClient, Exchange exchange) throws Inva private void deleteCluster(KafkaClient mskClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof DeleteClusterRequest) { + if (payload instanceof DeleteClusterRequest deleteClusterRequest) { DeleteClusterResponse result; try { - result = mskClient.deleteCluster((DeleteClusterRequest) payload); + result = mskClient.deleteCluster(deleteClusterRequest); } catch (AwsServiceException ase) { LOG.trace("Delete Cluster command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; @@ -236,10 +236,10 @@ private void deleteCluster(KafkaClient mskClient, Exchange exchange) throws Inva private void describeCluster(KafkaClient mskClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof DescribeClusterRequest) { + if (payload instanceof DescribeClusterRequest describeClusterRequest) { DescribeClusterResponse result; try { - result = mskClient.describeCluster((DescribeClusterRequest) payload); + result = mskClient.describeCluster(describeClusterRequest); } catch (AwsServiceException ase) { LOG.trace("Delete Cluster command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; diff --git a/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/utils/AWS2S3Utils.java b/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/utils/AWS2S3Utils.java index 37c008ca8f9af..9fc8ba221f660 100644 --- a/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/utils/AWS2S3Utils.java +++ b/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/utils/AWS2S3Utils.java @@ -91,8 +91,8 @@ public static String determineFileName(String keyName) { } public static long determineLengthInputStream(InputStream is) throws IOException { - if (is instanceof StreamCache) { - long len = ((StreamCache) is).length(); + if (is instanceof StreamCache streamCache) { + long len = streamCache.length(); if (len > 0) { return len; } diff --git a/components/camel-aws/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/Sns2Producer.java b/components/camel-aws/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/Sns2Producer.java index 6bad442841481..ed7a286613635 100644 --- a/components/camel-aws/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/Sns2Producer.java +++ b/components/camel-aws/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/Sns2Producer.java @@ -126,25 +126,25 @@ Map translateAttributes(Map heade // message attribute if (!headerFilterStrategy.applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), exchange)) { Object value = entry.getValue(); - if (value instanceof String && !((String) value).isEmpty()) { + if (value instanceof String stringValue && !stringValue.isEmpty()) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_STRING); - mav.stringValue((String) value); + mav.stringValue(stringValue); result.put(entry.getKey(), mav.build()); } else if (value instanceof Number) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_STRING); mav.stringValue(value.toString()); result.put(entry.getKey(), mav.build()); - } else if (value instanceof ByteBuffer) { + } else if (value instanceof ByteBuffer byteBuffer) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_BINARY); - mav.binaryValue(SdkBytes.fromByteBuffer((ByteBuffer) value)); + mav.binaryValue(SdkBytes.fromByteBuffer(byteBuffer)); result.put(entry.getKey(), mav.build()); - } else if (value instanceof byte[]) { + } else if (value instanceof byte[] byteArray) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_BINARY); - mav.binaryValue(SdkBytes.fromByteArray((byte[]) value)); + mav.binaryValue(SdkBytes.fromByteArray(byteArray)); result.put(entry.getKey(), mav.build()); } else if (value instanceof Date) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); diff --git a/components/camel-aws/camel-aws2-sqs/src/main/java/org/apache/camel/component/aws2/sqs/Sqs2MessageHelper.java b/components/camel-aws/camel-aws2-sqs/src/main/java/org/apache/camel/component/aws2/sqs/Sqs2MessageHelper.java index 32fc2aa0db4bb..18963f7eab971 100644 --- a/components/camel-aws/camel-aws2-sqs/src/main/java/org/apache/camel/component/aws2/sqs/Sqs2MessageHelper.java +++ b/components/camel-aws/camel-aws2-sqs/src/main/java/org/apache/camel/component/aws2/sqs/Sqs2MessageHelper.java @@ -31,20 +31,20 @@ private Sqs2MessageHelper() { } public static MessageAttributeValue toMessageAttributeValue(Object value) { - if (value instanceof String && !((String) value).isEmpty()) { + if (value instanceof String stringValue && !stringValue.isEmpty()) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_STRING); - mav.stringValue((String) value); + mav.stringValue(stringValue); return mav.build(); - } else if (value instanceof ByteBuffer) { + } else if (value instanceof ByteBuffer byteBuffer) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_BINARY); - mav.binaryValue(SdkBytes.fromByteBuffer((ByteBuffer) value)); + mav.binaryValue(SdkBytes.fromByteBuffer(byteBuffer)); return mav.build(); - } else if (value instanceof byte[]) { + } else if (value instanceof byte[] byteArray) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); mav.dataType(TYPE_BINARY); - mav.binaryValue(SdkBytes.fromByteArray((byte[]) value)); + mav.binaryValue(SdkBytes.fromByteArray(byteArray)); return mav.build(); } else if (value instanceof Boolean) { MessageAttributeValue.Builder mav = MessageAttributeValue.builder(); diff --git a/components/camel-aws/camel-aws2-sts/src/main/java/org/apache/camel/component/aws2/sts/STS2Producer.java b/components/camel-aws/camel-aws2-sts/src/main/java/org/apache/camel/component/aws2/sts/STS2Producer.java index 8b2c040e5d6ea..b6c288a71f9e0 100644 --- a/components/camel-aws/camel-aws2-sts/src/main/java/org/apache/camel/component/aws2/sts/STS2Producer.java +++ b/components/camel-aws/camel-aws2-sts/src/main/java/org/apache/camel/component/aws2/sts/STS2Producer.java @@ -93,10 +93,9 @@ public STS2Endpoint getEndpoint() { private void assumeRole(StsClient stsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof AssumeRoleRequest) { + if (payload instanceof AssumeRoleRequest request) { AssumeRoleResponse result; try { - AssumeRoleRequest request = (AssumeRoleRequest) payload; result = stsClient.assumeRole(request); } catch (AwsServiceException ase) { LOG.trace("Assume Role command returned the error code {}", ase.awsErrorDetails().errorCode()); @@ -148,10 +147,9 @@ private void assumeRole(StsClient stsClient, Exchange exchange) throws InvalidPa private void getSessionToken(StsClient stsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof GetSessionTokenRequest) { + if (payload instanceof GetSessionTokenRequest request) { GetSessionTokenResponse result; try { - GetSessionTokenRequest request = (GetSessionTokenRequest) payload; result = stsClient.getSessionToken(request); } catch (AwsServiceException ase) { LOG.trace("Get Session Token command returned the error code {}", ase.awsErrorDetails().errorCode()); @@ -183,10 +181,9 @@ private void getSessionToken(StsClient stsClient, Exchange exchange) throws Inva private void getFederationToken(StsClient stsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof GetFederationTokenRequest) { + if (payload instanceof GetFederationTokenRequest request) { GetFederationTokenResponse result; try { - GetFederationTokenRequest request = (GetFederationTokenRequest) payload; result = stsClient.getFederationToken(request); } catch (AwsServiceException ase) { LOG.trace("Get Federation Token command returned the error code {}", ase.awsErrorDetails().errorCode()); diff --git a/components/camel-aws/camel-aws2-translate/src/main/java/org/apache/camel/component/aws2/translate/Translate2Producer.java b/components/camel-aws/camel-aws2-translate/src/main/java/org/apache/camel/component/aws2/translate/Translate2Producer.java index 289b4dd36ddfa..c94175afe28d1 100644 --- a/components/camel-aws/camel-aws2-translate/src/main/java/org/apache/camel/component/aws2/translate/Translate2Producer.java +++ b/components/camel-aws/camel-aws2-translate/src/main/java/org/apache/camel/component/aws2/translate/Translate2Producer.java @@ -90,10 +90,10 @@ public Translate2Endpoint getEndpoint() { private void translateText(TranslateClient translateClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); - if (payload instanceof TranslateTextRequest) { + if (payload instanceof TranslateTextRequest translateTextRequest) { TranslateTextResponse result; try { - result = translateClient.translateText((TranslateTextRequest) payload); + result = translateClient.translateText(translateTextRequest); } catch (AwsServiceException ase) { LOG.trace("Translate Text command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; From 69838ca4af493b8995c81028120b876c1bff8c24 Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:36 +0000 Subject: [PATCH 13/14] (chores): fix SonarCloud S6201 in camel-azure Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../client/FunctionsInvocationClient.java | 8 +++---- .../azure/servicebus/ServiceBusProducer.java | 24 +++++++++---------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/components/camel-azure/camel-azure-functions/src/main/java/org/apache/camel/component/azure/functions/client/FunctionsInvocationClient.java b/components/camel-azure/camel-azure-functions/src/main/java/org/apache/camel/component/azure/functions/client/FunctionsInvocationClient.java index 6a2935924df17..979122cbdc855 100644 --- a/components/camel-azure/camel-azure-functions/src/main/java/org/apache/camel/component/azure/functions/client/FunctionsInvocationClient.java +++ b/components/camel-azure/camel-azure-functions/src/main/java/org/apache/camel/component/azure/functions/client/FunctionsInvocationClient.java @@ -122,10 +122,10 @@ public FunctionInvocationResponse invoke(String url, String method, Object body, } private String convertBodyToString(Object body) { - if (body instanceof String) { - return (String) body; - } else if (body instanceof byte[]) { - return new String((byte[]) body, StandardCharsets.UTF_8); + if (body instanceof String string) { + return string; + } else if (body instanceof byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); } else { // For other objects, use toString (caller should serialize to JSON if needed) return body.toString(); diff --git a/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusProducer.java b/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusProducer.java index 5169ef67324b1..48794e7e51711 100644 --- a/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusProducer.java +++ b/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusProducer.java @@ -191,12 +191,12 @@ private List convertBodyToList(final Iterable inputBody) { private Object convertBodyToBinary(Exchange exchange) { Object body = exchange.getMessage().getBody(); - if (body instanceof InputStream) { - return BinaryData.fromStream((InputStream) body); - } else if (body instanceof Path) { - return BinaryData.fromFile((Path) body); - } else if (body instanceof File) { - return BinaryData.fromFile(((File) body).toPath()); + if (body instanceof InputStream inputStream) { + return BinaryData.fromStream(inputStream); + } else if (body instanceof Path path) { + return BinaryData.fromFile(path); + } else if (body instanceof File file) { + return BinaryData.fromFile(file.toPath()); } else { return BinaryData.fromBytes(exchange.getMessage().getBody(byte[].class)); } @@ -207,12 +207,12 @@ private Object convertMessageBody(Object inputBody) { if (inputBody instanceof BinaryData) { return inputBody; } else if (getConfiguration().isBinary()) { - if (inputBody instanceof InputStream) { - return BinaryData.fromStream((InputStream) inputBody); - } else if (inputBody instanceof Path) { - return BinaryData.fromFile((Path) inputBody); - } else if (inputBody instanceof File) { - return BinaryData.fromFile(((File) inputBody).toPath()); + if (inputBody instanceof InputStream inputStream) { + return BinaryData.fromStream(inputStream); + } else if (inputBody instanceof Path path) { + return BinaryData.fromFile(path); + } else if (inputBody instanceof File file) { + return BinaryData.fromFile(file.toPath()); } else { return typeConverter.convertTo(byte[].class, inputBody); } From 8158f133919f4003e0c97a4211e1c01b7e0b7deb Mon Sep 17 00:00:00 2001 From: Otavio Rodolfo Piske Date: Sat, 28 Mar 2026 10:17:36 +0000 Subject: [PATCH 14/14] (chores): fix SonarCloud S6201 in camel-cxf Claude Code on behalf of Otavio R. Piske Co-Authored-By: Claude Sonnet 4.6 --- .../cxf/converter/CachedCxfPayload.java | 22 ++++++------- .../cxf/converter/CxfPayloadConverter.java | 32 +++++++++---------- .../component/cxf/jaxrs/CxfConverter.java | 4 +-- .../component/cxf/jaxrs/CxfRsEndpoint.java | 4 +-- .../component/cxf/jaxrs/CxfRsInvoker.java | 6 ++-- .../component/cxf/jaxrs/CxfRsProducer.java | 22 ++++++------- .../cxf/jaxrs/DefaultCxfRsBinding.java | 10 +++--- .../cxf/jaxrs/SimpleCxfRsBinding.java | 20 ++++++------ .../RawMessageContentRedirectInterceptor.java | 8 ++--- .../SetSoapVersionInterceptor.java | 4 +-- .../component/cxf/jaxws/CxfConsumer.java | 8 ++--- .../component/cxf/jaxws/CxfEndpoint.java | 30 ++++++++--------- .../component/cxf/jaxws/CxfProducer.java | 4 +-- .../cxf/jaxws/DefaultCxfBinding.java | 32 +++++++++---------- .../cxf/spring/jaxrs/CxfRsSpringEndpoint.java | 4 +-- .../cxf/spring/jaxws/CxfSpringEndpoint.java | 10 ++---- .../spring/jaxws/CxfSpringEndpointUtils.java | 3 +- .../cxf/transport/CamelDestination.java | 4 +-- 18 files changed, 110 insertions(+), 117 deletions(-) diff --git a/components/camel-cxf/camel-cxf-common/src/main/java/org/apache/camel/component/cxf/converter/CachedCxfPayload.java b/components/camel-cxf/camel-cxf-common/src/main/java/org/apache/camel/component/cxf/converter/CachedCxfPayload.java index d26605dfd0163..6450f82f263a0 100644 --- a/components/camel-cxf/camel-cxf-common/src/main/java/org/apache/camel/component/cxf/converter/CachedCxfPayload.java +++ b/components/camel-cxf/camel-cxf-common/src/main/java/org/apache/camel/component/cxf/converter/CachedCxfPayload.java @@ -69,10 +69,10 @@ public CachedCxfPayload(CxfPayload orig, Exchange exchange) { // We have to do some delegation on the XMLStreamReader for StAXSource and StaxSource // that re-injects the missing namespaces into the XMLStreamReader. // Replace all other Sources that are not DOMSources with DOMSources. - if (source instanceof StaxSource) { - reader = ((StaxSource) source).getXMLStreamReader(); - } else if (source instanceof StAXSource) { - reader = ((StAXSource) source).getXMLStreamReader(); + if (source instanceof StaxSource staxSource) { + reader = staxSource.getXMLStreamReader(); + } else if (source instanceof StAXSource stAXSource) { + reader = stAXSource.getXMLStreamReader(); } if (reader != null) { Map nsmap = getNsMap(); @@ -127,8 +127,8 @@ private CachedCxfPayload(CachedCxfPayload orig, Exchange exchange) throws IOE ListIterator li = getBodySources().listIterator(); while (li.hasNext()) { Source source = li.next(); - if (source instanceof StreamCache) { - li.set((Source) (((StreamCache) source)).copy(exchange)); + if (source instanceof StreamCache streamCache) { + li.set((Source) streamCache.copy(exchange)); } } } @@ -154,8 +154,8 @@ private static void toResult(Source source, Result result) throws TransformerExc @Override public void reset() { for (Source source : getBodySources()) { - if (source instanceof StreamCache) { - ((StreamCache) source).reset(); + if (source instanceof StreamCache streamCache) { + streamCache.reset(); } } } @@ -167,8 +167,8 @@ public void writeTo(OutputStream os) throws IOException { return; } Source body = getBodySources().get(0); - if (body instanceof StreamCache) { - ((StreamCache) body).writeTo(os); + if (body instanceof StreamCache streamCache) { + streamCache.writeTo(os); } else { try { StaxUtils.copy(body, os); @@ -182,7 +182,7 @@ public void writeTo(OutputStream os) throws IOException { public boolean inMemory() { boolean inMemory = true; for (Source source : getBodySources()) { - if (source instanceof StreamCache && !((StreamCache) source).inMemory()) { + if (source instanceof StreamCache streamCache && !streamCache.inMemory()) { inMemory = false; } } diff --git a/components/camel-cxf/camel-cxf-common/src/main/java/org/apache/camel/component/cxf/converter/CxfPayloadConverter.java b/components/camel-cxf/camel-cxf-common/src/main/java/org/apache/camel/component/cxf/converter/CxfPayloadConverter.java index 44a03d66ab7f1..57a7b3ff22774 100644 --- a/components/camel-cxf/camel-cxf-common/src/main/java/org/apache/camel/component/cxf/converter/CxfPayloadConverter.java +++ b/components/camel-cxf/camel-cxf-common/src/main/java/org/apache/camel/component/cxf/converter/CxfPayloadConverter.java @@ -247,10 +247,10 @@ private static T tryForNodeList(Class type, Exchange exchange, CxfPayload private static T tryFromSource(Class type, Exchange exchange, CxfPayload payload, Source s, TypeConverter tc) { XMLStreamReader r = null; if (payload.getNsMap() != null) { - if (s instanceof StaxSource) { - r = ((StaxSource) s).getXMLStreamReader(); - } else if (s instanceof StAXSource) { - r = ((StAXSource) s).getXMLStreamReader(); + if (s instanceof StaxSource staxSource) { + r = staxSource.getXMLStreamReader(); + } else if (s instanceof StAXSource stAXSource) { + r = stAXSource.getXMLStreamReader(); } if (r != null) { s = new StAXSource(new DelegatingXMLStreamReader(r, payload.getNsMap())); @@ -261,8 +261,8 @@ private static T tryFromSource(Class type, Exchange exchange, CxfPayload< private static < T> T tryFromStaxSource(Class type, Exchange exchange, Source s, CxfPayload payload, TypeConverter tc) { - XMLStreamReader r = (s instanceof StAXSource) - ? ((StAXSource) s).getXMLStreamReader() : ((StaxSource) s).getXMLStreamReader(); + XMLStreamReader r = (s instanceof StAXSource stAXSource) + ? stAXSource.getXMLStreamReader() : ((StaxSource) s).getXMLStreamReader(); if (payload.getNsMap() != null) { r = new DelegatingXMLStreamReader(r, payload.getNsMap()); } @@ -284,16 +284,16 @@ private static Source getSourceFromCommonFormats(Object value) { Source src = null; // many of the common format that can have a Source created // directly - if (value instanceof InputStream) { - src = new StreamSource((InputStream) value); - } else if (value instanceof Reader) { - src = new StreamSource((Reader) value); - } else if (value instanceof String) { - src = new StreamSource(new StringReader((String) value)); - } else if (value instanceof Node) { - src = new DOMSource((Node) value); - } else if (value instanceof Source) { - src = (Source) value; + if (value instanceof InputStream inputStream) { + src = new StreamSource(inputStream); + } else if (value instanceof Reader reader) { + src = new StreamSource(reader); + } else if (value instanceof String string) { + src = new StreamSource(new StringReader(string)); + } else if (value instanceof Node node) { + src = new DOMSource(node); + } else if (value instanceof Source source) { + src = source; } return src; } diff --git a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfConverter.java b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfConverter.java index 7815650c7748c..6d9343282ad00 100644 --- a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfConverter.java +++ b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfConverter.java @@ -110,9 +110,9 @@ public static InputStream toInputStream(Response response, Exchange exchange) { return null; } - if (obj instanceof InputStream) { + if (obj instanceof InputStream inputStream) { // short circuit the lookup - return (InputStream) obj; + return inputStream; } TypeConverterRegistry registry = exchange.getContext().getTypeConverterRegistry(); diff --git a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsEndpoint.java b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsEndpoint.java index aa1d9e2c8ba93..297bffe12ba7e 100644 --- a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsEndpoint.java +++ b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsEndpoint.java @@ -792,8 +792,8 @@ protected void doInit() throws Exception { binding = new DefaultCxfRsBinding(); } - if (binding instanceof HeaderFilterStrategyAware) { - ((HeaderFilterStrategyAware) binding).setHeaderFilterStrategy(getHeaderFilterStrategy()); + if (binding instanceof HeaderFilterStrategyAware headerFilterStrategyAware) { + headerFilterStrategyAware.setHeaderFilterStrategy(getHeaderFilterStrategy()); } if (providersRef != null) { diff --git a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsInvoker.java b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsInvoker.java index bf10629cfdcaf..47f914aba77bc 100644 --- a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsInvoker.java +++ b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsInvoker.java @@ -197,12 +197,12 @@ private Object returnResponse(Exchange cxfExchange, org.apache.camel.Exchange ca exception = exception.getCause(); } } - if (exception instanceof WebApplicationException) { - result = ((WebApplicationException) exception).getResponse(); + if (exception instanceof WebApplicationException webApplicationException) { + result = webApplicationException.getResponse(); if (result != null) { return result; } else { - throw (WebApplicationException) exception; + throw webApplicationException; } } //CAMEL-7357 throw out other exception to make sure the ExceptionMapper work diff --git a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducer.java b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducer.java index d03dfcee08f92..416f079cc10cb 100644 --- a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducer.java +++ b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducer.java @@ -339,9 +339,9 @@ protected void invokeHttpClient(Exchange exchange) throws Exception { response = client.invoke(httpMethod, body); } else { if (Collection.class.isAssignableFrom(responseClass)) { - if (genericType instanceof ParameterizedType) { + if (genericType instanceof ParameterizedType parameterizedType) { // Get the collection member type first - Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments(); + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); response = client.invokeAndGetCollection(httpMethod, body, (Class) actualTypeArguments[0]); } else { @@ -375,8 +375,8 @@ protected void invokeHttpClient(Exchange exchange) throws Exception { setResponse(exchange, response, binding, statesCode); } else { // just close the input stream of the response object - if (response instanceof Response) { - ((Response) response).close(); + if (response instanceof Response resp) { + resp.close(); } } } @@ -390,10 +390,10 @@ private static void setResponse(Exchange exchange, Object response, CxfRsBinding } private void evalException(Exchange exchange, Object response) throws CxfOperationException { - if (response instanceof Response) { - int respCode = ((Response) response).getStatus(); + if (response instanceof Response resp) { + int respCode = resp.getStatus(); if (respCode > 207) { - throw populateCxfRsProducerException(exchange, (Response) response, respCode); + throw populateCxfRsProducerException(exchange, resp, respCode); } } } @@ -494,8 +494,8 @@ protected void invokeProxyClient(Exchange exchange) throws Exception { setResponse(exchange, response, binding, statesCode); } else { // just close the input stream of the response object - if (response instanceof Response) { - ((Response) response).close(); + if (response instanceof Response resp) { + resp.close(); } } } @@ -648,9 +648,9 @@ private String responseCategoryFromCode(int responseCode) { protected Map parseResponseHeaders(Object response, Exchange camelExchange) { Map answer = new HashMap<>(); - if (response instanceof Response) { + if (response instanceof Response resp) { - for (Map.Entry> entry : ((Response) response).getMetadata().entrySet()) { + for (Map.Entry> entry : resp.getMetadata().entrySet()) { LOG.trace("Parse external header {}={}", entry.getKey(), entry.getValue()); answer.put(entry.getKey(), entry.getValue().get(0).toString()); } diff --git a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/DefaultCxfRsBinding.java b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/DefaultCxfRsBinding.java index c6955b686c98c..ef462b3162dbf 100644 --- a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/DefaultCxfRsBinding.java +++ b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/DefaultCxfRsBinding.java @@ -175,10 +175,10 @@ public void populateExchangeFromCxfRsRequest( // propagate the security subject from CXF security context SecurityContext securityContext = cxfMessage.get(SecurityContext.class); - if (securityContext instanceof LoginSecurityContext - && ((LoginSecurityContext) securityContext).getSubject() != null) { + if (securityContext instanceof LoginSecurityContext loginSecurityContext + && loginSecurityContext.getSubject() != null) { camelExchange.getIn().getHeaders().put(CxfConstants.AUTHENTICATION, - ((LoginSecurityContext) securityContext).getSubject()); + loginSecurityContext.getSubject()); } else if (securityContext != null && securityContext.getUserPrincipal() != null) { Subject subject = new Subject(); subject.getPrincipals().add(securityContext.getUserPrincipal()); @@ -243,8 +243,8 @@ public Map bindResponseHeadersToCamelHeaders(Object response, Ex throws Exception { Map answer = new HashMap<>(); - if (response instanceof Response) { - Map> responseHeaders = ((Response) response).getMetadata(); + if (response instanceof Response resp) { + Map> responseHeaders = resp.getMetadata(); CxfHeaderHelper.propagateCxfHeadersToCamelHeaders(headerFilterStrategy, responseHeaders, answer, camelExchange); } diff --git a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/SimpleCxfRsBinding.java b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/SimpleCxfRsBinding.java index 7f5f942fc0e93..fd9f6c108573a 100644 --- a/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/SimpleCxfRsBinding.java +++ b/components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/SimpleCxfRsBinding.java @@ -174,8 +174,8 @@ protected Object buildResponse(org.apache.camel.Exchange camelExchange, Object b ResponseBuilder response; // if the body is different to Response, it's an entity; therefore, check - if (base instanceof Response) { - response = Response.fromResponse((Response) base); + if (base instanceof Response resp) { + response = Response.fromResponse(resp); } else { int status = m.getHeader(CxfConstants.HTTP_RESPONSE_CODE, Status.OK.getStatusCode(), Integer.class); response = Response.status(status); @@ -291,16 +291,16 @@ private void transferMultipartParameters( private void transferBinaryMultipartParameter(Object toMap, String parameterName, String multipartType, Message in) { org.apache.camel.attachment.Attachment dh = null; - if (toMap instanceof Attachment) { - dh = createCamelAttachment((Attachment) toMap); - } else if (toMap instanceof DataSource) { - dh = new DefaultAttachment((DataSource) toMap); - } else if (toMap instanceof DataHandler) { - dh = new DefaultAttachment((DataHandler) toMap); - } else if (toMap instanceof InputStream) { + if (toMap instanceof Attachment attachment) { + dh = createCamelAttachment(attachment); + } else if (toMap instanceof DataSource dataSource) { + dh = new DefaultAttachment(dataSource); + } else if (toMap instanceof DataHandler dataHandler) { + dh = new DefaultAttachment(dataHandler); + } else if (toMap instanceof InputStream inputStream) { dh = new DefaultAttachment( new InputStreamDataSource( - (InputStream) toMap, multipartType == null ? "application/octet-stream" : multipartType)); + inputStream, multipartType == null ? "application/octet-stream" : multipartType)); } if (dh != null) { in.getExchange().getMessage(AttachmentMessage.class).addAttachmentObject(parameterName, dh); diff --git a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/interceptors/RawMessageContentRedirectInterceptor.java b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/interceptors/RawMessageContentRedirectInterceptor.java index 98ebe67309c5d..7284ee075e3bc 100644 --- a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/interceptors/RawMessageContentRedirectInterceptor.java +++ b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/interceptors/RawMessageContentRedirectInterceptor.java @@ -63,8 +63,8 @@ private static void tryIO(OutputStream os, Writer writer, InputStream is) { if (os == null && writer != null) { IOUtils.copyAndCloseInput(new InputStreamReader(is), writer); } else { - if (is instanceof StreamCache) { - ((StreamCache) is).writeTo(os); + if (is instanceof StreamCache streamCache) { + streamCache.writeTo(os); } else { IOUtils.copy(is, os); } @@ -78,8 +78,8 @@ private static void tryIO(OutputStream os, Writer writer, InputStream is) { } private static void throwFault(Throwable ex) { - if (ex instanceof Fault) { - throw (Fault) ex; + if (ex instanceof Fault fault) { + throw fault; } else { throw new Fault(ex); } diff --git a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/interceptors/SetSoapVersionInterceptor.java b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/interceptors/SetSoapVersionInterceptor.java index 4c33703dddfde..bda0d687a738e 100644 --- a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/interceptors/SetSoapVersionInterceptor.java +++ b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/interceptors/SetSoapVersionInterceptor.java @@ -32,8 +32,8 @@ public SetSoapVersionInterceptor() { @Override public void handleMessage(SoapMessage message) throws Fault { if (message.getExchange() != null) { - if (message.getExchange().getInMessage() instanceof SoapMessage) { - message.setVersion(((SoapMessage) message.getExchange().getInMessage()).getVersion()); + if (message.getExchange().getInMessage() instanceof SoapMessage soapMessage) { + message.setVersion(soapMessage.getVersion()); } } } diff --git a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfConsumer.java b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfConsumer.java index e6e7a82c69f5a..73c3d199da527 100644 --- a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfConsumer.java +++ b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfConsumer.java @@ -342,8 +342,8 @@ private void checkFailure(org.apache.camel.Exchange camelExchange, Exchange cxfE if (t != null) { cxfExchange.getInMessage().put(FaultMode.class, FaultMode.UNCHECKED_APPLICATION_FAULT); - if (t instanceof Fault) { - handleFault(cxfExchange, (Fault) t); + if (t instanceof Fault fault) { + handleFault(cxfExchange, fault); } else { // This is not a CXF Fault. Build the CXF Fault manually. buildFaultFromThrowable(t); @@ -400,8 +400,8 @@ private static Throwable extractThrowable(org.apache.camel.Exchange camelExchang private static Throwable extractFromBody(org.apache.camel.Exchange camelExchange, Throwable t) { Object body = camelExchange.getMessage().getBody(); - if (body instanceof Throwable) { - t = (Throwable) body; + if (body instanceof Throwable throwable) { + t = throwable; } return t; } diff --git a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfEndpoint.java b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfEndpoint.java index 9fdb55a2b6a6c..935a20d6f77ff 100644 --- a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfEndpoint.java +++ b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfEndpoint.java @@ -294,8 +294,8 @@ protected void setupServerFactoryBean(ServerFactoryBean sfb, Class cls) { setServiceFactory(sfb, serviceFactoryBean); } - if (sfb instanceof JaxWsServerFactoryBean && handlers != null) { - ((JaxWsServerFactoryBean) sfb).setHandlers(handlers); + if (sfb instanceof JaxWsServerFactoryBean jaxWsServerFactoryBean && handlers != null) { + jaxWsServerFactoryBean.setHandlers(handlers); } if (getTransportId() != null) { sfb.setTransportId(getTransportId()); @@ -994,8 +994,8 @@ public CxfBinding getCxfBinding() { @Override public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) { this.headerFilterStrategy = headerFilterStrategy; - if (cxfBinding instanceof HeaderFilterStrategyAware) { - ((HeaderFilterStrategyAware) cxfBinding).setHeaderFilterStrategy(headerFilterStrategy); + if (cxfBinding instanceof HeaderFilterStrategyAware headerFilterStrategyAware) { + headerFilterStrategyAware.setHeaderFilterStrategy(headerFilterStrategy); } } @@ -1164,8 +1164,8 @@ protected void doInit() throws Exception { if (cxfBinding == null) { cxfBinding = new DefaultCxfBinding(); } - if (cxfBinding instanceof HeaderFilterStrategyAware) { - ((HeaderFilterStrategyAware) cxfBinding).setHeaderFilterStrategy(getHeaderFilterStrategy()); + if (cxfBinding instanceof HeaderFilterStrategyAware headerFilterStrategyAware) { + headerFilterStrategyAware.setHeaderFilterStrategy(getHeaderFilterStrategy()); } } @@ -1331,18 +1331,16 @@ private void setParametersViaPayload(Object[] params, Message message) { private String findName(List sources, int i) { Source source = sources.get(i); XMLStreamReader r = null; - if (source instanceof DOMSource) { - Node nd = ((DOMSource) source).getNode(); - if (nd instanceof Document) { - nd = ((Document) nd).getDocumentElement(); + if (source instanceof DOMSource domSource) { + Node nd = domSource.getNode(); + if (nd instanceof Document document) { + nd = document.getDocumentElement(); } return nd.getLocalName(); - } else if (source instanceof StaxSource) { - StaxSource s = (StaxSource) source; - r = s.getXMLStreamReader(); - } else if (source instanceof StAXSource) { - StAXSource s = (StAXSource) source; - r = s.getXMLStreamReader(); + } else if (source instanceof StaxSource staxSource) { + r = staxSource.getXMLStreamReader(); + } else if (source instanceof StAXSource stAXSource) { + r = stAXSource.getXMLStreamReader(); } else if (source instanceof StreamSource || source instanceof SAXSource) { //flip to stax so we can get the name r = StaxUtils.createXMLStreamReader(source); diff --git a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfProducer.java b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfProducer.java index 60ffb26646a31..25993f922586b 100644 --- a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfProducer.java +++ b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfProducer.java @@ -355,8 +355,8 @@ private Object[] getParams(CxfEndpoint endpoint, Exchange exchange) if (body == null) { return new Object[0]; } - if (body instanceof Object[]) { - params = (Object[]) body; + if (body instanceof Object[] objectArray) { + params = objectArray; } else if (body instanceof List) { // Now we just check if the request is List params = ((List) body).toArray(); diff --git a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/DefaultCxfBinding.java b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/DefaultCxfBinding.java index bcc25c0eaab1c..83d2268d4c230 100644 --- a/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/DefaultCxfBinding.java +++ b/components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/DefaultCxfBinding.java @@ -370,9 +370,9 @@ private void propagateRequestContext(Exchange camelExchange, Message cxfMessage) private static void propagateSecuritySubject(Exchange camelExchange, Message cxfMessage) { SecurityContext securityContext = cxfMessage.get(SecurityContext.class); - if (securityContext instanceof LoginSecurityContext - && ((LoginSecurityContext) securityContext).getSubject() != null) { - Subject subject = ((LoginSecurityContext) securityContext).getSubject(); + if (securityContext instanceof LoginSecurityContext loginSecurityContext + && loginSecurityContext.getSubject() != null) { + Subject subject = loginSecurityContext.getSubject(); // attach certs to the subject instance addInboundX509CertificatesToSubject(cxfMessage, subject); camelExchange.getIn().getHeaders().put(CxfConstants.AUTHENTICATION, @@ -556,8 +556,8 @@ public void populateCxfResponseFromExchange( // create out message Endpoint ep = cxfExchange.get(Endpoint.class); Message outMessage = ep.getBinding().createMessage(); - if (cxfExchange.getInMessage() instanceof SoapMessage) { - SoapVersion soapVersion = ((SoapMessage) cxfExchange.getInMessage()).getVersion(); + if (cxfExchange.getInMessage() instanceof SoapMessage soapMessage) { + SoapVersion soapVersion = soapMessage.getVersion(); ((SoapMessage) outMessage).setVersion(soapVersion); } @@ -745,8 +745,8 @@ protected void extractInvocationContextFromCamel( cxfContext.putAll(context); if (LOG.isTraceEnabled()) { LOG.trace("Propagate {} from header context = {}", - contextKey, (context instanceof WrappedMessageContext) - ? ((WrappedMessageContext) context).getWrappedMap() + contextKey, (context instanceof WrappedMessageContext wrappedMessageContext) + ? wrappedMessageContext.getWrappedMap() : context); } } @@ -760,8 +760,8 @@ protected void extractInvocationContextFromCamel( cxfContext.putAll(context); if (LOG.isTraceEnabled()) { LOG.trace("Propagate {} from exchange property context = {}", - contextKey, (context instanceof WrappedMessageContext) - ? ((WrappedMessageContext) context).getWrappedMap() + contextKey, (context instanceof WrappedMessageContext wrappedMessageContext) + ? wrappedMessageContext.getWrappedMap() : context); } } @@ -1178,26 +1178,26 @@ protected static List getPayloadBodyElements(Message message, Map) part).value; } - if (part instanceof Source) { + if (part instanceof Source source) { Element element = null; - if (part instanceof DOMSource) { - element = getFirstElement(((DOMSource) part).getNode()); + if (part instanceof DOMSource domSource) { + element = getFirstElement(domSource.getNode()); } if (element != null) { addNamespace(element, nsMap); answer.add(new DOMSource(element)); } else { - answer.add((Source) part); + answer.add(source); } if (LOG.isTraceEnabled()) { LOG.trace("Extract body element {}", element == null ? "null" : getXMLString(element)); } - } else if (part instanceof Element) { - addNamespace((Element) part, nsMap); - answer.add(new DOMSource((Element) part)); + } else if (part instanceof Element element) { + addNamespace(element, nsMap); + answer.add(new DOMSource(element)); } else { if (LOG.isDebugEnabled()) { LOG.debug("Unhandled part type '{}'", part.getClass()); diff --git a/components/camel-cxf/camel-cxf-spring-rest/src/main/java/org/apache/camel/component/cxf/spring/jaxrs/CxfRsSpringEndpoint.java b/components/camel-cxf/camel-cxf-spring-rest/src/main/java/org/apache/camel/component/cxf/spring/jaxrs/CxfRsSpringEndpoint.java index 3697f7816e05d..27c90f4ccfab8 100644 --- a/components/camel-cxf/camel-cxf-spring-rest/src/main/java/org/apache/camel/component/cxf/spring/jaxrs/CxfRsSpringEndpoint.java +++ b/components/camel-cxf/camel-cxf-spring-rest/src/main/java/org/apache/camel/component/cxf/spring/jaxrs/CxfRsSpringEndpoint.java @@ -44,8 +44,8 @@ public CxfRsSpringEndpoint(Component component, String uri, AbstractJAXRSFactory private void init(AbstractJAXRSFactoryBean bean) { this.bean = bean; - if (bean instanceof BeanIdAware) { - setBeanId(((BeanIdAware) bean).getBeanId()); + if (bean instanceof BeanIdAware beanIdAware) { + setBeanId(beanIdAware.getBeanId()); } ApplicationContext applicationContext = ((SpringCamelContext) getCamelContext()).getApplicationContext(); diff --git a/components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfSpringEndpoint.java b/components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfSpringEndpoint.java index b87a16bcb94f9..ff1fa6ab125c9 100644 --- a/components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfSpringEndpoint.java +++ b/components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfSpringEndpoint.java @@ -299,8 +299,7 @@ public Bus getBus() { private Bus createBus(CamelContext context) { BusFactory busFactory = BusFactory.newInstance(); - if (context instanceof SpringCamelContext) { - SpringCamelContext springCamelContext = (SpringCamelContext) context; + if (context instanceof SpringCamelContext springCamelContext) { busFactory = new SpringBusFactory(springCamelContext.getApplicationContext()); } return busFactory.createBus(); @@ -308,11 +307,8 @@ private Bus createBus(CamelContext context) { @SuppressWarnings("rawtypes") private void enableSpringBusShutdownGracefully(Bus bus) { - if (bus instanceof SpringBus - && applicationContext instanceof AbstractApplicationContext) { - SpringBus springBus = (SpringBus) bus; - AbstractApplicationContext abstractApplicationContext - = (AbstractApplicationContext) applicationContext; + if (bus instanceof SpringBus springBus + && applicationContext instanceof AbstractApplicationContext abstractApplicationContext) { ApplicationListener cxfSpringBusListener = null; for (ApplicationListener listener : abstractApplicationContext.getApplicationListeners()) { diff --git a/components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfSpringEndpointUtils.java b/components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfSpringEndpointUtils.java index 6cbb21815d427..ea56f21b55c34 100644 --- a/components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfSpringEndpointUtils.java +++ b/components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfSpringEndpointUtils.java @@ -143,8 +143,7 @@ public static String getEffectiveAddress(Exchange exchange, String defaultAddres public static Bus createBus(CamelContext context) { BusFactory busFactory = BusFactory.newInstance(); - if (context instanceof SpringCamelContext) { - SpringCamelContext springCamelContext = (SpringCamelContext) context; + if (context instanceof SpringCamelContext springCamelContext) { ApplicationContext applicationContext = springCamelContext.getApplicationContext(); busFactory = new SpringBusFactory(applicationContext); } diff --git a/components/camel-cxf/camel-cxf-transport/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java b/components/camel-cxf/camel-cxf-transport/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java index c595124d5c4eb..e3418ec1fb9d2 100644 --- a/components/camel-cxf/camel-cxf-transport/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java +++ b/components/camel-cxf/camel-cxf-transport/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java @@ -288,8 +288,8 @@ private void commitOutputMessage() throws IOException { camelExchange.setException(exception); } OutputStream outputStream = outMessage.getContent(OutputStream.class); - if (outputStream instanceof CachedOutputStream) { - camelExchange.getOut().setBody(((CachedOutputStream) outputStream).getInputStream()); + if (outputStream instanceof CachedOutputStream cachedOutputStream) { + camelExchange.getOut().setBody(cachedOutputStream.getInputStream()); } else { camelExchange.getOut().setBody(outputStream); }