From ce697d215d6035a40904c74db8bb9515177e4870 Mon Sep 17 00:00:00 2001 From: Emmanuel GALLOIS Date: Thu, 21 May 2026 17:56:10 +0200 Subject: [PATCH 1/7] chore(QTDI-2893): use pattern matching for instanceof (S6201) Replace `instanceof` + manual cast patterns with Java 17 pattern matching for instanceof to reduce Sonar warnings (java:S6201). Both `(X) value` and `X.class.cast(value)` cast forms are handled. Excluded cases: - Conditions combined with `||` (pattern matching incompatible with alternation): AvroSchemaCache, SchemaConverter (Double||Float). - ParameterSetter#set: target variable declared outside the `if` block (would require restructuring). - Casts to a type different from the `instanceof` check (not S6201). --- .../beam/spi/record/AvroEntryBuilder.java | 3 +- .../runtime/beam/spi/record/AvroRecord.java | 46 +++++++++---------- .../beam/spi/record/AvroSchemaCache.java | 3 +- .../component/runtime/record/RecordImpl.java | 20 ++++---- .../runtime/manager/ComponentManager.java | 6 +-- .../manager/service/ServiceHelper.java | 4 +- .../xbean/converter/SchemaConverter.java | 32 ++++++------- .../service/ProducerFinderImplTest.java | 4 +- .../internal/impl/DefaultResponseLocator.java | 3 +- .../component/runtime/di/OutputsHandler.java | 8 ++-- .../runtime/di/schema/TaCoKitGuessSchema.java | 40 ++++++++-------- .../di/studio/AfterVariableExtracter.java | 4 +- .../runtime/di/studio/ParameterSetter.java | 4 +- .../di/studio/RuntimeContextInjector.java | 4 +- .../tools/validator/ActionValidator.java | 4 +- 15 files changed, 89 insertions(+), 96 deletions(-) diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java index 64eaee291f903..69e96ba8792ab 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java @@ -22,8 +22,7 @@ public class AvroEntryBuilder extends SchemaImpl.EntryImpl.BuilderImpl { @Override public Schema.Entry.Builder withElementSchema(final Schema schema) { - if (schema instanceof AvroSchema) { - final AvroSchema innerSchema = (AvroSchema) schema; + if (schema instanceof AvroSchema innerSchema) { AvroSchema avroSchema = this.authorizeNull(innerSchema); return super.withElementSchema(avroSchema); } diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java index 40fda0d05c3cc..14958d3ffe2f1 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java @@ -74,8 +74,7 @@ public AvroRecord(final IndexedRecord record) { } public AvroRecord(final Record record) { - if (record instanceof AvroRecord) { - final AvroRecord avr = (AvroRecord) record; + if (record instanceof AvroRecord avr) { this.delegate = avr.delegate; this.schema = avr.schema; return; @@ -105,12 +104,12 @@ private Object directMapping(final Object value, final Schema.Entry entry) { // RecordImpl store BigDecimal directly, no any convert as not necessary, so here need to convert to string for // beam's AvroCoder which cloud platform use // also here for any Collection as Array type - if (value instanceof BigDecimal) { - return BigDecimal.class.cast(value).toString(); + if (value instanceof BigDecimal bigDecimal) { + return bigDecimal.toString(); } - if (value instanceof Collection) { - return Collection.class.cast(value).stream().map(v -> this.directMapping(v, entry)).collect(toList()); + if (value instanceof Collection collection) { + return collection.stream().map(v -> this.directMapping(v, entry)).collect(toList()); } if (value instanceof RecordImpl) { return new AvroRecord((Record) value).delegate; @@ -118,28 +117,28 @@ private Object directMapping(final Object value, final Schema.Entry entry) { if (value instanceof Record) { return Unwrappable.class.cast(value).unwrap(IndexedRecord.class); } - if (value instanceof ZonedDateTime) { - return ZonedDateTime.class.cast(value).toInstant().toEpochMilli(); + if (value instanceof ZonedDateTime zonedDateTime) { + return zonedDateTime.toInstant().toEpochMilli(); } - if (value instanceof Date) { - return Date.class.cast(value).getTime(); + if (value instanceof Date date) { + return date.getTime(); } - if (value instanceof byte[]) { - return ByteBuffer.wrap(byte[].class.cast(value)); + if (value instanceof byte[] bytes) { + return ByteBuffer.wrap(bytes); } - if (value instanceof Long) { + if (value instanceof Long longValue) { String logicalType = entry.getLogicalType(); if (logicalType != null) { if (SchemaProperty.LogicalType.DATE.key().equals(logicalType)) { return Math.toIntExact( - Instant.ofEpochMilli((Long) value) + Instant.ofEpochMilli(longValue) .atZone(UTC) .toLocalDate() .toEpochDay()); // Avro stores dates as int } else if (LogicalType.TIME.key().equals(logicalType)) { // QTDI-1252: Avro time-millis logical type stores int milliseconds from 0:00:00 not from Unix Epoch - final Instant instant = Instant.ofEpochMilli((Long) value); + final Instant instant = Instant.ofEpochMilli(longValue); final ZonedDateTime zonedDateTime = instant.atZone(UTC); return Math.toIntExact(zonedDateTime.toLocalTime().toNanoOfDay() / 1_000_000); } @@ -245,12 +244,13 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi return expectedType.cast(value); } - if (value instanceof IndexedRecord && (Record.class == expectedType || Object.class == expectedType)) { - return expectedType.cast(new AvroRecord(IndexedRecord.class.cast(value))); + if (value instanceof IndexedRecord indexedRecord + && (Record.class == expectedType || Object.class == expectedType)) { + return expectedType.cast(new AvroRecord(indexedRecord)); } - if (value instanceof ByteBuffer && byte[].class == expectedType) { - return expectedType.cast(ByteBuffer.class.cast(value).array()); + if (value instanceof ByteBuffer byteBuffer && byte[].class == expectedType) { + return expectedType.cast(byteBuffer.array()); } final org.apache.avro.Schema fieldSchema = unwrapUnion(fieldSchemaRaw); @@ -311,8 +311,8 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi .cast(doMapCollection(itemType, Collection.class.cast(value), fieldSchema.getElementType())); } - if (value instanceof org.joda.time.DateTime && ZonedDateTime.class == expectedType) { - final long epochMilli = org.joda.time.DateTime.class.cast(value).getMillis(); + if (value instanceof org.joda.time.DateTime dateTime && ZonedDateTime.class == expectedType) { + final long epochMilli = dateTime.getMillis(); return expectedType.cast(ZonedDateTime.ofInstant(java.time.Instant.ofEpochMilli(epochMilli), UTC)); } @@ -338,7 +338,7 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi if (value instanceof Utf8 && Object.class == expectedType) { return expectedType.cast(value.toString()); } - if (Collection.class.isAssignableFrom(expectedType) && value instanceof Collection) { + if (Collection.class.isAssignableFrom(expectedType) && value instanceof Collection collection) { final org.apache.avro.Schema elementType = fieldSchema.getElementType(); final org.apache.avro.Schema elementSchema = unwrapUnion(elementType); Class toType = Object.class; @@ -347,7 +347,7 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi } else if (elementSchema.getType() == org.apache.avro.Schema.Type.ARRAY) { toType = Collection.class; } - final Collection objects = this.doMapCollection(toType, Collection.class.cast(value), elementSchema); + final Collection objects = this.doMapCollection(toType, collection, elementSchema); return expectedType.cast(objects); } return expectedType.cast(value); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java index 965e7611fd08a..14eaaadf53664 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java @@ -42,8 +42,7 @@ public AvroSchema find(final Schema schema) { if (schema == null || schema instanceof AvroSchema) { return (AvroSchema) schema; } - if (schema instanceof SchemaImpl) { - final SchemaImpl realSchema = (SchemaImpl) schema; + if (schema instanceof SchemaImpl realSchema) { if ((!this.cache.containsKey(realSchema)) && this.cache.size() >= AvroSchemaCache.MAX_SIZE) { this.removeOldest(); diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java index f56961dfca2ff..1602d11f66641 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java @@ -193,16 +193,16 @@ public Builder with(final Entry entry, final Object value) { if (entry.getType() == Schema.Type.DATETIME) { if (value == null) { withDateTime(entry, (ZonedDateTime) value); - } else if (value instanceof Long) { - withTimestamp(entry, (Long) value); - } else if (value instanceof Date) { - withDateTime(entry, (Date) value); - } else if (value instanceof ZonedDateTime) { - withDateTime(entry, (ZonedDateTime) value); - } else if (value instanceof Instant) { - withInstant(entry, (Instant) value); - } else if (value instanceof Temporal) { - withTimestamp(entry, ((Temporal) value).get(ChronoField.INSTANT_SECONDS) * 1000L); + } else if (value instanceof Long longValue) { + withTimestamp(entry, longValue); + } else if (value instanceof Date date) { + withDateTime(entry, date); + } else if (value instanceof ZonedDateTime zonedDateTime) { + withDateTime(entry, zonedDateTime); + } else if (value instanceof Instant instant) { + withInstant(entry, instant); + } else if (value instanceof Temporal temporal) { + withTimestamp(entry, temporal.get(ChronoField.INSTANT_SECONDS) * 1000L); } return this; } else { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java index b510ffffd1ecb..5f718f65c919b 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java @@ -781,14 +781,12 @@ public ParameterMeta findDatastoreParameterMeta(final String plugin, final Strin */ public static Map jsonToMap(final JsonValue jsonValue, final String path) { final Map result = new HashMap<>(); - if (jsonValue instanceof JsonObject) { - JsonObject jsonObj = (JsonObject) jsonValue; + if (jsonValue instanceof JsonObject jsonObj) { for (String key : jsonObj.keySet()) { String newPath = path.isEmpty() ? key : path + "." + key; result.putAll(jsonToMap(jsonObj.get(key), newPath)); } - } else if (jsonValue instanceof JsonArray) { - JsonArray jsonArray = (JsonArray) jsonValue; + } else if (jsonValue instanceof JsonArray jsonArray) { for (int i = 0; i < jsonArray.size(); i++) { String newPath = path + "[" + i + "]"; result.putAll(jsonToMap(jsonArray.get(i), newPath)); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java index df71b68221c60..0afa6685d1bca 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java @@ -57,8 +57,8 @@ public Object createServiceInstance(final ClassLoader loader, final String conta .initialize(instance, new InterceptorHandlerFacade(serviceClass.getConstructor().newInstance(), allServices)); } - if (instance instanceof BaseService) { - this.updateService((BaseService) instance, containerId, serviceClass.getName()); + if (instance instanceof BaseService baseService) { + this.updateService(baseService, containerId, serviceClass.getName()); } return instance; } catch (final InstantiationException | IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java index 8f51b1dc4fd2a..c6231dc3a4179 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java @@ -98,8 +98,8 @@ private Schema toSchema(final JsonObject json) { this.addProps(builder::withProp, json); final JsonValue orderValue = json.get("order"); - if (orderValue instanceof JsonString) { - final Schema.EntriesOrder order = Schema.EntriesOrder.of(((JsonString) orderValue).getString()); + if (orderValue instanceof JsonString jsonString) { + final Schema.EntriesOrder order = Schema.EntriesOrder.of(jsonString.getString()); return builder.build(order); } else { return builder.build(); @@ -109,11 +109,11 @@ private Schema toSchema(final JsonObject json) { private void treatElementSchema(final JsonObject json, final Consumer setter) { final JsonValue elementSchema = json.get(ELEMENT_SCHEMA); - if (elementSchema instanceof JsonObject) { - final Schema schema = this.toSchema((JsonObject) elementSchema); + if (elementSchema instanceof JsonObject jsonObject) { + final Schema schema = this.toSchema(jsonObject); setter.accept(schema); - } else if (elementSchema instanceof JsonString) { - final Schema.Type innerType = Schema.Type.valueOf(((JsonString) elementSchema).getString()); + } else if (elementSchema instanceof JsonString jsonString) { + final Schema.Type innerType = Schema.Type.valueOf(jsonString.getString()); setter.accept(this.factory.newSchemaBuilder(innerType).build()); } } @@ -276,17 +276,17 @@ private JsonValue toValue(final Object object) { if (object == null) { return JsonValue.NULL; } - if (object instanceof Integer) { - return Json.createValue((Integer) object); + if (object instanceof Integer i) { + return Json.createValue(i); } - if (object instanceof Long) { - return Json.createValue((Long) object); + if (object instanceof Long l) { + return Json.createValue(l); } if (object instanceof Double || object instanceof Float) { return Json.createValue((Double) object); } - if (object instanceof BigInteger) { - return Json.createValue((BigInteger) object); + if (object instanceof BigInteger bi) { + return Json.createValue(bi); } if (object instanceof Boolean) { if (object == Boolean.TRUE) { @@ -294,11 +294,11 @@ private JsonValue toValue(final Object object) { } return JsonValue.FALSE; } - if (object instanceof BigDecimal) { - return Json.createValue((BigDecimal) object); + if (object instanceof BigDecimal bd) { + return Json.createValue(bd); } - if (object instanceof String) { - return Json.createValue((String) object); + if (object instanceof String s) { + return Json.createValue(s); } return null; diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java index 79034d8e80770..6b229189412f6 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java @@ -77,8 +77,8 @@ void findException() { } private Record toRecord(final Object object) { - if (object instanceof Record) { - return (Record) object; + if (object instanceof Record rcd) { + return rcd; } return null; } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java index 8b4a82dd85e6c..e0481145dbdf3 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java @@ -254,8 +254,7 @@ public int hashCode() { public boolean equals(final Object obj) { if (this == obj) { return true; - } else if (obj instanceof ParameterizedType) { - final ParameterizedType that = (ParameterizedType) obj; + } else if (obj instanceof ParameterizedType that) { final Type thatRawType = that.getRawType(); return that.getOwnerType() == null && (rawType == null ? thatRawType == null : rawType.equals(thatRawType)) diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java index 5d9a30e1c07d4..1f49e1554244d 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java @@ -46,8 +46,8 @@ public OutputFactory asOutputFactory() { if (ref != null && value != null) { if (value instanceof javax.json.JsonValue) { ref.add(jsonb.fromJson(value.toString(), ref.getType())); - } else if (value instanceof Record) { - ref.add(registry.find(ref.getType()).newInstance(Record.class.cast(value))); + } else if (value instanceof Record rcd) { + ref.add(registry.find(ref.getType()).newInstance(rcd)); } else { ref.add(jsonb.fromJson(jsonb.toJson(value), ref.getType())); } @@ -67,8 +67,8 @@ public OutputFactory asOutputFactoryForGuessSchema() { if (ref != null && value != null) { if (value instanceof javax.json.JsonValue) { ref.add(jsonb.fromJson(value.toString(), ref.getType())); - } else if (value instanceof Record) { - ref.add(((Record) value).getSchema()); + } else if (value instanceof Record rcd) { + ref.add(rcd.getSchema()); } else if (value instanceof Schema) { ref.add(value); } else { diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java index 9c72735b566d5..6e36e7afea1dd 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java @@ -174,10 +174,10 @@ private void initClass2JavaTypeMap() { private DiscoverSchemaException transformException(final Exception e) { DiscoverSchemaException discoverSchemaException; - if (e instanceof DiscoverSchemaException) { - discoverSchemaException = DiscoverSchemaException.class.cast(e); - } else if (e instanceof ComponentException) { - discoverSchemaException = new DiscoverSchemaException((ComponentException) e); + if (e instanceof DiscoverSchemaException dse) { + discoverSchemaException = dse; + } else if (e instanceof ComponentException ce) { + discoverSchemaException = new DiscoverSchemaException(ce); } else { discoverSchemaException = new DiscoverSchemaException(e.getMessage(), e.getStackTrace(), EXCEPTION); } @@ -253,12 +253,11 @@ private void executeDiscoverSchemaExtendedAction(final Schema schema, final Stri } final Object schemaResult = actionRef.getInvoker().apply(buildActionConfig(actionRef, configuration, schema, branch)); - if (schemaResult instanceof Schema) { - final Schema result = (Schema) schemaResult; + if (schemaResult instanceof Schema result) { if (result.getEntries().isEmpty()) { throw new DiscoverSchemaException(ERROR_NO_AVAILABLE_SCHEMA_FOUND, EXCEPTION); } else { - fromSchema(Schema.class.cast(schemaResult)); + fromSchema(result); } } } @@ -468,8 +467,8 @@ public boolean guessSchemaThroughAction(final Schema schema) { : buildActionConfig(actionRef, configuration, schema, "INPUT"); final Object schemaResult = actionRef.getInvoker().apply(actionConfiguration); - if (schemaResult instanceof Schema) { - return fromSchema(Schema.class.cast(schemaResult)); + if (schemaResult instanceof Schema resultSchema) { + return fromSchema(resultSchema); } else { log.error(ERROR_INSTANCE_SCHEMA); @@ -501,8 +500,7 @@ private boolean fromSchema(final Schema schema) { public Collection getFixedSchema(final String execute) { SchemaConverter sc = new SchemaConverter(); Object o = sc.toObjectImpl(execute); - if (o instanceof Schema) { - final Schema schema = Schema.class.cast(o); + if (o instanceof Schema schema) { final Collection entries = schema.getEntries(); if (entries == null || entries.isEmpty()) { log.info(NO_COLUMN_FOUND_BY_GUESS_SCHEMA); @@ -675,10 +673,10 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { if (rowObject == null) { return false; } - if (rowObject instanceof Record) { - return fromSchema(Record.class.cast(rowObject).getSchema()); - } else if (rowObject instanceof java.util.Map) { - return guessInputSchemaThroughResults(input, (java.util.Map) rowObject); + if (rowObject instanceof Record record) { + return fromSchema(record.getSchema()); + } else if (rowObject instanceof java.util.Map map) { + return guessInputSchemaThroughResults(input, map); } else if (rowObject instanceof java.util.Collection) { throw new Exception("Can't guess schema from a Collection"); } else { @@ -707,12 +705,12 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { * @return true if completed; false if one more result row is needed. */ public boolean guessSchemaThroughResult(final Object rowObject) throws Exception { - if (rowObject instanceof java.util.Map) { - return guessSchemaThroughResult((java.util.Map) rowObject); - } else if (rowObject instanceof Schema) { - return fromSchema(Schema.class.cast(rowObject)); - } else if (rowObject instanceof Record) { - return fromSchema(Record.class.cast(rowObject).getSchema()); + if (rowObject instanceof java.util.Map map) { + return guessSchemaThroughResult(map); + } else if (rowObject instanceof Schema schema) { + return fromSchema(schema); + } else if (rowObject instanceof Record record) { + return fromSchema(record.getSchema()); } else if (rowObject instanceof java.util.Collection) { throw new Exception("Can't guess schema from a Collection"); } else { diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java index 37f2e428857fb..8062b181e84ee 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java @@ -40,8 +40,8 @@ public class AfterVariableExtracter { * @return map with after variables. */ public static Map extractAfterVariables(final Lifecycle lifecycle) { - if (lifecycle instanceof Delegated) { - final Object delegate = ((Delegated) lifecycle).getDelegate(); + if (lifecycle instanceof Delegated delegated) { + final Object delegate = delegated.getDelegate(); final ClassLoader classloader = ReflectionUtils.getClassLoader(lifecycle); diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java index b0461c4ed8757..adc60ff9c15d2 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java @@ -92,8 +92,8 @@ public void change(final String path, final Object value) { try { target = field.get(target); if (arrayLocation > -1) { - if (target instanceof List) { - target = List.class.cast(target).get(arrayLocation); + if (target instanceof List list) { + target = list.get(arrayLocation); } else { log.warn("expect a list, but not"); return; diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java index 9370724f2b2ac..cace2e87e06b0 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java @@ -35,8 +35,8 @@ public class RuntimeContextInjector { * @see Lifecycle */ public static void injectLifecycle(final Lifecycle lifecycle, final RuntimeContextHolder runtimeContext) { - if (lifecycle instanceof Delegated) { - final Object delegate = ((Delegated) lifecycle).getDelegate(); + if (lifecycle instanceof Delegated delegated) { + final Object delegate = delegated.getDelegate(); Class currentClass = delegate.getClass(); while (currentClass != null && currentClass != Object.class) { diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java index ef20ebc84b7fa..a6abe6bb6f84f 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java @@ -470,8 +470,8 @@ private boolean hasCorrectReturnType(final Method method) { private boolean hasStringInList(final Method method) { if (List.class.isAssignableFrom(method.getReturnType()) - && method.getGenericReturnType() instanceof ParameterizedType) { - Type[] actualTypeArguments = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments(); + && method.getGenericReturnType() instanceof ParameterizedType parameterizedType) { + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments.length > 0) { return "java.lang.String".equals(actualTypeArguments[0].getTypeName()); } From e6240c614ee7dd746fa217526956d5719c096835 Mon Sep 17 00:00:00 2001 From: Emmanuel GALLOIS Date: Thu, 21 May 2026 18:40:56 +0200 Subject: [PATCH 2/7] chore(QTDI-2893): rename pattern match --- .../component/runtime/di/schema/TaCoKitGuessSchema.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java index 6e36e7afea1dd..4783e851def3b 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java @@ -673,8 +673,8 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { if (rowObject == null) { return false; } - if (rowObject instanceof Record record) { - return fromSchema(record.getSchema()); + if (rowObject instanceof Record rcd) { + return fromSchema(rcd.getSchema()); } else if (rowObject instanceof java.util.Map map) { return guessInputSchemaThroughResults(input, map); } else if (rowObject instanceof java.util.Collection) { @@ -709,8 +709,8 @@ public boolean guessSchemaThroughResult(final Object rowObject) throws Exception return guessSchemaThroughResult(map); } else if (rowObject instanceof Schema schema) { return fromSchema(schema); - } else if (rowObject instanceof Record record) { - return fromSchema(record.getSchema()); + } else if (rowObject instanceof Record rcd) { + return fromSchema(rcd.getSchema()); } else if (rowObject instanceof java.util.Collection) { throw new Exception("Can't guess schema from a Collection"); } else { From 4a4ba7278dc3837d8801c61d1e16f9a9bd97bf7c Mon Sep 17 00:00:00 2001 From: Emmanuel GALLOIS Date: Wed, 3 Jun 2026 17:27:54 +0200 Subject: [PATCH 3/7] chore(QTDI-2893): S6201 changes after rebase --- .../validation/spi/ext/TypeValidation.java | 4 +- .../jsonschema/PojoJsonSchemaBuilder.java | 9 ++- .../runtime/beam/BaseProcessorFn.java | 4 +- .../sdk/component/runtime/beam/TalendIO.java | 8 +-- .../beam/coder/JsonpJsonObjectCoder.java | 2 +- .../service/AutoValueFluentApiFactory.java | 7 +- .../beam/spi/BeamComponentExtension.java | 4 +- .../runtime/beam/spi/BeamProducerFinder.java | 4 +- ..._CustomJdbcIO_DataSourceConfiguration.java | 3 +- .../transformer/BeamIOTransformerTest.java | 4 +- .../repository/RepositoryModelBuilder.java | 4 +- component-runtime-impl/pom.xml | 2 +- .../exception/InvocationExceptionWrapper.java | 12 ++-- .../runtime/input/LocalPartitionMapper.java | 3 +- .../runtime/record/MappingUtils.java | 14 ++-- .../runtime/record/RecordConverters.java | 35 +++++---- .../record/json/RecordJsonGenerator.java | 46 ++++++------ .../component/runtime/reflect/Defaults.java | 9 +-- .../runtime/visitor/ModelVisitor.java | 6 +- .../runtime/record/PluralRecordExtension.java | 2 +- .../runtime/manager/ComponentManager.java | 31 ++++---- .../runtime/manager/asm/Unsafes.java | 4 +- .../manager/chain/internal/JobImpl.java | 24 +++---- .../configuration/ConfigurationMapper.java | 2 +- .../interceptor/InterceptorHandlerFacade.java | 4 +- .../reflect/ParameterModelService.java | 72 +++++++++---------- .../manager/reflect/ReflectionService.java | 47 ++++++------ .../reflect/StringCompatibleTypes.java | 2 +- .../ConditionParameterEnricher.java | 7 +- .../DependencyParameterEnricher.java | 2 +- .../UiParameterEnricher.java | 6 +- .../ValidationParameterEnricher.java | 6 +- .../reflect/visibility/VisibilityService.java | 12 ++-- .../runtime/manager/service/InjectorImpl.java | 14 ++-- .../service/RecordPointerFactoryImpl.java | 9 ++- .../runtime/manager/service/ResolverImpl.java | 4 +- .../manager/service/http/RequestParser.java | 15 ++-- .../manager/util/DefaultValueInspector.java | 7 +- .../runtime/manager/xbean/FilterFactory.java | 2 +- .../runtime/manager/ComponentManagerTest.java | 3 +- .../manager/ConfigurationMigrationTest.java | 40 ++++++----- .../manager/ReflectionServiceTest.java | 6 +- .../service/RecordServiceImplTest.java | 45 ++++++------ ...efaultResponseLocatorCapturingHandler.java | 4 +- .../internal/impl/PassthroughHandler.java | 3 +- .../JUnit4HttpApiPerMethodConfigurator.java | 8 +-- .../junit/delegate/DelegatingRunner.java | 4 +- .../DecoratingEnvironmentProvider.java | 4 +- .../environment/MultiEnvironmentsRunner.java | 3 +- .../component/junit/lang/StreamDecorator.java | 16 ++--- .../component/junit5/ComponentExtension.java | 3 +- .../environment/EnvironmentalContext.java | 3 +- .../spark/junit5/internal/SparkExtension.java | 8 +-- .../server/front/ActionResourceImpl.java | 10 ++- .../front/ConfigurationTypeResourceImpl.java | 3 +- .../front/error/DefaultExceptionHandler.java | 8 +-- .../server/front/memory/AsyncContextImpl.java | 4 +- .../server/mdc/MdcRequestBinder.java | 4 +- .../service/statistic/StatisticService.java | 3 +- .../service/template/TemplateRenderer.java | 4 +- .../component/service/MockTableService.java | 3 +- .../component/runtime/di/JobStateAware.java | 4 +- .../component/runtime/di/beam/LoopState.java | 2 +- .../di/beam/components/DIPipeline.java | 8 +-- .../runtime/di/record/DiRowStructVisitor.java | 14 ++-- .../runtime/di/schema/TaCoKitGuessSchema.java | 16 ++--- .../runtime/di/studio/ParameterSetter.java | 4 +- .../components/DIBatchSimulationTest.java | 4 +- .../tools/webapp/WebAppComponentProxy.java | 10 ++- .../component/tools/AsciidoctorExecutor.java | 6 +- .../sdk/component/tools/CarBundler.java | 2 +- .../component/tools/ComponentValidator.java | 2 +- .../sdk/component/tools/DocBaseGenerator.java | 6 +- .../talend/sdk/component/tools/SVG2Png.java | 2 +- .../sdk/component/tools/StudioInstaller.java | 2 +- .../talend/sdk/component/tools/WebServer.java | 2 +- .../tools/validator/LayoutValidator.java | 11 ++- .../tools/ComponentValidatorTest.java | 5 +- .../classloader/ConfigurableClassLoader.java | 13 ++-- .../talend/sdk/component/ContainerTest.java | 4 +- .../runtime/documentation/Generator.java | 3 +- .../talend/runtime/documentation/Github.java | 4 +- .../component/service/MockTableService.java | 3 +- .../singer/kitap/RecordJsonMapper.java | 3 +- .../component/maven/WebsiteBuilderMojo.java | 4 +- .../components/vault/client/VaultClient.java | 12 ++-- 86 files changed, 383 insertions(+), 404 deletions(-) diff --git a/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java b/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java index 3bcad26b568d3..74728b2091965 100644 --- a/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java +++ b/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java @@ -38,10 +38,10 @@ public class TypeValidation implements ValidationExtension { @Override public Optional>> create(final ValidationContext model) { final JsonValue value = model.getSchema().get("type"); - if (value instanceof JsonString) { + if (value instanceof JsonString jsonString) { return Optional .of(new Impl(model.toPointer(), model.getValueProvider(), - mapType((JsonString) value).toArray(JsonValue.ValueType[]::new))); + mapType(jsonString).toArray(JsonValue.ValueType[]::new))); } if (value instanceof JsonArray) { return Optional diff --git a/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java b/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java index ad3af841abbba..1d02b45ee376b 100644 --- a/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java +++ b/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java @@ -64,7 +64,7 @@ public JsonSchema.Builder create(final Class pojo) { private JsonSchema buildSchema(final Field field) { final Type genericType = field.getGenericType(); - if ((genericType instanceof Class && CharSequence.class.isAssignableFrom((Class) genericType)) + if ((genericType instanceof Class clazz && CharSequence.class.isAssignableFrom(clazz)) || genericType == char.class || genericType == Character.class) { return schemas.computeIfAbsent((Class) genericType, k -> jsonSchema().withType("string").build()); } else if (genericType == long.class || genericType == Long.class || genericType == int.class @@ -76,15 +76,14 @@ private JsonSchema buildSchema(final Field field) { } else if (genericType == boolean.class || genericType == Boolean.class) { return schemas .computeIfAbsent((Class) genericType, k -> jsonSchema().withType("boolean").build()); - } else if (genericType instanceof Class) { - final Class clazz = (Class) genericType; + } else if (genericType instanceof Class classVal) { + final Class clazz = classVal; return ofNullable(schemas.get(clazz)).orElseGet(() -> { final JsonSchema jsonSchema = create(clazz).build(); schemas.put(clazz, jsonSchema); return jsonSchema; }); - } else if (genericType instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) genericType; + } else if (genericType instanceof ParameterizedType pt) { final Type rawType = pt.getRawType(); if (!(rawType instanceof Class)) { throw new IllegalArgumentException("Unsupported raw type: " + pt + ", this must be a Class"); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java index 096d18cd1a7d5..64a890b23d809 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java @@ -65,8 +65,8 @@ abstract class BaseProcessorFn extends DoFn { BaseProcessorFn(final Processor processor) { this.processor = processor; - if (processor instanceof ProcessorImpl) { - ((ProcessorImpl) processor) + if (processor instanceof ProcessorImpl processorImpl) { + processorImpl .getInternalConfiguration() .entrySet() .stream() diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java index 92b8ad56d0183..929415959ff17 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java @@ -77,8 +77,8 @@ public static Base, Mapper> read(final Mapper mapper String maxRecords = null; String maxDurationMs = null; boolean hasInternalConfParams = false; - if (mapper instanceof PartitionMapperImpl) { - Map conf = ((PartitionMapperImpl) mapper).getInternalConfiguration(); + if (mapper instanceof PartitionMapperImpl partitionMapperImpl) { + Map conf = partitionMapperImpl.getInternalConfiguration(); hasInternalConfParams = conf.keySet() .stream() .filter(k -> k.equals("$maxRecords") || k.equals("$maxDurationMs")) @@ -164,8 +164,8 @@ private static class InfiniteRead extends Base, Mapp private InfiniteRead(final Mapper delegate, final long maxRecordCount, final long maxDuration) { super(delegate); // ensure we consider localConfiguration - final Map internalConf = delegate instanceof PartitionMapperImpl - ? ((PartitionMapperImpl) delegate).getInternalConfiguration() + final Map internalConf = delegate instanceof PartitionMapperImpl partitionMapper + ? partitionMapper.getInternalConfiguration() : emptyMap(); StopConfiguration fromLocalConf = (StopConfiguration) Streaming.loadStopStrategy(delegate.plugin(), internalConf); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java index 4a2ac4b9bb7e2..41ee3cc4d5f10 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java @@ -71,7 +71,7 @@ public JsonObject decode(final InputStream inputStream) throws IOException { @Override public boolean equals(final Object obj) { - return obj instanceof JsonpJsonObjectCoder && ((JsonpJsonObjectCoder) obj).isValid(); + return obj instanceof JsonpJsonObjectCoder coder && coder.isValid(); } @Override diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java index fa02d34facb1f..479890b305e53 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java @@ -164,14 +164,13 @@ private Object createPrimitiveValue(final Object v, final Type type) { if (String.class == type) { // fast path return v; } - if (type instanceof Class && ((Class) type).isInstance(v)) { + if (type instanceof Class clazz && (clazz.isInstance(v))) { return v; } - if (type instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) type; + if (type instanceof ParameterizedType pt) { final Type raw = pt.getRawType(); // we know what we do if we use that - if (raw instanceof Class && ((Class) raw).isInstance(v)) { + if (raw instanceof Class clazz && clazz.isInstance(v)) { return v; } } diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java index 38a90bc6a0dc5..2725df179d041 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java @@ -66,10 +66,10 @@ public boolean isActive() { @Override public T unwrap(final Class type, final Object... args) { if ("org.talend.sdk.component.design.extension.flows.FlowsFactory".equals(type.getName()) && args != null - && args.length == 1 && args[0] instanceof ComponentFamilyMeta.BaseMeta) { + && args.length == 1 && args[0] instanceof ComponentFamilyMeta.BaseMeta baseMeta) { if (args[0] instanceof ComponentFamilyMeta.ProcessorMeta) { try { - final FlowsFactory factory = FlowsFactory.get((ComponentFamilyMeta.BaseMeta) args[0]); + final FlowsFactory factory = FlowsFactory.get(baseMeta); factory.getOutputFlows(); return type.cast(factory); } catch (final Exception e) { // no @ElementListener, let's default for native transforms diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java index ed4562a073ffd..e0ce3869304af 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java @@ -65,10 +65,10 @@ public Iterator find(final String familyName, final String inputName, fi } catch (Exception e) { log.warn("Component Kit Mapper instantiation failed, trying to wrap native beam mapper..."); final Object delegate = ((Delegated) mapper).getDelegate(); - if (delegate instanceof PTransform) { + if (delegate instanceof PTransform pTransform) { final UUID uuid = UUID.randomUUID(); QUEUE.put(uuid, new ArrayBlockingQueue<>(QUEUE_SIZE, true)); - return new QueueInput(delegate, familyName, inputName, familyName, (PTransform) delegate, + return new QueueInput(delegate, familyName, inputName, familyName, pTransform, uuid); } throw new IllegalStateException(e); diff --git a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/factory/service/io/AutoValue_CustomJdbcIO_DataSourceConfiguration.java b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/factory/service/io/AutoValue_CustomJdbcIO_DataSourceConfiguration.java index b42f2576a5e00..d56188404121a 100644 --- a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/factory/service/io/AutoValue_CustomJdbcIO_DataSourceConfiguration.java +++ b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/factory/service/io/AutoValue_CustomJdbcIO_DataSourceConfiguration.java @@ -86,8 +86,7 @@ public boolean equals(final Object o) { if (o == this) { return true; } - if (o instanceof CustomJdbcIO.DataSourceConfiguration) { - CustomJdbcIO.DataSourceConfiguration that = (CustomJdbcIO.DataSourceConfiguration) o; + if (o instanceof CustomJdbcIO.DataSourceConfiguration that) { return ((this.driverClassName == null) ? (that.getDriverClassName() == null) : this.driverClassName.equals(that.getDriverClassName())) && ((this.url == null) ? (that.getUrl() == null) : this.url.equals(that.getUrl())) diff --git a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java index 8e3778f6ccf5d..ef23993a5e46a 100644 --- a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java +++ b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java @@ -148,8 +148,8 @@ void coderSerialization() { private Object newInstance(final Class aClass, final ClassLoader validationLoader) { try { final Object instance = aClass.getConstructor().newInstance(); - if (instance instanceof SetValidator) { - ((SetValidator) instance) + if (instance instanceof SetValidator setValidatorVal) { + setValidatorVal .setValidator( () -> assertEquals(Thread.currentThread().getContextClassLoader(), validationLoader)); } diff --git a/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java b/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java index 7b589deec12a7..95a23426aa0c4 100644 --- a/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java +++ b/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java @@ -130,8 +130,8 @@ private Config createConfig(final String plugin, final ComponentManager.AllServi .setId(IdGenerator .get(plugin, c.getKey().getFamily(), c.getKey().getConfigType(), c.getKey().getConfigName())); - if (config.getJavaType() instanceof Class) { - final Class clazz = (Class) config.getJavaType(); + if (config.getJavaType() instanceof Class classVal) { + final Class clazz = classVal; final Version version = clazz.getAnnotation(Version.class); if (version != null) { c.setVersion(version.value()); diff --git a/component-runtime-impl/pom.xml b/component-runtime-impl/pom.xml index 797f126671551..c0390a6615856 100644 --- a/component-runtime-impl/pom.xml +++ b/component-runtime-impl/pom.xml @@ -56,7 +56,7 @@ nl.jqno.equalsverifier equalsverifier - 3.7.2 + 4.4.2 test diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java index 8f1664df492d2..f4fa4f3e9766a 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java @@ -42,15 +42,15 @@ private static RuntimeException mapException(final Throwable targetException, fi if (targetException == null) { return null; } - if (targetException instanceof ComponentException) { - return (ComponentException) targetException; + if (targetException instanceof ComponentException componentException) { + return componentException; } - if (targetException instanceof DiscoverSchemaException) { - return (DiscoverSchemaException) targetException; + if (targetException instanceof DiscoverSchemaException discoverSchemaException) { + return discoverSchemaException; } - if (targetException instanceof RuntimeException + if (targetException instanceof RuntimeException rte && targetException.getClass().getName().startsWith("java.")) { - final RuntimeException cast = (RuntimeException) targetException; + final RuntimeException cast = rte; if (cast.getCause() == null || (cast.getCause() != null && cast.getCause().getClass().getName().startsWith("java."))) { return cast; diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java index 65f169e23e40d..2bee553b2b832 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java @@ -61,8 +61,7 @@ public List split(final long desiredSize) { @Override public Input create() { - return input instanceof Input ? (Input) input - : new InputImpl(rootName(), name(), plugin(), input); + return input instanceof Input in ? in : new InputImpl(rootName(), name(), plugin(), input); } @Override diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java index 6c5fa2a3b5fb0..08c7ecb899166 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java @@ -68,9 +68,9 @@ public static Object coerce(final Class expectedType, final Object value, // non-matching types if (!expectedType.isInstance(value)) { // number classes mapping - if (value instanceof Number + if (value instanceof Number number && Number.class.isAssignableFrom(PRIMITIVE_WRAPPER_MAP.getOrDefault(expectedType, expectedType))) { - return mapNumber(expectedType, (Number) value); + return mapNumber(expectedType, number); } // mapping primitive <-> Class if (isAssignableTo(value.getClass(), expectedType)) { @@ -80,20 +80,20 @@ public static Object coerce(final Class expectedType, final Object value, return String.valueOf(value); } // TCOMP-2293 support Instant - if (value instanceof Instant) { + if (value instanceof Instant instantVal) { if (ZonedDateTime.class == expectedType) { - return ZonedDateTime.ofInstant((Instant) value, UTC); + return ZonedDateTime.ofInstant(instantVal, UTC); } else if (java.util.Date.class == expectedType) { - return java.sql.Timestamp.from((Instant) value); + return java.sql.Timestamp.from(instantVal); } else if (Long.class == expectedType) { - return ((Instant) value).toEpochMilli(); + return instantVal.toEpochMilli(); } } if (value instanceof Timestamp && (java.util.Date.class == expectedType || Instant.class == expectedType)) { return value; } - if (value instanceof long[]) { + if (value instanceof long[]) { // NOSONAR final Instant instant = Instant.ofEpochSecond(((long[]) value)[0], ((long[]) value)[1]); if (ZonedDateTime.class == expectedType) { return ZonedDateTime.ofInstant(instant, UTC); diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java index e8fc0b07e4f4c..c82f665525c17 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java @@ -68,11 +68,11 @@ public Record toRecord(final MappingMetaRegistry registry, final T data, fin if (data == null) { return null; } - if (data instanceof Record) { - return (Record) data; + if (data instanceof Record recordVal) { + return recordVal; } - if (data instanceof JsonObject) { - return json2Record(recordBuilderProvider.get(), (JsonObject) data); + if (data instanceof JsonObject jsonObject) { + return json2Record(recordBuilderProvider.get(), jsonObject); } final MappingMeta meta = registry.find(data.getClass()); @@ -172,17 +172,17 @@ private Schema getArrayElementSchema(final RecordBuilderFactory factory, final L } private Object mapJson(final RecordBuilderFactory factory, final JsonValue it) { - if (it instanceof JsonObject) { - return json2Record(factory, (JsonObject) it); + if (it instanceof JsonObject jsonObject) { + return json2Record(factory, jsonObject); } - if (it instanceof JsonArray) { - return ((JsonArray) it).stream().map(i -> mapJson(factory, i)).collect(toList()); + if (it instanceof JsonArray jsonArray) { + return jsonArray.stream().map(i -> mapJson(factory, i)).collect(toList()); } - if (it instanceof JsonString) { - return ((JsonString) it).getString(); + if (it instanceof JsonString jsonString) { + return jsonString.getString(); } - if (it instanceof JsonNumber) { - return ((JsonNumber) it).numberValue(); + if (it instanceof JsonNumber jsonNumber) { + return jsonNumber.numberValue(); } if (JsonValue.FALSE.equals(it)) { return false; @@ -237,8 +237,8 @@ public static Schema toSchema(final RecordBuilderFactory factory, final Object n .withElementSchema(toSchema(factory, collection.iterator().next())) .build(); } - if (next instanceof Record) { - return ((Record) next).getSchema(); + if (next instanceof Record recordVal) { + return recordVal.getSchema(); } throw new IllegalArgumentException("unsupported type for " + next); } @@ -259,13 +259,12 @@ public Object toType(final MappingMetaRegistry registry, final Object data, fina } final JsonObject inputAsJson; - if (data instanceof JsonObject) { + if (data instanceof JsonObject jsonObject) { if (JsonObject.class == parameterType) { return data; } - inputAsJson = (JsonObject) data; - } else if (data instanceof Record) { - final Record record = (Record) data; + inputAsJson = jsonObject; + } else if (data instanceof Record record) { if (!JsonObject.class.isAssignableFrom(parameterType)) { final MappingMeta mappingMeta = registry.find(parameterType); if (mappingMeta.isLinearMapping()) { diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java index 889b4038aea4c..fe71160a56dba 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java @@ -320,53 +320,49 @@ public JsonGenerator writeEnd() { final String name; Object previous = builders.getLast(); - if (previous instanceof NamedBuilder) { - final NamedBuilder namedBuilder = (NamedBuilder) previous; + if (previous instanceof NamedBuilder namedBuilder) { name = namedBuilder.name; previous = namedBuilder.builder; } else { name = null; } - if (last instanceof List) { - final List array = (List) last; - if (previous instanceof Collection) { - arrayBuilder = (Collection) previous; + if (last instanceof List array) { + if (previous instanceof Collection collectionVal) { + arrayBuilder = collectionVal; objectBuilder = null; arrayBuilder.add(array); - } else if (previous instanceof Record.Builder) { - objectBuilder = (Record.Builder) previous; + } else if (previous instanceof Record.Builder builderVar) { + objectBuilder = builderVar; arrayBuilder = null; objectBuilder.withArray(createEntryBuilderForArray(name, array).build(), prepareArray(array)); } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); } - } else if (last instanceof Record.Builder) { - final Record.Builder object = (Record.Builder) last; - if (previous instanceof Collection) { - arrayBuilder = (Collection) previous; + } else if (last instanceof Record.Builder object) { + if (previous instanceof Collection collection) { + arrayBuilder = collection; objectBuilder = null; arrayBuilder.add(object); - } else if (previous instanceof Record.Builder) { - objectBuilder = (Record.Builder) previous; + } else if (previous instanceof Record.Builder builderVar) { + objectBuilder = builderVar; arrayBuilder = null; objectBuilder.withRecord(name, objectBuilder.build()); } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); } - } else if (last instanceof NamedBuilder) { - final NamedBuilder namedBuilder = (NamedBuilder) last; - if (previous instanceof Record.Builder) { - objectBuilder = (Record.Builder) previous; - if (namedBuilder.builder instanceof List) { - final List array = (List) namedBuilder.builder; + } else if (last instanceof NamedBuilder namedBuilderVal) { + final NamedBuilder namedBuilder = namedBuilderVal; + if (previous instanceof Record.Builder builderVal) { + objectBuilder = builderVal; + if (namedBuilder.builder instanceof List array) { objectBuilder .withArray(createEntryBuilderForArray(namedBuilder.name, array).build(), prepareArray(array)); arrayBuilder = null; - } else if (namedBuilder.builder instanceof Record.Builder) { + } else if (namedBuilder.builder instanceof Record.Builder builder2) { objectBuilder - .withRecord(namedBuilder.name, ((Record.Builder) namedBuilder.builder).build()); + .withRecord(namedBuilder.name, builder2.build()); arrayBuilder = null; } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); @@ -384,7 +380,7 @@ public JsonGenerator writeEnd() { private List prepareArray(final List array) { return ((Collection) array) .stream() - .map(it -> it instanceof Record.Builder ? ((Record.Builder) it).build() : it) + .map(it -> it instanceof Record.Builder builder ? builder.build() : it) .collect(toList()); } @@ -514,8 +510,8 @@ public static class Factory implements JsonGeneratorFactory { @Override public JsonGenerator createGenerator(final Writer writer) { - if (writer instanceof OutputRecordHolder) { - return new RecordJsonGenerator(factory.get(), jsonb.get(), (OutputRecordHolder) writer); + if (writer instanceof OutputRecordHolder outputRecordHolder) { + return new RecordJsonGenerator(factory.get(), jsonb.get(), outputRecordHolder); } throw new IllegalArgumentException("Unsupported writer: " + writer); } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java index 98db632afb7ae..d632994d510a9 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java @@ -63,10 +63,11 @@ public class Defaults { .invokeWithArguments(args); } else { // j > 8 - can need some --add-opens, we will add a module-info later to be clean when dropping j8 final Method privateLookup = findPrivateLookup(); - HANDLER = (clazz, method, proxy, args) -> ((MethodHandles.Lookup) privateLookup.invoke(null, clazz, constructor.newInstance(clazz))) - .unreflectSpecial(method, clazz) - .bindTo(proxy) - .invokeWithArguments(args); + HANDLER = (clazz, method, proxy, + args) -> ((MethodHandles.Lookup) privateLookup.invoke(null, clazz, constructor.newInstance(clazz))) + .unreflectSpecial(method, clazz) + .bindTo(proxy) + .invokeWithArguments(args); } } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java index 82124ad6ff4cf..3e37a6a8c9203 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java @@ -134,13 +134,13 @@ private void validatePartitionMapper(final Class type) { } final ParameterizedType splitPt = (ParameterizedType) splitReturnType; - if (!(splitPt.getRawType() instanceof Class) - || !Collection.class.isAssignableFrom((Class) splitPt.getRawType())) { + if (!(splitPt.getRawType() instanceof Class clazz) + || !Collection.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(m + " must return a List of partition mapper, found: " + splitPt); } final Type arg = splitPt.getActualTypeArguments().length != 1 ? null : splitPt.getActualTypeArguments()[0]; - if (!(arg instanceof Class) || !type.isAssignableFrom((Class) arg)) { + if (!(arg instanceof Class) || !type.isAssignableFrom((Class) arg)) { // NOSONAR throw new IllegalArgumentException( m + " must return a Collection<" + type.getName() + "> but found: " + arg); } diff --git a/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java b/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java index 7f53b27b52b5a..135526c66418f 100644 --- a/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java +++ b/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java @@ -58,7 +58,7 @@ private Jsonb getJsonb(Jsonb jsonb) { // create a Jsonb instance which is PojoJsonbProvider as in component-runtime-manager return (Jsonb) Proxy .newProxyInstance(Thread.currentThread().getContextClassLoader(), - new Class[]{Jsonb.class, PojoJsonbProvider.class}, (proxy, method, args) -> { + new Class[] { Jsonb.class, PojoJsonbProvider.class }, (proxy, method, args) -> { if (method.getDeclaringClass() == Supplier.class) { return jsonb; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java index 1083dced65595..548789e63e1e7 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java @@ -873,7 +873,7 @@ public Optional createComponent(final String plugin, final String name, final int version, final Map configuration) { return findComponentInternal(plugin, name, componentType, version, configuration) // unwrap to access the actual instance which is the desired one - .map(i -> i instanceof Delegated ? ((Delegated) i).getDelegate() : i); + .map(i -> i instanceof Delegated delegated ? delegated.getDelegate() : i); } private Optional findComponentInternal(final String plugin, final String name, @@ -1414,9 +1414,9 @@ protected boolean isTracked(final String annotationType) { } } : optimizedFinder; } finally { - if (archive instanceof AutoCloseable) { + if (archive instanceof AutoCloseable autoCloseable) { try { - ((AutoCloseable) archive).close(); + autoCloseable.close(); } catch (final Exception e) { log.warn(e.getMessage()); } @@ -1794,16 +1794,16 @@ private Archive toArchive(final String module, final OriginalId originalId, } private URL archiveToUrl(final Archive mainArchive) { - if (mainArchive instanceof JarArchive) { - return ((JarArchive) mainArchive).getUrl(); - } else if (mainArchive instanceof FileArchive) { + if (mainArchive instanceof JarArchive jarArchive) { + return jarArchive.getUrl(); + } else if (mainArchive instanceof FileArchive fileArchive) { try { - return ((FileArchive) mainArchive).getDir().toURI().toURL(); + return fileArchive.getDir().toURI().toURL(); } catch (final MalformedURLException e) { throw new IllegalStateException(e); } - } else if (mainArchive instanceof NestedJarArchive) { - return ((NestedJarArchive) mainArchive).getRootMarker(); + } else if (mainArchive instanceof NestedJarArchive nestedJarArchive) { + return nestedJarArchive.getRootMarker(); } return null; } @@ -1922,7 +1922,8 @@ public void onPartitionMapper(final Class type, final PartitionMapper partiti () -> { final List params = parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() + .get(LocalConfiguration.class))); if (infinite) { if (partitionMapper.stoppable()) { addInfiniteMapperBuiltInParameters(type, params); @@ -1975,7 +1976,8 @@ public void onEmitter(final Class type, final Emitter emitter) { final Supplier> parameterMetas = lazy(() -> executeInContainer(plugin, () -> parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() + .get(LocalConfiguration.class))))); final Function, Object[]> parameterFactory = createParametersFactory(plugin, constructor, services.getServices(), parameterMetas); final String name = of(emitter.name()).filter(n -> !n.isEmpty()).orElseGet(type::getName); @@ -2159,7 +2161,8 @@ public void onDriverRunner(final Class type, final DriverRunner processor) { final Supplier> parameterMetas = lazy(() -> executeInContainer(plugin, () -> parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() + .get(LocalConfiguration.class))))); final Function, Object[]> parameterFactory = createParametersFactory(plugin, constructor, services.getServices(), parameterMetas); final String name = of(processor.name()).filter(n -> !n.isEmpty()).orElseGet(type::getName); @@ -2212,8 +2215,8 @@ private ComponentFamilyMeta getOrCreateComponent(final String component) { return this.component == null || !component.equals(this.component.getName()) ? (this.component = new ComponentFamilyMeta(plugin, asList(components.categories()), iconFinder.findIcon(familyAnnotationElement), comp, - familyAnnotationElement instanceof Class - ? getPackage((Class) familyAnnotationElement) + familyAnnotationElement instanceof Class clazz + ? getPackage(clazz) : "")) : this.component; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java index 67a825281c2fa..1ebd8ffad5c7b 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java @@ -182,8 +182,8 @@ public final class Unsafes { */ public static Class defineAndLoadClass(final ClassLoader classLoader, final String proxyName, final byte[] proxyBytes) { - if (classLoader instanceof ConfigurableClassLoader) { - return (Class) ((ConfigurableClassLoader) classLoader) + if (classLoader instanceof ConfigurableClassLoader configurableClassLoader) { + return (Class) configurableClassLoader .registerBytecode(proxyName.replace('/', '.'), proxyBytes); } Class clazz = classLoader.getClass(); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java index a14aeb5e5c54a..e1499cf65d11f 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java @@ -258,12 +258,12 @@ public ExecutorBuilder property(final String name, final Object value) { public void run() { ExecutorBuilder runner = this; final Object o = jobProperties.get(ExecutorBuilder.class.getName()); - if (o instanceof ExecutorBuilder) { - runner = (ExecutorBuilder) o; - } else if (o instanceof Class) { - runner = newRunner((Class) o); - } else if (o instanceof String) { - final String name = ((String) o).trim(); + if (o instanceof ExecutorBuilder executorBuilder) { + runner = executorBuilder; + } else if (o instanceof Class classVal) { + runner = newRunner(classVal); + } else if (o instanceof String string) { + final String name = string.trim(); if (!"standalone".equalsIgnoreCase(name) && !"default".equalsIgnoreCase(name) && !"local".equalsIgnoreCase(name)) { if ("beam".equalsIgnoreCase(name)) { @@ -356,8 +356,8 @@ private void localRun() { .orElseThrow(() -> new IllegalStateException( "No processor found for:" + component.getNode())); final AtomicInteger maxBatchSize = new AtomicInteger(1); - if (processor instanceof ProcessorImpl) { - ((ProcessorImpl) processor) + if (processor instanceof ProcessorImpl processorImpl) { + processorImpl .getInternalConfiguration() .entrySet() .stream() @@ -539,14 +539,14 @@ private List getConnections(final List edges, final Job.Comp public GroupKeyProvider getKeyProvider(final String componentId) { if (componentProperties.get(componentId) != null) { final Object o = componentProperties.get(componentId).get(GroupKeyProvider.class.getName()); - if (o instanceof GroupKeyProvider) { - return new GroupKeyProviderImpl((GroupKeyProvider) o); + if (o instanceof GroupKeyProvider groupKeyProvider) { + return new GroupKeyProviderImpl(groupKeyProvider); } } final Object o = jobProperties.get(GroupKeyProvider.class.getName()); - if (o instanceof GroupKeyProvider) { - return new GroupKeyProviderImpl((GroupKeyProvider) o); + if (o instanceof GroupKeyProvider groupKeyProvider) { + return new GroupKeyProviderImpl(groupKeyProvider); } final ServiceLoader services = ServiceLoader.load(GroupKeyProvider.class); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java index 29e075f327176..b42c8085e41bb 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java @@ -57,7 +57,7 @@ private Map map(final List nestedParameters, fina case OBJECT: return map(param.getNestedParameters(), value, indexes); case ARRAY: - final Collection values = value instanceof Collection ? (Collection) value + final Collection values = value instanceof Collection collection ? collection : /* array */asList((Object[]) value); final int arrayIndex = indexes.keySet().size(); final AtomicInteger valuesIndex = new AtomicInteger(0); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java index 3347344ad8679..3e1703a5a4f53 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java @@ -135,8 +135,8 @@ private Object doInvoke(final Method method, final Object[] args) { return method.invoke(delegate, args); } catch (final InvocationTargetException ite) { final Throwable cause = ite.getCause(); - if (cause instanceof RuntimeException) { - throw (RuntimeException) cause; + if (cause instanceof RuntimeException runtimeException) { + throw runtimeException; } throw new IllegalStateException(cause.getMessage()); } catch (final IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java index 38619cf3f577b..171058654e83e 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java @@ -91,12 +91,12 @@ public ParameterModelService(final PropertyEditorRegistry registry) { public boolean isService(final Param parameter) { final Class type; - if (parameter.type instanceof Class) { - type = (Class) parameter.type; - } else if (parameter.type instanceof ParameterizedType) { - final Type rawType = ((ParameterizedType) parameter.type).getRawType(); - if (rawType instanceof Class) { - type = (Class) rawType; + if (parameter.type instanceof Class classVal) { + type = classVal; + } else if (parameter.type instanceof ParameterizedType pt) { + final Type rawType = pt.getRawType(); + if (rawType instanceof Class classVal) { + type = classVal; } else { return false; } @@ -136,13 +136,12 @@ public Class declaringClass() { } private Stream extractTypeAnnotation(final Param parameter) { - if (parameter.type instanceof Class) { - return Stream.of(((Class) parameter.type).getAnnotations()); + if (parameter.type instanceof Class classVal) { + return Stream.of(classVal.getAnnotations()); } - if (parameter.type instanceof ParameterizedType) { - final ParameterizedType parameterizedType = (ParameterizedType) parameter.type; - if (parameterizedType.getRawType() instanceof Class) { - return Stream.of(((Class) parameterizedType.getRawType()).getAnnotations()); + if (parameter.type instanceof ParameterizedType parameterizedType) { + if (parameterizedType.getRawType() instanceof Class classVal) { + return Stream.of(classVal.getAnnotations()); } } return Stream.empty(); @@ -180,13 +179,13 @@ protected ParameterMeta buildParameter(final String name, final String prefix, f nested.addAll(meta); break; case ARRAY: - final Type nestedType = genericType instanceof Class && ((Class) genericType).isArray() - ? ((Class) genericType).getComponentType() + final Type nestedType = genericType instanceof Class clazz && clazz.isArray() + ? clazz.getComponentType() : ((ParameterizedType) genericType).getActualTypeArguments()[0]; addI18nPackageIfPossible(i18nPackages, nestedType); nested .addAll(buildParametersMetas(name + "[${index}]", normalizedPrefix + "[${index}].", nestedType, - nestedType instanceof Class ? ((Class) nestedType).getAnnotations() + nestedType instanceof Class clazz ? clazz.getAnnotations() : NO_ANNOTATIONS, i18nPackages, ignoreI18n, context)); break; @@ -208,8 +207,8 @@ protected ParameterMeta buildParameter(final String name, final String prefix, f } private void addI18nPackageIfPossible(final Collection i18nPackages, final Type type) { - if (type instanceof Class) { - final Package typePck = ((Class) type).getPackage(); + if (type instanceof Class classVal) { + final Package typePck = classVal.getPackage(); if (typePck != null && !typePck.getName().isEmpty() && !i18nPackages.contains(typePck.getName())) { i18nPackages.add(typePck.getName()); } @@ -219,8 +218,7 @@ private void addI18nPackageIfPossible(final Collection i18nPackages, fin private Map buildExtensions(final String name, final Type genericType, final Annotation[] annotations, final BaseParameterEnricher.Context context) { return getAnnotations(genericType, annotations).distinct().flatMap(a -> enrichers.stream().map(e -> { - if (e instanceof BaseParameterEnricher) { - final BaseParameterEnricher bpe = (BaseParameterEnricher) e; + if (e instanceof BaseParameterEnricher bpe) { return bpe.withContext(context, () -> bpe.onParameterAnnotation(name, genericType, a)); } return e.onParameterAnnotation(name, genericType, a); @@ -254,16 +252,16 @@ private Stream getReflectionAnnotations(final Type genericType, fina .concat(Stream.of(annotations), // if a class concat its annotations genericType instanceof Class - ? getClassAnnotations(genericType, annotations) - : (hasAClassFirstParameter(genericType) ? getClassAnnotations( - ((ParameterizedType) genericType).getActualTypeArguments()[0], - annotations) : Stream.empty())); + ? getClassAnnotations(genericType, annotations) + : (hasAClassFirstParameter(genericType) ? getClassAnnotations( + ((ParameterizedType) genericType).getActualTypeArguments()[0], + annotations) : Stream.empty())); } private boolean hasAClassFirstParameter(final Type genericType) { - return genericType instanceof ParameterizedType // if a list concat the item type annotations - && ((ParameterizedType) genericType).getActualTypeArguments().length == 1 - && ((ParameterizedType) genericType).getActualTypeArguments()[0] instanceof Class; + return genericType instanceof ParameterizedType pt // if a list concat the item type annotations + && pt.getActualTypeArguments().length == 1 + && pt.getActualTypeArguments()[0] instanceof Class; } private Stream getClassAnnotations(final Type genericType, final Annotation[] annotations) { @@ -275,8 +273,7 @@ private Stream getClassAnnotations(final Type genericType, final Ann private List buildParametersMetas(final String name, final String prefix, final Type type, final Annotation[] annotations, final Collection i18nPackages, final boolean ignoreI18n, final BaseParameterEnricher.Context context) { - if (type instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) type; + if (type instanceof ParameterizedType pt) { if (!(pt.getRawType() instanceof Class)) { throw new IllegalArgumentException("Unsupported raw type in ParameterizedType parameter: " + pt); } @@ -297,7 +294,7 @@ private List buildParametersMetas(final String name, final String } return Stream .concat(buildParametersMetas(name + ".key[${index}]", prefix + "key[${index}].", - (Class) pt.getActualTypeArguments()[0], annotations, i18nPackages, ignoreI18n, + (Class) pt.getActualTypeArguments()[0], annotations, i18nPackages, ignoreI18n, context).stream(), buildParametersMetas(name + ".value[${index}]", prefix + "value[${index}].", (Class) pt.getActualTypeArguments()[1], annotations, i18nPackages, @@ -305,7 +302,7 @@ private List buildParametersMetas(final String name, final String .collect(toList()); } } - if (type instanceof Class) { + if (type instanceof Class classVal) { switch (findType(type)) { case ENUM: case STRING: @@ -320,12 +317,12 @@ public String name() { @Override public Class declaringClass() { - return (Class) type; + return classVal; } }, type, annotations, i18nPackages, ignoreI18n, context)); default: } - return buildObjectParameters(prefix, (Class) type, i18nPackages, ignoreI18n, context); + return buildObjectParameters(prefix, classVal, i18nPackages, ignoreI18n, context); } throw new IllegalArgumentException("Unsupported parameter type: " + type); } @@ -374,8 +371,8 @@ public String findName(final AnnotatedElement parameter, final String defaultNam } private ParameterMeta.Type findType(final Type type) { - if (type instanceof Class) { - final Class clazz = (Class) type; + if (type instanceof Class classVal) { + final Class clazz = classVal; // we handled char before so we only have numbers now for primitives if (Primitives.unwrap(clazz) == boolean.class) { @@ -395,10 +392,9 @@ private ParameterMeta.Type findType(final Type type) { return ParameterMeta.Type.ARRAY; } } - if (type instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) type; - if (pt.getRawType() instanceof Class) { - final Class raw = (Class) pt.getRawType(); + if (type instanceof ParameterizedType pt) { + if (pt.getRawType() instanceof Class classVal) { + final Class raw = classVal; if (Collection.class.isAssignableFrom(raw)) { return ParameterMeta.Type.ARRAY; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java index 14e221e164dcc..f3712b8efd842 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java @@ -111,10 +111,10 @@ public Function, Object[]> parameterFactory(final Executable Stream.of(executable.getParameters()).map(parameter -> { final String name = parameterModelService.findName(parameter, parameter.getName()); final Type parameterizedType = parameter.getParameterizedType(); - if (parameterizedType instanceof Class) { + if (parameterizedType instanceof Class classVal) { if (parameter.isAnnotationPresent(Configuration.class)) { try { - final Class configClass = (Class) parameterizedType; + final Class configClass = classVal; return createConfigFactory(precomputed, loader, contextualSupplier, parameter.getName(), parameter.getAnnotation(Configuration.class), parameter.getAnnotations(), configClass); @@ -124,8 +124,7 @@ public Function, Object[]> parameterFactory(final Executable } final Object value = precomputed.get(parameterizedType); if (value != null) { - if (value instanceof Copiable) { - final Copiable copiable = (Copiable) value; + if (value instanceof Copiable copiable) { return (Function, Object>) config -> copiable.copy(value); } return (Function, Object>) config -> value; @@ -136,11 +135,10 @@ public Function, Object[]> parameterFactory(final Executable .apply(name, (Map) config); } - if (parameterizedType instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) parameterizedType; - if (pt.getRawType() instanceof Class) { - if (Collection.class.isAssignableFrom((Class) pt.getRawType())) { - final Class collectionType = (Class) pt.getRawType(); + if (parameterizedType instanceof ParameterizedType pt) { + if (pt.getRawType() instanceof Class classVal2) { + if (Collection.class.isAssignableFrom(classVal2)) { + final Class collectionType = classVal2; final Type itemType = pt.getActualTypeArguments()[0]; if (!(itemType instanceof Class)) { throw new IllegalArgumentException( @@ -181,8 +179,8 @@ public Function, Object[]> parameterFactory(final Executable contextualSupplier, name, collectionType, itemClass, collector, itemFactory, (Map) config, parameterMetas, precomputed); } - if (Map.class.isAssignableFrom((Class) pt.getRawType())) { - final Class mapType = (Class) pt.getRawType(); + if (Map.class.isAssignableFrom(classVal2)) { + final Class mapType = classVal2; final Type keyItemType = pt.getActualTypeArguments()[0]; final Type valueItemType = pt.getActualTypeArguments()[1]; if (!(keyItemType instanceof Class) || !(valueItemType instanceof Class)) { @@ -429,14 +427,14 @@ private Object createObject(final ClassLoader loader, final Function arrayClass = (Class) genericType; + if (genericType instanceof Class classVal) { + final Class arrayClass = classVal; if (arrayClass.isArray()) { // we could use Array.newInstance but for now use the list, shouldn't impact // much the perf - final Collection list = (Collection) createList(loader, contextualSupplier, prefix + enclosingName, List.class, - arrayClass.getComponentType(), toList(), createObjectFactory(loader, - contextualSupplier, arrayClass.getComponentType(), metas, precomputed), - new HashMap<>(listEntries), metas, precomputed); + final Collection list = + (Collection) createList(loader, contextualSupplier, prefix + enclosingName, List.class, + arrayClass.getComponentType(), toList(), createObjectFactory(loader, + contextualSupplier, arrayClass.getComponentType(), metas, precomputed), + new HashMap<>(listEntries), metas, precomputed); // we need that conversion to ensure the type matches final Object array = Array.newInstance(arrayClass.getComponentType(), list.size()); @@ -590,10 +589,8 @@ private Object createObject(final ClassLoader loader, final Function 0) { final String listName = nestedName.substring(0, idxStart); final Field field = findField(normalizeName(listName, metas), clazz); - if (field.getGenericType() instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) field.getGenericType(); - if (pt.getRawType() instanceof Class) { - final Class rawType = (Class) pt.getRawType(); + if (field.getGenericType() instanceof ParameterizedType pt) { + if (pt.getRawType() instanceof Class rawType) { if (Set.class.isAssignableFrom(rawType)) { addListElement(loader, contextualSupplier, config, prefix, preparedObjects, nestedName, listName, pt, () -> new HashSet<>(2), translate(metas, listName), precomputed); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/StringCompatibleTypes.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/StringCompatibleTypes.java index 0273ac31afbb1..550fbb5c49012 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/StringCompatibleTypes.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/StringCompatibleTypes.java @@ -28,6 +28,6 @@ final class StringCompatibleTypes { static boolean isKnown(final Type type, final PropertyEditorRegistry registry) { return String.class == type || char.class == type || Character.class == type - || (type instanceof Class && registry.findConverter((Class) type) != null); + || (type instanceof Class clazz && registry.findConverter(clazz) != null); } } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ConditionParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ConditionParameterEnricher.java index 27c2d10ca9433..927a13ee1206b 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ConditionParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ConditionParameterEnricher.java @@ -42,8 +42,7 @@ public Map onParameterAnnotation(final String parameterName, fin final Condition condition = annotation.annotationType().getAnnotation(Condition.class); if (condition != null) { final String type = condition.value(); - if (annotation instanceof ActiveIfs) { - final ActiveIfs activeIfs = (ActiveIfs) annotation; + if (annotation instanceof ActiveIfs activeIfs) { final Map metas = Stream .of(activeIfs.value()) .map(ai -> onParameterAnnotation(parameterName, parameterType, ai)) @@ -73,8 +72,8 @@ private Map toMeta(final Annotation annotation, final String typ .collect(toMap(m -> META_PREFIX + type + "::" + m.getName(), m -> { try { final Object invoke = m.invoke(annotation); - if (invoke instanceof String[]) { - return Stream.of((String[]) invoke).collect(joining(",")); + if (invoke instanceof String[] stringArr) { + return Stream.of(stringArr).collect(joining(",")); } if (ActiveIf.class == m.getDeclaringClass() && "evaluationStrategy".equals(m.getName())) { final ActiveIf.EvaluationStrategyOption[] options = diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java index b2c657929dbcb..d4a430031b638 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java @@ -64,7 +64,7 @@ private boolean isCollectionConnectorReference(final Type parameterType) { // Check it's a Collection (java.util) final Type rawType = parameterClass.getRawType(); - if ((!(rawType instanceof Class)) || !Collection.class.isAssignableFrom((Class) rawType)) { + if ((!(rawType instanceof Class clazz)) || !Collection.class.isAssignableFrom(clazz)) { return false; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java index b128da1a8f6df..8f23f73863e64 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java @@ -177,10 +177,10 @@ private String toString(final Annotation annotation, final Method m, } return string; } - if (invoke instanceof Class) { - return ((Class) invoke).getSimpleName().toLowerCase(ENGLISH); + if (invoke instanceof Class classVal) { + return classVal.getSimpleName().toLowerCase(ENGLISH); } - if (invoke instanceof String[]) { + if (invoke instanceof String[]) { // NOSONAR return Stream.of((String[]) invoke).collect(joining(",")); } return String.valueOf(invoke); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java index 988609adc19c5..70ae5e222fc9e 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java @@ -49,9 +49,9 @@ public Map onParameterAnnotation(final String parameterName, fin } private Class toClass(final Type parameterType) { - return parameterType instanceof ParameterizedType - ? toClass(((ParameterizedType) parameterType).getRawType()) - : (parameterType instanceof Class ? (Class) parameterType : null); + return parameterType instanceof ParameterizedType pt + ? toClass(pt.getRawType()) + : (parameterType instanceof Class clazz ? clazz : null); } private String getValueString(final Annotation annotation) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java index 22de0e34c3979..4097a041c919e 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java @@ -148,14 +148,14 @@ private boolean evaluate(final String expected, final JsonObject payload) { return "0".equals(expected); } final int expectedSize = Integer.parseInt(expected); - if (actual instanceof Collection) { - return expectedSize == ((Collection) actual).size(); + if (actual instanceof Collection collectionVal) { + return expectedSize == collectionVal.size(); } if (actual.getClass().isArray()) { return expectedSize == Array.getLength(actual); } - if (actual instanceof String) { - return expectedSize == ((String) actual).length(); + if (actual instanceof String string) { + return expectedSize == string.length(); } return false; default: @@ -190,8 +190,8 @@ private boolean evaluate(final String expected, final JsonObject payload) { .map(it -> it.contains(expected)) .orElse(false); } - if (actual instanceof Collection) { - final Collection collection = (Collection) actual; + if (actual instanceof Collection collectionVal) { + final Collection collection = collectionVal; return collection.stream().map(preprocessor).anyMatch(it -> it.contains(expected)); } if (actual.getClass().isArray()) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java index 35573ae45a40f..617b3591f5c9c 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java @@ -86,13 +86,12 @@ private void doInject(final Class type, final T instance) { }) .forEach(field -> { Object value = services.get(field.getType()); - if (value == null && field.getGenericType() instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) field.getGenericType(); - if (pt.getRawType() instanceof Class - && Collection.class.isAssignableFrom((Class) pt.getRawType())) { + if (value == null && field.getGenericType() instanceof ParameterizedType pt) { + if (pt.getRawType() instanceof Class clazz + && Collection.class.isAssignableFrom(clazz)) { final Type serviceType = pt.getActualTypeArguments()[0]; - if (serviceType instanceof Class) { - final Class serviceClass = (Class) serviceType; + if (serviceType instanceof Class classVal) { + final Class serviceClass = classVal; value = services .entrySet() .stream() @@ -128,7 +127,8 @@ private void doInject(final Class type, final T instance) { }) .forEach(field -> { try { - final Class configClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class configClass = + (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Supplier supplier = () -> { try { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java index 4e5bad59f9640..fb7562a1170a4 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java @@ -105,8 +105,7 @@ public T getEntry(final Record target, final Class type) { private Object getValue(final Object value, final String referenceToken, final int currentPosition, final int referencePosition) { - if (value instanceof Record) { - final Record record = (Record) value; + if (value instanceof Record record) { final Object nestedVal = getRecordEntry(referenceToken, record); if (nestedVal != null) { return nestedVal; @@ -114,7 +113,7 @@ private Object getValue(final Object value, final String referenceToken, final i throw new IllegalArgumentException( "'" + record + "' contains no value for name '" + referenceToken + "'"); } - if (value instanceof Collection) { + if (value instanceof Collection collection) { if (referenceToken.startsWith("+") || referenceToken.startsWith("-")) { throw new IllegalArgumentException( "An array index must not start with '" + referenceToken.charAt(0) + "'"); @@ -123,14 +122,14 @@ private Object getValue(final Object value, final String referenceToken, final i throw new IllegalArgumentException("An array index must not start with a leading '0'"); } - final Collection array = (Collection) value; + final Collection array = collection; try { final int arrayIndex = Integer.parseInt(referenceToken); if (arrayIndex >= array.size()) { throw new IllegalArgumentException( "'" + array + "' contains no element for index " + arrayIndex); } - return array instanceof List ? ((List) array).get(arrayIndex) + return array instanceof List list ? list.get(arrayIndex) : new ArrayList<>(array).get(arrayIndex); } catch (final NumberFormatException e) { throw new IllegalArgumentException("'" + referenceToken + "' is no valid array index", e); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java index 2518b8d8353b2..a6675e90d7692 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java @@ -97,8 +97,8 @@ public ClassLoaderDescriptor mapDescriptorToClassLoader(final InputStream descri ofNullable(configuration.getParentClassesFilter()).orElse(it -> false), ofNullable(configuration.getClassesFilter()).orElse(it -> true), nested.toArray(new String[0]), - parent instanceof ConfigurableClassLoader - ? ((ConfigurableClassLoader) parent).getJvmMarkers() + parent instanceof ConfigurableClassLoader configurableClassLoader + ? configurableClassLoader.getJvmMarkers() : new String[] { "" }, ofNullable(configuration.getParentResourcesFilter()).orElse(it -> true)); return new ClassLoaderDescriptorImpl(volatileLoader, resolved); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java index 3690f3b3ad8e2..1abfef827aacd 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java @@ -233,8 +233,8 @@ private BiFunction> buildPayloadProvider(fina if (payload == null) { return Optional.empty(); } - if (payload instanceof byte[]) { - return Optional.of((byte[]) payload); + if (payload instanceof byte[] bytes) { + return Optional.of(bytes); } if (encoders.size() == 1) { return Optional.of(encoders.values().iterator().next().encode(payload)); @@ -257,13 +257,12 @@ private Configurer findConfigurerInstance(final Method m) { static Class toClassType(final Type type) { Class cType = null; - if (type instanceof Class) { - cType = (Class) type; - } else if (type instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) type; + if (type instanceof Class classVal) { + cType = classVal; + } else if (type instanceof ParameterizedType pt) { if (pt.getRawType() == Response.class && pt.getActualTypeArguments().length == 1 - && pt.getActualTypeArguments()[0] instanceof Class) { - cType = (Class) pt.getActualTypeArguments()[0]; + && pt.getActualTypeArguments()[0] instanceof Class clazz) { + cType = clazz; } } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java index c91c70e78d2f5..d65ba3e42a3ad 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java @@ -51,14 +51,13 @@ public Instance createDemoInstance(final Object rootInstance, final ParameterMet final Type javaType = param.getJavaType(); if (javaType instanceof Class) { return new Instance(tryCreatingObjectInstance(javaType), true); - } else if (javaType instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) javaType; + } else if (javaType instanceof ParameterizedType pt) { final Type rawType = pt.getRawType(); - if (rawType instanceof Class && Collection.class.isAssignableFrom((Class) rawType) + if (rawType instanceof Class clazz && Collection.class.isAssignableFrom(clazz) && pt.getActualTypeArguments().length == 1 && pt.getActualTypeArguments()[0] instanceof Class) { final Object instance = tryCreatingObjectInstance(pt.getActualTypeArguments()[0]); - final Class collectionType = (Class) rawType; + final Class collectionType = clazz; if (Set.class == collectionType) { return new Instance(singleton(instance), true); } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java index bcbf8c81ec0b0..93cdaaabb631b 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java @@ -34,7 +34,7 @@ public class FilterFactory { public static Filter and(final Filter first, final Filter second) { if (Stream .of(first, second) - .anyMatch(f -> !(f instanceof FilterList) + .anyMatch(f -> !(f instanceof FilterList) // NOSONAR || !((FilterList) f).getFilters().stream().allMatch(PrefixFilter.class::isInstance))) { throw new IllegalArgumentException("And only works with filter list of prefix filters"); // for optims } diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java index 3aca230e76ffd..d9ef11418ea2b 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java @@ -611,7 +611,8 @@ void testLocalConfigurationFromEnvironment(@TempDir final File temporaryFolder) manager.addPlugin(plugin.getAbsolutePath()); final Container container = manager.getContainer().findAll().stream().findFirst().orElse(null); assertNotNull(container); - final LocalConfiguration envConf = (LocalConfiguration) container.get(AllServices.class).getServices().get(LocalConfiguration.class); + final LocalConfiguration envConf = + (LocalConfiguration) container.get(AllServices.class).getServices().get(LocalConfiguration.class); // check translated env vars assertEquals("/home/user", envConf.get("USER_PATH")); assertEquals("/home/user", envConf.get("USER.PATH")); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java index 11e4cf10371e9..ae2e86cda2cfb 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java @@ -42,12 +42,14 @@ void run(@TempDir final Path temporaryFolder) throws Exception { "META-INF/test/dependencies", "org.talend.test:type=plugin,value=%s")) { manager.addPlugin(jar.getAbsolutePath()); { - final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "configured1", 0, new HashMap() { + final Object nested = ((ProcessorImpl) manager + .findProcessor("chain", "configured1", 0, new HashMap() { - { - put("config.__version", "-1"); - } - }).orElseThrow(IllegalStateException::new)) + { + put("config.__version", "-1"); + } + }) + .orElseThrow(IllegalStateException::new)) .getDelegate(); final Object config = get(nested, "getConfig"); @@ -55,13 +57,15 @@ void run(@TempDir final Path temporaryFolder) throws Exception { assertEquals("ok", get(config, "getName")); } { - final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "configured2", 0, new HashMap() { + final Object nested = ((ProcessorImpl) manager + .findProcessor("chain", "configured2", 0, new HashMap() { - { - put("config.__version", "0"); - put("value.__version", "-1"); - } - }).orElseThrow(IllegalStateException::new)) + { + put("config.__version", "0"); + put("value.__version", "-1"); + } + }) + .orElseThrow(IllegalStateException::new)) .getDelegate(); assertEquals("set", get(nested, "getValue")); @@ -70,13 +74,15 @@ void run(@TempDir final Path temporaryFolder) throws Exception { assertEquals("ok", get(config, "getName")); } { - final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "migrationtest", -1, new HashMap() { + final Object nested = ((ProcessorImpl) manager + .findProcessor("chain", "migrationtest", -1, new HashMap() { - { - put("config.__version", "1"); - put("config.datastore.__version", "1"); - } - }).orElseThrow(IllegalStateException::new)) + { + put("config.__version", "1"); + put("config.datastore.__version", "1"); + } + }) + .orElseThrow(IllegalStateException::new)) .getDelegate(); final Object config = get(nested, "getConfig"); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java index 836bc2336470f..09a7aecc5d5c2 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java @@ -450,8 +450,10 @@ void copiable() throws NoSuchMethodException { new HttpClientFactoryImpl("test", reflectionService, JsonbBuilder.create(), emptyMap()) .create(UserHttpClient.class, "http://foo")); final Method httpMtd = TableOwner.class.getMethod("http", UserHttpClient.class); - final HttpClient client1 = (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; - final HttpClient client2 = (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; + final HttpClient client1 = + (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; + final HttpClient client2 = + (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; assertNotSame(client1, client2); final InvocationHandler handler1 = Proxy.getInvocationHandler(client1); final InvocationHandler handler2 = Proxy.getInvocationHandler(client2); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java index 4002678fd3919..059154dffe389 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java @@ -52,7 +52,8 @@ class RecordServiceImplTest { private final RecordBuilderFactory factory = new RecordBuilderFactoryImpl(null); - private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), Json.createGeneratorFactory(emptyMap()), + private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), + Json.createGeneratorFactory(emptyMap()), Json.createReaderFactory(emptyMap()), Json.createBuilderFactory(emptyMap()), Json.createParserFactory(emptyMap()), Json.createWriterFactory(emptyMap()), new JsonbConfig(), JsonbProvider.provider(), null, null, emptyList(), t -> factory, null) @@ -104,28 +105,28 @@ void visit() { assertEquals(3, service .visit((RecordVisitor) Proxy - .newProxyInstance(Thread.currentThread().getContextClassLoader(), - new Class[]{RecordVisitor.class}, (proxy, method, args) -> { - visited - .add(method.getName() + "/" - + (args == null ? "null" + .newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[] { RecordVisitor.class }, (proxy, method, args) -> { + visited + .add(method.getName() + "/" + + (args == null ? "null" : Stream - .of(args) - .filter(it -> !(it instanceof Schema.Entry)) - .collect(Collectors.toList()))); - switch (method.getName()) { - case "get": - return out.incrementAndGet(); - case "apply": - return asList(args) - .stream() - .mapToInt(Integer.class::cast) - .sum(); - default: - return method.getReturnType() == RecordVisitor.class ? proxy - : null; - } - }), + .of(args) + .filter(it -> !(it instanceof Schema.Entry)) + .collect(Collectors.toList()))); + switch (method.getName()) { + case "get": + return out.incrementAndGet(); + case "apply": + return asList(args) + .stream() + .mapToInt(Integer.class::cast) + .sum(); + default: + return method.getReturnType() == RecordVisitor.class ? proxy + : null; + } + }), baseRecord)); assertEquals(asList("onString/[Optional[Test]]", "onInt/[OptionalInt[33]]", "onRecord/[Optional[{\"street\":\"here\",\"number\":1}]]", "onString/[Optional[here]]", diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocatorCapturingHandler.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocatorCapturingHandler.java index 1854496603f25..73ef4b5cf5359 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocatorCapturingHandler.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocatorCapturingHandler.java @@ -69,8 +69,8 @@ protected void beforeResponse(final String requestUri, final FullHttpRequest req } model.setResponse(responseModel); - if (api.getResponseLocator() instanceof DefaultResponseLocator) { - ((DefaultResponseLocator) api.getResponseLocator()).addModel(model); + if (api.getResponseLocator() instanceof DefaultResponseLocator defaultLocator) { + defaultLocator.addModel(model); } } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java index cbc7f5656dc21..ddc316335c4fa 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java @@ -108,8 +108,7 @@ private void doHttpRequest(final FullHttpRequest request, final ChannelHandlerCo final HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); connection.setConnectTimeout(30000); connection.setReadTimeout(20000); - if (connection instanceof HttpsURLConnection && api.getSslContext() != null) { - final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection; + if (connection instanceof HttpsURLConnection httpsURLConnection && api.getSslContext() != null) { httpsURLConnection.setHostnameVerifier((h, s) -> true); httpsURLConnection.setSSLSocketFactory(api.getSslContext().getSocketFactory()); } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java index 89ca1f43af794..c7184575df1c4 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java @@ -36,18 +36,18 @@ public Statement apply(final Statement base, final Description description) { @Override public void evaluate() throws Throwable { final ResponseLocator responseLocator = server.getResponseLocator(); - if (responseLocator instanceof DefaultResponseLocator) { + if (responseLocator instanceof DefaultResponseLocator defaultResponseLocatorVal) { final DefaultResponseLocator defaultResponseLocator = - (DefaultResponseLocator) responseLocator; + defaultResponseLocatorVal; defaultResponseLocator.setTest(description.getClassName() + "_" + description.getMethodName()); } try { base.evaluate(); } finally { - if (responseLocator instanceof DefaultResponseLocator) { + if (responseLocator instanceof DefaultResponseLocator defaultResponseLocatorVal) { if (Handlers.isActive("capture")) { final DefaultResponseLocator defaultResponseLocator = - (DefaultResponseLocator) responseLocator; + defaultResponseLocatorVal; defaultResponseLocator.flush(Handlers.getBaseCapture()); } } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java index 8fc1ec1f86f4f..5c8e0f0c18202 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java @@ -47,8 +47,8 @@ public DelegatingRunner(final Class testClass) throws InitializationError { } catch (final InstantiationException | NoSuchMethodException | IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (final InvocationTargetException e) { - if (e.getCause() instanceof InitializationError) { - throw (InitializationError) e.getCause(); + if (e.getCause() instanceof InitializationError initError) { + throw initError; } throw new IllegalStateException(e.getTargetException()); } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java index 0323dcbdca40c..f10a752b2b934 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java @@ -32,8 +32,8 @@ public AutoCloseable start(final Class clazz, final Annotation[] annotations) } public String getName() { - return (provider instanceof BaseEnvironmentProvider - ? ((BaseEnvironmentProvider) provider).getName() + return (provider instanceof BaseEnvironmentProvider environmentProvider + ? environmentProvider.getName() : provider.getClass().getSimpleName()).replace("Environment", ""); } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java index a3ed168137f1b..fc5d3dc54ace1 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java @@ -32,8 +32,7 @@ public MultiEnvironmentsRunner(final Class testClass) throws InitializationEr @Override public void run(final RunNotifier notifier) { configuration.stream().forEach(e -> { - if (e instanceof DecoratingEnvironmentProvider) { - final DecoratingEnvironmentProvider dep = (DecoratingEnvironmentProvider) e; + if (e instanceof DecoratingEnvironmentProvider dep) { if (!dep.isActive()) { notifier.fireTestFinished(Description.createTestDescription(getTestClass(), dep.getName())); return; diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java index 717808045992b..1d93ddb82273b 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java @@ -54,17 +54,17 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg } }); if (stream) { - if (result instanceof Stream) { - return decorate((Stream) result, Stream.class, leafDecorator); + if (result instanceof Stream streamVal) { + return decorate(streamVal, Stream.class, leafDecorator); } - if (result instanceof IntStream) { - return decorate((IntStream) result, IntStream.class, leafDecorator); + if (result instanceof IntStream intStream) { + return decorate(intStream, IntStream.class, leafDecorator); } - if (result instanceof LongStream) { - return decorate((LongStream) result, LongStream.class, leafDecorator); + if (result instanceof LongStream longStream) { + return decorate(longStream, LongStream.class, leafDecorator); } - if (result instanceof DoubleStream) { - return decorate((DoubleStream) result, DoubleStream.class, leafDecorator); + if (result instanceof DoubleStream doubleStream) { + return decorate(doubleStream, DoubleStream.class, leafDecorator); } } return result; diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java index acb3dd1662862..34705cb7abc0f 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java @@ -112,7 +112,8 @@ public void doStart(final ExtensionContext extensionContext) { } public void doStop(final ExtensionContext extensionContext) { - ofNullable((EmbeddedComponentManager) extensionContext.getStore(NAMESPACE).get(EmbeddedComponentManager.class.getName())) + ofNullable((EmbeddedComponentManager) extensionContext.getStore(NAMESPACE) + .get(EmbeddedComponentManager.class.getName())) .ifPresent(EmbeddedComponentManager::close); } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java index 488f0856fe0f8..9961cdac27d96 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java @@ -130,8 +130,7 @@ public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionConte } private boolean isActive() { - return provider instanceof DecoratingEnvironmentProvider - && ((DecoratingEnvironmentProvider) provider).isActive(); + return provider instanceof DecoratingEnvironmentProvider envProvider && envProvider.isActive(); } @Override diff --git a/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java b/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java index acd1fd6c04c4e..0c8b3f407d907 100644 --- a/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java +++ b/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java @@ -67,11 +67,11 @@ public void beforeAll(final ExtensionContext extensionContext) throws Exception final Instances instances = start(); if (instances.getException() != null) { instances.close(); - if (instances.getException() instanceof Exception) { - throw (Exception) instances.getException(); + if (instances.getException() instanceof Exception exception) { + throw exception; } - if (instances.getException() instanceof Error) { - throw (Error) instances.getException(); + if (instances.getException() instanceof Error error) { + throw error; } throw new IllegalStateException(instances.getException()); } diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java index b49d797e7a1d9..88d6551bc922b 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java @@ -181,8 +181,7 @@ private CompletableFuture doExecuteLocalAction(final String family, fi } else { cause = e.getCause(); } - if (cause instanceof WebApplicationException) { - final WebApplicationException wae = (WebApplicationException) cause; + if (cause instanceof WebApplicationException wae) { final Response response = wae.getResponse(); String message = ""; if (wae.getResponse().getEntity() instanceof ErrorPayload) { @@ -212,12 +211,11 @@ private CompletableFuture doExecuteLocalAction(final String family, fi private Response onError(final Throwable re) { log.warn(re.getMessage(), re); - if (re.getCause() instanceof WebApplicationException) { - return ((WebApplicationException) re.getCause()).getResponse(); + if (re.getCause() instanceof WebApplicationException wae) { + return wae.getResponse(); } - if (re instanceof ComponentException) { - final ComponentException ce = (ComponentException) re; + if (re instanceof ComponentException ce) { throw new WebApplicationException(Response .status(ce.getErrorOrigin() == ComponentException.ErrorOrigin.USER ? 400 : ce.getErrorOrigin() == ComponentException.ErrorOrigin.BACKEND ? 456 : 520, diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java index 4625e44cc8302..a89a7ae572da8 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java @@ -190,8 +190,7 @@ public Map migrate(final String id, final int version, final Map return migrated; } catch (final Exception e) { // contract of migrate() do not impose to throw a ComponentException, so not likely to happen... - if (e instanceof ComponentException) { - final ComponentException ce = (ComponentException) e; + if (e instanceof ComponentException ce) { throw new WebApplicationException(Response .status(ce.getErrorOrigin() == ComponentException.ErrorOrigin.USER ? 400 : ce.getErrorOrigin() == ComponentException.ErrorOrigin.BACKEND ? 456 : 520, diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java index f6cbe9244fe66..0308b9c9d835e 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java @@ -52,14 +52,14 @@ private void init() { public Response toResponse(final Throwable exception) { log.error("[DefaultExceptionHandler#toResponse] Throwable: ", exception); final Response response; - if (exception instanceof WebApplicationException) { - response = ((WebApplicationException) exception).getResponse(); + if (exception instanceof WebApplicationException webApplicationException) { + response = webApplicationException.getResponse(); } else { final Optional optCause = Optional.ofNullable(exception.getCause()); if (optCause.isPresent()) { final Throwable cause = optCause.get(); - if (cause instanceof WebApplicationException) { - response = ((WebApplicationException) cause).getResponse(); + if (cause instanceof WebApplicationException webApplicationException) { + response = webApplicationException.getResponse(); } else { response = Response .status(Response.Status.INTERNAL_SERVER_ERROR) diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java index 1dea4226e58bc..54be1e5dcfb3e 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java @@ -66,8 +66,8 @@ AsyncContext start() { public void onError(final Throwable throwable) { final AsyncEvent event = new AsyncEvent(this, request, response, throwable); executeOnListeners(l -> l.onError(event), null); - if (!response.isCommitted() && response instanceof HttpServletResponse) { - final HttpServletResponse http = (HttpServletResponse) response; + if (!response.isCommitted() && response instanceof HttpServletResponse) { // NOSONAR + final HttpServletResponse http = response; http.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } complete(); diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java index 3b87aeb82b4c4..b6a1f84e06a0e 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java @@ -51,8 +51,8 @@ public void init(final FilterConfig filterConfig) { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { - if (request instanceof HttpServletRequest) { - ThreadContext.putAll(createContext((HttpServletRequest) request)); + if (request instanceof HttpServletRequest httpServletRequest) { + ThreadContext.putAll(createContext(httpServletRequest)); } chain.doFilter(request, response); } diff --git a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java index 1ad01ebbe8585..563b0332eec8d 100644 --- a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java +++ b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java @@ -153,8 +153,7 @@ public void capture(@Observes final CreateProject createProject) { final Throwable e = ofNullable(te.getCause()).orElse(te); if (retries - 1 == i) { // no need to retry failed(createProject); - throw e instanceof RuntimeException ? (RuntimeException) e - : new IllegalStateException(e); + throw e instanceof RuntimeException rte ? rte : new IllegalStateException(e); } if (retrySleep > 0) { diff --git a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java index eac99256783e3..c6ba36caca111 100644 --- a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java +++ b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java @@ -47,8 +47,8 @@ public Wrapper find(final String name, final List scopes) { final Wrapper wrapper = super.find(name, scopes); return s -> { final Object call = wrapper.call(s); - if (call instanceof Collection && !(call instanceof DecoratedCollection)) { - return new DecoratedCollection<>((Collection) call); + if (call instanceof Collection collection && !(call instanceof DecoratedCollection)) { + return new DecoratedCollection<>(collection); } return call; }; diff --git a/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java b/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java index f46b2c5e5f893..5c05ab2111008 100644 --- a/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java +++ b/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java @@ -61,8 +61,7 @@ public HealthCheckStatus healthCheck(@Option(NAME) final BasicAuthConfig dt, fin try { client.healthCheck(dt.getAuthorizationHeader()); } catch (Exception e) { - if (e instanceof HttpException) { - final HttpException ex = (HttpException) e; + if (e instanceof HttpException ex) { final JsonObject jError = (JsonObject) ex.getResponse().error(JsonObject.class); String errorMessage = null; if (jError != null && jError.containsKey("error")) { diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java index 6924c128a3eb8..43a34056fbb6a 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java @@ -54,11 +54,11 @@ public T get(final IndirectInstances key, final Class instance) { } static void init(final Object instance, final Map globalMap) { - if (instance instanceof JobStateAware) { + if (instance instanceof JobStateAware jobStateAware) { synchronized (globalMap) { final State state = (State) globalMap.computeIfAbsent(JobStateAware.class.getName(), k -> new State()); - ((JobStateAware) instance).setState(state); + jobStateAware.setState(state); } } } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java index aa84004f8300d..ca1827553f1f3 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java @@ -75,7 +75,7 @@ public void push(final Object value) { if (value == null) { return; } - queue.add(value instanceof Record ? (Record) value : toRecord(value)); + queue.add(value instanceof Record rcd ? rcd : toRecord(value)); semaphore.release(); } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java index 072b1f279398a..5174f46ce25ec 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java @@ -74,14 +74,14 @@ public OutputT apply(final String name, final PTransfo private PTransform wrapTransformIfNeeded(final PTransform root) { - if (root instanceof Read.Bounded) { - final BoundedSource source = ((Read.Bounded) root).getSource(); + if (root instanceof Read.Bounded bounded) { + final BoundedSource source = bounded.getSource(); final DelegatingBoundedSource boundedSource = new DelegatingBoundedSource(source, null); setState(boundedSource); return Read.from(boundedSource); } - if (root instanceof Read.Unbounded) { - final UnboundedSource source = ((Read.Unbounded) root).getSource(); + if (root instanceof Read.Unbounded unbounded) { + final UnboundedSource source = unbounded.getSource(); if (source instanceof InMemoryQueueIO.UnboundedQueuedInput) { return root; } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java index 39dac69a1b56e..d09689a843637 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java @@ -140,8 +140,8 @@ private void visit(final Object data) { onBoolean(name, raw); break; case StudioTypes.DATE: - if (raw instanceof Timestamp) { - onInstant(name, (Timestamp) raw); + if (raw instanceof Timestamp timestamp) { + onInstant(name, timestamp); break; } onDatetime(name, ((Date) raw).toInstant().atZone(UTC)); @@ -191,10 +191,10 @@ private void handleDynamic(final Object raw) { break; case StudioTypes.BYTE_ARRAY: final byte[] bytes; - if (value instanceof byte[]) { - bytes = (byte[]) value; - } else if (value instanceof ByteBuffer) { - bytes = ((ByteBuffer) value).array(); + if (value instanceof byte[] byteArr) { + bytes = byteArr; + } else if (value instanceof ByteBuffer byteBuffer) { + bytes = byteBuffer.array(); } else { log.warn("[visit] '{}' of type `id_byte[]` and content is contained in `{}`:" + " This should not happen! " @@ -226,7 +226,7 @@ private void handleDynamic(final Object raw) { break; case StudioTypes.DATE: final ZonedDateTime dateTime; - dateTime = ZonedDateTime.ofInstant(value instanceof Long ? ofEpochMilli((Long) value) + dateTime = ZonedDateTime.ofInstant(value instanceof Long longVal ? ofEpochMilli(longVal) : ((Date) value).toInstant(), UTC); onDatetime(metaName, dateTime); break; diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java index aab1d4a9250de..e80d5cc056b68 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java @@ -659,8 +659,8 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { final Mapper mapper = componentManager .findMapper(family, componentName, version, configuration) .orElseThrow(() -> new IllegalArgumentException("Can't find " + family + "#" + componentName)); - if (mapper instanceof JobStateAware) { - ((JobStateAware) mapper).setState(new JobStateAware.State()); + if (mapper instanceof JobStateAware jobStateAware) { + jobStateAware.setState(new JobStateAware.State()); } Input input = null; try { @@ -762,8 +762,8 @@ private boolean guessInputSchemaThroughResults(final Input input, final Map m.getParameters()[i].isAnnotationPresent(Output.class) && outBranchName.equals(m.getParameters()[i].getAnnotation(Output.class).value())) .mapToObj(i -> m.getGenericParameterTypes()[i]) - .filter(t -> t instanceof ParameterizedType - && ((ParameterizedType) t).getRawType() == OutputEmitter.class - && ((ParameterizedType) t).getActualTypeArguments().length == 1) + .filter(t -> t instanceof ParameterizedType pt + && pt.getRawType() == OutputEmitter.class + && pt.getActualTypeArguments().length == 1) .map(p -> ((ParameterizedType) p).getActualTypeArguments()[0])) .findFirst(); - if (type.isPresent() && type.get() instanceof Class) { + if (type.isPresent() && type.get() instanceof Class) { // NOSONAR final Class clazz = (Class) type.get(); if (clazz != JsonObject.class) { guessSchemaThroughResultClass(clazz); diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java index adc60ff9c15d2..d60ad6661950e 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java @@ -33,8 +33,8 @@ public class ParameterSetter { private final Object delegate; public ParameterSetter(final Lifecycle lifecycle) { - if (lifecycle instanceof Delegated) { - delegate = ((Delegated) lifecycle).getDelegate(); + if (lifecycle instanceof Delegated delegated) { + delegate = delegated.getDelegate(); } else { throw new IllegalArgumentException("Not supported implementation of lifecycle : " + lifecycle); } diff --git a/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java b/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java index 3acfc67c84fd3..d91339888b222 100644 --- a/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java +++ b/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java @@ -251,8 +251,8 @@ private void doRun(final ComponentManager manager, final Collection sour Object dataMapper; while ((dataMapper = inputMapper.next()) != null) { final String jsonValueMapper; - if (dataMapper instanceof javax.json.JsonValue) { - jsonValueMapper = ((javax.json.JsonValue) dataMapper).toString(); + if (dataMapper instanceof javax.json.JsonValue jsonValue) { + jsonValueMapper = jsonValue.toString(); } else if (dataMapper instanceof org.talend.sdk.component.api.record.Record) { jsonValueMapper = jsonbMapper .toJson(converters diff --git a/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java b/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java index 4a6a0dadb4ba7..18ac03ec00850 100644 --- a/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java +++ b/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java @@ -205,16 +205,14 @@ private String extractFamilyFromNode(final String id) { private void onException(final AsyncResponse response, final Throwable e) { final UiActionResult payload; final int status; - if (e instanceof WebException) { - final WebException we = (WebException) e; + if (e instanceof WebException we) { status = we.getStatus(); payload = actionService.map(we); - } else if (e instanceof CompletionException) { - final CompletionException actualException = (CompletionException) e; + } else if (e instanceof CompletionException actualException) { log.error(actualException.getMessage(), actualException); status = Response.Status.BAD_GATEWAY.getStatusCode(); - if (actualException.getCause() instanceof WebApplicationException) { - final Response resp = ((WebApplicationException) actualException.getCause()).getResponse(); + if (actualException.getCause() instanceof WebApplicationException wae) { + final Response resp = wae.getResponse(); if (response != null) { final String s = resp.readEntity(String.class); response.resume(Response.status(resp.getStatus()).entity(s).type(APPLICATION_JSON_TYPE).build()); diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java index 3ee1fb4dc3759..4372b656bfa41 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java @@ -288,14 +288,14 @@ protected Asciidoctor getAsciidoctor() { public void close() { onClose.run(); if (asciidoctor != null && !Boolean.getBoolean("talend.component.tools.jruby.teardown.skip")) { - if (asciidoctor instanceof AutoCloseable) { + if (asciidoctor instanceof AutoCloseable) { // NOSONAR try { ((AutoCloseable) asciidoctor).close(); } catch (final Exception e) { throw new IllegalStateException(e); } - } else if (asciidoctor instanceof JRubyAsciidoctor) { - ((JRubyAsciidoctor) asciidoctor).getRubyRuntime().tearDown(); + } else if (asciidoctor instanceof JRubyAsciidoctor jRubyAsciidoctor) { + jRubyAsciidoctor.getRubyRuntime().tearDown(); } } } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java b/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java index f125f3ab0e62b..e62a3b27df756 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java @@ -58,7 +58,7 @@ public class CarBundler implements Runnable { public CarBundler(final Configuration configuration, final Object log) { this.configuration = configuration; try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java index 4d0c5cc62bdb3..00ecc5cbc54f9 100755 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java @@ -81,7 +81,7 @@ public ComponentValidator(final Configuration configuration, final File[] classe this.validator = new SvgValidator(this.configuration.isValidateLegacyIcons()); try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java index a0705359277b3..8643f456355bb 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java @@ -95,7 +95,7 @@ public abstract class DocBaseGenerator extends BaseTask { this.locale = locale; this.output = output; try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } @@ -570,8 +570,8 @@ private String findDefault(final ParameterMeta p, final DefaultValueInspector.In .orElse(null); case ARRAY: return String - .valueOf(instance.getValue() instanceof Collection - ? ((Collection) instance.getValue()).size() + .valueOf(instance.getValue() instanceof Collection collection + ? collection.size() : Array.getLength(instance.getValue())); case OBJECT: default: diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java b/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java index 10073c197f423..22ca4cdaab26d 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java @@ -44,7 +44,7 @@ public SVG2Png(final Path iconsFolder, final boolean activeWorkarounds, final Ob this.iconsFolder = iconsFolder; this.activeWorkarounds = activeWorkarounds; try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java b/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java index 0336456d20601..5be7e05b57fef 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java @@ -63,7 +63,7 @@ public StudioInstaller(final String mainGav, final File studioHome, final Map serverArguments, final Integer port, f this.serverArguments = serverArguments; this.port = port; try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java index 35fb5e3e03577..faaa126c7e1f8 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java @@ -163,18 +163,17 @@ private boolean isArrayOfObject(final ParameterMeta param) { private Class toJavaType(final ParameterMeta p) { if (p.getType().equals(OBJECT) || p.getType().equals(ENUM)) { - if (p.getJavaType() instanceof Class) { - return (Class) p.getJavaType(); + if (p.getJavaType() instanceof Class classVal) { + return classVal; } throw new IllegalArgumentException("Unsupported type for parameter " + p.getPath() + " (from " + p.getSource().declaringClass() + "), ensure it is a Class"); } - if (p.getType().equals(ARRAY) && p.getJavaType() instanceof ParameterizedType) { - final ParameterizedType parameterizedType = (ParameterizedType) p.getJavaType(); + if (p.getType().equals(ARRAY) && p.getJavaType() instanceof ParameterizedType parameterizedType) { final Type[] arguments = parameterizedType.getActualTypeArguments(); - if (arguments.length == 1 && arguments[0] instanceof Class) { - return (Class) arguments[0]; + if (arguments.length == 1 && arguments[0] instanceof Class clazz) { + return clazz; } throw new IllegalArgumentException("Unsupported type for parameter " + p.getPath() + " (from " + p.getSource().declaringClass() + "), " + "ensure it is a ParameterizedType with one argument"); diff --git a/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java b/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java index 474b91aedde26..2557c4dd01359 100755 --- a/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java +++ b/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java @@ -182,8 +182,9 @@ public void beforeEach(final ExtensionContext context) { public void afterEach(final ExtensionContext context) { final ExtensionContext.Store store = context.getStore(NAMESPACE); final boolean fails = !((ComponentPackage) store.get(ComponentPackage.class.getName())).success(); - final String expectedMessage = ((ExceptionSpec) context.getStore(NAMESPACE).get(ExceptionSpec.class.getName())) - .getMessage(); + final String expectedMessage = + ((ExceptionSpec) context.getStore(NAMESPACE).get(ExceptionSpec.class.getName())) + .getMessage(); try { ((ComponentValidator) store.get(ComponentValidator.class.getName())).run(); if (fails) { diff --git a/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java b/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java index eb1c7f8a4d981..ebc19a7333570 100644 --- a/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java +++ b/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java @@ -178,8 +178,7 @@ private void loadNestedDependencies(final ClassLoader parent, final String[] nes final CodeSource codeSource; try { urlConnection = url.openConnection(); - if (urlConnection instanceof JarURLConnection) { - final JarURLConnection juc = (JarURLConnection) urlConnection; + if (urlConnection instanceof JarURLConnection juc) { manifest = juc.getManifest(); final Certificate[] certificates = juc.getCertificates(); @@ -446,8 +445,7 @@ private InputStream doGetResourceAsStream(final String name) { private InputStream getInputStream(final URL resource) throws IOException { final URLConnection urlc = resource.openConnection(); final InputStream is = urlc.getInputStream(); - if (urlc instanceof JarURLConnection) { - final JarURLConnection juc = (JarURLConnection) urlc; + if (urlc instanceof JarURLConnection juc) { final JarFile jar = juc.getJarFile(); synchronized (closeables) { if (!closeables.containsKey(jar)) { @@ -807,10 +805,9 @@ private Class loadInternal(final String name, final boolean resolve) { final String pckName = name.substring(0, i); final Package pck = super.getPackage(pckName); if (pck == null) { - if (!(connection instanceof JarURLConnection)) { + if (!(connection instanceof JarURLConnection urlConnection)) { doDefinePackage(null, null, pckName); } else { - final JarURLConnection urlConnection = (JarURLConnection) connection; doDefinePackage(urlConnection.getManifest(), urlConnection.getJarFileURL(), pckName); } } @@ -831,8 +828,8 @@ private Class loadInternal(final String name, final boolean resolve) { } bytes = outputStream.toByteArray(); } - final Certificate[] certificates = connection instanceof JarURLConnection - ? ((JarURLConnection) connection).getCertificates() + final Certificate[] certificates = connection instanceof JarURLConnection jarURLConnection + ? jarURLConnection.getCertificates() : NO_CERTIFICATES; bytes = doTransform(resourceName, bytes); clazz = super.defineClass(name, bytes, 0, bytes.length, new CodeSource(url, certificates)); diff --git a/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java b/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java index de3c39f354da0..4fb316674b12d 100644 --- a/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java +++ b/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java @@ -97,8 +97,8 @@ void proxying( throw new IllegalStateException(e); } catch (final InvocationTargetException e) { final Throwable targetException = e.getTargetException(); - if (targetException instanceof RuntimeException) { - throw (RuntimeException) targetException; + if (targetException instanceof RuntimeException runtimeException) { + throw runtimeException; } throw new IllegalStateException(targetException); } diff --git a/documentation/src/main/java/org/talend/runtime/documentation/Generator.java b/documentation/src/main/java/org/talend/runtime/documentation/Generator.java index a75a8aad81a99..2f08828472513 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/Generator.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/Generator.java @@ -373,7 +373,8 @@ private static void generatedScanningExclusions(final File generatedDir) { stream.println("Therefore, the following packages are ignored:"); stream.println(); stream.println("[.talend-filterlist]"); - ((KnownClassesFilter.OptimizedExclusionFilter) ((KnownClassesFilter) KnownClassesFilter.INSTANCE).getDelegateSkip()) + ((KnownClassesFilter.OptimizedExclusionFilter) ((KnownClassesFilter) KnownClassesFilter.INSTANCE) + .getDelegateSkip()) .getIncluded() .stream() .sorted() diff --git a/documentation/src/main/java/org/talend/runtime/documentation/Github.java b/documentation/src/main/java/org/talend/runtime/documentation/Github.java index c38abde6f1c30..78457b75ce99c 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/Github.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/Github.java @@ -112,8 +112,8 @@ public Collection load() { .collect(toList()))) .get(); } catch (final ExecutionException ee) { - if (ee.getCause() instanceof WebApplicationException) { - final Response response = ((WebApplicationException) ee.getCause()).getResponse(); + if (ee.getCause() instanceof WebApplicationException wae) { + final Response response = wae.getResponse(); if (response != null && response.getEntity() != null) { log.error(response.readEntity(String.class)); } diff --git a/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java b/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java index 941ef3457b307..b5f5d9cdc9b9b 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java @@ -61,8 +61,7 @@ public HealthCheckStatus healthCheck(@Option(BasicAuthConfig.NAME) final BasicAu try { client.healthCheck(dt.getAuthorizationHeader()); } catch (Exception e) { - if (e instanceof HttpException) { - final HttpException ex = (HttpException) e; + if (e instanceof HttpException ex) { final JsonObject jError = (JsonObject) ex.getResponse().error(JsonObject.class); String errorMessage = null; if (jError != null && jError.containsKey("error")) { diff --git a/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java b/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java index 45f84f5a4233d..591c2d79022e8 100644 --- a/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java +++ b/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java @@ -58,7 +58,8 @@ public class RecordJsonMapper implements Function { private final Singer singer; - private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), Json.createGeneratorFactory(emptyMap()), + private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), + Json.createGeneratorFactory(emptyMap()), Json.createReaderFactory(emptyMap()), Json.createBuilderFactory(emptyMap()), Json.createParserFactory(emptyMap()), Json.createWriterFactory(emptyMap()), new JsonbConfig(), JsonbProvider.provider(), null, null, emptyList(), t -> new RecordBuilderFactoryImpl("kitap"), null) diff --git a/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java b/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java index d38a57fdfed41..81ba36b2a7fb5 100644 --- a/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java +++ b/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java @@ -138,8 +138,8 @@ public Wrapper find(final String name, final List scopes) { final Wrapper wrapper = super.find(name, scopes); return s -> { final Object call = wrapper.call(s); - if (call instanceof Collection && !(call instanceof DecoratedCollection)) { - return new DecoratedCollection<>((Collection) call); + if (call instanceof Collection collection && !(call instanceof DecoratedCollection)) { + return new DecoratedCollection<>(collection); } return call; }; diff --git a/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java b/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java index c6d805ca35225..daeb98401de8f 100644 --- a/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java +++ b/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java @@ -153,8 +153,7 @@ public class VaultClient { private Pattern compiledPassthroughRegex; private final Predicate shouldRetry = cause -> { - if (cause instanceof WebApplicationException) { - final WebApplicationException wae = (WebApplicationException) cause; + if (cause instanceof WebApplicationException wae) { final int status = wae.getResponse().getStatus(); if (Status.NOT_FOUND.getStatusCode() == status || status >= 500) { return false; @@ -330,8 +329,7 @@ private CompletionStage> doDecipher(final Collection doAuth(final String role, final String s // .exceptionally(e -> { final Throwable cause = e.getCause(); - if (cause instanceof WebApplicationException) { - final WebApplicationException wae = (WebApplicationException) cause; + if (cause instanceof WebApplicationException wae) { final Response response = wae.getResponse(); String message = ""; if (wae.getResponse().getEntity() instanceof ErrorPayload) { @@ -471,8 +468,7 @@ private void throwError(final int status, final String message) { private void throwError(final Throwable cause) { String message = ""; int status = cantDecipherStatusCode; - if (cause instanceof WebApplicationException) { - final WebApplicationException wae = (WebApplicationException) cause; + if (cause instanceof WebApplicationException wae) { final Response response = wae.getResponse(); status = response.getStatus(); if (response != null) { From dee61f0c01f7054fcf73743dd4dc6841e5f45204 Mon Sep 17 00:00:00 2001 From: Emmanuel GALLOIS Date: Thu, 4 Jun 2026 11:30:43 +0200 Subject: [PATCH 4/7] chore(QTDI-2893): S6201 changes after code review --- .../talend/sdk/component/runtime/record/MappingUtils.java | 4 ++-- .../talend/sdk/component/runtime/visitor/ModelVisitor.java | 2 +- .../reflect/parameterenricher/UiParameterEnricher.java | 4 ++-- .../sdk/component/runtime/manager/xbean/FilterFactory.java | 2 +- .../http/junit4/JUnit4HttpApiPerMethodConfigurator.java | 4 +--- .../component/server/front/memory/AsyncContextImpl.java | 7 +++++-- .../component/runtime/di/schema/TaCoKitGuessSchema.java | 3 +-- .../talend/sdk/component/tools/AsciidoctorExecutor.java | 5 ++++- 8 files changed, 17 insertions(+), 14 deletions(-) diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java index 08c7ecb899166..c6ee833b95f04 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java @@ -93,8 +93,8 @@ public static Object coerce(final Class expectedType, final Object value, && (java.util.Date.class == expectedType || Instant.class == expectedType)) { return value; } - if (value instanceof long[]) { // NOSONAR - final Instant instant = Instant.ofEpochSecond(((long[]) value)[0], ((long[]) value)[1]); + if (value instanceof long[] longArray) { + final Instant instant = Instant.ofEpochSecond(longArray[0], longArray[1]); if (ZonedDateTime.class == expectedType) { return ZonedDateTime.ofInstant(instant, UTC); } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java index 3e37a6a8c9203..f5bd234fe020b 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java @@ -140,7 +140,7 @@ private void validatePartitionMapper(final Class type) { } final Type arg = splitPt.getActualTypeArguments().length != 1 ? null : splitPt.getActualTypeArguments()[0]; - if (!(arg instanceof Class) || !type.isAssignableFrom((Class) arg)) { // NOSONAR + if (!(arg instanceof Class) || !type.isAssignableFrom((Class) arg)) { throw new IllegalArgumentException( m + " must return a Collection<" + type.getName() + "> but found: " + arg); } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java index 8f23f73863e64..e5405456f6d7d 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java @@ -180,8 +180,8 @@ private String toString(final Annotation annotation, final Method m, if (invoke instanceof Class classVal) { return classVal.getSimpleName().toLowerCase(ENGLISH); } - if (invoke instanceof String[]) { // NOSONAR - return Stream.of((String[]) invoke).collect(joining(",")); + if (invoke instanceof String[] stringArray) { + return Stream.of(stringArray).collect(joining(",")); } return String.valueOf(invoke); } catch (final InvocationTargetException | IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java index 93cdaaabb631b..bcbf8c81ec0b0 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java @@ -34,7 +34,7 @@ public class FilterFactory { public static Filter and(final Filter first, final Filter second) { if (Stream .of(first, second) - .anyMatch(f -> !(f instanceof FilterList) // NOSONAR + .anyMatch(f -> !(f instanceof FilterList) || !((FilterList) f).getFilters().stream().allMatch(PrefixFilter.class::isInstance))) { throw new IllegalArgumentException("And only works with filter list of prefix filters"); // for optims } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java index c7184575df1c4..e6649dee7d56d 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java @@ -44,10 +44,8 @@ public void evaluate() throws Throwable { try { base.evaluate(); } finally { - if (responseLocator instanceof DefaultResponseLocator defaultResponseLocatorVal) { + if (responseLocator instanceof DefaultResponseLocator defaultResponseLocator) { if (Handlers.isActive("capture")) { - final DefaultResponseLocator defaultResponseLocator = - defaultResponseLocatorVal; defaultResponseLocator.flush(Handlers.getBaseCapture()); } } diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java index 54be1e5dcfb3e..bb0c01fef7bc2 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java @@ -63,11 +63,14 @@ AsyncContext start() { return this; } + @SuppressWarnings("java:S6201") + // unconditional patterns in instanceof are not supported in -source 17 + // TODO: remove the @SuppressWarnings and apply S6201 when java 21+ only is supported. public void onError(final Throwable throwable) { final AsyncEvent event = new AsyncEvent(this, request, response, throwable); executeOnListeners(l -> l.onError(event), null); - if (!response.isCommitted() && response instanceof HttpServletResponse) { // NOSONAR - final HttpServletResponse http = response; + if (!response.isCommitted() && response instanceof HttpServletResponse) { + final HttpServletResponse http = (HttpServletResponse) response; http.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } complete(); diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java index e80d5cc056b68..4e8b303581da7 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java @@ -783,8 +783,7 @@ public void fromOutputEmitterPojo(final Processor processor, final String outBra && pt.getActualTypeArguments().length == 1) .map(p -> ((ParameterizedType) p).getActualTypeArguments()[0])) .findFirst(); - if (type.isPresent() && type.get() instanceof Class) { // NOSONAR - final Class clazz = (Class) type.get(); + if (type.isPresent() && type.get() instanceof Class clazz) { if (clazz != JsonObject.class) { guessSchemaThroughResultClass(clazz); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java index 4372b656bfa41..92919f1bd8142 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java @@ -284,11 +284,14 @@ protected Asciidoctor getAsciidoctor() { return asciidoctor == null ? asciidoctor = Asciidoctor.Factory.create() : asciidoctor; } + @SuppressWarnings("java:S6201") + // unconditional patterns in instanceof are not supported in -source 17 + // TODO: remove the @SuppressWarnings and apply S6201 when java 21+ only is supported. @Override public void close() { onClose.run(); if (asciidoctor != null && !Boolean.getBoolean("talend.component.tools.jruby.teardown.skip")) { - if (asciidoctor instanceof AutoCloseable) { // NOSONAR + if (asciidoctor instanceof AutoCloseable) { try { ((AutoCloseable) asciidoctor).close(); } catch (final Exception e) { From 32956b8d66ef7c667c51b906bf1b8a0444257079 Mon Sep 17 00:00:00 2001 From: Emmanuel GALLOIS Date: Thu, 4 Jun 2026 13:43:45 +0200 Subject: [PATCH 5/7] chore(QTDI-2893): reset to master --- .../validation/spi/ext/TypeValidation.java | 4 +- .../jsonschema/PojoJsonSchemaBuilder.java | 9 +-- .../runtime/beam/BaseProcessorFn.java | 4 +- .../sdk/component/runtime/beam/TalendIO.java | 8 +-- .../beam/coder/JsonpJsonObjectCoder.java | 2 +- .../service/AutoValueFluentApiFactory.java | 7 +- .../beam/spi/BeamComponentExtension.java | 4 +- .../runtime/beam/spi/BeamProducerFinder.java | 4 +- .../beam/spi/record/AvroEntryBuilder.java | 3 +- .../runtime/beam/spi/record/AvroRecord.java | 46 ++++++------ .../beam/spi/record/AvroSchemaCache.java | 3 +- ..._CustomJdbcIO_DataSourceConfiguration.java | 3 +- .../transformer/BeamIOTransformerTest.java | 4 +- .../repository/RepositoryModelBuilder.java | 4 +- component-runtime-impl/pom.xml | 2 +- .../exception/InvocationExceptionWrapper.java | 12 ++-- .../runtime/input/LocalPartitionMapper.java | 3 +- .../runtime/record/MappingUtils.java | 16 ++--- .../runtime/record/RecordConverters.java | 35 ++++----- .../component/runtime/record/RecordImpl.java | 20 +++--- .../record/json/RecordJsonGenerator.java | 46 ++++++------ .../component/runtime/reflect/Defaults.java | 9 ++- .../runtime/visitor/ModelVisitor.java | 4 +- .../runtime/record/PluralRecordExtension.java | 2 +- .../runtime/manager/ComponentManager.java | 37 +++++----- .../runtime/manager/asm/Unsafes.java | 4 +- .../manager/chain/internal/JobImpl.java | 24 +++---- .../configuration/ConfigurationMapper.java | 2 +- .../interceptor/InterceptorHandlerFacade.java | 4 +- .../reflect/ParameterModelService.java | 72 ++++++++++--------- .../manager/reflect/ReflectionService.java | 47 ++++++------ .../reflect/StringCompatibleTypes.java | 2 +- .../ConditionParameterEnricher.java | 7 +- .../DependencyParameterEnricher.java | 2 +- .../UiParameterEnricher.java | 8 +-- .../ValidationParameterEnricher.java | 6 +- .../reflect/visibility/VisibilityService.java | 12 ++-- .../runtime/manager/service/InjectorImpl.java | 14 ++-- .../service/RecordPointerFactoryImpl.java | 9 +-- .../runtime/manager/service/ResolverImpl.java | 4 +- .../manager/service/ServiceHelper.java | 4 +- .../manager/service/http/RequestParser.java | 15 ++-- .../manager/util/DefaultValueInspector.java | 7 +- .../xbean/converter/SchemaConverter.java | 32 ++++----- .../runtime/manager/ComponentManagerTest.java | 3 +- .../manager/ConfigurationMigrationTest.java | 40 +++++------ .../manager/ReflectionServiceTest.java | 6 +- .../service/ProducerFinderImplTest.java | 4 +- .../service/RecordServiceImplTest.java | 45 ++++++------ .../internal/impl/DefaultResponseLocator.java | 3 +- ...efaultResponseLocatorCapturingHandler.java | 4 +- .../internal/impl/PassthroughHandler.java | 3 +- .../JUnit4HttpApiPerMethodConfigurator.java | 8 ++- .../junit/delegate/DelegatingRunner.java | 4 +- .../DecoratingEnvironmentProvider.java | 4 +- .../environment/MultiEnvironmentsRunner.java | 3 +- .../component/junit/lang/StreamDecorator.java | 16 ++--- .../component/junit5/ComponentExtension.java | 3 +- .../environment/EnvironmentalContext.java | 3 +- .../spark/junit5/internal/SparkExtension.java | 8 +-- .../server/front/ActionResourceImpl.java | 10 +-- .../front/ConfigurationTypeResourceImpl.java | 3 +- .../front/error/DefaultExceptionHandler.java | 8 +-- .../server/front/memory/AsyncContextImpl.java | 3 - .../server/mdc/MdcRequestBinder.java | 4 +- .../service/statistic/StatisticService.java | 3 +- .../service/template/TemplateRenderer.java | 4 +- .../component/service/MockTableService.java | 3 +- .../component/runtime/di/JobStateAware.java | 4 +- .../component/runtime/di/OutputsHandler.java | 8 +-- .../component/runtime/di/beam/LoopState.java | 2 +- .../di/beam/components/DIPipeline.java | 8 +-- .../runtime/di/record/DiRowStructVisitor.java | 14 ++-- .../runtime/di/schema/TaCoKitGuessSchema.java | 57 ++++++++------- .../di/studio/AfterVariableExtracter.java | 4 +- .../runtime/di/studio/ParameterSetter.java | 8 +-- .../di/studio/RuntimeContextInjector.java | 4 +- .../components/DIBatchSimulationTest.java | 4 +- .../tools/webapp/WebAppComponentProxy.java | 10 +-- .../component/tools/AsciidoctorExecutor.java | 7 +- .../sdk/component/tools/CarBundler.java | 2 +- .../component/tools/ComponentValidator.java | 2 +- .../sdk/component/tools/DocBaseGenerator.java | 6 +- .../talend/sdk/component/tools/SVG2Png.java | 2 +- .../sdk/component/tools/StudioInstaller.java | 2 +- .../talend/sdk/component/tools/WebServer.java | 2 +- .../tools/validator/ActionValidator.java | 4 +- .../tools/validator/LayoutValidator.java | 11 +-- .../tools/ComponentValidatorTest.java | 5 +- .../classloader/ConfigurableClassLoader.java | 13 ++-- .../talend/sdk/component/ContainerTest.java | 4 +- .../runtime/documentation/Generator.java | 3 +- .../talend/runtime/documentation/Github.java | 4 +- .../component/service/MockTableService.java | 3 +- .../singer/kitap/RecordJsonMapper.java | 3 +- .../component/maven/WebsiteBuilderMojo.java | 4 +- .../components/vault/client/VaultClient.java | 12 ++-- 97 files changed, 499 insertions(+), 474 deletions(-) diff --git a/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java b/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java index 74728b2091965..3bcad26b568d3 100644 --- a/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java +++ b/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java @@ -38,10 +38,10 @@ public class TypeValidation implements ValidationExtension { @Override public Optional>> create(final ValidationContext model) { final JsonValue value = model.getSchema().get("type"); - if (value instanceof JsonString jsonString) { + if (value instanceof JsonString) { return Optional .of(new Impl(model.toPointer(), model.getValueProvider(), - mapType(jsonString).toArray(JsonValue.ValueType[]::new))); + mapType((JsonString) value).toArray(JsonValue.ValueType[]::new))); } if (value instanceof JsonArray) { return Optional diff --git a/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java b/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java index 1d02b45ee376b..ad3af841abbba 100644 --- a/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java +++ b/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java @@ -64,7 +64,7 @@ public JsonSchema.Builder create(final Class pojo) { private JsonSchema buildSchema(final Field field) { final Type genericType = field.getGenericType(); - if ((genericType instanceof Class clazz && CharSequence.class.isAssignableFrom(clazz)) + if ((genericType instanceof Class && CharSequence.class.isAssignableFrom((Class) genericType)) || genericType == char.class || genericType == Character.class) { return schemas.computeIfAbsent((Class) genericType, k -> jsonSchema().withType("string").build()); } else if (genericType == long.class || genericType == Long.class || genericType == int.class @@ -76,14 +76,15 @@ private JsonSchema buildSchema(final Field field) { } else if (genericType == boolean.class || genericType == Boolean.class) { return schemas .computeIfAbsent((Class) genericType, k -> jsonSchema().withType("boolean").build()); - } else if (genericType instanceof Class classVal) { - final Class clazz = classVal; + } else if (genericType instanceof Class) { + final Class clazz = (Class) genericType; return ofNullable(schemas.get(clazz)).orElseGet(() -> { final JsonSchema jsonSchema = create(clazz).build(); schemas.put(clazz, jsonSchema); return jsonSchema; }); - } else if (genericType instanceof ParameterizedType pt) { + } else if (genericType instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) genericType; final Type rawType = pt.getRawType(); if (!(rawType instanceof Class)) { throw new IllegalArgumentException("Unsupported raw type: " + pt + ", this must be a Class"); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java index 64a890b23d809..096d18cd1a7d5 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java @@ -65,8 +65,8 @@ abstract class BaseProcessorFn extends DoFn { BaseProcessorFn(final Processor processor) { this.processor = processor; - if (processor instanceof ProcessorImpl processorImpl) { - processorImpl + if (processor instanceof ProcessorImpl) { + ((ProcessorImpl) processor) .getInternalConfiguration() .entrySet() .stream() diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java index 929415959ff17..92b8ad56d0183 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java @@ -77,8 +77,8 @@ public static Base, Mapper> read(final Mapper mapper String maxRecords = null; String maxDurationMs = null; boolean hasInternalConfParams = false; - if (mapper instanceof PartitionMapperImpl partitionMapperImpl) { - Map conf = partitionMapperImpl.getInternalConfiguration(); + if (mapper instanceof PartitionMapperImpl) { + Map conf = ((PartitionMapperImpl) mapper).getInternalConfiguration(); hasInternalConfParams = conf.keySet() .stream() .filter(k -> k.equals("$maxRecords") || k.equals("$maxDurationMs")) @@ -164,8 +164,8 @@ private static class InfiniteRead extends Base, Mapp private InfiniteRead(final Mapper delegate, final long maxRecordCount, final long maxDuration) { super(delegate); // ensure we consider localConfiguration - final Map internalConf = delegate instanceof PartitionMapperImpl partitionMapper - ? partitionMapper.getInternalConfiguration() + final Map internalConf = delegate instanceof PartitionMapperImpl + ? ((PartitionMapperImpl) delegate).getInternalConfiguration() : emptyMap(); StopConfiguration fromLocalConf = (StopConfiguration) Streaming.loadStopStrategy(delegate.plugin(), internalConf); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java index 41ee3cc4d5f10..4a2ac4b9bb7e2 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java @@ -71,7 +71,7 @@ public JsonObject decode(final InputStream inputStream) throws IOException { @Override public boolean equals(final Object obj) { - return obj instanceof JsonpJsonObjectCoder coder && coder.isValid(); + return obj instanceof JsonpJsonObjectCoder && ((JsonpJsonObjectCoder) obj).isValid(); } @Override diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java index 479890b305e53..fa02d34facb1f 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java @@ -164,13 +164,14 @@ private Object createPrimitiveValue(final Object v, final Type type) { if (String.class == type) { // fast path return v; } - if (type instanceof Class clazz && (clazz.isInstance(v))) { + if (type instanceof Class && ((Class) type).isInstance(v)) { return v; } - if (type instanceof ParameterizedType pt) { + if (type instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) type; final Type raw = pt.getRawType(); // we know what we do if we use that - if (raw instanceof Class clazz && clazz.isInstance(v)) { + if (raw instanceof Class && ((Class) raw).isInstance(v)) { return v; } } diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java index 2725df179d041..38a90bc6a0dc5 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java @@ -66,10 +66,10 @@ public boolean isActive() { @Override public T unwrap(final Class type, final Object... args) { if ("org.talend.sdk.component.design.extension.flows.FlowsFactory".equals(type.getName()) && args != null - && args.length == 1 && args[0] instanceof ComponentFamilyMeta.BaseMeta baseMeta) { + && args.length == 1 && args[0] instanceof ComponentFamilyMeta.BaseMeta) { if (args[0] instanceof ComponentFamilyMeta.ProcessorMeta) { try { - final FlowsFactory factory = FlowsFactory.get(baseMeta); + final FlowsFactory factory = FlowsFactory.get((ComponentFamilyMeta.BaseMeta) args[0]); factory.getOutputFlows(); return type.cast(factory); } catch (final Exception e) { // no @ElementListener, let's default for native transforms diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java index e0ce3869304af..ed4562a073ffd 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java @@ -65,10 +65,10 @@ public Iterator find(final String familyName, final String inputName, fi } catch (Exception e) { log.warn("Component Kit Mapper instantiation failed, trying to wrap native beam mapper..."); final Object delegate = ((Delegated) mapper).getDelegate(); - if (delegate instanceof PTransform pTransform) { + if (delegate instanceof PTransform) { final UUID uuid = UUID.randomUUID(); QUEUE.put(uuid, new ArrayBlockingQueue<>(QUEUE_SIZE, true)); - return new QueueInput(delegate, familyName, inputName, familyName, pTransform, + return new QueueInput(delegate, familyName, inputName, familyName, (PTransform) delegate, uuid); } throw new IllegalStateException(e); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java index 69e96ba8792ab..64eaee291f903 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java @@ -22,7 +22,8 @@ public class AvroEntryBuilder extends SchemaImpl.EntryImpl.BuilderImpl { @Override public Schema.Entry.Builder withElementSchema(final Schema schema) { - if (schema instanceof AvroSchema innerSchema) { + if (schema instanceof AvroSchema) { + final AvroSchema innerSchema = (AvroSchema) schema; AvroSchema avroSchema = this.authorizeNull(innerSchema); return super.withElementSchema(avroSchema); } diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java index 1afee752bb042..cdc831c7ed30f 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java @@ -74,7 +74,8 @@ public AvroRecord(final IndexedRecord record) { } public AvroRecord(final Record record) { - if (record instanceof AvroRecord avr) { + if (record instanceof AvroRecord) { + final AvroRecord avr = (AvroRecord) record; this.delegate = avr.delegate; this.schema = avr.schema; return; @@ -104,12 +105,12 @@ private Object directMapping(final Object value, final Schema.Entry entry) { // RecordImpl store BigDecimal directly, no any convert as not necessary, so here need to convert to string for // beam's AvroCoder which cloud platform use // also here for any Collection as Array type - if (value instanceof BigDecimal bigDecimal) { - return bigDecimal.toString(); + if (value instanceof BigDecimal) { + return ((BigDecimal) value).toString(); } - if (value instanceof Collection collection) { - return collection.stream().map(v -> this.directMapping(v, entry)).collect(toList()); + if (value instanceof Collection) { + return ((Collection) value).stream().map(v -> this.directMapping(v, entry)).collect(toList()); } if (value instanceof RecordImpl) { return new AvroRecord((Record) value).delegate; @@ -117,28 +118,28 @@ private Object directMapping(final Object value, final Schema.Entry entry) { if (value instanceof Record) { return ((Unwrappable) value).unwrap(IndexedRecord.class); } - if (value instanceof ZonedDateTime zonedDateTime) { - return zonedDateTime.toInstant().toEpochMilli(); + if (value instanceof ZonedDateTime) { + return ((ZonedDateTime) value).toInstant().toEpochMilli(); } - if (value instanceof Date date) { - return date.getTime(); + if (value instanceof Date) { + return ((Date) value).getTime(); } - if (value instanceof byte[] bytes) { - return ByteBuffer.wrap(bytes); + if (value instanceof byte[]) { + return ByteBuffer.wrap((byte[]) value); } - if (value instanceof Long longValue) { + if (value instanceof Long) { String logicalType = entry.getLogicalType(); if (logicalType != null) { if (SchemaProperty.LogicalType.DATE.key().equals(logicalType)) { return Math.toIntExact( - Instant.ofEpochMilli(longValue) + Instant.ofEpochMilli((Long) value) .atZone(UTC) .toLocalDate() .toEpochDay()); // Avro stores dates as int } else if (LogicalType.TIME.key().equals(logicalType)) { // QTDI-1252: Avro time-millis logical type stores int milliseconds from 0:00:00 not from Unix Epoch - final Instant instant = Instant.ofEpochMilli(longValue); + final Instant instant = Instant.ofEpochMilli((Long) value); final ZonedDateTime zonedDateTime = instant.atZone(UTC); return Math.toIntExact(zonedDateTime.toLocalTime().toNanoOfDay() / 1_000_000); } @@ -244,13 +245,12 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi return expectedType.cast(value); } - if (value instanceof IndexedRecord indexedRecord - && (Record.class == expectedType || Object.class == expectedType)) { - return expectedType.cast(new AvroRecord(indexedRecord)); + if (value instanceof IndexedRecord && (Record.class == expectedType || Object.class == expectedType)) { + return expectedType.cast(new AvroRecord((IndexedRecord) value)); } - if (value instanceof ByteBuffer byteBuffer && byte[].class == expectedType) { - return expectedType.cast(byteBuffer.array()); + if (value instanceof ByteBuffer && byte[].class == expectedType) { + return expectedType.cast(((ByteBuffer) value).array()); } final org.apache.avro.Schema fieldSchema = unwrapUnion(fieldSchemaRaw); @@ -311,8 +311,8 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi .cast(doMapCollection(itemType, (Collection) value, fieldSchema.getElementType())); } - if (value instanceof org.joda.time.DateTime dateTime && ZonedDateTime.class == expectedType) { - final long epochMilli = dateTime.getMillis(); + if (value instanceof org.joda.time.DateTime && ZonedDateTime.class == expectedType) { + final long epochMilli = ((org.joda.time.DateTime) value).getMillis(); return expectedType.cast(ZonedDateTime.ofInstant(java.time.Instant.ofEpochMilli(epochMilli), UTC)); } @@ -338,7 +338,7 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi if (value instanceof Utf8 && Object.class == expectedType) { return expectedType.cast(value.toString()); } - if (Collection.class.isAssignableFrom(expectedType) && value instanceof Collection collection) { + if (Collection.class.isAssignableFrom(expectedType) && value instanceof Collection) { final org.apache.avro.Schema elementType = fieldSchema.getElementType(); final org.apache.avro.Schema elementSchema = unwrapUnion(elementType); Class toType = Object.class; @@ -347,7 +347,7 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi } else if (elementSchema.getType() == org.apache.avro.Schema.Type.ARRAY) { toType = Collection.class; } - final Collection objects = this.doMapCollection(toType, collection, elementSchema); + final Collection objects = this.doMapCollection(toType, (Collection) value, elementSchema); return expectedType.cast(objects); } return expectedType.cast(value); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java index 14eaaadf53664..965e7611fd08a 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java @@ -42,7 +42,8 @@ public AvroSchema find(final Schema schema) { if (schema == null || schema instanceof AvroSchema) { return (AvroSchema) schema; } - if (schema instanceof SchemaImpl realSchema) { + if (schema instanceof SchemaImpl) { + final SchemaImpl realSchema = (SchemaImpl) schema; if ((!this.cache.containsKey(realSchema)) && this.cache.size() >= AvroSchemaCache.MAX_SIZE) { this.removeOldest(); diff --git a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/factory/service/io/AutoValue_CustomJdbcIO_DataSourceConfiguration.java b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/factory/service/io/AutoValue_CustomJdbcIO_DataSourceConfiguration.java index d56188404121a..b42f2576a5e00 100644 --- a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/factory/service/io/AutoValue_CustomJdbcIO_DataSourceConfiguration.java +++ b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/factory/service/io/AutoValue_CustomJdbcIO_DataSourceConfiguration.java @@ -86,7 +86,8 @@ public boolean equals(final Object o) { if (o == this) { return true; } - if (o instanceof CustomJdbcIO.DataSourceConfiguration that) { + if (o instanceof CustomJdbcIO.DataSourceConfiguration) { + CustomJdbcIO.DataSourceConfiguration that = (CustomJdbcIO.DataSourceConfiguration) o; return ((this.driverClassName == null) ? (that.getDriverClassName() == null) : this.driverClassName.equals(that.getDriverClassName())) && ((this.url == null) ? (that.getUrl() == null) : this.url.equals(that.getUrl())) diff --git a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java index ef23993a5e46a..8e3778f6ccf5d 100644 --- a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java +++ b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java @@ -148,8 +148,8 @@ void coderSerialization() { private Object newInstance(final Class aClass, final ClassLoader validationLoader) { try { final Object instance = aClass.getConstructor().newInstance(); - if (instance instanceof SetValidator setValidatorVal) { - setValidatorVal + if (instance instanceof SetValidator) { + ((SetValidator) instance) .setValidator( () -> assertEquals(Thread.currentThread().getContextClassLoader(), validationLoader)); } diff --git a/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java b/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java index 95a23426aa0c4..7b589deec12a7 100644 --- a/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java +++ b/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java @@ -130,8 +130,8 @@ private Config createConfig(final String plugin, final ComponentManager.AllServi .setId(IdGenerator .get(plugin, c.getKey().getFamily(), c.getKey().getConfigType(), c.getKey().getConfigName())); - if (config.getJavaType() instanceof Class classVal) { - final Class clazz = classVal; + if (config.getJavaType() instanceof Class) { + final Class clazz = (Class) config.getJavaType(); final Version version = clazz.getAnnotation(Version.class); if (version != null) { c.setVersion(version.value()); diff --git a/component-runtime-impl/pom.xml b/component-runtime-impl/pom.xml index c0390a6615856..797f126671551 100644 --- a/component-runtime-impl/pom.xml +++ b/component-runtime-impl/pom.xml @@ -56,7 +56,7 @@ nl.jqno.equalsverifier equalsverifier - 4.4.2 + 3.7.2 test diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java index f4fa4f3e9766a..8f1664df492d2 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java @@ -42,15 +42,15 @@ private static RuntimeException mapException(final Throwable targetException, fi if (targetException == null) { return null; } - if (targetException instanceof ComponentException componentException) { - return componentException; + if (targetException instanceof ComponentException) { + return (ComponentException) targetException; } - if (targetException instanceof DiscoverSchemaException discoverSchemaException) { - return discoverSchemaException; + if (targetException instanceof DiscoverSchemaException) { + return (DiscoverSchemaException) targetException; } - if (targetException instanceof RuntimeException rte + if (targetException instanceof RuntimeException && targetException.getClass().getName().startsWith("java.")) { - final RuntimeException cast = rte; + final RuntimeException cast = (RuntimeException) targetException; if (cast.getCause() == null || (cast.getCause() != null && cast.getCause().getClass().getName().startsWith("java."))) { return cast; diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java index 2bee553b2b832..65f169e23e40d 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java @@ -61,7 +61,8 @@ public List split(final long desiredSize) { @Override public Input create() { - return input instanceof Input in ? in : new InputImpl(rootName(), name(), plugin(), input); + return input instanceof Input ? (Input) input + : new InputImpl(rootName(), name(), plugin(), input); } @Override diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java index c6ee833b95f04..6c5fa2a3b5fb0 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java @@ -68,9 +68,9 @@ public static Object coerce(final Class expectedType, final Object value, // non-matching types if (!expectedType.isInstance(value)) { // number classes mapping - if (value instanceof Number number + if (value instanceof Number && Number.class.isAssignableFrom(PRIMITIVE_WRAPPER_MAP.getOrDefault(expectedType, expectedType))) { - return mapNumber(expectedType, number); + return mapNumber(expectedType, (Number) value); } // mapping primitive <-> Class if (isAssignableTo(value.getClass(), expectedType)) { @@ -80,21 +80,21 @@ public static Object coerce(final Class expectedType, final Object value, return String.valueOf(value); } // TCOMP-2293 support Instant - if (value instanceof Instant instantVal) { + if (value instanceof Instant) { if (ZonedDateTime.class == expectedType) { - return ZonedDateTime.ofInstant(instantVal, UTC); + return ZonedDateTime.ofInstant((Instant) value, UTC); } else if (java.util.Date.class == expectedType) { - return java.sql.Timestamp.from(instantVal); + return java.sql.Timestamp.from((Instant) value); } else if (Long.class == expectedType) { - return instantVal.toEpochMilli(); + return ((Instant) value).toEpochMilli(); } } if (value instanceof Timestamp && (java.util.Date.class == expectedType || Instant.class == expectedType)) { return value; } - if (value instanceof long[] longArray) { - final Instant instant = Instant.ofEpochSecond(longArray[0], longArray[1]); + if (value instanceof long[]) { + final Instant instant = Instant.ofEpochSecond(((long[]) value)[0], ((long[]) value)[1]); if (ZonedDateTime.class == expectedType) { return ZonedDateTime.ofInstant(instant, UTC); } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java index c82f665525c17..e8fc0b07e4f4c 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java @@ -68,11 +68,11 @@ public Record toRecord(final MappingMetaRegistry registry, final T data, fin if (data == null) { return null; } - if (data instanceof Record recordVal) { - return recordVal; + if (data instanceof Record) { + return (Record) data; } - if (data instanceof JsonObject jsonObject) { - return json2Record(recordBuilderProvider.get(), jsonObject); + if (data instanceof JsonObject) { + return json2Record(recordBuilderProvider.get(), (JsonObject) data); } final MappingMeta meta = registry.find(data.getClass()); @@ -172,17 +172,17 @@ private Schema getArrayElementSchema(final RecordBuilderFactory factory, final L } private Object mapJson(final RecordBuilderFactory factory, final JsonValue it) { - if (it instanceof JsonObject jsonObject) { - return json2Record(factory, jsonObject); + if (it instanceof JsonObject) { + return json2Record(factory, (JsonObject) it); } - if (it instanceof JsonArray jsonArray) { - return jsonArray.stream().map(i -> mapJson(factory, i)).collect(toList()); + if (it instanceof JsonArray) { + return ((JsonArray) it).stream().map(i -> mapJson(factory, i)).collect(toList()); } - if (it instanceof JsonString jsonString) { - return jsonString.getString(); + if (it instanceof JsonString) { + return ((JsonString) it).getString(); } - if (it instanceof JsonNumber jsonNumber) { - return jsonNumber.numberValue(); + if (it instanceof JsonNumber) { + return ((JsonNumber) it).numberValue(); } if (JsonValue.FALSE.equals(it)) { return false; @@ -237,8 +237,8 @@ public static Schema toSchema(final RecordBuilderFactory factory, final Object n .withElementSchema(toSchema(factory, collection.iterator().next())) .build(); } - if (next instanceof Record recordVal) { - return recordVal.getSchema(); + if (next instanceof Record) { + return ((Record) next).getSchema(); } throw new IllegalArgumentException("unsupported type for " + next); } @@ -259,12 +259,13 @@ public Object toType(final MappingMetaRegistry registry, final Object data, fina } final JsonObject inputAsJson; - if (data instanceof JsonObject jsonObject) { + if (data instanceof JsonObject) { if (JsonObject.class == parameterType) { return data; } - inputAsJson = jsonObject; - } else if (data instanceof Record record) { + inputAsJson = (JsonObject) data; + } else if (data instanceof Record) { + final Record record = (Record) data; if (!JsonObject.class.isAssignableFrom(parameterType)) { final MappingMeta mappingMeta = registry.find(parameterType); if (mappingMeta.isLinearMapping()) { diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java index 1602d11f66641..f56961dfca2ff 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java @@ -193,16 +193,16 @@ public Builder with(final Entry entry, final Object value) { if (entry.getType() == Schema.Type.DATETIME) { if (value == null) { withDateTime(entry, (ZonedDateTime) value); - } else if (value instanceof Long longValue) { - withTimestamp(entry, longValue); - } else if (value instanceof Date date) { - withDateTime(entry, date); - } else if (value instanceof ZonedDateTime zonedDateTime) { - withDateTime(entry, zonedDateTime); - } else if (value instanceof Instant instant) { - withInstant(entry, instant); - } else if (value instanceof Temporal temporal) { - withTimestamp(entry, temporal.get(ChronoField.INSTANT_SECONDS) * 1000L); + } else if (value instanceof Long) { + withTimestamp(entry, (Long) value); + } else if (value instanceof Date) { + withDateTime(entry, (Date) value); + } else if (value instanceof ZonedDateTime) { + withDateTime(entry, (ZonedDateTime) value); + } else if (value instanceof Instant) { + withInstant(entry, (Instant) value); + } else if (value instanceof Temporal) { + withTimestamp(entry, ((Temporal) value).get(ChronoField.INSTANT_SECONDS) * 1000L); } return this; } else { diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java index fe71160a56dba..889b4038aea4c 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java @@ -320,49 +320,53 @@ public JsonGenerator writeEnd() { final String name; Object previous = builders.getLast(); - if (previous instanceof NamedBuilder namedBuilder) { + if (previous instanceof NamedBuilder) { + final NamedBuilder namedBuilder = (NamedBuilder) previous; name = namedBuilder.name; previous = namedBuilder.builder; } else { name = null; } - if (last instanceof List array) { - if (previous instanceof Collection collectionVal) { - arrayBuilder = collectionVal; + if (last instanceof List) { + final List array = (List) last; + if (previous instanceof Collection) { + arrayBuilder = (Collection) previous; objectBuilder = null; arrayBuilder.add(array); - } else if (previous instanceof Record.Builder builderVar) { - objectBuilder = builderVar; + } else if (previous instanceof Record.Builder) { + objectBuilder = (Record.Builder) previous; arrayBuilder = null; objectBuilder.withArray(createEntryBuilderForArray(name, array).build(), prepareArray(array)); } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); } - } else if (last instanceof Record.Builder object) { - if (previous instanceof Collection collection) { - arrayBuilder = collection; + } else if (last instanceof Record.Builder) { + final Record.Builder object = (Record.Builder) last; + if (previous instanceof Collection) { + arrayBuilder = (Collection) previous; objectBuilder = null; arrayBuilder.add(object); - } else if (previous instanceof Record.Builder builderVar) { - objectBuilder = builderVar; + } else if (previous instanceof Record.Builder) { + objectBuilder = (Record.Builder) previous; arrayBuilder = null; objectBuilder.withRecord(name, objectBuilder.build()); } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); } - } else if (last instanceof NamedBuilder namedBuilderVal) { - final NamedBuilder namedBuilder = namedBuilderVal; - if (previous instanceof Record.Builder builderVal) { - objectBuilder = builderVal; - if (namedBuilder.builder instanceof List array) { + } else if (last instanceof NamedBuilder) { + final NamedBuilder namedBuilder = (NamedBuilder) last; + if (previous instanceof Record.Builder) { + objectBuilder = (Record.Builder) previous; + if (namedBuilder.builder instanceof List) { + final List array = (List) namedBuilder.builder; objectBuilder .withArray(createEntryBuilderForArray(namedBuilder.name, array).build(), prepareArray(array)); arrayBuilder = null; - } else if (namedBuilder.builder instanceof Record.Builder builder2) { + } else if (namedBuilder.builder instanceof Record.Builder) { objectBuilder - .withRecord(namedBuilder.name, builder2.build()); + .withRecord(namedBuilder.name, ((Record.Builder) namedBuilder.builder).build()); arrayBuilder = null; } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); @@ -380,7 +384,7 @@ public JsonGenerator writeEnd() { private List prepareArray(final List array) { return ((Collection) array) .stream() - .map(it -> it instanceof Record.Builder builder ? builder.build() : it) + .map(it -> it instanceof Record.Builder ? ((Record.Builder) it).build() : it) .collect(toList()); } @@ -510,8 +514,8 @@ public static class Factory implements JsonGeneratorFactory { @Override public JsonGenerator createGenerator(final Writer writer) { - if (writer instanceof OutputRecordHolder outputRecordHolder) { - return new RecordJsonGenerator(factory.get(), jsonb.get(), outputRecordHolder); + if (writer instanceof OutputRecordHolder) { + return new RecordJsonGenerator(factory.get(), jsonb.get(), (OutputRecordHolder) writer); } throw new IllegalArgumentException("Unsupported writer: " + writer); } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java index d632994d510a9..98db632afb7ae 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java @@ -63,11 +63,10 @@ public class Defaults { .invokeWithArguments(args); } else { // j > 8 - can need some --add-opens, we will add a module-info later to be clean when dropping j8 final Method privateLookup = findPrivateLookup(); - HANDLER = (clazz, method, proxy, - args) -> ((MethodHandles.Lookup) privateLookup.invoke(null, clazz, constructor.newInstance(clazz))) - .unreflectSpecial(method, clazz) - .bindTo(proxy) - .invokeWithArguments(args); + HANDLER = (clazz, method, proxy, args) -> ((MethodHandles.Lookup) privateLookup.invoke(null, clazz, constructor.newInstance(clazz))) + .unreflectSpecial(method, clazz) + .bindTo(proxy) + .invokeWithArguments(args); } } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java index f5bd234fe020b..82124ad6ff4cf 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java @@ -134,8 +134,8 @@ private void validatePartitionMapper(final Class type) { } final ParameterizedType splitPt = (ParameterizedType) splitReturnType; - if (!(splitPt.getRawType() instanceof Class clazz) - || !Collection.class.isAssignableFrom(clazz)) { + if (!(splitPt.getRawType() instanceof Class) + || !Collection.class.isAssignableFrom((Class) splitPt.getRawType())) { throw new IllegalArgumentException(m + " must return a List of partition mapper, found: " + splitPt); } diff --git a/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java b/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java index 135526c66418f..7f53b27b52b5a 100644 --- a/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java +++ b/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java @@ -58,7 +58,7 @@ private Jsonb getJsonb(Jsonb jsonb) { // create a Jsonb instance which is PojoJsonbProvider as in component-runtime-manager return (Jsonb) Proxy .newProxyInstance(Thread.currentThread().getContextClassLoader(), - new Class[] { Jsonb.class, PojoJsonbProvider.class }, (proxy, method, args) -> { + new Class[]{Jsonb.class, PojoJsonbProvider.class}, (proxy, method, args) -> { if (method.getDeclaringClass() == Supplier.class) { return jsonb; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java index 548789e63e1e7..c68698476beae 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java @@ -807,12 +807,14 @@ public ParameterMeta findDatastoreParameterMeta(final String plugin, final Strin */ public static Map jsonToMap(final JsonValue jsonValue, final String path) { final Map result = new HashMap<>(); - if (jsonValue instanceof JsonObject jsonObj) { + if (jsonValue instanceof JsonObject) { + JsonObject jsonObj = (JsonObject) jsonValue; for (String key : jsonObj.keySet()) { String newPath = path.isEmpty() ? key : path + "." + key; result.putAll(jsonToMap(jsonObj.get(key), newPath)); } - } else if (jsonValue instanceof JsonArray jsonArray) { + } else if (jsonValue instanceof JsonArray) { + JsonArray jsonArray = (JsonArray) jsonValue; for (int i = 0; i < jsonArray.size(); i++) { String newPath = path + "[" + i + "]"; result.putAll(jsonToMap(jsonArray.get(i), newPath)); @@ -873,7 +875,7 @@ public Optional createComponent(final String plugin, final String name, final int version, final Map configuration) { return findComponentInternal(plugin, name, componentType, version, configuration) // unwrap to access the actual instance which is the desired one - .map(i -> i instanceof Delegated delegated ? delegated.getDelegate() : i); + .map(i -> i instanceof Delegated ? ((Delegated) i).getDelegate() : i); } private Optional findComponentInternal(final String plugin, final String name, @@ -1414,9 +1416,9 @@ protected boolean isTracked(final String annotationType) { } } : optimizedFinder; } finally { - if (archive instanceof AutoCloseable autoCloseable) { + if (archive instanceof AutoCloseable) { try { - autoCloseable.close(); + ((AutoCloseable) archive).close(); } catch (final Exception e) { log.warn(e.getMessage()); } @@ -1794,16 +1796,16 @@ private Archive toArchive(final String module, final OriginalId originalId, } private URL archiveToUrl(final Archive mainArchive) { - if (mainArchive instanceof JarArchive jarArchive) { - return jarArchive.getUrl(); - } else if (mainArchive instanceof FileArchive fileArchive) { + if (mainArchive instanceof JarArchive) { + return ((JarArchive) mainArchive).getUrl(); + } else if (mainArchive instanceof FileArchive) { try { - return fileArchive.getDir().toURI().toURL(); + return ((FileArchive) mainArchive).getDir().toURI().toURL(); } catch (final MalformedURLException e) { throw new IllegalStateException(e); } - } else if (mainArchive instanceof NestedJarArchive nestedJarArchive) { - return nestedJarArchive.getRootMarker(); + } else if (mainArchive instanceof NestedJarArchive) { + return ((NestedJarArchive) mainArchive).getRootMarker(); } return null; } @@ -1922,8 +1924,7 @@ public void onPartitionMapper(final Class type, final PartitionMapper partiti () -> { final List params = parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() - .get(LocalConfiguration.class))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))); if (infinite) { if (partitionMapper.stoppable()) { addInfiniteMapperBuiltInParameters(type, params); @@ -1976,8 +1977,7 @@ public void onEmitter(final Class type, final Emitter emitter) { final Supplier> parameterMetas = lazy(() -> executeInContainer(plugin, () -> parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() - .get(LocalConfiguration.class))))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))))); final Function, Object[]> parameterFactory = createParametersFactory(plugin, constructor, services.getServices(), parameterMetas); final String name = of(emitter.name()).filter(n -> !n.isEmpty()).orElseGet(type::getName); @@ -2161,8 +2161,7 @@ public void onDriverRunner(final Class type, final DriverRunner processor) { final Supplier> parameterMetas = lazy(() -> executeInContainer(plugin, () -> parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() - .get(LocalConfiguration.class))))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))))); final Function, Object[]> parameterFactory = createParametersFactory(plugin, constructor, services.getServices(), parameterMetas); final String name = of(processor.name()).filter(n -> !n.isEmpty()).orElseGet(type::getName); @@ -2215,8 +2214,8 @@ private ComponentFamilyMeta getOrCreateComponent(final String component) { return this.component == null || !component.equals(this.component.getName()) ? (this.component = new ComponentFamilyMeta(plugin, asList(components.categories()), iconFinder.findIcon(familyAnnotationElement), comp, - familyAnnotationElement instanceof Class clazz - ? getPackage(clazz) + familyAnnotationElement instanceof Class + ? getPackage((Class) familyAnnotationElement) : "")) : this.component; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java index 1ebd8ffad5c7b..67a825281c2fa 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java @@ -182,8 +182,8 @@ public final class Unsafes { */ public static Class defineAndLoadClass(final ClassLoader classLoader, final String proxyName, final byte[] proxyBytes) { - if (classLoader instanceof ConfigurableClassLoader configurableClassLoader) { - return (Class) configurableClassLoader + if (classLoader instanceof ConfigurableClassLoader) { + return (Class) ((ConfigurableClassLoader) classLoader) .registerBytecode(proxyName.replace('/', '.'), proxyBytes); } Class clazz = classLoader.getClass(); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java index e1499cf65d11f..a14aeb5e5c54a 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java @@ -258,12 +258,12 @@ public ExecutorBuilder property(final String name, final Object value) { public void run() { ExecutorBuilder runner = this; final Object o = jobProperties.get(ExecutorBuilder.class.getName()); - if (o instanceof ExecutorBuilder executorBuilder) { - runner = executorBuilder; - } else if (o instanceof Class classVal) { - runner = newRunner(classVal); - } else if (o instanceof String string) { - final String name = string.trim(); + if (o instanceof ExecutorBuilder) { + runner = (ExecutorBuilder) o; + } else if (o instanceof Class) { + runner = newRunner((Class) o); + } else if (o instanceof String) { + final String name = ((String) o).trim(); if (!"standalone".equalsIgnoreCase(name) && !"default".equalsIgnoreCase(name) && !"local".equalsIgnoreCase(name)) { if ("beam".equalsIgnoreCase(name)) { @@ -356,8 +356,8 @@ private void localRun() { .orElseThrow(() -> new IllegalStateException( "No processor found for:" + component.getNode())); final AtomicInteger maxBatchSize = new AtomicInteger(1); - if (processor instanceof ProcessorImpl processorImpl) { - processorImpl + if (processor instanceof ProcessorImpl) { + ((ProcessorImpl) processor) .getInternalConfiguration() .entrySet() .stream() @@ -539,14 +539,14 @@ private List getConnections(final List edges, final Job.Comp public GroupKeyProvider getKeyProvider(final String componentId) { if (componentProperties.get(componentId) != null) { final Object o = componentProperties.get(componentId).get(GroupKeyProvider.class.getName()); - if (o instanceof GroupKeyProvider groupKeyProvider) { - return new GroupKeyProviderImpl(groupKeyProvider); + if (o instanceof GroupKeyProvider) { + return new GroupKeyProviderImpl((GroupKeyProvider) o); } } final Object o = jobProperties.get(GroupKeyProvider.class.getName()); - if (o instanceof GroupKeyProvider groupKeyProvider) { - return new GroupKeyProviderImpl(groupKeyProvider); + if (o instanceof GroupKeyProvider) { + return new GroupKeyProviderImpl((GroupKeyProvider) o); } final ServiceLoader services = ServiceLoader.load(GroupKeyProvider.class); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java index b42c8085e41bb..29e075f327176 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java @@ -57,7 +57,7 @@ private Map map(final List nestedParameters, fina case OBJECT: return map(param.getNestedParameters(), value, indexes); case ARRAY: - final Collection values = value instanceof Collection collection ? collection + final Collection values = value instanceof Collection ? (Collection) value : /* array */asList((Object[]) value); final int arrayIndex = indexes.keySet().size(); final AtomicInteger valuesIndex = new AtomicInteger(0); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java index 3e1703a5a4f53..3347344ad8679 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java @@ -135,8 +135,8 @@ private Object doInvoke(final Method method, final Object[] args) { return method.invoke(delegate, args); } catch (final InvocationTargetException ite) { final Throwable cause = ite.getCause(); - if (cause instanceof RuntimeException runtimeException) { - throw runtimeException; + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; } throw new IllegalStateException(cause.getMessage()); } catch (final IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java index 171058654e83e..38619cf3f577b 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java @@ -91,12 +91,12 @@ public ParameterModelService(final PropertyEditorRegistry registry) { public boolean isService(final Param parameter) { final Class type; - if (parameter.type instanceof Class classVal) { - type = classVal; - } else if (parameter.type instanceof ParameterizedType pt) { - final Type rawType = pt.getRawType(); - if (rawType instanceof Class classVal) { - type = classVal; + if (parameter.type instanceof Class) { + type = (Class) parameter.type; + } else if (parameter.type instanceof ParameterizedType) { + final Type rawType = ((ParameterizedType) parameter.type).getRawType(); + if (rawType instanceof Class) { + type = (Class) rawType; } else { return false; } @@ -136,12 +136,13 @@ public Class declaringClass() { } private Stream extractTypeAnnotation(final Param parameter) { - if (parameter.type instanceof Class classVal) { - return Stream.of(classVal.getAnnotations()); + if (parameter.type instanceof Class) { + return Stream.of(((Class) parameter.type).getAnnotations()); } - if (parameter.type instanceof ParameterizedType parameterizedType) { - if (parameterizedType.getRawType() instanceof Class classVal) { - return Stream.of(classVal.getAnnotations()); + if (parameter.type instanceof ParameterizedType) { + final ParameterizedType parameterizedType = (ParameterizedType) parameter.type; + if (parameterizedType.getRawType() instanceof Class) { + return Stream.of(((Class) parameterizedType.getRawType()).getAnnotations()); } } return Stream.empty(); @@ -179,13 +180,13 @@ protected ParameterMeta buildParameter(final String name, final String prefix, f nested.addAll(meta); break; case ARRAY: - final Type nestedType = genericType instanceof Class clazz && clazz.isArray() - ? clazz.getComponentType() + final Type nestedType = genericType instanceof Class && ((Class) genericType).isArray() + ? ((Class) genericType).getComponentType() : ((ParameterizedType) genericType).getActualTypeArguments()[0]; addI18nPackageIfPossible(i18nPackages, nestedType); nested .addAll(buildParametersMetas(name + "[${index}]", normalizedPrefix + "[${index}].", nestedType, - nestedType instanceof Class clazz ? clazz.getAnnotations() + nestedType instanceof Class ? ((Class) nestedType).getAnnotations() : NO_ANNOTATIONS, i18nPackages, ignoreI18n, context)); break; @@ -207,8 +208,8 @@ protected ParameterMeta buildParameter(final String name, final String prefix, f } private void addI18nPackageIfPossible(final Collection i18nPackages, final Type type) { - if (type instanceof Class classVal) { - final Package typePck = classVal.getPackage(); + if (type instanceof Class) { + final Package typePck = ((Class) type).getPackage(); if (typePck != null && !typePck.getName().isEmpty() && !i18nPackages.contains(typePck.getName())) { i18nPackages.add(typePck.getName()); } @@ -218,7 +219,8 @@ private void addI18nPackageIfPossible(final Collection i18nPackages, fin private Map buildExtensions(final String name, final Type genericType, final Annotation[] annotations, final BaseParameterEnricher.Context context) { return getAnnotations(genericType, annotations).distinct().flatMap(a -> enrichers.stream().map(e -> { - if (e instanceof BaseParameterEnricher bpe) { + if (e instanceof BaseParameterEnricher) { + final BaseParameterEnricher bpe = (BaseParameterEnricher) e; return bpe.withContext(context, () -> bpe.onParameterAnnotation(name, genericType, a)); } return e.onParameterAnnotation(name, genericType, a); @@ -252,16 +254,16 @@ private Stream getReflectionAnnotations(final Type genericType, fina .concat(Stream.of(annotations), // if a class concat its annotations genericType instanceof Class - ? getClassAnnotations(genericType, annotations) - : (hasAClassFirstParameter(genericType) ? getClassAnnotations( - ((ParameterizedType) genericType).getActualTypeArguments()[0], - annotations) : Stream.empty())); + ? getClassAnnotations(genericType, annotations) + : (hasAClassFirstParameter(genericType) ? getClassAnnotations( + ((ParameterizedType) genericType).getActualTypeArguments()[0], + annotations) : Stream.empty())); } private boolean hasAClassFirstParameter(final Type genericType) { - return genericType instanceof ParameterizedType pt // if a list concat the item type annotations - && pt.getActualTypeArguments().length == 1 - && pt.getActualTypeArguments()[0] instanceof Class; + return genericType instanceof ParameterizedType // if a list concat the item type annotations + && ((ParameterizedType) genericType).getActualTypeArguments().length == 1 + && ((ParameterizedType) genericType).getActualTypeArguments()[0] instanceof Class; } private Stream getClassAnnotations(final Type genericType, final Annotation[] annotations) { @@ -273,7 +275,8 @@ private Stream getClassAnnotations(final Type genericType, final Ann private List buildParametersMetas(final String name, final String prefix, final Type type, final Annotation[] annotations, final Collection i18nPackages, final boolean ignoreI18n, final BaseParameterEnricher.Context context) { - if (type instanceof ParameterizedType pt) { + if (type instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) type; if (!(pt.getRawType() instanceof Class)) { throw new IllegalArgumentException("Unsupported raw type in ParameterizedType parameter: " + pt); } @@ -294,7 +297,7 @@ private List buildParametersMetas(final String name, final String } return Stream .concat(buildParametersMetas(name + ".key[${index}]", prefix + "key[${index}].", - (Class) pt.getActualTypeArguments()[0], annotations, i18nPackages, ignoreI18n, + (Class) pt.getActualTypeArguments()[0], annotations, i18nPackages, ignoreI18n, context).stream(), buildParametersMetas(name + ".value[${index}]", prefix + "value[${index}].", (Class) pt.getActualTypeArguments()[1], annotations, i18nPackages, @@ -302,7 +305,7 @@ private List buildParametersMetas(final String name, final String .collect(toList()); } } - if (type instanceof Class classVal) { + if (type instanceof Class) { switch (findType(type)) { case ENUM: case STRING: @@ -317,12 +320,12 @@ public String name() { @Override public Class declaringClass() { - return classVal; + return (Class) type; } }, type, annotations, i18nPackages, ignoreI18n, context)); default: } - return buildObjectParameters(prefix, classVal, i18nPackages, ignoreI18n, context); + return buildObjectParameters(prefix, (Class) type, i18nPackages, ignoreI18n, context); } throw new IllegalArgumentException("Unsupported parameter type: " + type); } @@ -371,8 +374,8 @@ public String findName(final AnnotatedElement parameter, final String defaultNam } private ParameterMeta.Type findType(final Type type) { - if (type instanceof Class classVal) { - final Class clazz = classVal; + if (type instanceof Class) { + final Class clazz = (Class) type; // we handled char before so we only have numbers now for primitives if (Primitives.unwrap(clazz) == boolean.class) { @@ -392,9 +395,10 @@ private ParameterMeta.Type findType(final Type type) { return ParameterMeta.Type.ARRAY; } } - if (type instanceof ParameterizedType pt) { - if (pt.getRawType() instanceof Class classVal) { - final Class raw = classVal; + if (type instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) type; + if (pt.getRawType() instanceof Class) { + final Class raw = (Class) pt.getRawType(); if (Collection.class.isAssignableFrom(raw)) { return ParameterMeta.Type.ARRAY; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java index f3712b8efd842..14e221e164dcc 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java @@ -111,10 +111,10 @@ public Function, Object[]> parameterFactory(final Executable Stream.of(executable.getParameters()).map(parameter -> { final String name = parameterModelService.findName(parameter, parameter.getName()); final Type parameterizedType = parameter.getParameterizedType(); - if (parameterizedType instanceof Class classVal) { + if (parameterizedType instanceof Class) { if (parameter.isAnnotationPresent(Configuration.class)) { try { - final Class configClass = classVal; + final Class configClass = (Class) parameterizedType; return createConfigFactory(precomputed, loader, contextualSupplier, parameter.getName(), parameter.getAnnotation(Configuration.class), parameter.getAnnotations(), configClass); @@ -124,7 +124,8 @@ public Function, Object[]> parameterFactory(final Executable } final Object value = precomputed.get(parameterizedType); if (value != null) { - if (value instanceof Copiable copiable) { + if (value instanceof Copiable) { + final Copiable copiable = (Copiable) value; return (Function, Object>) config -> copiable.copy(value); } return (Function, Object>) config -> value; @@ -135,10 +136,11 @@ public Function, Object[]> parameterFactory(final Executable .apply(name, (Map) config); } - if (parameterizedType instanceof ParameterizedType pt) { - if (pt.getRawType() instanceof Class classVal2) { - if (Collection.class.isAssignableFrom(classVal2)) { - final Class collectionType = classVal2; + if (parameterizedType instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) parameterizedType; + if (pt.getRawType() instanceof Class) { + if (Collection.class.isAssignableFrom((Class) pt.getRawType())) { + final Class collectionType = (Class) pt.getRawType(); final Type itemType = pt.getActualTypeArguments()[0]; if (!(itemType instanceof Class)) { throw new IllegalArgumentException( @@ -179,8 +181,8 @@ public Function, Object[]> parameterFactory(final Executable contextualSupplier, name, collectionType, itemClass, collector, itemFactory, (Map) config, parameterMetas, precomputed); } - if (Map.class.isAssignableFrom(classVal2)) { - final Class mapType = classVal2; + if (Map.class.isAssignableFrom((Class) pt.getRawType())) { + final Class mapType = (Class) pt.getRawType(); final Type keyItemType = pt.getActualTypeArguments()[0]; final Type valueItemType = pt.getActualTypeArguments()[1]; if (!(keyItemType instanceof Class) || !(valueItemType instanceof Class)) { @@ -427,14 +429,14 @@ private Object createObject(final ClassLoader loader, final Function arrayClass = classVal; + if (genericType instanceof Class) { + final Class arrayClass = (Class) genericType; if (arrayClass.isArray()) { // we could use Array.newInstance but for now use the list, shouldn't impact // much the perf - final Collection list = - (Collection) createList(loader, contextualSupplier, prefix + enclosingName, List.class, - arrayClass.getComponentType(), toList(), createObjectFactory(loader, - contextualSupplier, arrayClass.getComponentType(), metas, precomputed), - new HashMap<>(listEntries), metas, precomputed); + final Collection list = (Collection) createList(loader, contextualSupplier, prefix + enclosingName, List.class, + arrayClass.getComponentType(), toList(), createObjectFactory(loader, + contextualSupplier, arrayClass.getComponentType(), metas, precomputed), + new HashMap<>(listEntries), metas, precomputed); // we need that conversion to ensure the type matches final Object array = Array.newInstance(arrayClass.getComponentType(), list.size()); @@ -589,8 +590,10 @@ private Object createObject(final ClassLoader loader, final Function 0) { final String listName = nestedName.substring(0, idxStart); final Field field = findField(normalizeName(listName, metas), clazz); - if (field.getGenericType() instanceof ParameterizedType pt) { - if (pt.getRawType() instanceof Class rawType) { + if (field.getGenericType() instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) field.getGenericType(); + if (pt.getRawType() instanceof Class) { + final Class rawType = (Class) pt.getRawType(); if (Set.class.isAssignableFrom(rawType)) { addListElement(loader, contextualSupplier, config, prefix, preparedObjects, nestedName, listName, pt, () -> new HashSet<>(2), translate(metas, listName), precomputed); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/StringCompatibleTypes.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/StringCompatibleTypes.java index 550fbb5c49012..0273ac31afbb1 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/StringCompatibleTypes.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/StringCompatibleTypes.java @@ -28,6 +28,6 @@ final class StringCompatibleTypes { static boolean isKnown(final Type type, final PropertyEditorRegistry registry) { return String.class == type || char.class == type || Character.class == type - || (type instanceof Class clazz && registry.findConverter(clazz) != null); + || (type instanceof Class && registry.findConverter((Class) type) != null); } } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ConditionParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ConditionParameterEnricher.java index 927a13ee1206b..27c2d10ca9433 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ConditionParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ConditionParameterEnricher.java @@ -42,7 +42,8 @@ public Map onParameterAnnotation(final String parameterName, fin final Condition condition = annotation.annotationType().getAnnotation(Condition.class); if (condition != null) { final String type = condition.value(); - if (annotation instanceof ActiveIfs activeIfs) { + if (annotation instanceof ActiveIfs) { + final ActiveIfs activeIfs = (ActiveIfs) annotation; final Map metas = Stream .of(activeIfs.value()) .map(ai -> onParameterAnnotation(parameterName, parameterType, ai)) @@ -72,8 +73,8 @@ private Map toMeta(final Annotation annotation, final String typ .collect(toMap(m -> META_PREFIX + type + "::" + m.getName(), m -> { try { final Object invoke = m.invoke(annotation); - if (invoke instanceof String[] stringArr) { - return Stream.of(stringArr).collect(joining(",")); + if (invoke instanceof String[]) { + return Stream.of((String[]) invoke).collect(joining(",")); } if (ActiveIf.class == m.getDeclaringClass() && "evaluationStrategy".equals(m.getName())) { final ActiveIf.EvaluationStrategyOption[] options = diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java index d4a430031b638..b2c657929dbcb 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java @@ -64,7 +64,7 @@ private boolean isCollectionConnectorReference(final Type parameterType) { // Check it's a Collection (java.util) final Type rawType = parameterClass.getRawType(); - if ((!(rawType instanceof Class clazz)) || !Collection.class.isAssignableFrom(clazz)) { + if ((!(rawType instanceof Class)) || !Collection.class.isAssignableFrom((Class) rawType)) { return false; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java index e5405456f6d7d..b128da1a8f6df 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java @@ -177,11 +177,11 @@ private String toString(final Annotation annotation, final Method m, } return string; } - if (invoke instanceof Class classVal) { - return classVal.getSimpleName().toLowerCase(ENGLISH); + if (invoke instanceof Class) { + return ((Class) invoke).getSimpleName().toLowerCase(ENGLISH); } - if (invoke instanceof String[] stringArray) { - return Stream.of(stringArray).collect(joining(",")); + if (invoke instanceof String[]) { + return Stream.of((String[]) invoke).collect(joining(",")); } return String.valueOf(invoke); } catch (final InvocationTargetException | IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java index 70ae5e222fc9e..988609adc19c5 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java @@ -49,9 +49,9 @@ public Map onParameterAnnotation(final String parameterName, fin } private Class toClass(final Type parameterType) { - return parameterType instanceof ParameterizedType pt - ? toClass(pt.getRawType()) - : (parameterType instanceof Class clazz ? clazz : null); + return parameterType instanceof ParameterizedType + ? toClass(((ParameterizedType) parameterType).getRawType()) + : (parameterType instanceof Class ? (Class) parameterType : null); } private String getValueString(final Annotation annotation) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java index 4097a041c919e..22de0e34c3979 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java @@ -148,14 +148,14 @@ private boolean evaluate(final String expected, final JsonObject payload) { return "0".equals(expected); } final int expectedSize = Integer.parseInt(expected); - if (actual instanceof Collection collectionVal) { - return expectedSize == collectionVal.size(); + if (actual instanceof Collection) { + return expectedSize == ((Collection) actual).size(); } if (actual.getClass().isArray()) { return expectedSize == Array.getLength(actual); } - if (actual instanceof String string) { - return expectedSize == string.length(); + if (actual instanceof String) { + return expectedSize == ((String) actual).length(); } return false; default: @@ -190,8 +190,8 @@ private boolean evaluate(final String expected, final JsonObject payload) { .map(it -> it.contains(expected)) .orElse(false); } - if (actual instanceof Collection collectionVal) { - final Collection collection = collectionVal; + if (actual instanceof Collection) { + final Collection collection = (Collection) actual; return collection.stream().map(preprocessor).anyMatch(it -> it.contains(expected)); } if (actual.getClass().isArray()) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java index 617b3591f5c9c..35573ae45a40f 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java @@ -86,12 +86,13 @@ private void doInject(final Class type, final T instance) { }) .forEach(field -> { Object value = services.get(field.getType()); - if (value == null && field.getGenericType() instanceof ParameterizedType pt) { - if (pt.getRawType() instanceof Class clazz - && Collection.class.isAssignableFrom(clazz)) { + if (value == null && field.getGenericType() instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) field.getGenericType(); + if (pt.getRawType() instanceof Class + && Collection.class.isAssignableFrom((Class) pt.getRawType())) { final Type serviceType = pt.getActualTypeArguments()[0]; - if (serviceType instanceof Class classVal) { - final Class serviceClass = classVal; + if (serviceType instanceof Class) { + final Class serviceClass = (Class) serviceType; value = services .entrySet() .stream() @@ -127,8 +128,7 @@ private void doInject(final Class type, final T instance) { }) .forEach(field -> { try { - final Class configClass = - (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class configClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Supplier supplier = () -> { try { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java index fb7562a1170a4..4e5bad59f9640 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java @@ -105,7 +105,8 @@ public T getEntry(final Record target, final Class type) { private Object getValue(final Object value, final String referenceToken, final int currentPosition, final int referencePosition) { - if (value instanceof Record record) { + if (value instanceof Record) { + final Record record = (Record) value; final Object nestedVal = getRecordEntry(referenceToken, record); if (nestedVal != null) { return nestedVal; @@ -113,7 +114,7 @@ private Object getValue(final Object value, final String referenceToken, final i throw new IllegalArgumentException( "'" + record + "' contains no value for name '" + referenceToken + "'"); } - if (value instanceof Collection collection) { + if (value instanceof Collection) { if (referenceToken.startsWith("+") || referenceToken.startsWith("-")) { throw new IllegalArgumentException( "An array index must not start with '" + referenceToken.charAt(0) + "'"); @@ -122,14 +123,14 @@ private Object getValue(final Object value, final String referenceToken, final i throw new IllegalArgumentException("An array index must not start with a leading '0'"); } - final Collection array = collection; + final Collection array = (Collection) value; try { final int arrayIndex = Integer.parseInt(referenceToken); if (arrayIndex >= array.size()) { throw new IllegalArgumentException( "'" + array + "' contains no element for index " + arrayIndex); } - return array instanceof List list ? list.get(arrayIndex) + return array instanceof List ? ((List) array).get(arrayIndex) : new ArrayList<>(array).get(arrayIndex); } catch (final NumberFormatException e) { throw new IllegalArgumentException("'" + referenceToken + "' is no valid array index", e); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java index a6675e90d7692..2518b8d8353b2 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java @@ -97,8 +97,8 @@ public ClassLoaderDescriptor mapDescriptorToClassLoader(final InputStream descri ofNullable(configuration.getParentClassesFilter()).orElse(it -> false), ofNullable(configuration.getClassesFilter()).orElse(it -> true), nested.toArray(new String[0]), - parent instanceof ConfigurableClassLoader configurableClassLoader - ? configurableClassLoader.getJvmMarkers() + parent instanceof ConfigurableClassLoader + ? ((ConfigurableClassLoader) parent).getJvmMarkers() : new String[] { "" }, ofNullable(configuration.getParentResourcesFilter()).orElse(it -> true)); return new ClassLoaderDescriptorImpl(volatileLoader, resolved); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java index 0afa6685d1bca..df71b68221c60 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java @@ -57,8 +57,8 @@ public Object createServiceInstance(final ClassLoader loader, final String conta .initialize(instance, new InterceptorHandlerFacade(serviceClass.getConstructor().newInstance(), allServices)); } - if (instance instanceof BaseService baseService) { - this.updateService(baseService, containerId, serviceClass.getName()); + if (instance instanceof BaseService) { + this.updateService((BaseService) instance, containerId, serviceClass.getName()); } return instance; } catch (final InstantiationException | IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java index 1abfef827aacd..3690f3b3ad8e2 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java @@ -233,8 +233,8 @@ private BiFunction> buildPayloadProvider(fina if (payload == null) { return Optional.empty(); } - if (payload instanceof byte[] bytes) { - return Optional.of(bytes); + if (payload instanceof byte[]) { + return Optional.of((byte[]) payload); } if (encoders.size() == 1) { return Optional.of(encoders.values().iterator().next().encode(payload)); @@ -257,12 +257,13 @@ private Configurer findConfigurerInstance(final Method m) { static Class toClassType(final Type type) { Class cType = null; - if (type instanceof Class classVal) { - cType = classVal; - } else if (type instanceof ParameterizedType pt) { + if (type instanceof Class) { + cType = (Class) type; + } else if (type instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) type; if (pt.getRawType() == Response.class && pt.getActualTypeArguments().length == 1 - && pt.getActualTypeArguments()[0] instanceof Class clazz) { - cType = clazz; + && pt.getActualTypeArguments()[0] instanceof Class) { + cType = (Class) pt.getActualTypeArguments()[0]; } } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java index d65ba3e42a3ad..c91c70e78d2f5 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java @@ -51,13 +51,14 @@ public Instance createDemoInstance(final Object rootInstance, final ParameterMet final Type javaType = param.getJavaType(); if (javaType instanceof Class) { return new Instance(tryCreatingObjectInstance(javaType), true); - } else if (javaType instanceof ParameterizedType pt) { + } else if (javaType instanceof ParameterizedType) { + final ParameterizedType pt = (ParameterizedType) javaType; final Type rawType = pt.getRawType(); - if (rawType instanceof Class clazz && Collection.class.isAssignableFrom(clazz) + if (rawType instanceof Class && Collection.class.isAssignableFrom((Class) rawType) && pt.getActualTypeArguments().length == 1 && pt.getActualTypeArguments()[0] instanceof Class) { final Object instance = tryCreatingObjectInstance(pt.getActualTypeArguments()[0]); - final Class collectionType = clazz; + final Class collectionType = (Class) rawType; if (Set.class == collectionType) { return new Instance(singleton(instance), true); } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java index c6231dc3a4179..8f51b1dc4fd2a 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java @@ -98,8 +98,8 @@ private Schema toSchema(final JsonObject json) { this.addProps(builder::withProp, json); final JsonValue orderValue = json.get("order"); - if (orderValue instanceof JsonString jsonString) { - final Schema.EntriesOrder order = Schema.EntriesOrder.of(jsonString.getString()); + if (orderValue instanceof JsonString) { + final Schema.EntriesOrder order = Schema.EntriesOrder.of(((JsonString) orderValue).getString()); return builder.build(order); } else { return builder.build(); @@ -109,11 +109,11 @@ private Schema toSchema(final JsonObject json) { private void treatElementSchema(final JsonObject json, final Consumer setter) { final JsonValue elementSchema = json.get(ELEMENT_SCHEMA); - if (elementSchema instanceof JsonObject jsonObject) { - final Schema schema = this.toSchema(jsonObject); + if (elementSchema instanceof JsonObject) { + final Schema schema = this.toSchema((JsonObject) elementSchema); setter.accept(schema); - } else if (elementSchema instanceof JsonString jsonString) { - final Schema.Type innerType = Schema.Type.valueOf(jsonString.getString()); + } else if (elementSchema instanceof JsonString) { + final Schema.Type innerType = Schema.Type.valueOf(((JsonString) elementSchema).getString()); setter.accept(this.factory.newSchemaBuilder(innerType).build()); } } @@ -276,17 +276,17 @@ private JsonValue toValue(final Object object) { if (object == null) { return JsonValue.NULL; } - if (object instanceof Integer i) { - return Json.createValue(i); + if (object instanceof Integer) { + return Json.createValue((Integer) object); } - if (object instanceof Long l) { - return Json.createValue(l); + if (object instanceof Long) { + return Json.createValue((Long) object); } if (object instanceof Double || object instanceof Float) { return Json.createValue((Double) object); } - if (object instanceof BigInteger bi) { - return Json.createValue(bi); + if (object instanceof BigInteger) { + return Json.createValue((BigInteger) object); } if (object instanceof Boolean) { if (object == Boolean.TRUE) { @@ -294,11 +294,11 @@ private JsonValue toValue(final Object object) { } return JsonValue.FALSE; } - if (object instanceof BigDecimal bd) { - return Json.createValue(bd); + if (object instanceof BigDecimal) { + return Json.createValue((BigDecimal) object); } - if (object instanceof String s) { - return Json.createValue(s); + if (object instanceof String) { + return Json.createValue((String) object); } return null; diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java index d9ef11418ea2b..3aca230e76ffd 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java @@ -611,8 +611,7 @@ void testLocalConfigurationFromEnvironment(@TempDir final File temporaryFolder) manager.addPlugin(plugin.getAbsolutePath()); final Container container = manager.getContainer().findAll().stream().findFirst().orElse(null); assertNotNull(container); - final LocalConfiguration envConf = - (LocalConfiguration) container.get(AllServices.class).getServices().get(LocalConfiguration.class); + final LocalConfiguration envConf = (LocalConfiguration) container.get(AllServices.class).getServices().get(LocalConfiguration.class); // check translated env vars assertEquals("/home/user", envConf.get("USER_PATH")); assertEquals("/home/user", envConf.get("USER.PATH")); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java index ae2e86cda2cfb..11e4cf10371e9 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java @@ -42,14 +42,12 @@ void run(@TempDir final Path temporaryFolder) throws Exception { "META-INF/test/dependencies", "org.talend.test:type=plugin,value=%s")) { manager.addPlugin(jar.getAbsolutePath()); { - final Object nested = ((ProcessorImpl) manager - .findProcessor("chain", "configured1", 0, new HashMap() { + final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "configured1", 0, new HashMap() { - { - put("config.__version", "-1"); - } - }) - .orElseThrow(IllegalStateException::new)) + { + put("config.__version", "-1"); + } + }).orElseThrow(IllegalStateException::new)) .getDelegate(); final Object config = get(nested, "getConfig"); @@ -57,15 +55,13 @@ void run(@TempDir final Path temporaryFolder) throws Exception { assertEquals("ok", get(config, "getName")); } { - final Object nested = ((ProcessorImpl) manager - .findProcessor("chain", "configured2", 0, new HashMap() { + final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "configured2", 0, new HashMap() { - { - put("config.__version", "0"); - put("value.__version", "-1"); - } - }) - .orElseThrow(IllegalStateException::new)) + { + put("config.__version", "0"); + put("value.__version", "-1"); + } + }).orElseThrow(IllegalStateException::new)) .getDelegate(); assertEquals("set", get(nested, "getValue")); @@ -74,15 +70,13 @@ void run(@TempDir final Path temporaryFolder) throws Exception { assertEquals("ok", get(config, "getName")); } { - final Object nested = ((ProcessorImpl) manager - .findProcessor("chain", "migrationtest", -1, new HashMap() { + final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "migrationtest", -1, new HashMap() { - { - put("config.__version", "1"); - put("config.datastore.__version", "1"); - } - }) - .orElseThrow(IllegalStateException::new)) + { + put("config.__version", "1"); + put("config.datastore.__version", "1"); + } + }).orElseThrow(IllegalStateException::new)) .getDelegate(); final Object config = get(nested, "getConfig"); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java index 09a7aecc5d5c2..836bc2336470f 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java @@ -450,10 +450,8 @@ void copiable() throws NoSuchMethodException { new HttpClientFactoryImpl("test", reflectionService, JsonbBuilder.create(), emptyMap()) .create(UserHttpClient.class, "http://foo")); final Method httpMtd = TableOwner.class.getMethod("http", UserHttpClient.class); - final HttpClient client1 = - (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; - final HttpClient client2 = - (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; + final HttpClient client1 = (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; + final HttpClient client2 = (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; assertNotSame(client1, client2); final InvocationHandler handler1 = Proxy.getInvocationHandler(client1); final InvocationHandler handler2 = Proxy.getInvocationHandler(client2); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java index 6b229189412f6..79034d8e80770 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java @@ -77,8 +77,8 @@ void findException() { } private Record toRecord(final Object object) { - if (object instanceof Record rcd) { - return rcd; + if (object instanceof Record) { + return (Record) object; } return null; } diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java index 059154dffe389..4002678fd3919 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java @@ -52,8 +52,7 @@ class RecordServiceImplTest { private final RecordBuilderFactory factory = new RecordBuilderFactoryImpl(null); - private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), - Json.createGeneratorFactory(emptyMap()), + private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), Json.createGeneratorFactory(emptyMap()), Json.createReaderFactory(emptyMap()), Json.createBuilderFactory(emptyMap()), Json.createParserFactory(emptyMap()), Json.createWriterFactory(emptyMap()), new JsonbConfig(), JsonbProvider.provider(), null, null, emptyList(), t -> factory, null) @@ -105,28 +104,28 @@ void visit() { assertEquals(3, service .visit((RecordVisitor) Proxy - .newProxyInstance(Thread.currentThread().getContextClassLoader(), - new Class[] { RecordVisitor.class }, (proxy, method, args) -> { - visited - .add(method.getName() + "/" - + (args == null ? "null" + .newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[]{RecordVisitor.class}, (proxy, method, args) -> { + visited + .add(method.getName() + "/" + + (args == null ? "null" : Stream - .of(args) - .filter(it -> !(it instanceof Schema.Entry)) - .collect(Collectors.toList()))); - switch (method.getName()) { - case "get": - return out.incrementAndGet(); - case "apply": - return asList(args) - .stream() - .mapToInt(Integer.class::cast) - .sum(); - default: - return method.getReturnType() == RecordVisitor.class ? proxy - : null; - } - }), + .of(args) + .filter(it -> !(it instanceof Schema.Entry)) + .collect(Collectors.toList()))); + switch (method.getName()) { + case "get": + return out.incrementAndGet(); + case "apply": + return asList(args) + .stream() + .mapToInt(Integer.class::cast) + .sum(); + default: + return method.getReturnType() == RecordVisitor.class ? proxy + : null; + } + }), baseRecord)); assertEquals(asList("onString/[Optional[Test]]", "onInt/[OptionalInt[33]]", "onRecord/[Optional[{\"street\":\"here\",\"number\":1}]]", "onString/[Optional[here]]", diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java index 213b75e7a8fe2..955394bb6d60c 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java @@ -254,7 +254,8 @@ public int hashCode() { public boolean equals(final Object obj) { if (this == obj) { return true; - } else if (obj instanceof ParameterizedType that) { + } else if (obj instanceof ParameterizedType) { + final ParameterizedType that = (ParameterizedType) obj; final Type thatRawType = that.getRawType(); return that.getOwnerType() == null && (rawType == null ? thatRawType == null : rawType.equals(thatRawType)) diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocatorCapturingHandler.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocatorCapturingHandler.java index 73ef4b5cf5359..1854496603f25 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocatorCapturingHandler.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocatorCapturingHandler.java @@ -69,8 +69,8 @@ protected void beforeResponse(final String requestUri, final FullHttpRequest req } model.setResponse(responseModel); - if (api.getResponseLocator() instanceof DefaultResponseLocator defaultLocator) { - defaultLocator.addModel(model); + if (api.getResponseLocator() instanceof DefaultResponseLocator) { + ((DefaultResponseLocator) api.getResponseLocator()).addModel(model); } } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java index ddc316335c4fa..cbc7f5656dc21 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java @@ -108,7 +108,8 @@ private void doHttpRequest(final FullHttpRequest request, final ChannelHandlerCo final HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); connection.setConnectTimeout(30000); connection.setReadTimeout(20000); - if (connection instanceof HttpsURLConnection httpsURLConnection && api.getSslContext() != null) { + if (connection instanceof HttpsURLConnection && api.getSslContext() != null) { + final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection; httpsURLConnection.setHostnameVerifier((h, s) -> true); httpsURLConnection.setSSLSocketFactory(api.getSslContext().getSocketFactory()); } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java index e6649dee7d56d..89ca1f43af794 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java @@ -36,16 +36,18 @@ public Statement apply(final Statement base, final Description description) { @Override public void evaluate() throws Throwable { final ResponseLocator responseLocator = server.getResponseLocator(); - if (responseLocator instanceof DefaultResponseLocator defaultResponseLocatorVal) { + if (responseLocator instanceof DefaultResponseLocator) { final DefaultResponseLocator defaultResponseLocator = - defaultResponseLocatorVal; + (DefaultResponseLocator) responseLocator; defaultResponseLocator.setTest(description.getClassName() + "_" + description.getMethodName()); } try { base.evaluate(); } finally { - if (responseLocator instanceof DefaultResponseLocator defaultResponseLocator) { + if (responseLocator instanceof DefaultResponseLocator) { if (Handlers.isActive("capture")) { + final DefaultResponseLocator defaultResponseLocator = + (DefaultResponseLocator) responseLocator; defaultResponseLocator.flush(Handlers.getBaseCapture()); } } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java index 5c8e0f0c18202..8fc1ec1f86f4f 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java @@ -47,8 +47,8 @@ public DelegatingRunner(final Class testClass) throws InitializationError { } catch (final InstantiationException | NoSuchMethodException | IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (final InvocationTargetException e) { - if (e.getCause() instanceof InitializationError initError) { - throw initError; + if (e.getCause() instanceof InitializationError) { + throw (InitializationError) e.getCause(); } throw new IllegalStateException(e.getTargetException()); } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java index f10a752b2b934..0323dcbdca40c 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java @@ -32,8 +32,8 @@ public AutoCloseable start(final Class clazz, final Annotation[] annotations) } public String getName() { - return (provider instanceof BaseEnvironmentProvider environmentProvider - ? environmentProvider.getName() + return (provider instanceof BaseEnvironmentProvider + ? ((BaseEnvironmentProvider) provider).getName() : provider.getClass().getSimpleName()).replace("Environment", ""); } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java index fc5d3dc54ace1..a3ed168137f1b 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java @@ -32,7 +32,8 @@ public MultiEnvironmentsRunner(final Class testClass) throws InitializationEr @Override public void run(final RunNotifier notifier) { configuration.stream().forEach(e -> { - if (e instanceof DecoratingEnvironmentProvider dep) { + if (e instanceof DecoratingEnvironmentProvider) { + final DecoratingEnvironmentProvider dep = (DecoratingEnvironmentProvider) e; if (!dep.isActive()) { notifier.fireTestFinished(Description.createTestDescription(getTestClass(), dep.getName())); return; diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java index 1d93ddb82273b..717808045992b 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java @@ -54,17 +54,17 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg } }); if (stream) { - if (result instanceof Stream streamVal) { - return decorate(streamVal, Stream.class, leafDecorator); + if (result instanceof Stream) { + return decorate((Stream) result, Stream.class, leafDecorator); } - if (result instanceof IntStream intStream) { - return decorate(intStream, IntStream.class, leafDecorator); + if (result instanceof IntStream) { + return decorate((IntStream) result, IntStream.class, leafDecorator); } - if (result instanceof LongStream longStream) { - return decorate(longStream, LongStream.class, leafDecorator); + if (result instanceof LongStream) { + return decorate((LongStream) result, LongStream.class, leafDecorator); } - if (result instanceof DoubleStream doubleStream) { - return decorate(doubleStream, DoubleStream.class, leafDecorator); + if (result instanceof DoubleStream) { + return decorate((DoubleStream) result, DoubleStream.class, leafDecorator); } } return result; diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java index 34705cb7abc0f..acb3dd1662862 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java @@ -112,8 +112,7 @@ public void doStart(final ExtensionContext extensionContext) { } public void doStop(final ExtensionContext extensionContext) { - ofNullable((EmbeddedComponentManager) extensionContext.getStore(NAMESPACE) - .get(EmbeddedComponentManager.class.getName())) + ofNullable((EmbeddedComponentManager) extensionContext.getStore(NAMESPACE).get(EmbeddedComponentManager.class.getName())) .ifPresent(EmbeddedComponentManager::close); } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java index 9961cdac27d96..488f0856fe0f8 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java @@ -130,7 +130,8 @@ public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionConte } private boolean isActive() { - return provider instanceof DecoratingEnvironmentProvider envProvider && envProvider.isActive(); + return provider instanceof DecoratingEnvironmentProvider + && ((DecoratingEnvironmentProvider) provider).isActive(); } @Override diff --git a/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java b/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java index 0c8b3f407d907..acd1fd6c04c4e 100644 --- a/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java +++ b/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java @@ -67,11 +67,11 @@ public void beforeAll(final ExtensionContext extensionContext) throws Exception final Instances instances = start(); if (instances.getException() != null) { instances.close(); - if (instances.getException() instanceof Exception exception) { - throw exception; + if (instances.getException() instanceof Exception) { + throw (Exception) instances.getException(); } - if (instances.getException() instanceof Error error) { - throw error; + if (instances.getException() instanceof Error) { + throw (Error) instances.getException(); } throw new IllegalStateException(instances.getException()); } diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java index 88d6551bc922b..b49d797e7a1d9 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java @@ -181,7 +181,8 @@ private CompletableFuture doExecuteLocalAction(final String family, fi } else { cause = e.getCause(); } - if (cause instanceof WebApplicationException wae) { + if (cause instanceof WebApplicationException) { + final WebApplicationException wae = (WebApplicationException) cause; final Response response = wae.getResponse(); String message = ""; if (wae.getResponse().getEntity() instanceof ErrorPayload) { @@ -211,11 +212,12 @@ private CompletableFuture doExecuteLocalAction(final String family, fi private Response onError(final Throwable re) { log.warn(re.getMessage(), re); - if (re.getCause() instanceof WebApplicationException wae) { - return wae.getResponse(); + if (re.getCause() instanceof WebApplicationException) { + return ((WebApplicationException) re.getCause()).getResponse(); } - if (re instanceof ComponentException ce) { + if (re instanceof ComponentException) { + final ComponentException ce = (ComponentException) re; throw new WebApplicationException(Response .status(ce.getErrorOrigin() == ComponentException.ErrorOrigin.USER ? 400 : ce.getErrorOrigin() == ComponentException.ErrorOrigin.BACKEND ? 456 : 520, diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java index a89a7ae572da8..4625e44cc8302 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java @@ -190,7 +190,8 @@ public Map migrate(final String id, final int version, final Map return migrated; } catch (final Exception e) { // contract of migrate() do not impose to throw a ComponentException, so not likely to happen... - if (e instanceof ComponentException ce) { + if (e instanceof ComponentException) { + final ComponentException ce = (ComponentException) e; throw new WebApplicationException(Response .status(ce.getErrorOrigin() == ComponentException.ErrorOrigin.USER ? 400 : ce.getErrorOrigin() == ComponentException.ErrorOrigin.BACKEND ? 456 : 520, diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java index 0308b9c9d835e..f6cbe9244fe66 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java @@ -52,14 +52,14 @@ private void init() { public Response toResponse(final Throwable exception) { log.error("[DefaultExceptionHandler#toResponse] Throwable: ", exception); final Response response; - if (exception instanceof WebApplicationException webApplicationException) { - response = webApplicationException.getResponse(); + if (exception instanceof WebApplicationException) { + response = ((WebApplicationException) exception).getResponse(); } else { final Optional optCause = Optional.ofNullable(exception.getCause()); if (optCause.isPresent()) { final Throwable cause = optCause.get(); - if (cause instanceof WebApplicationException webApplicationException) { - response = webApplicationException.getResponse(); + if (cause instanceof WebApplicationException) { + response = ((WebApplicationException) cause).getResponse(); } else { response = Response .status(Response.Status.INTERNAL_SERVER_ERROR) diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java index bb0c01fef7bc2..1dea4226e58bc 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java @@ -63,9 +63,6 @@ AsyncContext start() { return this; } - @SuppressWarnings("java:S6201") - // unconditional patterns in instanceof are not supported in -source 17 - // TODO: remove the @SuppressWarnings and apply S6201 when java 21+ only is supported. public void onError(final Throwable throwable) { final AsyncEvent event = new AsyncEvent(this, request, response, throwable); executeOnListeners(l -> l.onError(event), null); diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java index b6a1f84e06a0e..3b87aeb82b4c4 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java @@ -51,8 +51,8 @@ public void init(final FilterConfig filterConfig) { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { - if (request instanceof HttpServletRequest httpServletRequest) { - ThreadContext.putAll(createContext(httpServletRequest)); + if (request instanceof HttpServletRequest) { + ThreadContext.putAll(createContext((HttpServletRequest) request)); } chain.doFilter(request, response); } diff --git a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java index 563b0332eec8d..1ad01ebbe8585 100644 --- a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java +++ b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java @@ -153,7 +153,8 @@ public void capture(@Observes final CreateProject createProject) { final Throwable e = ofNullable(te.getCause()).orElse(te); if (retries - 1 == i) { // no need to retry failed(createProject); - throw e instanceof RuntimeException rte ? rte : new IllegalStateException(e); + throw e instanceof RuntimeException ? (RuntimeException) e + : new IllegalStateException(e); } if (retrySleep > 0) { diff --git a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java index c6ba36caca111..eac99256783e3 100644 --- a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java +++ b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java @@ -47,8 +47,8 @@ public Wrapper find(final String name, final List scopes) { final Wrapper wrapper = super.find(name, scopes); return s -> { final Object call = wrapper.call(s); - if (call instanceof Collection collection && !(call instanceof DecoratedCollection)) { - return new DecoratedCollection<>(collection); + if (call instanceof Collection && !(call instanceof DecoratedCollection)) { + return new DecoratedCollection<>((Collection) call); } return call; }; diff --git a/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java b/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java index 5c05ab2111008..f46b2c5e5f893 100644 --- a/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java +++ b/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java @@ -61,7 +61,8 @@ public HealthCheckStatus healthCheck(@Option(NAME) final BasicAuthConfig dt, fin try { client.healthCheck(dt.getAuthorizationHeader()); } catch (Exception e) { - if (e instanceof HttpException ex) { + if (e instanceof HttpException) { + final HttpException ex = (HttpException) e; final JsonObject jError = (JsonObject) ex.getResponse().error(JsonObject.class); String errorMessage = null; if (jError != null && jError.containsKey("error")) { diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java index 43a34056fbb6a..6924c128a3eb8 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java @@ -54,11 +54,11 @@ public T get(final IndirectInstances key, final Class instance) { } static void init(final Object instance, final Map globalMap) { - if (instance instanceof JobStateAware jobStateAware) { + if (instance instanceof JobStateAware) { synchronized (globalMap) { final State state = (State) globalMap.computeIfAbsent(JobStateAware.class.getName(), k -> new State()); - jobStateAware.setState(state); + ((JobStateAware) instance).setState(state); } } } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java index 1f49e1554244d..77a5a00ad3163 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java @@ -46,8 +46,8 @@ public OutputFactory asOutputFactory() { if (ref != null && value != null) { if (value instanceof javax.json.JsonValue) { ref.add(jsonb.fromJson(value.toString(), ref.getType())); - } else if (value instanceof Record rcd) { - ref.add(registry.find(ref.getType()).newInstance(rcd)); + } else if (value instanceof Record) { + ref.add(registry.find(ref.getType()).newInstance((Record) value)); } else { ref.add(jsonb.fromJson(jsonb.toJson(value), ref.getType())); } @@ -67,8 +67,8 @@ public OutputFactory asOutputFactoryForGuessSchema() { if (ref != null && value != null) { if (value instanceof javax.json.JsonValue) { ref.add(jsonb.fromJson(value.toString(), ref.getType())); - } else if (value instanceof Record rcd) { - ref.add(rcd.getSchema()); + } else if (value instanceof Record) { + ref.add(((Record) value).getSchema()); } else if (value instanceof Schema) { ref.add(value); } else { diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java index ca1827553f1f3..aa84004f8300d 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java @@ -75,7 +75,7 @@ public void push(final Object value) { if (value == null) { return; } - queue.add(value instanceof Record rcd ? rcd : toRecord(value)); + queue.add(value instanceof Record ? (Record) value : toRecord(value)); semaphore.release(); } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java index 5174f46ce25ec..072b1f279398a 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java @@ -74,14 +74,14 @@ public OutputT apply(final String name, final PTransfo private PTransform wrapTransformIfNeeded(final PTransform root) { - if (root instanceof Read.Bounded bounded) { - final BoundedSource source = bounded.getSource(); + if (root instanceof Read.Bounded) { + final BoundedSource source = ((Read.Bounded) root).getSource(); final DelegatingBoundedSource boundedSource = new DelegatingBoundedSource(source, null); setState(boundedSource); return Read.from(boundedSource); } - if (root instanceof Read.Unbounded unbounded) { - final UnboundedSource source = unbounded.getSource(); + if (root instanceof Read.Unbounded) { + final UnboundedSource source = ((Read.Unbounded) root).getSource(); if (source instanceof InMemoryQueueIO.UnboundedQueuedInput) { return root; } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java index d09689a843637..39dac69a1b56e 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java @@ -140,8 +140,8 @@ private void visit(final Object data) { onBoolean(name, raw); break; case StudioTypes.DATE: - if (raw instanceof Timestamp timestamp) { - onInstant(name, timestamp); + if (raw instanceof Timestamp) { + onInstant(name, (Timestamp) raw); break; } onDatetime(name, ((Date) raw).toInstant().atZone(UTC)); @@ -191,10 +191,10 @@ private void handleDynamic(final Object raw) { break; case StudioTypes.BYTE_ARRAY: final byte[] bytes; - if (value instanceof byte[] byteArr) { - bytes = byteArr; - } else if (value instanceof ByteBuffer byteBuffer) { - bytes = byteBuffer.array(); + if (value instanceof byte[]) { + bytes = (byte[]) value; + } else if (value instanceof ByteBuffer) { + bytes = ((ByteBuffer) value).array(); } else { log.warn("[visit] '{}' of type `id_byte[]` and content is contained in `{}`:" + " This should not happen! " @@ -226,7 +226,7 @@ private void handleDynamic(final Object raw) { break; case StudioTypes.DATE: final ZonedDateTime dateTime; - dateTime = ZonedDateTime.ofInstant(value instanceof Long longVal ? ofEpochMilli(longVal) + dateTime = ZonedDateTime.ofInstant(value instanceof Long ? ofEpochMilli((Long) value) : ((Date) value).toInstant(), UTC); onDatetime(metaName, dateTime); break; diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java index 4e8b303581da7..fa939a1d9bf79 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java @@ -174,10 +174,10 @@ private void initClass2JavaTypeMap() { private DiscoverSchemaException transformException(final Exception e) { DiscoverSchemaException discoverSchemaException; - if (e instanceof DiscoverSchemaException dse) { - discoverSchemaException = dse; - } else if (e instanceof ComponentException ce) { - discoverSchemaException = new DiscoverSchemaException(ce); + if (e instanceof DiscoverSchemaException) { + discoverSchemaException = (DiscoverSchemaException) e; + } else if (e instanceof ComponentException) { + discoverSchemaException = new DiscoverSchemaException((ComponentException) e); } else { discoverSchemaException = new DiscoverSchemaException(e.getMessage(), e.getStackTrace(), EXCEPTION); } @@ -253,11 +253,12 @@ private void executeDiscoverSchemaExtendedAction(final Schema schema, final Stri } final Object schemaResult = actionRef.getInvoker().apply(buildActionConfig(actionRef, configuration, schema, branch)); - if (schemaResult instanceof Schema result) { + if (schemaResult instanceof Schema) { + final Schema result = (Schema) schemaResult; if (result.getEntries().isEmpty()) { throw new DiscoverSchemaException(ERROR_NO_AVAILABLE_SCHEMA_FOUND, EXCEPTION); } else { - fromSchema(result); + fromSchema((Schema) schemaResult); } } } @@ -467,8 +468,8 @@ public boolean guessSchemaThroughAction(final Schema schema) { : buildActionConfig(actionRef, configuration, schema, "INPUT"); final Object schemaResult = actionRef.getInvoker().apply(actionConfiguration); - if (schemaResult instanceof Schema resultSchema) { - return fromSchema(resultSchema); + if (schemaResult instanceof Schema) { + return fromSchema((Schema) schemaResult); } else { log.error(ERROR_INSTANCE_SCHEMA); @@ -500,7 +501,8 @@ private boolean fromSchema(final Schema schema) { public Collection getFixedSchema(final String execute) { SchemaConverter sc = new SchemaConverter(); Object o = sc.toObjectImpl(execute); - if (o instanceof Schema schema) { + if (o instanceof Schema) { + final Schema schema = (Schema) o; final Collection entries = schema.getEntries(); if (entries == null || entries.isEmpty()) { log.info(NO_COLUMN_FOUND_BY_GUESS_SCHEMA); @@ -659,8 +661,8 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { final Mapper mapper = componentManager .findMapper(family, componentName, version, configuration) .orElseThrow(() -> new IllegalArgumentException("Can't find " + family + "#" + componentName)); - if (mapper instanceof JobStateAware jobStateAware) { - jobStateAware.setState(new JobStateAware.State()); + if (mapper instanceof JobStateAware) { + ((JobStateAware) mapper).setState(new JobStateAware.State()); } Input input = null; try { @@ -673,10 +675,10 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { if (rowObject == null) { return false; } - if (rowObject instanceof Record rcd) { - return fromSchema(rcd.getSchema()); - } else if (rowObject instanceof java.util.Map map) { - return guessInputSchemaThroughResults(input, map); + if (rowObject instanceof Record) { + return fromSchema(((Record) rowObject).getSchema()); + } else if (rowObject instanceof java.util.Map) { + return guessInputSchemaThroughResults(input, (java.util.Map) rowObject); } else if (rowObject instanceof java.util.Collection) { throw new Exception("Can't guess schema from a Collection"); } else { @@ -705,12 +707,12 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { * @return true if completed; false if one more result row is needed. */ public boolean guessSchemaThroughResult(final Object rowObject) throws Exception { - if (rowObject instanceof java.util.Map map) { - return guessSchemaThroughResult(map); - } else if (rowObject instanceof Schema schema) { - return fromSchema(schema); - } else if (rowObject instanceof Record rcd) { - return fromSchema(rcd.getSchema()); + if (rowObject instanceof java.util.Map) { + return guessSchemaThroughResult((java.util.Map) rowObject); + } else if (rowObject instanceof Schema) { + return fromSchema((Schema) rowObject); + } else if (rowObject instanceof Record) { + return fromSchema(((Record) rowObject).getSchema()); } else if (rowObject instanceof java.util.Collection) { throw new Exception("Can't guess schema from a Collection"); } else { @@ -762,8 +764,8 @@ private boolean guessInputSchemaThroughResults(final Input input, final Map m.getParameters()[i].isAnnotationPresent(Output.class) && outBranchName.equals(m.getParameters()[i].getAnnotation(Output.class).value())) .mapToObj(i -> m.getGenericParameterTypes()[i]) - .filter(t -> t instanceof ParameterizedType pt - && pt.getRawType() == OutputEmitter.class - && pt.getActualTypeArguments().length == 1) + .filter(t -> t instanceof ParameterizedType + && ((ParameterizedType) t).getRawType() == OutputEmitter.class + && ((ParameterizedType) t).getActualTypeArguments().length == 1) .map(p -> ((ParameterizedType) p).getActualTypeArguments()[0])) .findFirst(); - if (type.isPresent() && type.get() instanceof Class clazz) { + if (type.isPresent() && type.get() instanceof Class) { + final Class clazz = (Class) type.get(); if (clazz != JsonObject.class) { guessSchemaThroughResultClass(clazz); } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java index 8062b181e84ee..37f2e428857fb 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java @@ -40,8 +40,8 @@ public class AfterVariableExtracter { * @return map with after variables. */ public static Map extractAfterVariables(final Lifecycle lifecycle) { - if (lifecycle instanceof Delegated delegated) { - final Object delegate = delegated.getDelegate(); + if (lifecycle instanceof Delegated) { + final Object delegate = ((Delegated) lifecycle).getDelegate(); final ClassLoader classloader = ReflectionUtils.getClassLoader(lifecycle); diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java index d60ad6661950e..077cb4c1359c4 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java @@ -33,8 +33,8 @@ public class ParameterSetter { private final Object delegate; public ParameterSetter(final Lifecycle lifecycle) { - if (lifecycle instanceof Delegated delegated) { - delegate = delegated.getDelegate(); + if (lifecycle instanceof Delegated) { + delegate = ((Delegated) lifecycle).getDelegate(); } else { throw new IllegalArgumentException("Not supported implementation of lifecycle : " + lifecycle); } @@ -92,8 +92,8 @@ public void change(final String path, final Object value) { try { target = field.get(target); if (arrayLocation > -1) { - if (target instanceof List list) { - target = list.get(arrayLocation); + if (target instanceof List) { + target = ((List) target).get(arrayLocation); } else { log.warn("expect a list, but not"); return; diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java index cace2e87e06b0..9370724f2b2ac 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java @@ -35,8 +35,8 @@ public class RuntimeContextInjector { * @see Lifecycle */ public static void injectLifecycle(final Lifecycle lifecycle, final RuntimeContextHolder runtimeContext) { - if (lifecycle instanceof Delegated delegated) { - final Object delegate = delegated.getDelegate(); + if (lifecycle instanceof Delegated) { + final Object delegate = ((Delegated) lifecycle).getDelegate(); Class currentClass = delegate.getClass(); while (currentClass != null && currentClass != Object.class) { diff --git a/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java b/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java index d91339888b222..3acfc67c84fd3 100644 --- a/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java +++ b/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java @@ -251,8 +251,8 @@ private void doRun(final ComponentManager manager, final Collection sour Object dataMapper; while ((dataMapper = inputMapper.next()) != null) { final String jsonValueMapper; - if (dataMapper instanceof javax.json.JsonValue jsonValue) { - jsonValueMapper = jsonValue.toString(); + if (dataMapper instanceof javax.json.JsonValue) { + jsonValueMapper = ((javax.json.JsonValue) dataMapper).toString(); } else if (dataMapper instanceof org.talend.sdk.component.api.record.Record) { jsonValueMapper = jsonbMapper .toJson(converters diff --git a/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java b/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java index 18ac03ec00850..4a6a0dadb4ba7 100644 --- a/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java +++ b/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java @@ -205,14 +205,16 @@ private String extractFamilyFromNode(final String id) { private void onException(final AsyncResponse response, final Throwable e) { final UiActionResult payload; final int status; - if (e instanceof WebException we) { + if (e instanceof WebException) { + final WebException we = (WebException) e; status = we.getStatus(); payload = actionService.map(we); - } else if (e instanceof CompletionException actualException) { + } else if (e instanceof CompletionException) { + final CompletionException actualException = (CompletionException) e; log.error(actualException.getMessage(), actualException); status = Response.Status.BAD_GATEWAY.getStatusCode(); - if (actualException.getCause() instanceof WebApplicationException wae) { - final Response resp = wae.getResponse(); + if (actualException.getCause() instanceof WebApplicationException) { + final Response resp = ((WebApplicationException) actualException.getCause()).getResponse(); if (response != null) { final String s = resp.readEntity(String.class); response.resume(Response.status(resp.getStatus()).entity(s).type(APPLICATION_JSON_TYPE).build()); diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java index 92919f1bd8142..3ee1fb4dc3759 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java @@ -284,9 +284,6 @@ protected Asciidoctor getAsciidoctor() { return asciidoctor == null ? asciidoctor = Asciidoctor.Factory.create() : asciidoctor; } - @SuppressWarnings("java:S6201") - // unconditional patterns in instanceof are not supported in -source 17 - // TODO: remove the @SuppressWarnings and apply S6201 when java 21+ only is supported. @Override public void close() { onClose.run(); @@ -297,8 +294,8 @@ public void close() { } catch (final Exception e) { throw new IllegalStateException(e); } - } else if (asciidoctor instanceof JRubyAsciidoctor jRubyAsciidoctor) { - jRubyAsciidoctor.getRubyRuntime().tearDown(); + } else if (asciidoctor instanceof JRubyAsciidoctor) { + ((JRubyAsciidoctor) asciidoctor).getRubyRuntime().tearDown(); } } } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java b/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java index e62a3b27df756..f125f3ab0e62b 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java @@ -58,7 +58,7 @@ public class CarBundler implements Runnable { public CarBundler(final Configuration configuration, final Object log) { this.configuration = configuration; try { - this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); + this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java index 00ecc5cbc54f9..4d0c5cc62bdb3 100755 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java @@ -81,7 +81,7 @@ public ComponentValidator(final Configuration configuration, final File[] classe this.validator = new SvgValidator(this.configuration.isValidateLegacyIcons()); try { - this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); + this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java index 8643f456355bb..a0705359277b3 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java @@ -95,7 +95,7 @@ public abstract class DocBaseGenerator extends BaseTask { this.locale = locale; this.output = output; try { - this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); + this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } @@ -570,8 +570,8 @@ private String findDefault(final ParameterMeta p, final DefaultValueInspector.In .orElse(null); case ARRAY: return String - .valueOf(instance.getValue() instanceof Collection collection - ? collection.size() + .valueOf(instance.getValue() instanceof Collection + ? ((Collection) instance.getValue()).size() : Array.getLength(instance.getValue())); case OBJECT: default: diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java b/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java index 22ca4cdaab26d..10073c197f423 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java @@ -44,7 +44,7 @@ public SVG2Png(final Path iconsFolder, final boolean activeWorkarounds, final Ob this.iconsFolder = iconsFolder; this.activeWorkarounds = activeWorkarounds; try { - this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); + this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java b/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java index 5be7e05b57fef..0336456d20601 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java @@ -63,7 +63,7 @@ public StudioInstaller(final String mainGav, final File studioHome, final Map serverArguments, final Integer port, f this.serverArguments = serverArguments; this.port = port; try { - this.log = log instanceof Log lg ? lg : new ReflectiveLog(log); + this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java index a6abe6bb6f84f..ef20ebc84b7fa 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java @@ -470,8 +470,8 @@ private boolean hasCorrectReturnType(final Method method) { private boolean hasStringInList(final Method method) { if (List.class.isAssignableFrom(method.getReturnType()) - && method.getGenericReturnType() instanceof ParameterizedType parameterizedType) { - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); + && method.getGenericReturnType() instanceof ParameterizedType) { + Type[] actualTypeArguments = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments(); if (actualTypeArguments.length > 0) { return "java.lang.String".equals(actualTypeArguments[0].getTypeName()); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java index faaa126c7e1f8..35fb5e3e03577 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java @@ -163,17 +163,18 @@ private boolean isArrayOfObject(final ParameterMeta param) { private Class toJavaType(final ParameterMeta p) { if (p.getType().equals(OBJECT) || p.getType().equals(ENUM)) { - if (p.getJavaType() instanceof Class classVal) { - return classVal; + if (p.getJavaType() instanceof Class) { + return (Class) p.getJavaType(); } throw new IllegalArgumentException("Unsupported type for parameter " + p.getPath() + " (from " + p.getSource().declaringClass() + "), ensure it is a Class"); } - if (p.getType().equals(ARRAY) && p.getJavaType() instanceof ParameterizedType parameterizedType) { + if (p.getType().equals(ARRAY) && p.getJavaType() instanceof ParameterizedType) { + final ParameterizedType parameterizedType = (ParameterizedType) p.getJavaType(); final Type[] arguments = parameterizedType.getActualTypeArguments(); - if (arguments.length == 1 && arguments[0] instanceof Class clazz) { - return clazz; + if (arguments.length == 1 && arguments[0] instanceof Class) { + return (Class) arguments[0]; } throw new IllegalArgumentException("Unsupported type for parameter " + p.getPath() + " (from " + p.getSource().declaringClass() + "), " + "ensure it is a ParameterizedType with one argument"); diff --git a/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java b/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java index 2557c4dd01359..474b91aedde26 100755 --- a/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java +++ b/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java @@ -182,9 +182,8 @@ public void beforeEach(final ExtensionContext context) { public void afterEach(final ExtensionContext context) { final ExtensionContext.Store store = context.getStore(NAMESPACE); final boolean fails = !((ComponentPackage) store.get(ComponentPackage.class.getName())).success(); - final String expectedMessage = - ((ExceptionSpec) context.getStore(NAMESPACE).get(ExceptionSpec.class.getName())) - .getMessage(); + final String expectedMessage = ((ExceptionSpec) context.getStore(NAMESPACE).get(ExceptionSpec.class.getName())) + .getMessage(); try { ((ComponentValidator) store.get(ComponentValidator.class.getName())).run(); if (fails) { diff --git a/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java b/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java index ebc19a7333570..eb1c7f8a4d981 100644 --- a/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java +++ b/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java @@ -178,7 +178,8 @@ private void loadNestedDependencies(final ClassLoader parent, final String[] nes final CodeSource codeSource; try { urlConnection = url.openConnection(); - if (urlConnection instanceof JarURLConnection juc) { + if (urlConnection instanceof JarURLConnection) { + final JarURLConnection juc = (JarURLConnection) urlConnection; manifest = juc.getManifest(); final Certificate[] certificates = juc.getCertificates(); @@ -445,7 +446,8 @@ private InputStream doGetResourceAsStream(final String name) { private InputStream getInputStream(final URL resource) throws IOException { final URLConnection urlc = resource.openConnection(); final InputStream is = urlc.getInputStream(); - if (urlc instanceof JarURLConnection juc) { + if (urlc instanceof JarURLConnection) { + final JarURLConnection juc = (JarURLConnection) urlc; final JarFile jar = juc.getJarFile(); synchronized (closeables) { if (!closeables.containsKey(jar)) { @@ -805,9 +807,10 @@ private Class loadInternal(final String name, final boolean resolve) { final String pckName = name.substring(0, i); final Package pck = super.getPackage(pckName); if (pck == null) { - if (!(connection instanceof JarURLConnection urlConnection)) { + if (!(connection instanceof JarURLConnection)) { doDefinePackage(null, null, pckName); } else { + final JarURLConnection urlConnection = (JarURLConnection) connection; doDefinePackage(urlConnection.getManifest(), urlConnection.getJarFileURL(), pckName); } } @@ -828,8 +831,8 @@ private Class loadInternal(final String name, final boolean resolve) { } bytes = outputStream.toByteArray(); } - final Certificate[] certificates = connection instanceof JarURLConnection jarURLConnection - ? jarURLConnection.getCertificates() + final Certificate[] certificates = connection instanceof JarURLConnection + ? ((JarURLConnection) connection).getCertificates() : NO_CERTIFICATES; bytes = doTransform(resourceName, bytes); clazz = super.defineClass(name, bytes, 0, bytes.length, new CodeSource(url, certificates)); diff --git a/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java b/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java index 4fb316674b12d..de3c39f354da0 100644 --- a/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java +++ b/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java @@ -97,8 +97,8 @@ void proxying( throw new IllegalStateException(e); } catch (final InvocationTargetException e) { final Throwable targetException = e.getTargetException(); - if (targetException instanceof RuntimeException runtimeException) { - throw runtimeException; + if (targetException instanceof RuntimeException) { + throw (RuntimeException) targetException; } throw new IllegalStateException(targetException); } diff --git a/documentation/src/main/java/org/talend/runtime/documentation/Generator.java b/documentation/src/main/java/org/talend/runtime/documentation/Generator.java index 2f08828472513..a75a8aad81a99 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/Generator.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/Generator.java @@ -373,8 +373,7 @@ private static void generatedScanningExclusions(final File generatedDir) { stream.println("Therefore, the following packages are ignored:"); stream.println(); stream.println("[.talend-filterlist]"); - ((KnownClassesFilter.OptimizedExclusionFilter) ((KnownClassesFilter) KnownClassesFilter.INSTANCE) - .getDelegateSkip()) + ((KnownClassesFilter.OptimizedExclusionFilter) ((KnownClassesFilter) KnownClassesFilter.INSTANCE).getDelegateSkip()) .getIncluded() .stream() .sorted() diff --git a/documentation/src/main/java/org/talend/runtime/documentation/Github.java b/documentation/src/main/java/org/talend/runtime/documentation/Github.java index 78457b75ce99c..c38abde6f1c30 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/Github.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/Github.java @@ -112,8 +112,8 @@ public Collection load() { .collect(toList()))) .get(); } catch (final ExecutionException ee) { - if (ee.getCause() instanceof WebApplicationException wae) { - final Response response = wae.getResponse(); + if (ee.getCause() instanceof WebApplicationException) { + final Response response = ((WebApplicationException) ee.getCause()).getResponse(); if (response != null && response.getEntity() != null) { log.error(response.readEntity(String.class)); } diff --git a/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java b/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java index b5f5d9cdc9b9b..941ef3457b307 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java @@ -61,7 +61,8 @@ public HealthCheckStatus healthCheck(@Option(BasicAuthConfig.NAME) final BasicAu try { client.healthCheck(dt.getAuthorizationHeader()); } catch (Exception e) { - if (e instanceof HttpException ex) { + if (e instanceof HttpException) { + final HttpException ex = (HttpException) e; final JsonObject jError = (JsonObject) ex.getResponse().error(JsonObject.class); String errorMessage = null; if (jError != null && jError.containsKey("error")) { diff --git a/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java b/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java index 591c2d79022e8..45f84f5a4233d 100644 --- a/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java +++ b/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java @@ -58,8 +58,7 @@ public class RecordJsonMapper implements Function { private final Singer singer; - private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), - Json.createGeneratorFactory(emptyMap()), + private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), Json.createGeneratorFactory(emptyMap()), Json.createReaderFactory(emptyMap()), Json.createBuilderFactory(emptyMap()), Json.createParserFactory(emptyMap()), Json.createWriterFactory(emptyMap()), new JsonbConfig(), JsonbProvider.provider(), null, null, emptyList(), t -> new RecordBuilderFactoryImpl("kitap"), null) diff --git a/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java b/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java index 81ba36b2a7fb5..d38a57fdfed41 100644 --- a/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java +++ b/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java @@ -138,8 +138,8 @@ public Wrapper find(final String name, final List scopes) { final Wrapper wrapper = super.find(name, scopes); return s -> { final Object call = wrapper.call(s); - if (call instanceof Collection collection && !(call instanceof DecoratedCollection)) { - return new DecoratedCollection<>(collection); + if (call instanceof Collection && !(call instanceof DecoratedCollection)) { + return new DecoratedCollection<>((Collection) call); } return call; }; diff --git a/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java b/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java index daeb98401de8f..c6d805ca35225 100644 --- a/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java +++ b/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java @@ -153,7 +153,8 @@ public class VaultClient { private Pattern compiledPassthroughRegex; private final Predicate shouldRetry = cause -> { - if (cause instanceof WebApplicationException wae) { + if (cause instanceof WebApplicationException) { + final WebApplicationException wae = (WebApplicationException) cause; final int status = wae.getResponse().getStatus(); if (Status.NOT_FOUND.getStatusCode() == status || status >= 500) { return false; @@ -329,7 +330,8 @@ private CompletionStage> doDecipher(final Collection doAuth(final String role, final String s // .exceptionally(e -> { final Throwable cause = e.getCause(); - if (cause instanceof WebApplicationException wae) { + if (cause instanceof WebApplicationException) { + final WebApplicationException wae = (WebApplicationException) cause; final Response response = wae.getResponse(); String message = ""; if (wae.getResponse().getEntity() instanceof ErrorPayload) { @@ -468,7 +471,8 @@ private void throwError(final int status, final String message) { private void throwError(final Throwable cause) { String message = ""; int status = cantDecipherStatusCode; - if (cause instanceof WebApplicationException wae) { + if (cause instanceof WebApplicationException) { + final WebApplicationException wae = (WebApplicationException) cause; final Response response = wae.getResponse(); status = response.getStatus(); if (response != null) { From e051e5e96b2a0c3a4ca15eb9e562aefb74743e22 Mon Sep 17 00:00:00 2001 From: Emmanuel GALLOIS Date: Thu, 4 Jun 2026 12:15:37 +0200 Subject: [PATCH 6/7] chore(QTDI-2893): S6201 intellij processed --- .../validation/spi/ext/TypeValidation.java | 4 +- .../jsonschema/PojoJsonSchemaBuilder.java | 8 +-- .../runtime/beam/BaseProcessorFn.java | 4 +- .../sdk/component/runtime/beam/TalendIO.java | 8 +-- .../beam/coder/JsonpJsonObjectCoder.java | 2 +- .../service/AutoValueFluentApiFactory.java | 11 ++-- .../runtime/beam/spi/BeamProducerFinder.java | 4 +- .../beam/spi/record/AvroEntryBuilder.java | 3 +- .../runtime/beam/spi/record/AvroRecord.java | 45 ++++++++------- .../beam/spi/record/AvroSchemaCache.java | 3 +- .../beam/transformer/BeamIOTransformer.java | 3 +- .../transformer/BeamIOTransformerTest.java | 4 +- .../exception/InvocationExceptionWrapper.java | 11 ++-- .../runtime/input/LocalPartitionMapper.java | 2 +- .../runtime/record/MappingUtils.java | 16 +++--- .../runtime/record/RecordConverters.java | 39 +++++++------ .../component/runtime/record/RecordImpl.java | 20 +++---- .../component/runtime/record/SchemaImpl.java | 3 +- .../record/json/RecordJsonGenerator.java | 42 +++++++------- .../component/runtime/reflect/Parameters.java | 3 +- .../runtime/visitor/ModelVisitor.java | 14 ++--- .../runtime/record/MappingUtilsTest.java | 4 +- .../runtime/manager/ComponentManager.java | 28 +++++----- .../runtime/manager/asm/Unsafes.java | 5 +- .../manager/chain/internal/JobImpl.java | 24 ++++---- .../configuration/ConfigurationMapper.java | 2 +- .../interceptor/InterceptorHandlerFacade.java | 4 +- .../reflect/ParameterModelService.java | 50 ++++++++--------- .../manager/reflect/ReflectionService.java | 26 ++++----- .../reflect/StringCompatibleTypes.java | 2 +- .../ConditionParameterEnricher.java | 7 +-- .../DependencyParameterEnricher.java | 9 ++- .../UiParameterEnricher.java | 8 +-- .../ValidationParameterEnricher.java | 6 +- .../reflect/visibility/VisibilityService.java | 8 +-- .../runtime/manager/service/InjectorImpl.java | 3 +- .../service/RecordPointerFactoryImpl.java | 5 +- .../runtime/manager/service/ResolverImpl.java | 4 +- .../manager/service/ServiceHelper.java | 4 +- .../manager/service/http/RequestParser.java | 15 +++-- .../manager/util/DefaultValueInspector.java | 7 +-- .../runtime/manager/xbean/FilterFactory.java | 4 +- .../xbean/converter/SchemaConverter.java | 32 +++++------ .../service/ProducerFinderImplTest.java | 4 +- .../internal/impl/DefaultResponseLocator.java | 3 +- .../junit/http/internal/impl/HandlerImpl.java | 3 +- .../internal/impl/PassthroughHandler.java | 3 +- .../http/internal/junit5/JUnit5HttpApi.java | 4 +- .../JUnit4HttpApiPerMethodConfigurator.java | 8 +-- .../DecoratingEnvironmentProvider.java | 4 +- .../environment/MultiEnvironmentsRunner.java | 3 +- .../component/junit/lang/StreamDecorator.java | 16 +++--- .../environment/EnvironmentalContext.java | 4 +- .../server/front/ActionResourceImpl.java | 6 +- .../front/ConfigurationTypeResourceImpl.java | 3 +- .../front/error/DefaultExceptionHandler.java | 8 +-- .../server/front/memory/AsyncContextImpl.java | 7 +-- .../server/mdc/MdcRequestBinder.java | 4 +- .../service/SimpleQueryLanguageCompiler.java | 4 +- .../service/VirtualDependenciesService.java | 4 +- .../service/statistic/StatisticService.java | 2 +- .../service/template/TemplateRenderer.java | 4 +- .../component/service/MockTableService.java | 3 +- .../component/runtime/di/JobStateAware.java | 4 +- .../component/runtime/di/OutputsHandler.java | 8 +-- .../component/runtime/di/beam/LoopState.java | 2 +- .../di/beam/components/DIPipeline.java | 8 +-- .../runtime/di/record/DiRowStructVisitor.java | 20 +++---- .../runtime/di/schema/TaCoKitGuessSchema.java | 55 +++++++++---------- .../di/studio/AfterVariableExtracter.java | 4 +- .../runtime/di/studio/ParameterSetter.java | 8 +-- .../di/studio/RuntimeContextInjector.java | 4 +- .../components/DIBatchSimulationTest.java | 4 +- .../tools/webapp/WebAppComponentProxy.java | 6 +- .../component/tools/AsciidoctorExecutor.java | 4 +- .../sdk/component/tools/CarBundler.java | 2 +- .../component/tools/ComponentValidator.java | 2 +- .../sdk/component/tools/DocBaseGenerator.java | 2 +- .../talend/sdk/component/tools/SVG2Png.java | 2 +- .../sdk/component/tools/StudioInstaller.java | 2 +- .../talend/sdk/component/tools/WebServer.java | 2 +- .../tools/validator/LayoutValidator.java | 3 +- .../classloader/ConfigurableClassLoader.java | 13 ++--- .../talend/sdk/component/ContainerTest.java | 4 +- .../component/service/MockTableService.java | 3 +- .../component/maven/WebsiteBuilderMojo.java | 4 +- .../components/vault/client/VaultClient.java | 12 ++-- 87 files changed, 358 insertions(+), 423 deletions(-) diff --git a/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java b/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java index 3bcad26b568d3..74728b2091965 100644 --- a/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java +++ b/component-form/component-form-core/src/main/java/org/talend/sdk/component/form/internal/validation/spi/ext/TypeValidation.java @@ -38,10 +38,10 @@ public class TypeValidation implements ValidationExtension { @Override public Optional>> create(final ValidationContext model) { final JsonValue value = model.getSchema().get("type"); - if (value instanceof JsonString) { + if (value instanceof JsonString jsonString) { return Optional .of(new Impl(model.toPointer(), model.getValueProvider(), - mapType((JsonString) value).toArray(JsonValue.ValueType[]::new))); + mapType(jsonString).toArray(JsonValue.ValueType[]::new))); } if (value instanceof JsonArray) { return Optional diff --git a/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java b/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java index ad3af841abbba..c0d7b59cbd93c 100644 --- a/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java +++ b/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java @@ -64,7 +64,7 @@ public JsonSchema.Builder create(final Class pojo) { private JsonSchema buildSchema(final Field field) { final Type genericType = field.getGenericType(); - if ((genericType instanceof Class && CharSequence.class.isAssignableFrom((Class) genericType)) + if ((genericType instanceof Class aClass && CharSequence.class.isAssignableFrom(aClass)) || genericType == char.class || genericType == Character.class) { return schemas.computeIfAbsent((Class) genericType, k -> jsonSchema().withType("string").build()); } else if (genericType == long.class || genericType == Long.class || genericType == int.class @@ -83,8 +83,7 @@ private JsonSchema buildSchema(final Field field) { schemas.put(clazz, jsonSchema); return jsonSchema; }); - } else if (genericType instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) genericType; + } else if (genericType instanceof ParameterizedType pt) { final Type rawType = pt.getRawType(); if (!(rawType instanceof Class)) { throw new IllegalArgumentException("Unsupported raw type: " + pt + ", this must be a Class"); @@ -92,11 +91,10 @@ private JsonSchema buildSchema(final Field field) { final Class rawClazz = (Class) rawType; if (Collection.class.isAssignableFrom(rawClazz) && pt.getActualTypeArguments().length == 1) { final Type itemType = pt.getActualTypeArguments()[0]; - if (!(itemType instanceof Class)) { + if (!(itemType instanceof Class itemClass)) { throw new IllegalArgumentException( "Unsupported generic type for item type: " + pt + ", this must be a Class"); } - final Class itemClass = (Class) itemType; final JsonSchema nested = ofNullable(schemas.get(itemType)).orElseGet(() -> { final JsonSchema jsonSchema = create(itemClass).build(); schemas.put(itemClass, jsonSchema); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java index 096d18cd1a7d5..da51d6accf366 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/BaseProcessorFn.java @@ -65,8 +65,8 @@ abstract class BaseProcessorFn extends DoFn { BaseProcessorFn(final Processor processor) { this.processor = processor; - if (processor instanceof ProcessorImpl) { - ((ProcessorImpl) processor) + if (processor instanceof ProcessorImpl processor1) { + processor1 .getInternalConfiguration() .entrySet() .stream() diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java index 92b8ad56d0183..5859da1fc9caf 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/TalendIO.java @@ -77,8 +77,8 @@ public static Base, Mapper> read(final Mapper mapper String maxRecords = null; String maxDurationMs = null; boolean hasInternalConfParams = false; - if (mapper instanceof PartitionMapperImpl) { - Map conf = ((PartitionMapperImpl) mapper).getInternalConfiguration(); + if (mapper instanceof PartitionMapperImpl partitionMapper) { + Map conf = partitionMapper.getInternalConfiguration(); hasInternalConfParams = conf.keySet() .stream() .filter(k -> k.equals("$maxRecords") || k.equals("$maxDurationMs")) @@ -164,8 +164,8 @@ private static class InfiniteRead extends Base, Mapp private InfiniteRead(final Mapper delegate, final long maxRecordCount, final long maxDuration) { super(delegate); // ensure we consider localConfiguration - final Map internalConf = delegate instanceof PartitionMapperImpl - ? ((PartitionMapperImpl) delegate).getInternalConfiguration() + final Map internalConf = delegate instanceof PartitionMapperImpl partitionMapper + ? partitionMapper.getInternalConfiguration() : emptyMap(); StopConfiguration fromLocalConf = (StopConfiguration) Streaming.loadStopStrategy(delegate.plugin(), internalConf); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java index 4a2ac4b9bb7e2..2168a8e805186 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/coder/JsonpJsonObjectCoder.java @@ -71,7 +71,7 @@ public JsonObject decode(final InputStream inputStream) throws IOException { @Override public boolean equals(final Object obj) { - return obj instanceof JsonpJsonObjectCoder && ((JsonpJsonObjectCoder) obj).isValid(); + return obj instanceof JsonpJsonObjectCoder jsonpJsonObjectCoder && jsonpJsonObjectCoder.isValid(); } @Override diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java index fa02d34facb1f..aa9c0b5639da7 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/factory/service/AutoValueFluentApiFactory.java @@ -131,10 +131,10 @@ private Object createValue(final Map config, final String prefix } private Object createObjectValue(final Map config, final Type paramType, final String prefix) { - if (!(paramType instanceof Class)) { + if (!(paramType instanceof Class aClass)) { throw new IllegalArgumentException("Unsupported type: " + paramType); } - final Method factory = findFactory((Class) paramType, "create"); + final Method factory = findFactory(aClass, "create"); final List> params = Stream .of(factory.getParameters()) .map(p -> new AbstractMap.SimpleEntry<>(p.getName(), @@ -164,14 +164,13 @@ private Object createPrimitiveValue(final Object v, final Type type) { if (String.class == type) { // fast path return v; } - if (type instanceof Class && ((Class) type).isInstance(v)) { + if (type instanceof Class aClass1 && aClass1.isInstance(v)) { return v; } - if (type instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) type; + if (type instanceof ParameterizedType pt) { final Type raw = pt.getRawType(); // we know what we do if we use that - if (raw instanceof Class && ((Class) raw).isInstance(v)) { + if (raw instanceof Class aClass && aClass.isInstance(v)) { return v; } } diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java index ed4562a073ffd..e0ce3869304af 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamProducerFinder.java @@ -65,10 +65,10 @@ public Iterator find(final String familyName, final String inputName, fi } catch (Exception e) { log.warn("Component Kit Mapper instantiation failed, trying to wrap native beam mapper..."); final Object delegate = ((Delegated) mapper).getDelegate(); - if (delegate instanceof PTransform) { + if (delegate instanceof PTransform pTransform) { final UUID uuid = UUID.randomUUID(); QUEUE.put(uuid, new ArrayBlockingQueue<>(QUEUE_SIZE, true)); - return new QueueInput(delegate, familyName, inputName, familyName, (PTransform) delegate, + return new QueueInput(delegate, familyName, inputName, familyName, pTransform, uuid); } throw new IllegalStateException(e); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java index 64eaee291f903..69e96ba8792ab 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroEntryBuilder.java @@ -22,8 +22,7 @@ public class AvroEntryBuilder extends SchemaImpl.EntryImpl.BuilderImpl { @Override public Schema.Entry.Builder withElementSchema(final Schema schema) { - if (schema instanceof AvroSchema) { - final AvroSchema innerSchema = (AvroSchema) schema; + if (schema instanceof AvroSchema innerSchema) { AvroSchema avroSchema = this.authorizeNull(innerSchema); return super.withElementSchema(avroSchema); } diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java index cdc831c7ed30f..056af2704d727 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java @@ -74,8 +74,7 @@ public AvroRecord(final IndexedRecord record) { } public AvroRecord(final Record record) { - if (record instanceof AvroRecord) { - final AvroRecord avr = (AvroRecord) record; + if (record instanceof AvroRecord avr) { this.delegate = avr.delegate; this.schema = avr.schema; return; @@ -105,12 +104,12 @@ private Object directMapping(final Object value, final Schema.Entry entry) { // RecordImpl store BigDecimal directly, no any convert as not necessary, so here need to convert to string for // beam's AvroCoder which cloud platform use // also here for any Collection as Array type - if (value instanceof BigDecimal) { - return ((BigDecimal) value).toString(); + if (value instanceof BigDecimal bigDecimal) { + return bigDecimal.toString(); } - if (value instanceof Collection) { - return ((Collection) value).stream().map(v -> this.directMapping(v, entry)).collect(toList()); + if (value instanceof Collection collection) { + return collection.stream().map(v -> this.directMapping(v, entry)).collect(toList()); } if (value instanceof RecordImpl) { return new AvroRecord((Record) value).delegate; @@ -118,28 +117,28 @@ private Object directMapping(final Object value, final Schema.Entry entry) { if (value instanceof Record) { return ((Unwrappable) value).unwrap(IndexedRecord.class); } - if (value instanceof ZonedDateTime) { - return ((ZonedDateTime) value).toInstant().toEpochMilli(); + if (value instanceof ZonedDateTime dateTime) { + return dateTime.toInstant().toEpochMilli(); } - if (value instanceof Date) { - return ((Date) value).getTime(); + if (value instanceof Date date) { + return date.getTime(); } - if (value instanceof byte[]) { - return ByteBuffer.wrap((byte[]) value); + if (value instanceof byte[] bytes) { + return ByteBuffer.wrap(bytes); } - if (value instanceof Long) { + if (value instanceof Long l) { String logicalType = entry.getLogicalType(); if (logicalType != null) { if (SchemaProperty.LogicalType.DATE.key().equals(logicalType)) { return Math.toIntExact( - Instant.ofEpochMilli((Long) value) + Instant.ofEpochMilli(l) .atZone(UTC) .toLocalDate() .toEpochDay()); // Avro stores dates as int } else if (LogicalType.TIME.key().equals(logicalType)) { // QTDI-1252: Avro time-millis logical type stores int milliseconds from 0:00:00 not from Unix Epoch - final Instant instant = Instant.ofEpochMilli((Long) value); + final Instant instant = Instant.ofEpochMilli(l); final ZonedDateTime zonedDateTime = instant.atZone(UTC); return Math.toIntExact(zonedDateTime.toLocalTime().toNanoOfDay() / 1_000_000); } @@ -245,12 +244,12 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi return expectedType.cast(value); } - if (value instanceof IndexedRecord && (Record.class == expectedType || Object.class == expectedType)) { - return expectedType.cast(new AvroRecord((IndexedRecord) value)); + if (value instanceof IndexedRecord indexedRecord && (Record.class == expectedType || Object.class == expectedType)) { + return expectedType.cast(new AvroRecord(indexedRecord)); } - if (value instanceof ByteBuffer && byte[].class == expectedType) { - return expectedType.cast(((ByteBuffer) value).array()); + if (value instanceof ByteBuffer byteBuffer && byte[].class == expectedType) { + return expectedType.cast(byteBuffer.array()); } final org.apache.avro.Schema fieldSchema = unwrapUnion(fieldSchemaRaw); @@ -311,8 +310,8 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi .cast(doMapCollection(itemType, (Collection) value, fieldSchema.getElementType())); } - if (value instanceof org.joda.time.DateTime && ZonedDateTime.class == expectedType) { - final long epochMilli = ((org.joda.time.DateTime) value).getMillis(); + if (value instanceof org.joda.time.DateTime dateTime && ZonedDateTime.class == expectedType) { + final long epochMilli = dateTime.getMillis(); return expectedType.cast(ZonedDateTime.ofInstant(java.time.Instant.ofEpochMilli(epochMilli), UTC)); } @@ -338,7 +337,7 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi if (value instanceof Utf8 && Object.class == expectedType) { return expectedType.cast(value.toString()); } - if (Collection.class.isAssignableFrom(expectedType) && value instanceof Collection) { + if (Collection.class.isAssignableFrom(expectedType) && value instanceof Collection collection) { final org.apache.avro.Schema elementType = fieldSchema.getElementType(); final org.apache.avro.Schema elementSchema = unwrapUnion(elementType); Class toType = Object.class; @@ -347,7 +346,7 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi } else if (elementSchema.getType() == org.apache.avro.Schema.Type.ARRAY) { toType = Collection.class; } - final Collection objects = this.doMapCollection(toType, (Collection) value, elementSchema); + final Collection objects = this.doMapCollection(toType, collection, elementSchema); return expectedType.cast(objects); } return expectedType.cast(value); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java index 965e7611fd08a..14eaaadf53664 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroSchemaCache.java @@ -42,8 +42,7 @@ public AvroSchema find(final Schema schema) { if (schema == null || schema instanceof AvroSchema) { return (AvroSchema) schema; } - if (schema instanceof SchemaImpl) { - final SchemaImpl realSchema = (SchemaImpl) schema; + if (schema instanceof SchemaImpl realSchema) { if ((!this.cache.containsKey(realSchema)) && this.cache.size() >= AvroSchemaCache.MAX_SIZE) { this.removeOldest(); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformer.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformer.java index a0399e4356548..6161156eb04d4 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformer.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformer.java @@ -87,11 +87,10 @@ public BeamIOTransformer() { @Override public byte[] transform(final ClassLoader loader, final String className, final Class classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] classfileBuffer) { - if (className == null || !(loader instanceof ConfigurableClassLoader)) { + if (className == null || !(loader instanceof ConfigurableClassLoader classLoader)) { return classfileBuffer; } - final ConfigurableClassLoader classLoader = (ConfigurableClassLoader) loader; final String javaClassName = toClassName(className); if (!KnownClassesFilter.INSTANCE.accept(javaClassName) && !canBeABeamIO(classLoader, javaClassName)) { return classfileBuffer; diff --git a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java index 8e3778f6ccf5d..dbc9828219596 100644 --- a/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java +++ b/component-runtime-beam/src/test/java/org/talend/sdk/component/runtime/beam/transformer/BeamIOTransformerTest.java @@ -148,8 +148,8 @@ void coderSerialization() { private Object newInstance(final Class aClass, final ClassLoader validationLoader) { try { final Object instance = aClass.getConstructor().newInstance(); - if (instance instanceof SetValidator) { - ((SetValidator) instance) + if (instance instanceof SetValidator setValidator) { + setValidator .setValidator( () -> assertEquals(Thread.currentThread().getContextClassLoader(), validationLoader)); } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java index 8f1664df492d2..95fd645e84d99 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/base/lang/exception/InvocationExceptionWrapper.java @@ -42,15 +42,14 @@ private static RuntimeException mapException(final Throwable targetException, fi if (targetException == null) { return null; } - if (targetException instanceof ComponentException) { - return (ComponentException) targetException; + if (targetException instanceof ComponentException componentException) { + return componentException; } - if (targetException instanceof DiscoverSchemaException) { - return (DiscoverSchemaException) targetException; + if (targetException instanceof DiscoverSchemaException discoverSchemaException) { + return discoverSchemaException; } - if (targetException instanceof RuntimeException + if (targetException instanceof RuntimeException cast && targetException.getClass().getName().startsWith("java.")) { - final RuntimeException cast = (RuntimeException) targetException; if (cast.getCause() == null || (cast.getCause() != null && cast.getCause().getClass().getName().startsWith("java."))) { return cast; diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java index 65f169e23e40d..40da1370699fa 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/input/LocalPartitionMapper.java @@ -61,7 +61,7 @@ public List split(final long desiredSize) { @Override public Input create() { - return input instanceof Input ? (Input) input + return input instanceof Input input1 ? input1 : new InputImpl(rootName(), name(), plugin(), input); } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java index 6c5fa2a3b5fb0..151f13ce9ba70 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/MappingUtils.java @@ -68,9 +68,9 @@ public static Object coerce(final Class expectedType, final Object value, // non-matching types if (!expectedType.isInstance(value)) { // number classes mapping - if (value instanceof Number + if (value instanceof Number number && Number.class.isAssignableFrom(PRIMITIVE_WRAPPER_MAP.getOrDefault(expectedType, expectedType))) { - return mapNumber(expectedType, (Number) value); + return mapNumber(expectedType, number); } // mapping primitive <-> Class if (isAssignableTo(value.getClass(), expectedType)) { @@ -80,21 +80,21 @@ public static Object coerce(final Class expectedType, final Object value, return String.valueOf(value); } // TCOMP-2293 support Instant - if (value instanceof Instant) { + if (value instanceof Instant instant1) { if (ZonedDateTime.class == expectedType) { - return ZonedDateTime.ofInstant((Instant) value, UTC); + return ZonedDateTime.ofInstant(instant1, UTC); } else if (java.util.Date.class == expectedType) { - return java.sql.Timestamp.from((Instant) value); + return java.sql.Timestamp.from(instant1); } else if (Long.class == expectedType) { - return ((Instant) value).toEpochMilli(); + return instant1.toEpochMilli(); } } if (value instanceof Timestamp && (java.util.Date.class == expectedType || Instant.class == expectedType)) { return value; } - if (value instanceof long[]) { - final Instant instant = Instant.ofEpochSecond(((long[]) value)[0], ((long[]) value)[1]); + if (value instanceof long[] longs) { + final Instant instant = Instant.ofEpochSecond(longs[0], longs[1]); if (ZonedDateTime.class == expectedType) { return ZonedDateTime.ofInstant(instant, UTC); } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java index e8fc0b07e4f4c..de9acf350af03 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordConverters.java @@ -68,11 +68,11 @@ public Record toRecord(final MappingMetaRegistry registry, final T data, fin if (data == null) { return null; } - if (data instanceof Record) { - return (Record) data; + if (data instanceof Record record) { + return record; } - if (data instanceof JsonObject) { - return json2Record(recordBuilderProvider.get(), (JsonObject) data); + if (data instanceof JsonObject jsonObject) { + return json2Record(recordBuilderProvider.get(), jsonObject); } final MappingMeta meta = registry.find(data.getClass()); @@ -82,8 +82,8 @@ public Record toRecord(final MappingMetaRegistry registry, final T data, fin final Jsonb jsonb = jsonbProvider.get(); if (!(data instanceof String) && !data.getClass().isPrimitive() - && jsonb instanceof PojoJsonbProvider) { - final Jsonb pojoMapper = ((PojoJsonbProvider) jsonb).get(); + && jsonb instanceof PojoJsonbProvider pojoJsonbProvider) { + final Jsonb pojoMapper = pojoJsonbProvider.get(); final OutputRecordHolder holder = new OutputRecordHolder(data); try (final OutputRecordHolder stream = holder) { pojoMapper.toJson(data, stream); @@ -172,17 +172,17 @@ private Schema getArrayElementSchema(final RecordBuilderFactory factory, final L } private Object mapJson(final RecordBuilderFactory factory, final JsonValue it) { - if (it instanceof JsonObject) { - return json2Record(factory, (JsonObject) it); + if (it instanceof JsonObject jsonObject) { + return json2Record(factory, jsonObject); } - if (it instanceof JsonArray) { - return ((JsonArray) it).stream().map(i -> mapJson(factory, i)).collect(toList()); + if (it instanceof JsonArray jsonValues) { + return jsonValues.stream().map(i -> mapJson(factory, i)).collect(toList()); } - if (it instanceof JsonString) { - return ((JsonString) it).getString(); + if (it instanceof JsonString jsonString) { + return jsonString.getString(); } - if (it instanceof JsonNumber) { - return ((JsonNumber) it).numberValue(); + if (it instanceof JsonNumber jsonNumber) { + return jsonNumber.numberValue(); } if (JsonValue.FALSE.equals(it)) { return false; @@ -237,8 +237,8 @@ public static Schema toSchema(final RecordBuilderFactory factory, final Object n .withElementSchema(toSchema(factory, collection.iterator().next())) .build(); } - if (next instanceof Record) { - return ((Record) next).getSchema(); + if (next instanceof Record record) { + return record.getSchema(); } throw new IllegalArgumentException("unsupported type for " + next); } @@ -259,13 +259,12 @@ public Object toType(final MappingMetaRegistry registry, final Object data, fina } final JsonObject inputAsJson; - if (data instanceof JsonObject) { + if (data instanceof JsonObject jsonObject) { if (JsonObject.class == parameterType) { return data; } - inputAsJson = (JsonObject) data; - } else if (data instanceof Record) { - final Record record = (Record) data; + inputAsJson = jsonObject; + } else if (data instanceof Record record) { if (!JsonObject.class.isAssignableFrom(parameterType)) { final MappingMeta mappingMeta = registry.find(parameterType); if (mappingMeta.isLinearMapping()) { diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java index f56961dfca2ff..a8efe15a3a1ee 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/RecordImpl.java @@ -193,16 +193,16 @@ public Builder with(final Entry entry, final Object value) { if (entry.getType() == Schema.Type.DATETIME) { if (value == null) { withDateTime(entry, (ZonedDateTime) value); - } else if (value instanceof Long) { - withTimestamp(entry, (Long) value); - } else if (value instanceof Date) { - withDateTime(entry, (Date) value); - } else if (value instanceof ZonedDateTime) { - withDateTime(entry, (ZonedDateTime) value); - } else if (value instanceof Instant) { - withInstant(entry, (Instant) value); - } else if (value instanceof Temporal) { - withTimestamp(entry, ((Temporal) value).get(ChronoField.INSTANT_SECONDS) * 1000L); + } else if (value instanceof Long l) { + withTimestamp(entry, l); + } else if (value instanceof Date date) { + withDateTime(entry, date); + } else if (value instanceof ZonedDateTime zonedDateTime) { + withDateTime(entry, zonedDateTime); + } else if (value instanceof Instant instant) { + withInstant(entry, instant); + } else if (value instanceof Temporal temporal) { + withTimestamp(entry, temporal.get(ChronoField.INSTANT_SECONDS) * 1000L); } return this; } else { diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/SchemaImpl.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/SchemaImpl.java index 665b30d5a4cbd..532b4c9a08093 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/SchemaImpl.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/SchemaImpl.java @@ -99,10 +99,9 @@ public boolean equals(final Object obj) { if (obj == this) { return true; } - if (!(obj instanceof SchemaImpl)) { + if (!(obj instanceof SchemaImpl other)) { return false; } - final SchemaImpl other = (SchemaImpl) obj; if (!other.canEqual(this)) { return false; } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java index 889b4038aea4c..6f4c47e4f7055 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java @@ -320,35 +320,32 @@ public JsonGenerator writeEnd() { final String name; Object previous = builders.getLast(); - if (previous instanceof NamedBuilder) { - final NamedBuilder namedBuilder = (NamedBuilder) previous; + if (previous instanceof NamedBuilder namedBuilder) { name = namedBuilder.name; previous = namedBuilder.builder; } else { name = null; } - if (last instanceof List) { - final List array = (List) last; - if (previous instanceof Collection) { - arrayBuilder = (Collection) previous; + if (last instanceof List array) { + if (previous instanceof Collection collection) { + arrayBuilder = collection; objectBuilder = null; arrayBuilder.add(array); - } else if (previous instanceof Record.Builder) { - objectBuilder = (Record.Builder) previous; + } else if (previous instanceof Record.Builder builder) { + objectBuilder = builder; arrayBuilder = null; objectBuilder.withArray(createEntryBuilderForArray(name, array).build(), prepareArray(array)); } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); } - } else if (last instanceof Record.Builder) { - final Record.Builder object = (Record.Builder) last; - if (previous instanceof Collection) { - arrayBuilder = (Collection) previous; + } else if (last instanceof Record.Builder object) { + if (previous instanceof Collection collection) { + arrayBuilder = collection; objectBuilder = null; arrayBuilder.add(object); - } else if (previous instanceof Record.Builder) { - objectBuilder = (Record.Builder) previous; + } else if (previous instanceof Record.Builder builder) { + objectBuilder = builder; arrayBuilder = null; objectBuilder.withRecord(name, objectBuilder.build()); } else { @@ -356,17 +353,16 @@ public JsonGenerator writeEnd() { } } else if (last instanceof NamedBuilder) { final NamedBuilder namedBuilder = (NamedBuilder) last; - if (previous instanceof Record.Builder) { - objectBuilder = (Record.Builder) previous; - if (namedBuilder.builder instanceof List) { - final List array = (List) namedBuilder.builder; + if (previous instanceof Record.Builder builder1) { + objectBuilder = builder1; + if (namedBuilder.builder instanceof List array) { objectBuilder .withArray(createEntryBuilderForArray(namedBuilder.name, array).build(), prepareArray(array)); arrayBuilder = null; - } else if (namedBuilder.builder instanceof Record.Builder) { + } else if (namedBuilder.builder instanceof Record.Builder builder) { objectBuilder - .withRecord(namedBuilder.name, ((Record.Builder) namedBuilder.builder).build()); + .withRecord(namedBuilder.name, builder.build()); arrayBuilder = null; } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); @@ -384,7 +380,7 @@ public JsonGenerator writeEnd() { private List prepareArray(final List array) { return ((Collection) array) .stream() - .map(it -> it instanceof Record.Builder ? ((Record.Builder) it).build() : it) + .map(it -> it instanceof Record.Builder builder ? builder.build() : it) .collect(toList()); } @@ -514,8 +510,8 @@ public static class Factory implements JsonGeneratorFactory { @Override public JsonGenerator createGenerator(final Writer writer) { - if (writer instanceof OutputRecordHolder) { - return new RecordJsonGenerator(factory.get(), jsonb.get(), (OutputRecordHolder) writer); + if (writer instanceof OutputRecordHolder outputRecordHolder) { + return new RecordJsonGenerator(factory.get(), jsonb.get(), outputRecordHolder); } throw new IllegalArgumentException("Unsupported writer: " + writer); } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Parameters.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Parameters.java index 8e069975fc762..a5d26d2905918 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Parameters.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Parameters.java @@ -32,10 +32,9 @@ public class Parameters { public static boolean isGroupBuffer(final Type type) { - if (!(type instanceof ParameterizedType)) { + if (!(type instanceof ParameterizedType parameterizedType)) { return false; } - final ParameterizedType parameterizedType = (ParameterizedType) type; if (!(parameterizedType.getRawType() instanceof Class) || parameterizedType.getActualTypeArguments().length != 1) { return false; diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java index 82124ad6ff4cf..a94543a8b7156 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java @@ -129,18 +129,17 @@ private void validatePartitionMapper(final Class type) { throw new IllegalArgumentException(m + " must not have any parameter without @PartitionSize"); } final Type splitReturnType = m.getGenericReturnType(); - if (!(splitReturnType instanceof ParameterizedType)) { + if (!(splitReturnType instanceof ParameterizedType splitPt)) { throw new IllegalArgumentException(m + " must return a Collection<" + type.getName() + ">"); } - final ParameterizedType splitPt = (ParameterizedType) splitReturnType; if (!(splitPt.getRawType() instanceof Class) || !Collection.class.isAssignableFrom((Class) splitPt.getRawType())) { throw new IllegalArgumentException(m + " must return a List of partition mapper, found: " + splitPt); } final Type arg = splitPt.getActualTypeArguments().length != 1 ? null : splitPt.getActualTypeArguments()[0]; - if (!(arg instanceof Class) || !type.isAssignableFrom((Class) arg)) { + if (!(arg instanceof Class aClass) || !type.isAssignableFrom(aClass)) { throw new IllegalArgumentException( m + " must return a Collection<" + type.getName() + "> but found: " + arg); } @@ -254,10 +253,9 @@ private void validateProducer(final Class input, final List afterGrou } private boolean validOutputParam(final Parameter p) { - if (!(p.getParameterizedType() instanceof ParameterizedType)) { + if (!(p.getParameterizedType() instanceof ParameterizedType pt)) { return false; } - final ParameterizedType pt = (ParameterizedType) p.getParameterizedType(); return OutputEmitter.class == pt.getRawType(); } @@ -314,16 +312,14 @@ private void validateAfterVariableContainer(final Class type) { * Where the key is String and value is Object */ private static boolean isValidAfterVariableContainer(final Type type) { - if (!(type instanceof ParameterizedType)) { + if (!(type instanceof ParameterizedType paramType)) { return false; } - final ParameterizedType paramType = (ParameterizedType) type; - if (!(paramType.getRawType() instanceof Class) || paramType.getActualTypeArguments().length != 2) { + if (!(paramType.getRawType() instanceof Class containerType) || paramType.getActualTypeArguments().length != 2) { return false; } - final Class containerType = (Class) paramType.getRawType(); return Map.class.isAssignableFrom(containerType) && paramType.getActualTypeArguments()[0].equals(String.class) && paramType.getActualTypeArguments()[1].equals(Object.class); } diff --git a/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/MappingUtilsTest.java b/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/MappingUtilsTest.java index dbd66bd6d8f23..9af1027682cf3 100644 --- a/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/MappingUtilsTest.java +++ b/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/MappingUtilsTest.java @@ -115,8 +115,8 @@ void coerce() { @MethodSource("mapStringProvider") void mapString(final Class expectedType, final String inputValue, final Object expectedResult) { Object mapped = MappingUtils.coerce(expectedType, inputValue, "::testing::mapString"); - if (expectedResult instanceof byte[]) { - Assertions.assertArrayEquals((byte[]) expectedResult, (byte[]) mapped); + if (expectedResult instanceof byte[] bytes) { + Assertions.assertArrayEquals(bytes, (byte[]) mapped); } else { Assertions.assertEquals(expectedResult, mapped); } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java index c68698476beae..f605d761ddb81 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java @@ -807,14 +807,12 @@ public ParameterMeta findDatastoreParameterMeta(final String plugin, final Strin */ public static Map jsonToMap(final JsonValue jsonValue, final String path) { final Map result = new HashMap<>(); - if (jsonValue instanceof JsonObject) { - JsonObject jsonObj = (JsonObject) jsonValue; + if (jsonValue instanceof JsonObject jsonObj) { for (String key : jsonObj.keySet()) { String newPath = path.isEmpty() ? key : path + "." + key; result.putAll(jsonToMap(jsonObj.get(key), newPath)); } - } else if (jsonValue instanceof JsonArray) { - JsonArray jsonArray = (JsonArray) jsonValue; + } else if (jsonValue instanceof JsonArray jsonArray) { for (int i = 0; i < jsonArray.size(); i++) { String newPath = path + "[" + i + "]"; result.putAll(jsonToMap(jsonArray.get(i), newPath)); @@ -875,7 +873,7 @@ public Optional createComponent(final String plugin, final String name, final int version, final Map configuration) { return findComponentInternal(plugin, name, componentType, version, configuration) // unwrap to access the actual instance which is the desired one - .map(i -> i instanceof Delegated ? ((Delegated) i).getDelegate() : i); + .map(i -> i instanceof Delegated delegated ? delegated.getDelegate() : i); } private Optional findComponentInternal(final String plugin, final String name, @@ -1416,9 +1414,9 @@ protected boolean isTracked(final String annotationType) { } } : optimizedFinder; } finally { - if (archive instanceof AutoCloseable) { + if (archive instanceof AutoCloseable autoCloseable) { try { - ((AutoCloseable) archive).close(); + autoCloseable.close(); } catch (final Exception e) { log.warn(e.getMessage()); } @@ -1796,16 +1794,16 @@ private Archive toArchive(final String module, final OriginalId originalId, } private URL archiveToUrl(final Archive mainArchive) { - if (mainArchive instanceof JarArchive) { - return ((JarArchive) mainArchive).getUrl(); - } else if (mainArchive instanceof FileArchive) { + if (mainArchive instanceof JarArchive jarArchive) { + return jarArchive.getUrl(); + } else if (mainArchive instanceof FileArchive fileArchive) { try { - return ((FileArchive) mainArchive).getDir().toURI().toURL(); + return fileArchive.getDir().toURI().toURL(); } catch (final MalformedURLException e) { throw new IllegalStateException(e); } - } else if (mainArchive instanceof NestedJarArchive) { - return ((NestedJarArchive) mainArchive).getRootMarker(); + } else if (mainArchive instanceof NestedJarArchive entries) { + return entries.getRootMarker(); } return null; } @@ -2214,8 +2212,8 @@ private ComponentFamilyMeta getOrCreateComponent(final String component) { return this.component == null || !component.equals(this.component.getName()) ? (this.component = new ComponentFamilyMeta(plugin, asList(components.categories()), iconFinder.findIcon(familyAnnotationElement), comp, - familyAnnotationElement instanceof Class - ? getPackage((Class) familyAnnotationElement) + familyAnnotationElement instanceof Class aClass + ? getPackage(aClass) : "")) : this.component; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java index 67a825281c2fa..557f4abebcd9d 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/asm/Unsafes.java @@ -182,9 +182,8 @@ public final class Unsafes { */ public static Class defineAndLoadClass(final ClassLoader classLoader, final String proxyName, final byte[] proxyBytes) { - if (classLoader instanceof ConfigurableClassLoader) { - return (Class) ((ConfigurableClassLoader) classLoader) - .registerBytecode(proxyName.replace('/', '.'), proxyBytes); + if (classLoader instanceof ConfigurableClassLoader configurableClassLoader) { + return (Class) configurableClassLoader.registerBytecode(proxyName.replace('/', '.'), proxyBytes); } Class clazz = classLoader.getClass(); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java index a14aeb5e5c54a..ca92a6e29cb9b 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/chain/internal/JobImpl.java @@ -258,12 +258,12 @@ public ExecutorBuilder property(final String name, final Object value) { public void run() { ExecutorBuilder runner = this; final Object o = jobProperties.get(ExecutorBuilder.class.getName()); - if (o instanceof ExecutorBuilder) { - runner = (ExecutorBuilder) o; - } else if (o instanceof Class) { - runner = newRunner((Class) o); - } else if (o instanceof String) { - final String name = ((String) o).trim(); + if (o instanceof ExecutorBuilder executorBuilder) { + runner = executorBuilder; + } else if (o instanceof Class aClass) { + runner = newRunner(aClass); + } else if (o instanceof String string) { + final String name = string.trim(); if (!"standalone".equalsIgnoreCase(name) && !"default".equalsIgnoreCase(name) && !"local".equalsIgnoreCase(name)) { if ("beam".equalsIgnoreCase(name)) { @@ -356,8 +356,8 @@ private void localRun() { .orElseThrow(() -> new IllegalStateException( "No processor found for:" + component.getNode())); final AtomicInteger maxBatchSize = new AtomicInteger(1); - if (processor instanceof ProcessorImpl) { - ((ProcessorImpl) processor) + if (processor instanceof ProcessorImpl processor1) { + processor1 .getInternalConfiguration() .entrySet() .stream() @@ -539,14 +539,14 @@ private List getConnections(final List edges, final Job.Comp public GroupKeyProvider getKeyProvider(final String componentId) { if (componentProperties.get(componentId) != null) { final Object o = componentProperties.get(componentId).get(GroupKeyProvider.class.getName()); - if (o instanceof GroupKeyProvider) { - return new GroupKeyProviderImpl((GroupKeyProvider) o); + if (o instanceof GroupKeyProvider groupKeyProvider) { + return new GroupKeyProviderImpl(groupKeyProvider); } } final Object o = jobProperties.get(GroupKeyProvider.class.getName()); - if (o instanceof GroupKeyProvider) { - return new GroupKeyProviderImpl((GroupKeyProvider) o); + if (o instanceof GroupKeyProvider groupKeyProvider) { + return new GroupKeyProviderImpl(groupKeyProvider); } final ServiceLoader services = ServiceLoader.load(GroupKeyProvider.class); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java index 29e075f327176..b42c8085e41bb 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/configuration/ConfigurationMapper.java @@ -57,7 +57,7 @@ private Map map(final List nestedParameters, fina case OBJECT: return map(param.getNestedParameters(), value, indexes); case ARRAY: - final Collection values = value instanceof Collection ? (Collection) value + final Collection values = value instanceof Collection collection ? collection : /* array */asList((Object[]) value); final int arrayIndex = indexes.keySet().size(); final AtomicInteger valuesIndex = new AtomicInteger(0); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java index 3347344ad8679..3e1703a5a4f53 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/interceptor/InterceptorHandlerFacade.java @@ -135,8 +135,8 @@ private Object doInvoke(final Method method, final Object[] args) { return method.invoke(delegate, args); } catch (final InvocationTargetException ite) { final Throwable cause = ite.getCause(); - if (cause instanceof RuntimeException) { - throw (RuntimeException) cause; + if (cause instanceof RuntimeException runtimeException) { + throw runtimeException; } throw new IllegalStateException(cause.getMessage()); } catch (final IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java index 38619cf3f577b..96caf7eee76e2 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java @@ -91,12 +91,12 @@ public ParameterModelService(final PropertyEditorRegistry registry) { public boolean isService(final Param parameter) { final Class type; - if (parameter.type instanceof Class) { - type = (Class) parameter.type; - } else if (parameter.type instanceof ParameterizedType) { - final Type rawType = ((ParameterizedType) parameter.type).getRawType(); - if (rawType instanceof Class) { - type = (Class) rawType; + if (parameter.type instanceof Class aClass1) { + type = aClass1; + } else if (parameter.type instanceof ParameterizedType parameterizedType) { + final Type rawType = parameterizedType.getRawType(); + if (rawType instanceof Class aClass) { + type = aClass; } else { return false; } @@ -136,11 +136,10 @@ public Class declaringClass() { } private Stream extractTypeAnnotation(final Param parameter) { - if (parameter.type instanceof Class) { - return Stream.of(((Class) parameter.type).getAnnotations()); + if (parameter.type instanceof Class aClass) { + return Stream.of(aClass.getAnnotations()); } - if (parameter.type instanceof ParameterizedType) { - final ParameterizedType parameterizedType = (ParameterizedType) parameter.type; + if (parameter.type instanceof ParameterizedType parameterizedType) { if (parameterizedType.getRawType() instanceof Class) { return Stream.of(((Class) parameterizedType.getRawType()).getAnnotations()); } @@ -180,13 +179,13 @@ protected ParameterMeta buildParameter(final String name, final String prefix, f nested.addAll(meta); break; case ARRAY: - final Type nestedType = genericType instanceof Class && ((Class) genericType).isArray() - ? ((Class) genericType).getComponentType() + final Type nestedType = genericType instanceof Class aClass1 && aClass1.isArray() + ? aClass1.getComponentType() : ((ParameterizedType) genericType).getActualTypeArguments()[0]; addI18nPackageIfPossible(i18nPackages, nestedType); nested .addAll(buildParametersMetas(name + "[${index}]", normalizedPrefix + "[${index}].", nestedType, - nestedType instanceof Class ? ((Class) nestedType).getAnnotations() + nestedType instanceof Class aClass ? aClass.getAnnotations() : NO_ANNOTATIONS, i18nPackages, ignoreI18n, context)); break; @@ -208,8 +207,8 @@ protected ParameterMeta buildParameter(final String name, final String prefix, f } private void addI18nPackageIfPossible(final Collection i18nPackages, final Type type) { - if (type instanceof Class) { - final Package typePck = ((Class) type).getPackage(); + if (type instanceof Class aClass) { + final Package typePck = aClass.getPackage(); if (typePck != null && !typePck.getName().isEmpty() && !i18nPackages.contains(typePck.getName())) { i18nPackages.add(typePck.getName()); } @@ -219,8 +218,7 @@ private void addI18nPackageIfPossible(final Collection i18nPackages, fin private Map buildExtensions(final String name, final Type genericType, final Annotation[] annotations, final BaseParameterEnricher.Context context) { return getAnnotations(genericType, annotations).distinct().flatMap(a -> enrichers.stream().map(e -> { - if (e instanceof BaseParameterEnricher) { - final BaseParameterEnricher bpe = (BaseParameterEnricher) e; + if (e instanceof BaseParameterEnricher bpe) { return bpe.withContext(context, () -> bpe.onParameterAnnotation(name, genericType, a)); } return e.onParameterAnnotation(name, genericType, a); @@ -261,9 +259,9 @@ private Stream getReflectionAnnotations(final Type genericType, fina } private boolean hasAClassFirstParameter(final Type genericType) { - return genericType instanceof ParameterizedType // if a list concat the item type annotations - && ((ParameterizedType) genericType).getActualTypeArguments().length == 1 - && ((ParameterizedType) genericType).getActualTypeArguments()[0] instanceof Class; + return genericType instanceof ParameterizedType parameterizedType // if a list concat the item type annotations + && parameterizedType.getActualTypeArguments().length == 1 + && parameterizedType.getActualTypeArguments()[0] instanceof Class; } private Stream getClassAnnotations(final Type genericType, final Annotation[] annotations) { @@ -275,8 +273,7 @@ private Stream getClassAnnotations(final Type genericType, final Ann private List buildParametersMetas(final String name, final String prefix, final Type type, final Annotation[] annotations, final Collection i18nPackages, final boolean ignoreI18n, final BaseParameterEnricher.Context context) { - if (type instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) type; + if (type instanceof ParameterizedType pt) { if (!(pt.getRawType() instanceof Class)) { throw new IllegalArgumentException("Unsupported raw type in ParameterizedType parameter: " + pt); } @@ -305,7 +302,7 @@ private List buildParametersMetas(final String name, final String .collect(toList()); } } - if (type instanceof Class) { + if (type instanceof Class aClass) { switch (findType(type)) { case ENUM: case STRING: @@ -320,12 +317,12 @@ public String name() { @Override public Class declaringClass() { - return (Class) type; + return aClass; } }, type, annotations, i18nPackages, ignoreI18n, context)); default: } - return buildObjectParameters(prefix, (Class) type, i18nPackages, ignoreI18n, context); + return buildObjectParameters(prefix, aClass, i18nPackages, ignoreI18n, context); } throw new IllegalArgumentException("Unsupported parameter type: " + type); } @@ -395,8 +392,7 @@ private ParameterMeta.Type findType(final Type type) { return ParameterMeta.Type.ARRAY; } } - if (type instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) type; + if (type instanceof ParameterizedType pt) { if (pt.getRawType() instanceof Class) { final Class raw = (Class) pt.getRawType(); if (Collection.class.isAssignableFrom(raw)) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java index 14e221e164dcc..f7774ec56d922 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java @@ -111,10 +111,9 @@ public Function, Object[]> parameterFactory(final Executable Stream.of(executable.getParameters()).map(parameter -> { final String name = parameterModelService.findName(parameter, parameter.getName()); final Type parameterizedType = parameter.getParameterizedType(); - if (parameterizedType instanceof Class) { + if (parameterizedType instanceof Class configClass) { if (parameter.isAnnotationPresent(Configuration.class)) { try { - final Class configClass = (Class) parameterizedType; return createConfigFactory(precomputed, loader, contextualSupplier, parameter.getName(), parameter.getAnnotation(Configuration.class), parameter.getAnnotations(), configClass); @@ -124,8 +123,7 @@ public Function, Object[]> parameterFactory(final Executable } final Object value = precomputed.get(parameterizedType); if (value != null) { - if (value instanceof Copiable) { - final Copiable copiable = (Copiable) value; + if (value instanceof Copiable copiable) { return (Function, Object>) config -> copiable.copy(value); } return (Function, Object>) config -> value; @@ -136,8 +134,7 @@ public Function, Object[]> parameterFactory(final Executable .apply(name, (Map) config); } - if (parameterizedType instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) parameterizedType; + if (parameterizedType instanceof ParameterizedType pt) { if (pt.getRawType() instanceof Class) { if (Collection.class.isAssignableFrom((Class) pt.getRawType())) { final Class collectionType = (Class) pt.getRawType(); @@ -429,14 +426,14 @@ private Object createObject(final ClassLoader loader, final Function 0) { final String listName = nestedName.substring(0, idxStart); final Field field = findField(normalizeName(listName, metas), clazz); - if (field.getGenericType() instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) field.getGenericType(); + if (field.getGenericType() instanceof ParameterizedType pt) { if (pt.getRawType() instanceof Class) { final Class rawType = (Class) pt.getRawType(); if (Set.class.isAssignableFrom(rawType)) { @@ -664,11 +660,10 @@ private Object createObject(final ClassLoader loader, final Function onParameterAnnotation(final String parameterName, fin final Condition condition = annotation.annotationType().getAnnotation(Condition.class); if (condition != null) { final String type = condition.value(); - if (annotation instanceof ActiveIfs) { - final ActiveIfs activeIfs = (ActiveIfs) annotation; + if (annotation instanceof ActiveIfs activeIfs) { final Map metas = Stream .of(activeIfs.value()) .map(ai -> onParameterAnnotation(parameterName, parameterType, ai)) @@ -73,8 +72,8 @@ private Map toMeta(final Annotation annotation, final String typ .collect(toMap(m -> META_PREFIX + type + "::" + m.getName(), m -> { try { final Object invoke = m.invoke(annotation); - if (invoke instanceof String[]) { - return Stream.of((String[]) invoke).collect(joining(",")); + if (invoke instanceof String[] strings) { + return Stream.of(strings).collect(joining(",")); } if (ActiveIf.class == m.getDeclaringClass() && "evaluationStrategy".equals(m.getName())) { final ActiveIf.EvaluationStrategyOption[] options = diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java index b2c657929dbcb..509741e340477 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/DependencyParameterEnricher.java @@ -57,14 +57,13 @@ public Map onParameterAnnotation(final String parameterName, // don't work with Map (composed collection), nor List (not used in framework) private boolean isCollectionConnectorReference(final Type parameterType) { // check generic - if (!(parameterType instanceof ParameterizedType)) { + if (!(parameterType instanceof ParameterizedType parameterClass)) { return false; } - final ParameterizedType parameterClass = (ParameterizedType) parameterType; // Check it's a Collection (java.util) final Type rawType = parameterClass.getRawType(); - if ((!(rawType instanceof Class)) || !Collection.class.isAssignableFrom((Class) rawType)) { + if ((!(rawType instanceof Class aClass)) || !Collection.class.isAssignableFrom(aClass)) { return false; } @@ -79,8 +78,8 @@ private boolean isCollectionConnectorReference(final Type parameterType) { // Check if parameter is of type or subtype of ConnectorReference private boolean isConnectorReference(final Type parameterType) { - return parameterType instanceof Class - && Stream.of(((Class) parameterType).getDeclaredFields()) + return parameterType instanceof Class aClass + && Stream.of(aClass.getDeclaredFields()) .anyMatch(field -> field.isAnnotationPresent(ConnectorRef.class)); } } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java index b128da1a8f6df..59d6138982849 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/UiParameterEnricher.java @@ -177,11 +177,11 @@ private String toString(final Annotation annotation, final Method m, } return string; } - if (invoke instanceof Class) { - return ((Class) invoke).getSimpleName().toLowerCase(ENGLISH); + if (invoke instanceof Class aClass) { + return aClass.getSimpleName().toLowerCase(ENGLISH); } - if (invoke instanceof String[]) { - return Stream.of((String[]) invoke).collect(joining(",")); + if (invoke instanceof String[] strings) { + return Stream.of(strings).collect(joining(",")); } return String.valueOf(invoke); } catch (final InvocationTargetException | IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java index 988609adc19c5..06c08ec042e67 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/parameterenricher/ValidationParameterEnricher.java @@ -49,9 +49,9 @@ public Map onParameterAnnotation(final String parameterName, fin } private Class toClass(final Type parameterType) { - return parameterType instanceof ParameterizedType - ? toClass(((ParameterizedType) parameterType).getRawType()) - : (parameterType instanceof Class ? (Class) parameterType : null); + return parameterType instanceof ParameterizedType parameterizedType + ? toClass(parameterizedType.getRawType()) + : (parameterType instanceof Class aClass ? aClass : null); } private String getValueString(final Annotation annotation) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java index 22de0e34c3979..91485be4a12c5 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java @@ -148,14 +148,14 @@ private boolean evaluate(final String expected, final JsonObject payload) { return "0".equals(expected); } final int expectedSize = Integer.parseInt(expected); - if (actual instanceof Collection) { - return expectedSize == ((Collection) actual).size(); + if (actual instanceof Collection collection1) { + return expectedSize == collection1.size(); } if (actual.getClass().isArray()) { return expectedSize == Array.getLength(actual); } - if (actual instanceof String) { - return expectedSize == ((String) actual).length(); + if (actual instanceof String s) { + return expectedSize == s.length(); } return false; default: diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java index 35573ae45a40f..15d6c5d0a346a 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java @@ -86,8 +86,7 @@ private void doInject(final Class type, final T instance) { }) .forEach(field -> { Object value = services.get(field.getType()); - if (value == null && field.getGenericType() instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) field.getGenericType(); + if (value == null && field.getGenericType() instanceof ParameterizedType pt) { if (pt.getRawType() instanceof Class && Collection.class.isAssignableFrom((Class) pt.getRawType())) { final Type serviceType = pt.getActualTypeArguments()[0]; diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java index 4e5bad59f9640..62978c351c6d1 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java @@ -105,8 +105,7 @@ public T getEntry(final Record target, final Class type) { private Object getValue(final Object value, final String referenceToken, final int currentPosition, final int referencePosition) { - if (value instanceof Record) { - final Record record = (Record) value; + if (value instanceof Record record) { final Object nestedVal = getRecordEntry(referenceToken, record); if (nestedVal != null) { return nestedVal; @@ -130,7 +129,7 @@ private Object getValue(final Object value, final String referenceToken, final i throw new IllegalArgumentException( "'" + array + "' contains no element for index " + arrayIndex); } - return array instanceof List ? ((List) array).get(arrayIndex) + return array instanceof List list ? list.get(arrayIndex) : new ArrayList<>(array).get(arrayIndex); } catch (final NumberFormatException e) { throw new IllegalArgumentException("'" + referenceToken + "' is no valid array index", e); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java index 2518b8d8353b2..a6675e90d7692 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ResolverImpl.java @@ -97,8 +97,8 @@ public ClassLoaderDescriptor mapDescriptorToClassLoader(final InputStream descri ofNullable(configuration.getParentClassesFilter()).orElse(it -> false), ofNullable(configuration.getClassesFilter()).orElse(it -> true), nested.toArray(new String[0]), - parent instanceof ConfigurableClassLoader - ? ((ConfigurableClassLoader) parent).getJvmMarkers() + parent instanceof ConfigurableClassLoader configurableClassLoader + ? configurableClassLoader.getJvmMarkers() : new String[] { "" }, ofNullable(configuration.getParentResourcesFilter()).orElse(it -> true)); return new ClassLoaderDescriptorImpl(volatileLoader, resolved); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java index df71b68221c60..0afa6685d1bca 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/ServiceHelper.java @@ -57,8 +57,8 @@ public Object createServiceInstance(final ClassLoader loader, final String conta .initialize(instance, new InterceptorHandlerFacade(serviceClass.getConstructor().newInstance(), allServices)); } - if (instance instanceof BaseService) { - this.updateService((BaseService) instance, containerId, serviceClass.getName()); + if (instance instanceof BaseService baseService) { + this.updateService(baseService, containerId, serviceClass.getName()); } return instance; } catch (final InstantiationException | IllegalAccessException e) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java index 3690f3b3ad8e2..7695b521d4e08 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java @@ -233,8 +233,8 @@ private BiFunction> buildPayloadProvider(fina if (payload == null) { return Optional.empty(); } - if (payload instanceof byte[]) { - return Optional.of((byte[]) payload); + if (payload instanceof byte[] bytes) { + return Optional.of(bytes); } if (encoders.size() == 1) { return Optional.of(encoders.values().iterator().next().encode(payload)); @@ -257,10 +257,9 @@ private Configurer findConfigurerInstance(final Method m) { static Class toClassType(final Type type) { Class cType = null; - if (type instanceof Class) { - cType = (Class) type; - } else if (type instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) type; + if (type instanceof Class aClass) { + cType = aClass; + } else if (type instanceof ParameterizedType pt) { if (pt.getRawType() == Response.class && pt.getActualTypeArguments().length == 1 && pt.getActualTypeArguments()[0] instanceof Class) { cType = (Class) pt.getActualTypeArguments()[0]; @@ -412,8 +411,8 @@ public Collection apply(final Object[] args) { private Stream> mapValues(final QueryEncodable config, final String key, final Object v) { - if (v instanceof Collection) { - final Stream collection = ((Collection) v) + if (v instanceof Collection objects) { + final Stream collection = objects .stream() .filter(Objects::nonNull) .map(String::valueOf) diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java index c91c70e78d2f5..9a33805f56de4 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/util/DefaultValueInspector.java @@ -51,14 +51,13 @@ public Instance createDemoInstance(final Object rootInstance, final ParameterMet final Type javaType = param.getJavaType(); if (javaType instanceof Class) { return new Instance(tryCreatingObjectInstance(javaType), true); - } else if (javaType instanceof ParameterizedType) { - final ParameterizedType pt = (ParameterizedType) javaType; + } else if (javaType instanceof ParameterizedType pt) { final Type rawType = pt.getRawType(); - if (rawType instanceof Class && Collection.class.isAssignableFrom((Class) rawType) + if (rawType instanceof Class aClass && Collection.class.isAssignableFrom(aClass) && pt.getActualTypeArguments().length == 1 && pt.getActualTypeArguments()[0] instanceof Class) { final Object instance = tryCreatingObjectInstance(pt.getActualTypeArguments()[0]); - final Class collectionType = (Class) rawType; + final Class collectionType = aClass; if (Set.class == collectionType) { return new Instance(singleton(instance), true); } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java index bcbf8c81ec0b0..ed841dc664e09 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/FilterFactory.java @@ -34,8 +34,8 @@ public class FilterFactory { public static Filter and(final Filter first, final Filter second) { if (Stream .of(first, second) - .anyMatch(f -> !(f instanceof FilterList) - || !((FilterList) f).getFilters().stream().allMatch(PrefixFilter.class::isInstance))) { + .anyMatch(f -> !(f instanceof FilterList filterList) + || !filterList.getFilters().stream().allMatch(PrefixFilter.class::isInstance))) { throw new IllegalArgumentException("And only works with filter list of prefix filters"); // for optims } final FilterList list1 = (FilterList) first; diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java index 8f51b1dc4fd2a..417f68521065c 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/xbean/converter/SchemaConverter.java @@ -98,8 +98,8 @@ private Schema toSchema(final JsonObject json) { this.addProps(builder::withProp, json); final JsonValue orderValue = json.get("order"); - if (orderValue instanceof JsonString) { - final Schema.EntriesOrder order = Schema.EntriesOrder.of(((JsonString) orderValue).getString()); + if (orderValue instanceof JsonString jsonString) { + final Schema.EntriesOrder order = Schema.EntriesOrder.of(jsonString.getString()); return builder.build(order); } else { return builder.build(); @@ -109,11 +109,11 @@ private Schema toSchema(final JsonObject json) { private void treatElementSchema(final JsonObject json, final Consumer setter) { final JsonValue elementSchema = json.get(ELEMENT_SCHEMA); - if (elementSchema instanceof JsonObject) { - final Schema schema = this.toSchema((JsonObject) elementSchema); + if (elementSchema instanceof JsonObject jsonObject) { + final Schema schema = this.toSchema(jsonObject); setter.accept(schema); - } else if (elementSchema instanceof JsonString) { - final Schema.Type innerType = Schema.Type.valueOf(((JsonString) elementSchema).getString()); + } else if (elementSchema instanceof JsonString jsonString) { + final Schema.Type innerType = Schema.Type.valueOf(jsonString.getString()); setter.accept(this.factory.newSchemaBuilder(innerType).build()); } } @@ -276,17 +276,17 @@ private JsonValue toValue(final Object object) { if (object == null) { return JsonValue.NULL; } - if (object instanceof Integer) { - return Json.createValue((Integer) object); + if (object instanceof Integer i) { + return Json.createValue(i); } - if (object instanceof Long) { - return Json.createValue((Long) object); + if (object instanceof Long l) { + return Json.createValue(l); } if (object instanceof Double || object instanceof Float) { return Json.createValue((Double) object); } - if (object instanceof BigInteger) { - return Json.createValue((BigInteger) object); + if (object instanceof BigInteger bigInteger) { + return Json.createValue(bigInteger); } if (object instanceof Boolean) { if (object == Boolean.TRUE) { @@ -294,11 +294,11 @@ private JsonValue toValue(final Object object) { } return JsonValue.FALSE; } - if (object instanceof BigDecimal) { - return Json.createValue((BigDecimal) object); + if (object instanceof BigDecimal bigDecimal) { + return Json.createValue(bigDecimal); } - if (object instanceof String) { - return Json.createValue((String) object); + if (object instanceof String s) { + return Json.createValue(s); } return null; diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java index 79034d8e80770..8d47398eb5168 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/ProducerFinderImplTest.java @@ -77,8 +77,8 @@ void findException() { } private Record toRecord(final Object object) { - if (object instanceof Record) { - return (Record) object; + if (object instanceof Record record) { + return record; } return null; } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java index 955394bb6d60c..213b75e7a8fe2 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/DefaultResponseLocator.java @@ -254,8 +254,7 @@ public int hashCode() { public boolean equals(final Object obj) { if (this == obj) { return true; - } else if (obj instanceof ParameterizedType) { - final ParameterizedType that = (ParameterizedType) obj; + } else if (obj instanceof ParameterizedType that) { final Type thatRawType = that.getRawType(); return that.getOwnerType() == null && (rawType == null ? thatRawType == null : rawType.equals(thatRawType)) diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/HandlerImpl.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/HandlerImpl.java index 6bb9f4e155ab6..95671c8e62e4e 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/HandlerImpl.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/HandlerImpl.java @@ -182,8 +182,7 @@ public synchronized void close() { } }); if (!(handler.getExecutor() instanceof AutoCloseable) - && handler.getExecutor() instanceof ExecutorService) { - final ExecutorService executorService = (ExecutorService) handler.getExecutor(); + && handler.getExecutor() instanceof ExecutorService executorService) { executorService.shutdownNow(); // we don't need to wait here } } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java index cbc7f5656dc21..ddc316335c4fa 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/impl/PassthroughHandler.java @@ -108,8 +108,7 @@ private void doHttpRequest(final FullHttpRequest request, final ChannelHandlerCo final HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); connection.setConnectTimeout(30000); connection.setReadTimeout(20000); - if (connection instanceof HttpsURLConnection && api.getSslContext() != null) { - final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection; + if (connection instanceof HttpsURLConnection httpsURLConnection && api.getSslContext() != null) { httpsURLConnection.setHostnameVerifier((h, s) -> true); httpsURLConnection.setSSLSocketFactory(api.getSslContext().getSocketFactory()); } diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/junit5/JUnit5HttpApi.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/junit5/JUnit5HttpApi.java index c263e2e6473f0..526afef80b709 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/junit5/JUnit5HttpApi.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/internal/junit5/JUnit5HttpApi.java @@ -85,7 +85,7 @@ public Class injectionMarker() { public void beforeEach(final ExtensionContext extensionContext) { // test name final ResponseLocator responseLocator = getResponseLocator(); - if (!(responseLocator instanceof DefaultResponseLocator)) { + if (!(responseLocator instanceof DefaultResponseLocator defaultResponseLocator)) { return; } final String test = extensionContext.getTestMethod().map(m -> { @@ -99,7 +99,7 @@ public void beforeEach(final ExtensionContext extensionContext) { .orElseGet(() -> m.getDeclaringClass().getName() + "_" + m.getName() + (displayName.equals(m.getName()) ? "" : ("_" + displayName))); }).orElse(null); - ((DefaultResponseLocator) responseLocator).setTest(test); + defaultResponseLocator.setTest(test); } @Override diff --git a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java index 89ca1f43af794..d7d751a522303 100644 --- a/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java +++ b/component-runtime-testing/component-runtime-http-junit/src/main/java/org/talend/sdk/component/junit/http/junit4/JUnit4HttpApiPerMethodConfigurator.java @@ -36,18 +36,14 @@ public Statement apply(final Statement base, final Description description) { @Override public void evaluate() throws Throwable { final ResponseLocator responseLocator = server.getResponseLocator(); - if (responseLocator instanceof DefaultResponseLocator) { - final DefaultResponseLocator defaultResponseLocator = - (DefaultResponseLocator) responseLocator; + if (responseLocator instanceof DefaultResponseLocator defaultResponseLocator) { defaultResponseLocator.setTest(description.getClassName() + "_" + description.getMethodName()); } try { base.evaluate(); } finally { - if (responseLocator instanceof DefaultResponseLocator) { + if (responseLocator instanceof DefaultResponseLocator defaultResponseLocator) { if (Handlers.isActive("capture")) { - final DefaultResponseLocator defaultResponseLocator = - (DefaultResponseLocator) responseLocator; defaultResponseLocator.flush(Handlers.getBaseCapture()); } } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java index 0323dcbdca40c..9fa6246256c7f 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/DecoratingEnvironmentProvider.java @@ -32,8 +32,8 @@ public AutoCloseable start(final Class clazz, final Annotation[] annotations) } public String getName() { - return (provider instanceof BaseEnvironmentProvider - ? ((BaseEnvironmentProvider) provider).getName() + return (provider instanceof BaseEnvironmentProvider baseEnvironmentProvider + ? baseEnvironmentProvider.getName() : provider.getClass().getSimpleName()).replace("Environment", ""); } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java index a3ed168137f1b..fc5d3dc54ace1 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/environment/MultiEnvironmentsRunner.java @@ -32,8 +32,7 @@ public MultiEnvironmentsRunner(final Class testClass) throws InitializationEr @Override public void run(final RunNotifier notifier) { configuration.stream().forEach(e -> { - if (e instanceof DecoratingEnvironmentProvider) { - final DecoratingEnvironmentProvider dep = (DecoratingEnvironmentProvider) e; + if (e instanceof DecoratingEnvironmentProvider dep) { if (!dep.isActive()) { notifier.fireTestFinished(Description.createTestDescription(getTestClass(), dep.getName())); return; diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java index 717808045992b..1401af809e539 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/lang/StreamDecorator.java @@ -54,17 +54,17 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg } }); if (stream) { - if (result instanceof Stream) { - return decorate((Stream) result, Stream.class, leafDecorator); + if (result instanceof Stream stream1) { + return decorate(stream1, Stream.class, leafDecorator); } - if (result instanceof IntStream) { - return decorate((IntStream) result, IntStream.class, leafDecorator); + if (result instanceof IntStream intStream) { + return decorate(intStream, IntStream.class, leafDecorator); } - if (result instanceof LongStream) { - return decorate((LongStream) result, LongStream.class, leafDecorator); + if (result instanceof LongStream longStream) { + return decorate(longStream, LongStream.class, leafDecorator); } - if (result instanceof DoubleStream) { - return decorate((DoubleStream) result, DoubleStream.class, leafDecorator); + if (result instanceof DoubleStream doubleStream) { + return decorate(doubleStream, DoubleStream.class, leafDecorator); } } return result; diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java index 488f0856fe0f8..b3b7ec5302a81 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentalContext.java @@ -130,8 +130,8 @@ public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionConte } private boolean isActive() { - return provider instanceof DecoratingEnvironmentProvider - && ((DecoratingEnvironmentProvider) provider).isActive(); + return provider instanceof DecoratingEnvironmentProvider decoratingEnvironmentProvider + && decoratingEnvironmentProvider.isActive(); } @Override diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java index b49d797e7a1d9..a2d1bd35a687e 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java @@ -181,8 +181,7 @@ private CompletableFuture doExecuteLocalAction(final String family, fi } else { cause = e.getCause(); } - if (cause instanceof WebApplicationException) { - final WebApplicationException wae = (WebApplicationException) cause; + if (cause instanceof WebApplicationException wae) { final Response response = wae.getResponse(); String message = ""; if (wae.getResponse().getEntity() instanceof ErrorPayload) { @@ -216,8 +215,7 @@ private Response onError(final Throwable re) { return ((WebApplicationException) re.getCause()).getResponse(); } - if (re instanceof ComponentException) { - final ComponentException ce = (ComponentException) re; + if (re instanceof ComponentException ce) { throw new WebApplicationException(Response .status(ce.getErrorOrigin() == ComponentException.ErrorOrigin.USER ? 400 : ce.getErrorOrigin() == ComponentException.ErrorOrigin.BACKEND ? 456 : 520, diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java index 4625e44cc8302..a89a7ae572da8 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ConfigurationTypeResourceImpl.java @@ -190,8 +190,7 @@ public Map migrate(final String id, final int version, final Map return migrated; } catch (final Exception e) { // contract of migrate() do not impose to throw a ComponentException, so not likely to happen... - if (e instanceof ComponentException) { - final ComponentException ce = (ComponentException) e; + if (e instanceof ComponentException ce) { throw new WebApplicationException(Response .status(ce.getErrorOrigin() == ComponentException.ErrorOrigin.USER ? 400 : ce.getErrorOrigin() == ComponentException.ErrorOrigin.BACKEND ? 456 : 520, diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java index f6cbe9244fe66..e3efdaf8db3a2 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/error/DefaultExceptionHandler.java @@ -52,14 +52,14 @@ private void init() { public Response toResponse(final Throwable exception) { log.error("[DefaultExceptionHandler#toResponse] Throwable: ", exception); final Response response; - if (exception instanceof WebApplicationException) { - response = ((WebApplicationException) exception).getResponse(); + if (exception instanceof WebApplicationException applicationException) { + response = applicationException.getResponse(); } else { final Optional optCause = Optional.ofNullable(exception.getCause()); if (optCause.isPresent()) { final Throwable cause = optCause.get(); - if (cause instanceof WebApplicationException) { - response = ((WebApplicationException) cause).getResponse(); + if (cause instanceof WebApplicationException webApplicationException) { + response = webApplicationException.getResponse(); } else { response = Response .status(Response.Status.INTERNAL_SERVER_ERROR) diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java index 1dea4226e58bc..f306f313dc7b2 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java @@ -106,12 +106,10 @@ public boolean hasOriginalRequestAndResponse() { @Override public void dispatch() { final ServletRequest servletRequest = getRequest(); - if (!(servletRequest instanceof HttpServletRequest)) { + if (!(servletRequest instanceof HttpServletRequest sr)) { throw new IllegalStateException("Not a http request: " + servletRequest); } - final HttpServletRequest sr = (HttpServletRequest) servletRequest; - String path = sr.getRequestURI(); final String cpath = sr.getContextPath(); if (cpath.length() > 1) { @@ -128,11 +126,10 @@ public void dispatch(final String path) { @Override public void dispatch(final ServletContext context, final String path) { final ServletRequest servletRequest = getRequest(); - if (!(servletRequest instanceof HttpServletRequest)) { + if (!(servletRequest instanceof HttpServletRequest request)) { throw new IllegalStateException("Not a http request: " + servletRequest); } - final HttpServletRequest request = (HttpServletRequest) servletRequest; if (request.getAttribute(ASYNC_REQUEST_URI) == null) { request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI()); request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath()); diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java index 3b87aeb82b4c4..b6a1f84e06a0e 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/mdc/MdcRequestBinder.java @@ -51,8 +51,8 @@ public void init(final FilterConfig filterConfig) { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { - if (request instanceof HttpServletRequest) { - ThreadContext.putAll(createContext((HttpServletRequest) request)); + if (request instanceof HttpServletRequest httpServletRequest) { + ThreadContext.putAll(createContext(httpServletRequest)); } chain.doFilter(request, response); } diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/service/SimpleQueryLanguageCompiler.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/service/SimpleQueryLanguageCompiler.java index 853f6c1fbe185..12fe226c707d0 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/service/SimpleQueryLanguageCompiler.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/service/SimpleQueryLanguageCompiler.java @@ -145,10 +145,10 @@ private Predicate toPredicate(final String key, final String operator, fi .orElseThrow(() -> new IllegalArgumentException("Missing evaluator for '" + mapName + "'")); return new ComparePredicate<>(comparator, t -> { final Object map = evaluator.apply(t); - if (!(map instanceof Map)) { + if (!(map instanceof Map map1)) { throw new IllegalArgumentException(map + " is not a map"); } - return ((Map) map).get(mapKey); + return map1.get(mapKey); }, expectedValue); } } diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/service/VirtualDependenciesService.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/service/VirtualDependenciesService.java index 03920e0e33770..fe3f5909bae47 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/service/VirtualDependenciesService.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/service/VirtualDependenciesService.java @@ -398,10 +398,10 @@ public String get(final String key) { @Override public Set keys() { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (!(loader instanceof ConfigurableClassLoader)) { + if (!(loader instanceof ConfigurableClassLoader configurableClassLoader)) { return emptySet(); } - final String id = ((ConfigurableClassLoader) loader).getId(); + final String id = configurableClassLoader.getId(); final Enrichment enrichment = delegate.getEnrichmentFor(id); if (enrichment == null || enrichment.customConfiguration == null) { return emptySet(); diff --git a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java index 1ad01ebbe8585..a0fad2e05cd4a 100644 --- a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java +++ b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/statistic/StatisticService.java @@ -153,7 +153,7 @@ public void capture(@Observes final CreateProject createProject) { final Throwable e = ofNullable(te.getCause()).orElse(te); if (retries - 1 == i) { // no need to retry failed(createProject); - throw e instanceof RuntimeException ? (RuntimeException) e + throw e instanceof RuntimeException runtimeException ? runtimeException : new IllegalStateException(e); } diff --git a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java index eac99256783e3..c6ba36caca111 100644 --- a/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java +++ b/component-starter-server/src/main/java/org/talend/sdk/component/starter/server/service/template/TemplateRenderer.java @@ -47,8 +47,8 @@ public Wrapper find(final String name, final List scopes) { final Wrapper wrapper = super.find(name, scopes); return s -> { final Object call = wrapper.call(s); - if (call instanceof Collection && !(call instanceof DecoratedCollection)) { - return new DecoratedCollection<>((Collection) call); + if (call instanceof Collection collection && !(call instanceof DecoratedCollection)) { + return new DecoratedCollection<>(collection); } return call; }; diff --git a/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java b/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java index f46b2c5e5f893..5c05ab2111008 100644 --- a/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java +++ b/component-starter-server/src/test/java/org/talend/sdk/component/starter/server/front/apidemo/component/service/MockTableService.java @@ -61,8 +61,7 @@ public HealthCheckStatus healthCheck(@Option(NAME) final BasicAuthConfig dt, fin try { client.healthCheck(dt.getAuthorizationHeader()); } catch (Exception e) { - if (e instanceof HttpException) { - final HttpException ex = (HttpException) e; + if (e instanceof HttpException ex) { final JsonObject jError = (JsonObject) ex.getResponse().error(JsonObject.class); String errorMessage = null; if (jError != null && jError.containsKey("error")) { diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java index 6924c128a3eb8..43a34056fbb6a 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/JobStateAware.java @@ -54,11 +54,11 @@ public T get(final IndirectInstances key, final Class instance) { } static void init(final Object instance, final Map globalMap) { - if (instance instanceof JobStateAware) { + if (instance instanceof JobStateAware jobStateAware) { synchronized (globalMap) { final State state = (State) globalMap.computeIfAbsent(JobStateAware.class.getName(), k -> new State()); - ((JobStateAware) instance).setState(state); + jobStateAware.setState(state); } } } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java index 77a5a00ad3163..0768b3c3b1044 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/OutputsHandler.java @@ -46,8 +46,8 @@ public OutputFactory asOutputFactory() { if (ref != null && value != null) { if (value instanceof javax.json.JsonValue) { ref.add(jsonb.fromJson(value.toString(), ref.getType())); - } else if (value instanceof Record) { - ref.add(registry.find(ref.getType()).newInstance((Record) value)); + } else if (value instanceof Record record) { + ref.add(registry.find(ref.getType()).newInstance(record)); } else { ref.add(jsonb.fromJson(jsonb.toJson(value), ref.getType())); } @@ -67,8 +67,8 @@ public OutputFactory asOutputFactoryForGuessSchema() { if (ref != null && value != null) { if (value instanceof javax.json.JsonValue) { ref.add(jsonb.fromJson(value.toString(), ref.getType())); - } else if (value instanceof Record) { - ref.add(((Record) value).getSchema()); + } else if (value instanceof Record record) { + ref.add(record.getSchema()); } else if (value instanceof Schema) { ref.add(value); } else { diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java index aa84004f8300d..3110aa63f2204 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/LoopState.java @@ -75,7 +75,7 @@ public void push(final Object value) { if (value == null) { return; } - queue.add(value instanceof Record ? (Record) value : toRecord(value)); + queue.add(value instanceof Record record ? record : toRecord(value)); semaphore.release(); } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java index 072b1f279398a..5174f46ce25ec 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/beam/components/DIPipeline.java @@ -74,14 +74,14 @@ public OutputT apply(final String name, final PTransfo private PTransform wrapTransformIfNeeded(final PTransform root) { - if (root instanceof Read.Bounded) { - final BoundedSource source = ((Read.Bounded) root).getSource(); + if (root instanceof Read.Bounded bounded) { + final BoundedSource source = bounded.getSource(); final DelegatingBoundedSource boundedSource = new DelegatingBoundedSource(source, null); setState(boundedSource); return Read.from(boundedSource); } - if (root instanceof Read.Unbounded) { - final UnboundedSource source = ((Read.Unbounded) root).getSource(); + if (root instanceof Read.Unbounded unbounded) { + final UnboundedSource source = unbounded.getSource(); if (source instanceof InMemoryQueueIO.UnboundedQueuedInput) { return root; } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java index 39dac69a1b56e..748444aa582fc 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/record/DiRowStructVisitor.java @@ -140,8 +140,8 @@ private void visit(final Object data) { onBoolean(name, raw); break; case StudioTypes.DATE: - if (raw instanceof Timestamp) { - onInstant(name, (Timestamp) raw); + if (raw instanceof Timestamp timestamp) { + onInstant(name, timestamp); break; } onDatetime(name, ((Date) raw).toInstant().atZone(UTC)); @@ -191,10 +191,10 @@ private void handleDynamic(final Object raw) { break; case StudioTypes.BYTE_ARRAY: final byte[] bytes; - if (value instanceof byte[]) { - bytes = (byte[]) value; - } else if (value instanceof ByteBuffer) { - bytes = ((ByteBuffer) value).array(); + if (value instanceof byte[] bytes1) { + bytes = bytes1; + } else if (value instanceof ByteBuffer byteBuffer) { + bytes = byteBuffer.array(); } else { log.warn("[visit] '{}' of type `id_byte[]` and content is contained in `{}`:" + " This should not happen! " @@ -226,7 +226,7 @@ private void handleDynamic(final Object raw) { break; case StudioTypes.DATE: final ZonedDateTime dateTime; - dateTime = ZonedDateTime.ofInstant(value instanceof Long ? ofEpochMilli((Long) value) + dateTime = ZonedDateTime.ofInstant(value instanceof Long l ? ofEpochMilli(l) : ((Date) value).toInstant(), UTC); onDatetime(metaName, dateTime); break; @@ -563,7 +563,7 @@ private Entry toCollectionEntry(final String name, final String originalName, fi } private Schema elementSchema(final Type type, final Object value) { - if (type != ARRAY || !(value instanceof Collection)) { + if (type != ARRAY || !(value instanceof Collection objects)) { return factory.newSchemaBuilder(type).build(); } @@ -572,8 +572,8 @@ private Schema elementSchema(final Type type, final Object value) { // we inherit the logic that we evaluate the type by its first element. (at least it's fast ) // looks like we support only homogeneous structures - if (!((Collection) value).isEmpty()) { - columnValue = ((Collection) value).iterator().next(); + if (!objects.isEmpty()) { + columnValue = objects.iterator().next(); elementType = getTypeFromValue(columnValue); } diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java index fa939a1d9bf79..61b889a7d7320 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java @@ -174,10 +174,10 @@ private void initClass2JavaTypeMap() { private DiscoverSchemaException transformException(final Exception e) { DiscoverSchemaException discoverSchemaException; - if (e instanceof DiscoverSchemaException) { - discoverSchemaException = (DiscoverSchemaException) e; - } else if (e instanceof ComponentException) { - discoverSchemaException = new DiscoverSchemaException((ComponentException) e); + if (e instanceof DiscoverSchemaException schemaException) { + discoverSchemaException = schemaException; + } else if (e instanceof ComponentException componentException) { + discoverSchemaException = new DiscoverSchemaException(componentException); } else { discoverSchemaException = new DiscoverSchemaException(e.getMessage(), e.getStackTrace(), EXCEPTION); } @@ -253,12 +253,12 @@ private void executeDiscoverSchemaExtendedAction(final Schema schema, final Stri } final Object schemaResult = actionRef.getInvoker().apply(buildActionConfig(actionRef, configuration, schema, branch)); - if (schemaResult instanceof Schema) { - final Schema result = (Schema) schemaResult; + if (schemaResult instanceof Schema schema1) { + final Schema result = schema1; if (result.getEntries().isEmpty()) { throw new DiscoverSchemaException(ERROR_NO_AVAILABLE_SCHEMA_FOUND, EXCEPTION); } else { - fromSchema((Schema) schemaResult); + fromSchema(schema1); } } } @@ -468,8 +468,8 @@ public boolean guessSchemaThroughAction(final Schema schema) { : buildActionConfig(actionRef, configuration, schema, "INPUT"); final Object schemaResult = actionRef.getInvoker().apply(actionConfiguration); - if (schemaResult instanceof Schema) { - return fromSchema((Schema) schemaResult); + if (schemaResult instanceof Schema schema1) { + return fromSchema(schema1); } else { log.error(ERROR_INSTANCE_SCHEMA); @@ -501,8 +501,7 @@ private boolean fromSchema(final Schema schema) { public Collection getFixedSchema(final String execute) { SchemaConverter sc = new SchemaConverter(); Object o = sc.toObjectImpl(execute); - if (o instanceof Schema) { - final Schema schema = (Schema) o; + if (o instanceof Schema schema) { final Collection entries = schema.getEntries(); if (entries == null || entries.isEmpty()) { log.info(NO_COLUMN_FOUND_BY_GUESS_SCHEMA); @@ -661,8 +660,8 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { final Mapper mapper = componentManager .findMapper(family, componentName, version, configuration) .orElseThrow(() -> new IllegalArgumentException("Can't find " + family + "#" + componentName)); - if (mapper instanceof JobStateAware) { - ((JobStateAware) mapper).setState(new JobStateAware.State()); + if (mapper instanceof JobStateAware jobStateAware) { + jobStateAware.setState(new JobStateAware.State()); } Input input = null; try { @@ -675,10 +674,10 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { if (rowObject == null) { return false; } - if (rowObject instanceof Record) { - return fromSchema(((Record) rowObject).getSchema()); - } else if (rowObject instanceof java.util.Map) { - return guessInputSchemaThroughResults(input, (java.util.Map) rowObject); + if (rowObject instanceof Record record) { + return fromSchema(record.getSchema()); + } else if (rowObject instanceof Map map) { + return guessInputSchemaThroughResults(input, map); } else if (rowObject instanceof java.util.Collection) { throw new Exception("Can't guess schema from a Collection"); } else { @@ -707,12 +706,12 @@ private boolean guessInputComponentSchemaThroughResult() throws Exception { * @return true if completed; false if one more result row is needed. */ public boolean guessSchemaThroughResult(final Object rowObject) throws Exception { - if (rowObject instanceof java.util.Map) { - return guessSchemaThroughResult((java.util.Map) rowObject); - } else if (rowObject instanceof Schema) { - return fromSchema((Schema) rowObject); - } else if (rowObject instanceof Record) { - return fromSchema(((Record) rowObject).getSchema()); + if (rowObject instanceof Map map) { + return guessSchemaThroughResult(map); + } else if (rowObject instanceof Schema schema) { + return fromSchema(schema); + } else if (rowObject instanceof Record record) { + return fromSchema(record.getSchema()); } else if (rowObject instanceof java.util.Collection) { throw new Exception("Can't guess schema from a Collection"); } else { @@ -764,8 +763,8 @@ private boolean guessInputSchemaThroughResults(final Input input, final Map m.getParameters()[i].isAnnotationPresent(Output.class) && outBranchName.equals(m.getParameters()[i].getAnnotation(Output.class).value())) .mapToObj(i -> m.getGenericParameterTypes()[i]) - .filter(t -> t instanceof ParameterizedType - && ((ParameterizedType) t).getRawType() == OutputEmitter.class - && ((ParameterizedType) t).getActualTypeArguments().length == 1) + .filter(t -> t instanceof ParameterizedType parameterizedType + && parameterizedType.getRawType() == OutputEmitter.class + && parameterizedType.getActualTypeArguments().length == 1) .map(p -> ((ParameterizedType) p).getActualTypeArguments()[0])) .findFirst(); if (type.isPresent() && type.get() instanceof Class) { diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java index 37f2e428857fb..8062b181e84ee 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/AfterVariableExtracter.java @@ -40,8 +40,8 @@ public class AfterVariableExtracter { * @return map with after variables. */ public static Map extractAfterVariables(final Lifecycle lifecycle) { - if (lifecycle instanceof Delegated) { - final Object delegate = ((Delegated) lifecycle).getDelegate(); + if (lifecycle instanceof Delegated delegated) { + final Object delegate = delegated.getDelegate(); final ClassLoader classloader = ReflectionUtils.getClassLoader(lifecycle); diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java index 077cb4c1359c4..d60ad6661950e 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/ParameterSetter.java @@ -33,8 +33,8 @@ public class ParameterSetter { private final Object delegate; public ParameterSetter(final Lifecycle lifecycle) { - if (lifecycle instanceof Delegated) { - delegate = ((Delegated) lifecycle).getDelegate(); + if (lifecycle instanceof Delegated delegated) { + delegate = delegated.getDelegate(); } else { throw new IllegalArgumentException("Not supported implementation of lifecycle : " + lifecycle); } @@ -92,8 +92,8 @@ public void change(final String path, final Object value) { try { target = field.get(target); if (arrayLocation > -1) { - if (target instanceof List) { - target = ((List) target).get(arrayLocation); + if (target instanceof List list) { + target = list.get(arrayLocation); } else { log.warn("expect a list, but not"); return; diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java index 9370724f2b2ac..cace2e87e06b0 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/studio/RuntimeContextInjector.java @@ -35,8 +35,8 @@ public class RuntimeContextInjector { * @see Lifecycle */ public static void injectLifecycle(final Lifecycle lifecycle, final RuntimeContextHolder runtimeContext) { - if (lifecycle instanceof Delegated) { - final Object delegate = ((Delegated) lifecycle).getDelegate(); + if (lifecycle instanceof Delegated delegated) { + final Object delegate = delegated.getDelegate(); Class currentClass = delegate.getClass(); while (currentClass != null && currentClass != Object.class) { diff --git a/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java b/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java index 3acfc67c84fd3..d91339888b222 100644 --- a/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java +++ b/component-studio/component-runtime-di/src/test/java/org/talend/sdk/component/runtime/di/beam/components/DIBatchSimulationTest.java @@ -251,8 +251,8 @@ private void doRun(final ComponentManager manager, final Collection sour Object dataMapper; while ((dataMapper = inputMapper.next()) != null) { final String jsonValueMapper; - if (dataMapper instanceof javax.json.JsonValue) { - jsonValueMapper = ((javax.json.JsonValue) dataMapper).toString(); + if (dataMapper instanceof javax.json.JsonValue jsonValue) { + jsonValueMapper = jsonValue.toString(); } else if (dataMapper instanceof org.talend.sdk.component.api.record.Record) { jsonValueMapper = jsonbMapper .toJson(converters diff --git a/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java b/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java index 4a6a0dadb4ba7..96b3ab016eed2 100644 --- a/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java +++ b/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java @@ -205,12 +205,10 @@ private String extractFamilyFromNode(final String id) { private void onException(final AsyncResponse response, final Throwable e) { final UiActionResult payload; final int status; - if (e instanceof WebException) { - final WebException we = (WebException) e; + if (e instanceof WebException we) { status = we.getStatus(); payload = actionService.map(we); - } else if (e instanceof CompletionException) { - final CompletionException actualException = (CompletionException) e; + } else if (e instanceof CompletionException actualException) { log.error(actualException.getMessage(), actualException); status = Response.Status.BAD_GATEWAY.getStatusCode(); if (actualException.getCause() instanceof WebApplicationException) { diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java index 3ee1fb4dc3759..fcca78e43fff2 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java @@ -294,8 +294,8 @@ public void close() { } catch (final Exception e) { throw new IllegalStateException(e); } - } else if (asciidoctor instanceof JRubyAsciidoctor) { - ((JRubyAsciidoctor) asciidoctor).getRubyRuntime().tearDown(); + } else if (asciidoctor instanceof JRubyAsciidoctor jRubyAsciidoctor) { + jRubyAsciidoctor.getRubyRuntime().tearDown(); } } } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java b/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java index f125f3ab0e62b..bbb756ecb6e76 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/CarBundler.java @@ -58,7 +58,7 @@ public class CarBundler implements Runnable { public CarBundler(final Configuration configuration, final Object log) { this.configuration = configuration; try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log log1 ? log1 : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java index 4d0c5cc62bdb3..ba725664e1ece 100755 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/ComponentValidator.java @@ -81,7 +81,7 @@ public ComponentValidator(final Configuration configuration, final File[] classe this.validator = new SvgValidator(this.configuration.isValidateLegacyIcons()); try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log log1 ? log1 : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java index a0705359277b3..f5d4c33636172 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java @@ -95,7 +95,7 @@ public abstract class DocBaseGenerator extends BaseTask { this.locale = locale; this.output = output; try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log log1 ? log1 : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java b/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java index 10073c197f423..06ce15583fefb 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/SVG2Png.java @@ -44,7 +44,7 @@ public SVG2Png(final Path iconsFolder, final boolean activeWorkarounds, final Ob this.iconsFolder = iconsFolder; this.activeWorkarounds = activeWorkarounds; try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log log1 ? log1 : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java b/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java index 0336456d20601..4e12af79e4d4f 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/StudioInstaller.java @@ -63,7 +63,7 @@ public StudioInstaller(final String mainGav, final File studioHome, final Map serverArguments, final Integer port, f this.serverArguments = serverArguments; this.port = port; try { - this.log = log instanceof Log ? (Log) log : new ReflectiveLog(log); + this.log = log instanceof Log log1 ? log1 : new ReflectiveLog(log); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(e); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java index 35fb5e3e03577..3f7e5e3fba267 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java @@ -170,8 +170,7 @@ private Class toJavaType(final ParameterMeta p) { + p.getSource().declaringClass() + "), ensure it is a Class"); } - if (p.getType().equals(ARRAY) && p.getJavaType() instanceof ParameterizedType) { - final ParameterizedType parameterizedType = (ParameterizedType) p.getJavaType(); + if (p.getType().equals(ARRAY) && p.getJavaType() instanceof ParameterizedType parameterizedType) { final Type[] arguments = parameterizedType.getActualTypeArguments(); if (arguments.length == 1 && arguments[0] instanceof Class) { return (Class) arguments[0]; diff --git a/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java b/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java index eb1c7f8a4d981..ebc19a7333570 100644 --- a/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java +++ b/container/container-core/src/main/java/org/talend/sdk/component/classloader/ConfigurableClassLoader.java @@ -178,8 +178,7 @@ private void loadNestedDependencies(final ClassLoader parent, final String[] nes final CodeSource codeSource; try { urlConnection = url.openConnection(); - if (urlConnection instanceof JarURLConnection) { - final JarURLConnection juc = (JarURLConnection) urlConnection; + if (urlConnection instanceof JarURLConnection juc) { manifest = juc.getManifest(); final Certificate[] certificates = juc.getCertificates(); @@ -446,8 +445,7 @@ private InputStream doGetResourceAsStream(final String name) { private InputStream getInputStream(final URL resource) throws IOException { final URLConnection urlc = resource.openConnection(); final InputStream is = urlc.getInputStream(); - if (urlc instanceof JarURLConnection) { - final JarURLConnection juc = (JarURLConnection) urlc; + if (urlc instanceof JarURLConnection juc) { final JarFile jar = juc.getJarFile(); synchronized (closeables) { if (!closeables.containsKey(jar)) { @@ -807,10 +805,9 @@ private Class loadInternal(final String name, final boolean resolve) { final String pckName = name.substring(0, i); final Package pck = super.getPackage(pckName); if (pck == null) { - if (!(connection instanceof JarURLConnection)) { + if (!(connection instanceof JarURLConnection urlConnection)) { doDefinePackage(null, null, pckName); } else { - final JarURLConnection urlConnection = (JarURLConnection) connection; doDefinePackage(urlConnection.getManifest(), urlConnection.getJarFileURL(), pckName); } } @@ -831,8 +828,8 @@ private Class loadInternal(final String name, final boolean resolve) { } bytes = outputStream.toByteArray(); } - final Certificate[] certificates = connection instanceof JarURLConnection - ? ((JarURLConnection) connection).getCertificates() + final Certificate[] certificates = connection instanceof JarURLConnection jarURLConnection + ? jarURLConnection.getCertificates() : NO_CERTIFICATES; bytes = doTransform(resourceName, bytes); clazz = super.defineClass(name, bytes, 0, bytes.length, new CodeSource(url, certificates)); diff --git a/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java b/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java index de3c39f354da0..4fb316674b12d 100644 --- a/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java +++ b/container/container-core/src/test/java/org/talend/sdk/component/ContainerTest.java @@ -97,8 +97,8 @@ void proxying( throw new IllegalStateException(e); } catch (final InvocationTargetException e) { final Throwable targetException = e.getTargetException(); - if (targetException instanceof RuntimeException) { - throw (RuntimeException) targetException; + if (targetException instanceof RuntimeException runtimeException) { + throw runtimeException; } throw new IllegalStateException(targetException); } diff --git a/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java b/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java index 941ef3457b307..b5f5d9cdc9b9b 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/component/service/MockTableService.java @@ -61,8 +61,7 @@ public HealthCheckStatus healthCheck(@Option(BasicAuthConfig.NAME) final BasicAu try { client.healthCheck(dt.getAuthorizationHeader()); } catch (Exception e) { - if (e instanceof HttpException) { - final HttpException ex = (HttpException) e; + if (e instanceof HttpException ex) { final JsonObject jError = (JsonObject) ex.getResponse().error(JsonObject.class); String errorMessage = null; if (jError != null && jError.containsKey("error")) { diff --git a/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java b/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java index d38a57fdfed41..81ba36b2a7fb5 100644 --- a/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java +++ b/talend-component-maven-plugin/src/main/java/org/talend/sdk/component/maven/WebsiteBuilderMojo.java @@ -138,8 +138,8 @@ public Wrapper find(final String name, final List scopes) { final Wrapper wrapper = super.find(name, scopes); return s -> { final Object call = wrapper.call(s); - if (call instanceof Collection && !(call instanceof DecoratedCollection)) { - return new DecoratedCollection<>((Collection) call); + if (call instanceof Collection collection && !(call instanceof DecoratedCollection)) { + return new DecoratedCollection<>(collection); } return call; }; diff --git a/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java b/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java index c6d805ca35225..daeb98401de8f 100644 --- a/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java +++ b/vault-client/src/main/java/org/talend/sdk/components/vault/client/VaultClient.java @@ -153,8 +153,7 @@ public class VaultClient { private Pattern compiledPassthroughRegex; private final Predicate shouldRetry = cause -> { - if (cause instanceof WebApplicationException) { - final WebApplicationException wae = (WebApplicationException) cause; + if (cause instanceof WebApplicationException wae) { final int status = wae.getResponse().getStatus(); if (Status.NOT_FOUND.getStatusCode() == status || status >= 500) { return false; @@ -330,8 +329,7 @@ private CompletionStage> doDecipher(final Collection doAuth(final String role, final String s // .exceptionally(e -> { final Throwable cause = e.getCause(); - if (cause instanceof WebApplicationException) { - final WebApplicationException wae = (WebApplicationException) cause; + if (cause instanceof WebApplicationException wae) { final Response response = wae.getResponse(); String message = ""; if (wae.getResponse().getEntity() instanceof ErrorPayload) { @@ -471,8 +468,7 @@ private void throwError(final int status, final String message) { private void throwError(final Throwable cause) { String message = ""; int status = cantDecipherStatusCode; - if (cause instanceof WebApplicationException) { - final WebApplicationException wae = (WebApplicationException) cause; + if (cause instanceof WebApplicationException wae) { final Response response = wae.getResponse(); status = response.getStatus(); if (response != null) { From 9ef66144872099e54ac4511af7dcb5f1420c0dee Mon Sep 17 00:00:00 2001 From: Emmanuel GALLOIS Date: Thu, 4 Jun 2026 13:41:23 +0200 Subject: [PATCH 7/7] chore(QTDI-2893): S6201 manual processed --- .../jsonschema/PojoJsonSchemaBuilder.java | 3 +- .../beam/spi/BeamComponentExtension.java | 4 +- .../runtime/beam/spi/record/AvroRecord.java | 3 +- .../repository/RepositoryModelBuilder.java | 4 +- .../record/json/RecordJsonGenerator.java | 3 +- .../component/runtime/reflect/Defaults.java | 9 ++-- .../runtime/visitor/ModelVisitor.java | 7 +-- .../runtime/record/PluralRecordExtension.java | 2 +- .../runtime/manager/ComponentManager.java | 9 ++-- .../reflect/ParameterModelService.java | 20 ++++----- .../manager/reflect/ReflectionService.java | 21 +++++---- .../reflect/visibility/VisibilityService.java | 4 +- .../runtime/manager/service/InjectorImpl.java | 11 ++--- .../service/RecordPointerFactoryImpl.java | 3 +- .../manager/service/http/RequestParser.java | 4 +- .../runtime/manager/ComponentManagerTest.java | 3 +- .../manager/ConfigurationMigrationTest.java | 40 ++++++++++------- .../manager/ReflectionServiceTest.java | 6 ++- .../service/RecordServiceImplTest.java | 45 ++++++++++--------- .../junit/delegate/DelegatingRunner.java | 4 +- .../component/junit5/ComponentExtension.java | 3 +- .../spark/junit5/internal/SparkExtension.java | 8 ++-- .../server/front/ActionResourceImpl.java | 4 +- .../server/front/memory/AsyncContextImpl.java | 3 ++ .../runtime/di/schema/TaCoKitGuessSchema.java | 3 +- .../tools/webapp/WebAppComponentProxy.java | 4 +- .../component/tools/AsciidoctorExecutor.java | 3 ++ .../sdk/component/tools/DocBaseGenerator.java | 4 +- .../tools/validator/ActionValidator.java | 4 +- .../tools/validator/LayoutValidator.java | 8 ++-- .../tools/ComponentValidatorTest.java | 5 ++- .../runtime/documentation/Generator.java | 3 +- .../talend/runtime/documentation/Github.java | 4 +- .../singer/kitap/RecordJsonMapper.java | 3 +- 34 files changed, 142 insertions(+), 122 deletions(-) diff --git a/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java b/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java index c0d7b59cbd93c..f60edc3ed8abe 100644 --- a/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java +++ b/component-form/component-form-model/src/main/java/org/talend/sdk/component/form/model/jsonschema/PojoJsonSchemaBuilder.java @@ -76,8 +76,7 @@ private JsonSchema buildSchema(final Field field) { } else if (genericType == boolean.class || genericType == Boolean.class) { return schemas .computeIfAbsent((Class) genericType, k -> jsonSchema().withType("boolean").build()); - } else if (genericType instanceof Class) { - final Class clazz = (Class) genericType; + } else if (genericType instanceof Class clazz) { return ofNullable(schemas.get(clazz)).orElseGet(() -> { final JsonSchema jsonSchema = create(clazz).build(); schemas.put(clazz, jsonSchema); diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java index 38a90bc6a0dc5..2725df179d041 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/BeamComponentExtension.java @@ -66,10 +66,10 @@ public boolean isActive() { @Override public T unwrap(final Class type, final Object... args) { if ("org.talend.sdk.component.design.extension.flows.FlowsFactory".equals(type.getName()) && args != null - && args.length == 1 && args[0] instanceof ComponentFamilyMeta.BaseMeta) { + && args.length == 1 && args[0] instanceof ComponentFamilyMeta.BaseMeta baseMeta) { if (args[0] instanceof ComponentFamilyMeta.ProcessorMeta) { try { - final FlowsFactory factory = FlowsFactory.get((ComponentFamilyMeta.BaseMeta) args[0]); + final FlowsFactory factory = FlowsFactory.get(baseMeta); factory.getOutputFlows(); return type.cast(factory); } catch (final Exception e) { // no @ElementListener, let's default for native transforms diff --git a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java index 056af2704d727..13d4cb2ff7b2c 100644 --- a/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java +++ b/component-runtime-beam/src/main/java/org/talend/sdk/component/runtime/beam/spi/record/AvroRecord.java @@ -244,7 +244,8 @@ private T doMap(final Class expectedType, final org.apache.avro.Schema fi return expectedType.cast(value); } - if (value instanceof IndexedRecord indexedRecord && (Record.class == expectedType || Object.class == expectedType)) { + if (value instanceof IndexedRecord indexedRecord + && (Record.class == expectedType || Object.class == expectedType)) { return expectedType.cast(new AvroRecord(indexedRecord)); } diff --git a/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java b/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java index 7b589deec12a7..bf645434bd6b9 100644 --- a/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java +++ b/component-runtime-design-extension/src/main/java/org/talend/sdk/component/design/extension/repository/RepositoryModelBuilder.java @@ -130,8 +130,8 @@ private Config createConfig(final String plugin, final ComponentManager.AllServi .setId(IdGenerator .get(plugin, c.getKey().getFamily(), c.getKey().getConfigType(), c.getKey().getConfigName())); - if (config.getJavaType() instanceof Class) { - final Class clazz = (Class) config.getJavaType(); + if (config.getJavaType() instanceof Class javaTypeClass) { + final Class clazz = javaTypeClass; final Version version = clazz.getAnnotation(Version.class); if (version != null) { c.setVersion(version.value()); diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java index 6f4c47e4f7055..909b8b94a8360 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/record/json/RecordJsonGenerator.java @@ -351,8 +351,7 @@ public JsonGenerator writeEnd() { } else { throw new IllegalArgumentException("Unsupported previous builder: " + previous); } - } else if (last instanceof NamedBuilder) { - final NamedBuilder namedBuilder = (NamedBuilder) last; + } else if (last instanceof NamedBuilder namedBuilder) { if (previous instanceof Record.Builder builder1) { objectBuilder = builder1; if (namedBuilder.builder instanceof List array) { diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java index 98db632afb7ae..d632994d510a9 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/reflect/Defaults.java @@ -63,10 +63,11 @@ public class Defaults { .invokeWithArguments(args); } else { // j > 8 - can need some --add-opens, we will add a module-info later to be clean when dropping j8 final Method privateLookup = findPrivateLookup(); - HANDLER = (clazz, method, proxy, args) -> ((MethodHandles.Lookup) privateLookup.invoke(null, clazz, constructor.newInstance(clazz))) - .unreflectSpecial(method, clazz) - .bindTo(proxy) - .invokeWithArguments(args); + HANDLER = (clazz, method, proxy, + args) -> ((MethodHandles.Lookup) privateLookup.invoke(null, clazz, constructor.newInstance(clazz))) + .unreflectSpecial(method, clazz) + .bindTo(proxy) + .invokeWithArguments(args); } } diff --git a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java index a94543a8b7156..468e4c674f97d 100644 --- a/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java +++ b/component-runtime-impl/src/main/java/org/talend/sdk/component/runtime/visitor/ModelVisitor.java @@ -133,8 +133,8 @@ private void validatePartitionMapper(final Class type) { throw new IllegalArgumentException(m + " must return a Collection<" + type.getName() + ">"); } - if (!(splitPt.getRawType() instanceof Class) - || !Collection.class.isAssignableFrom((Class) splitPt.getRawType())) { + if (!(splitPt.getRawType() instanceof Class clazz) + || !Collection.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(m + " must return a List of partition mapper, found: " + splitPt); } @@ -316,7 +316,8 @@ private static boolean isValidAfterVariableContainer(final Type type) { return false; } - if (!(paramType.getRawType() instanceof Class containerType) || paramType.getActualTypeArguments().length != 2) { + if (!(paramType.getRawType() instanceof Class containerType) + || paramType.getActualTypeArguments().length != 2) { return false; } diff --git a/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java b/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java index 7f53b27b52b5a..135526c66418f 100644 --- a/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java +++ b/component-runtime-impl/src/test/java/org/talend/sdk/component/runtime/record/PluralRecordExtension.java @@ -58,7 +58,7 @@ private Jsonb getJsonb(Jsonb jsonb) { // create a Jsonb instance which is PojoJsonbProvider as in component-runtime-manager return (Jsonb) Proxy .newProxyInstance(Thread.currentThread().getContextClassLoader(), - new Class[]{Jsonb.class, PojoJsonbProvider.class}, (proxy, method, args) -> { + new Class[] { Jsonb.class, PojoJsonbProvider.class }, (proxy, method, args) -> { if (method.getDeclaringClass() == Supplier.class) { return jsonb; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java index f605d761ddb81..46a88f5da34a5 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/ComponentManager.java @@ -1922,7 +1922,8 @@ public void onPartitionMapper(final Class type, final PartitionMapper partiti () -> { final List params = parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() + .get(LocalConfiguration.class))); if (infinite) { if (partitionMapper.stoppable()) { addInfiniteMapperBuiltInParameters(type, params); @@ -1975,7 +1976,8 @@ public void onEmitter(final Class type, final Emitter emitter) { final Supplier> parameterMetas = lazy(() -> executeInContainer(plugin, () -> parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() + .get(LocalConfiguration.class))))); final Function, Object[]> parameterFactory = createParametersFactory(plugin, constructor, services.getServices(), parameterMetas); final String name = of(emitter.name()).filter(n -> !n.isEmpty()).orElseGet(type::getName); @@ -2159,7 +2161,8 @@ public void onDriverRunner(final Class type, final DriverRunner processor) { final Supplier> parameterMetas = lazy(() -> executeInContainer(plugin, () -> parameterModelService .buildParameterMetas(constructor, getPackage(type), - new BaseParameterEnricher.Context((LocalConfiguration) services.getServices().get(LocalConfiguration.class))))); + new BaseParameterEnricher.Context((LocalConfiguration) services.getServices() + .get(LocalConfiguration.class))))); final Function, Object[]> parameterFactory = createParametersFactory(plugin, constructor, services.getServices(), parameterMetas); final String name = of(processor.name()).filter(n -> !n.isEmpty()).orElseGet(type::getName); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java index 96caf7eee76e2..1ebbf0808e959 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ParameterModelService.java @@ -140,8 +140,8 @@ private Stream extractTypeAnnotation(final Param parameter) { return Stream.of(aClass.getAnnotations()); } if (parameter.type instanceof ParameterizedType parameterizedType) { - if (parameterizedType.getRawType() instanceof Class) { - return Stream.of(((Class) parameterizedType.getRawType()).getAnnotations()); + if (parameterizedType.getRawType() instanceof Class clazz) { + return Stream.of(clazz.getAnnotations()); } } return Stream.empty(); @@ -252,10 +252,10 @@ private Stream getReflectionAnnotations(final Type genericType, fina .concat(Stream.of(annotations), // if a class concat its annotations genericType instanceof Class - ? getClassAnnotations(genericType, annotations) - : (hasAClassFirstParameter(genericType) ? getClassAnnotations( - ((ParameterizedType) genericType).getActualTypeArguments()[0], - annotations) : Stream.empty())); + ? getClassAnnotations(genericType, annotations) + : (hasAClassFirstParameter(genericType) ? getClassAnnotations( + ((ParameterizedType) genericType).getActualTypeArguments()[0], + annotations) : Stream.empty())); } private boolean hasAClassFirstParameter(final Type genericType) { @@ -294,7 +294,7 @@ private List buildParametersMetas(final String name, final String } return Stream .concat(buildParametersMetas(name + ".key[${index}]", prefix + "key[${index}].", - (Class) pt.getActualTypeArguments()[0], annotations, i18nPackages, ignoreI18n, + (Class) pt.getActualTypeArguments()[0], annotations, i18nPackages, ignoreI18n, context).stream(), buildParametersMetas(name + ".value[${index}]", prefix + "value[${index}].", (Class) pt.getActualTypeArguments()[1], annotations, i18nPackages, @@ -371,8 +371,7 @@ public String findName(final AnnotatedElement parameter, final String defaultNam } private ParameterMeta.Type findType(final Type type) { - if (type instanceof Class) { - final Class clazz = (Class) type; + if (type instanceof Class clazz) { // we handled char before so we only have numbers now for primitives if (Primitives.unwrap(clazz) == boolean.class) { @@ -393,8 +392,7 @@ private ParameterMeta.Type findType(final Type type) { } } if (type instanceof ParameterizedType pt) { - if (pt.getRawType() instanceof Class) { - final Class raw = (Class) pt.getRawType(); + if (pt.getRawType() instanceof Class raw) { if (Collection.class.isAssignableFrom(raw)) { return ParameterMeta.Type.ARRAY; } diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java index f7774ec56d922..9d832bdc10852 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/ReflectionService.java @@ -135,9 +135,9 @@ public Function, Object[]> parameterFactory(final Executable } if (parameterizedType instanceof ParameterizedType pt) { - if (pt.getRawType() instanceof Class) { - if (Collection.class.isAssignableFrom((Class) pt.getRawType())) { - final Class collectionType = (Class) pt.getRawType(); + if (pt.getRawType() instanceof Class clazz) { + if (Collection.class.isAssignableFrom(clazz)) { + final Class collectionType = clazz; final Type itemType = pt.getActualTypeArguments()[0]; if (!(itemType instanceof Class)) { throw new IllegalArgumentException( @@ -516,15 +516,15 @@ private Object createObject(final ClassLoader loader, final Function arrayClass = (Class) genericType; + if (genericType instanceof Class arrayClass) { if (arrayClass.isArray()) { // we could use Array.newInstance but for now use the list, shouldn't impact // much the perf - final Collection list = (Collection) createList(loader, contextualSupplier, prefix + enclosingName, List.class, - arrayClass.getComponentType(), toList(), createObjectFactory(loader, - contextualSupplier, arrayClass.getComponentType(), metas, precomputed), - new HashMap<>(listEntries), metas, precomputed); + final Collection list = + (Collection) createList(loader, contextualSupplier, prefix + enclosingName, List.class, + arrayClass.getComponentType(), toList(), createObjectFactory(loader, + contextualSupplier, arrayClass.getComponentType(), metas, precomputed), + new HashMap<>(listEntries), metas, precomputed); // we need that conversion to ensure the type matches final Object array = Array.newInstance(arrayClass.getComponentType(), list.size()); @@ -588,8 +588,7 @@ private Object createObject(final ClassLoader loader, final Function rawType = (Class) pt.getRawType(); + if (pt.getRawType() instanceof Class rawType) { if (Set.class.isAssignableFrom(rawType)) { addListElement(loader, contextualSupplier, config, prefix, preparedObjects, nestedName, listName, pt, () -> new HashSet<>(2), translate(metas, listName), precomputed); diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java index 91485be4a12c5..297ccda94a3fe 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/reflect/visibility/VisibilityService.java @@ -190,8 +190,8 @@ private boolean evaluate(final String expected, final JsonObject payload) { .map(it -> it.contains(expected)) .orElse(false); } - if (actual instanceof Collection) { - final Collection collection = (Collection) actual; + if (actual instanceof Collection collectionClass) { + final Collection collection = collectionClass; return collection.stream().map(preprocessor).anyMatch(it -> it.contains(expected)); } if (actual.getClass().isArray()) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java index 15d6c5d0a346a..8a5725661ec00 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/InjectorImpl.java @@ -87,11 +87,11 @@ private void doInject(final Class type, final T instance) { .forEach(field -> { Object value = services.get(field.getType()); if (value == null && field.getGenericType() instanceof ParameterizedType pt) { - if (pt.getRawType() instanceof Class - && Collection.class.isAssignableFrom((Class) pt.getRawType())) { + if (pt.getRawType() instanceof Class clazz + && Collection.class.isAssignableFrom(clazz)) { final Type serviceType = pt.getActualTypeArguments()[0]; - if (serviceType instanceof Class) { - final Class serviceClass = (Class) serviceType; + if (serviceType instanceof Class stClass) { + final Class serviceClass = stClass; value = services .entrySet() .stream() @@ -127,7 +127,8 @@ private void doInject(final Class type, final T instance) { }) .forEach(field -> { try { - final Class configClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class configClass = + (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Supplier supplier = () -> { try { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java index 62978c351c6d1..94971ece87fe4 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/RecordPointerFactoryImpl.java @@ -113,7 +113,7 @@ private Object getValue(final Object value, final String referenceToken, final i throw new IllegalArgumentException( "'" + record + "' contains no value for name '" + referenceToken + "'"); } - if (value instanceof Collection) { + if (value instanceof Collection array) { if (referenceToken.startsWith("+") || referenceToken.startsWith("-")) { throw new IllegalArgumentException( "An array index must not start with '" + referenceToken.charAt(0) + "'"); @@ -122,7 +122,6 @@ private Object getValue(final Object value, final String referenceToken, final i throw new IllegalArgumentException("An array index must not start with a leading '0'"); } - final Collection array = (Collection) value; try { final int arrayIndex = Integer.parseInt(referenceToken); if (arrayIndex >= array.size()) { diff --git a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java index 7695b521d4e08..ffe80be8aa322 100644 --- a/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java +++ b/component-runtime-manager/src/main/java/org/talend/sdk/component/runtime/manager/service/http/RequestParser.java @@ -261,8 +261,8 @@ static Class toClassType(final Type type) { cType = aClass; } else if (type instanceof ParameterizedType pt) { if (pt.getRawType() == Response.class && pt.getActualTypeArguments().length == 1 - && pt.getActualTypeArguments()[0] instanceof Class) { - cType = (Class) pt.getActualTypeArguments()[0]; + && pt.getActualTypeArguments()[0] instanceof Class ptClass) { + cType = ptClass; } } diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java index 3aca230e76ffd..d9ef11418ea2b 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ComponentManagerTest.java @@ -611,7 +611,8 @@ void testLocalConfigurationFromEnvironment(@TempDir final File temporaryFolder) manager.addPlugin(plugin.getAbsolutePath()); final Container container = manager.getContainer().findAll().stream().findFirst().orElse(null); assertNotNull(container); - final LocalConfiguration envConf = (LocalConfiguration) container.get(AllServices.class).getServices().get(LocalConfiguration.class); + final LocalConfiguration envConf = + (LocalConfiguration) container.get(AllServices.class).getServices().get(LocalConfiguration.class); // check translated env vars assertEquals("/home/user", envConf.get("USER_PATH")); assertEquals("/home/user", envConf.get("USER.PATH")); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java index 11e4cf10371e9..ae2e86cda2cfb 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ConfigurationMigrationTest.java @@ -42,12 +42,14 @@ void run(@TempDir final Path temporaryFolder) throws Exception { "META-INF/test/dependencies", "org.talend.test:type=plugin,value=%s")) { manager.addPlugin(jar.getAbsolutePath()); { - final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "configured1", 0, new HashMap() { + final Object nested = ((ProcessorImpl) manager + .findProcessor("chain", "configured1", 0, new HashMap() { - { - put("config.__version", "-1"); - } - }).orElseThrow(IllegalStateException::new)) + { + put("config.__version", "-1"); + } + }) + .orElseThrow(IllegalStateException::new)) .getDelegate(); final Object config = get(nested, "getConfig"); @@ -55,13 +57,15 @@ void run(@TempDir final Path temporaryFolder) throws Exception { assertEquals("ok", get(config, "getName")); } { - final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "configured2", 0, new HashMap() { + final Object nested = ((ProcessorImpl) manager + .findProcessor("chain", "configured2", 0, new HashMap() { - { - put("config.__version", "0"); - put("value.__version", "-1"); - } - }).orElseThrow(IllegalStateException::new)) + { + put("config.__version", "0"); + put("value.__version", "-1"); + } + }) + .orElseThrow(IllegalStateException::new)) .getDelegate(); assertEquals("set", get(nested, "getValue")); @@ -70,13 +74,15 @@ void run(@TempDir final Path temporaryFolder) throws Exception { assertEquals("ok", get(config, "getName")); } { - final Object nested = ((ProcessorImpl) manager.findProcessor("chain", "migrationtest", -1, new HashMap() { + final Object nested = ((ProcessorImpl) manager + .findProcessor("chain", "migrationtest", -1, new HashMap() { - { - put("config.__version", "1"); - put("config.datastore.__version", "1"); - } - }).orElseThrow(IllegalStateException::new)) + { + put("config.__version", "1"); + put("config.datastore.__version", "1"); + } + }) + .orElseThrow(IllegalStateException::new)) .getDelegate(); final Object config = get(nested, "getConfig"); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java index 836bc2336470f..09a7aecc5d5c2 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/ReflectionServiceTest.java @@ -450,8 +450,10 @@ void copiable() throws NoSuchMethodException { new HttpClientFactoryImpl("test", reflectionService, JsonbBuilder.create(), emptyMap()) .create(UserHttpClient.class, "http://foo")); final Method httpMtd = TableOwner.class.getMethod("http", UserHttpClient.class); - final HttpClient client1 = (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; - final HttpClient client2 = (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; + final HttpClient client1 = + (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; + final HttpClient client2 = + (HttpClient) reflectionService.parameterFactory(httpMtd, precomputed, null).apply(emptyMap())[0]; assertNotSame(client1, client2); final InvocationHandler handler1 = Proxy.getInvocationHandler(client1); final InvocationHandler handler2 = Proxy.getInvocationHandler(client2); diff --git a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java index 4002678fd3919..059154dffe389 100644 --- a/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java +++ b/component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/service/RecordServiceImplTest.java @@ -52,7 +52,8 @@ class RecordServiceImplTest { private final RecordBuilderFactory factory = new RecordBuilderFactoryImpl(null); - private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), Json.createGeneratorFactory(emptyMap()), + private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), + Json.createGeneratorFactory(emptyMap()), Json.createReaderFactory(emptyMap()), Json.createBuilderFactory(emptyMap()), Json.createParserFactory(emptyMap()), Json.createWriterFactory(emptyMap()), new JsonbConfig(), JsonbProvider.provider(), null, null, emptyList(), t -> factory, null) @@ -104,28 +105,28 @@ void visit() { assertEquals(3, service .visit((RecordVisitor) Proxy - .newProxyInstance(Thread.currentThread().getContextClassLoader(), - new Class[]{RecordVisitor.class}, (proxy, method, args) -> { - visited - .add(method.getName() + "/" - + (args == null ? "null" + .newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[] { RecordVisitor.class }, (proxy, method, args) -> { + visited + .add(method.getName() + "/" + + (args == null ? "null" : Stream - .of(args) - .filter(it -> !(it instanceof Schema.Entry)) - .collect(Collectors.toList()))); - switch (method.getName()) { - case "get": - return out.incrementAndGet(); - case "apply": - return asList(args) - .stream() - .mapToInt(Integer.class::cast) - .sum(); - default: - return method.getReturnType() == RecordVisitor.class ? proxy - : null; - } - }), + .of(args) + .filter(it -> !(it instanceof Schema.Entry)) + .collect(Collectors.toList()))); + switch (method.getName()) { + case "get": + return out.incrementAndGet(); + case "apply": + return asList(args) + .stream() + .mapToInt(Integer.class::cast) + .sum(); + default: + return method.getReturnType() == RecordVisitor.class ? proxy + : null; + } + }), baseRecord)); assertEquals(asList("onString/[Optional[Test]]", "onInt/[OptionalInt[33]]", "onRecord/[Optional[{\"street\":\"here\",\"number\":1}]]", "onString/[Optional[here]]", diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java index 8fc1ec1f86f4f..00c5157d8fc72 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit/delegate/DelegatingRunner.java @@ -47,8 +47,8 @@ public DelegatingRunner(final Class testClass) throws InitializationError { } catch (final InstantiationException | NoSuchMethodException | IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (final InvocationTargetException e) { - if (e.getCause() instanceof InitializationError) { - throw (InitializationError) e.getCause(); + if (e.getCause() instanceof InitializationError initializationError) { + throw initializationError; } throw new IllegalStateException(e.getTargetException()); } diff --git a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java index acb3dd1662862..34705cb7abc0f 100644 --- a/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java +++ b/component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/ComponentExtension.java @@ -112,7 +112,8 @@ public void doStart(final ExtensionContext extensionContext) { } public void doStop(final ExtensionContext extensionContext) { - ofNullable((EmbeddedComponentManager) extensionContext.getStore(NAMESPACE).get(EmbeddedComponentManager.class.getName())) + ofNullable((EmbeddedComponentManager) extensionContext.getStore(NAMESPACE) + .get(EmbeddedComponentManager.class.getName())) .ifPresent(EmbeddedComponentManager::close); } diff --git a/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java b/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java index acd1fd6c04c4e..0c8b3f407d907 100644 --- a/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java +++ b/component-runtime-testing/component-runtime-testing-spark/src/main/java/org/talend/sdk/component/runtime/testing/spark/junit5/internal/SparkExtension.java @@ -67,11 +67,11 @@ public void beforeAll(final ExtensionContext extensionContext) throws Exception final Instances instances = start(); if (instances.getException() != null) { instances.close(); - if (instances.getException() instanceof Exception) { - throw (Exception) instances.getException(); + if (instances.getException() instanceof Exception exception) { + throw exception; } - if (instances.getException() instanceof Error) { - throw (Error) instances.getException(); + if (instances.getException() instanceof Error error) { + throw error; } throw new IllegalStateException(instances.getException()); } diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java index a2d1bd35a687e..88d6551bc922b 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/ActionResourceImpl.java @@ -211,8 +211,8 @@ private CompletableFuture doExecuteLocalAction(final String family, fi private Response onError(final Throwable re) { log.warn(re.getMessage(), re); - if (re.getCause() instanceof WebApplicationException) { - return ((WebApplicationException) re.getCause()).getResponse(); + if (re.getCause() instanceof WebApplicationException wae) { + return wae.getResponse(); } if (re instanceof ComponentException ce) { diff --git a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java index f306f313dc7b2..57fd73eeb947c 100644 --- a/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java +++ b/component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/memory/AsyncContextImpl.java @@ -63,6 +63,9 @@ AsyncContext start() { return this; } + @SuppressWarnings("java:S6201") + // unconditional patterns in instanceof are not supported in -source 17 + // TODO: remove the @SuppressWarnings and apply S6201 when java 21+ only is supported. public void onError(final Throwable throwable) { final AsyncEvent event = new AsyncEvent(this, request, response, throwable); executeOnListeners(l -> l.onError(event), null); diff --git a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java index 61b889a7d7320..d7d226408b493 100644 --- a/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java +++ b/component-studio/component-runtime-di/src/main/java/org/talend/sdk/component/runtime/di/schema/TaCoKitGuessSchema.java @@ -784,8 +784,7 @@ public void fromOutputEmitterPojo(final Processor processor, final String outBra && parameterizedType.getActualTypeArguments().length == 1) .map(p -> ((ParameterizedType) p).getActualTypeArguments()[0])) .findFirst(); - if (type.isPresent() && type.get() instanceof Class) { - final Class clazz = (Class) type.get(); + if (type.isPresent() && type.get() instanceof Class clazz) { if (clazz != JsonObject.class) { guessSchemaThroughResultClass(clazz); } diff --git a/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java b/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java index 96b3ab016eed2..c6e7c67fb969c 100644 --- a/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java +++ b/component-tools-webapp/src/main/java/org/talend/sdk/component/tools/webapp/WebAppComponentProxy.java @@ -211,8 +211,8 @@ private void onException(final AsyncResponse response, final Throwable e) { } else if (e instanceof CompletionException actualException) { log.error(actualException.getMessage(), actualException); status = Response.Status.BAD_GATEWAY.getStatusCode(); - if (actualException.getCause() instanceof WebApplicationException) { - final Response resp = ((WebApplicationException) actualException.getCause()).getResponse(); + if (actualException.getCause() instanceof WebApplicationException wae) { + final Response resp = (wae).getResponse(); if (response != null) { final String s = resp.readEntity(String.class); response.resume(Response.status(resp.getStatus()).entity(s).type(APPLICATION_JSON_TYPE).build()); diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java index fcca78e43fff2..92919f1bd8142 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/AsciidoctorExecutor.java @@ -284,6 +284,9 @@ protected Asciidoctor getAsciidoctor() { return asciidoctor == null ? asciidoctor = Asciidoctor.Factory.create() : asciidoctor; } + @SuppressWarnings("java:S6201") + // unconditional patterns in instanceof are not supported in -source 17 + // TODO: remove the @SuppressWarnings and apply S6201 when java 21+ only is supported. @Override public void close() { onClose.run(); diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java index f5d4c33636172..167518543be56 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/DocBaseGenerator.java @@ -570,8 +570,8 @@ private String findDefault(final ParameterMeta p, final DefaultValueInspector.In .orElse(null); case ARRAY: return String - .valueOf(instance.getValue() instanceof Collection - ? ((Collection) instance.getValue()).size() + .valueOf(instance.getValue() instanceof Collection collection + ? collection.size() : Array.getLength(instance.getValue())); case OBJECT: default: diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java index ef20ebc84b7fa..a6abe6bb6f84f 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/ActionValidator.java @@ -470,8 +470,8 @@ private boolean hasCorrectReturnType(final Method method) { private boolean hasStringInList(final Method method) { if (List.class.isAssignableFrom(method.getReturnType()) - && method.getGenericReturnType() instanceof ParameterizedType) { - Type[] actualTypeArguments = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments(); + && method.getGenericReturnType() instanceof ParameterizedType parameterizedType) { + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments.length > 0) { return "java.lang.String".equals(actualTypeArguments[0].getTypeName()); } diff --git a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java index 3f7e5e3fba267..4c48eddd96fa2 100644 --- a/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java +++ b/component-tools/src/main/java/org/talend/sdk/component/tools/validator/LayoutValidator.java @@ -163,8 +163,8 @@ private boolean isArrayOfObject(final ParameterMeta param) { private Class toJavaType(final ParameterMeta p) { if (p.getType().equals(OBJECT) || p.getType().equals(ENUM)) { - if (p.getJavaType() instanceof Class) { - return (Class) p.getJavaType(); + if (p.getJavaType() instanceof Class clazz) { + return clazz; } throw new IllegalArgumentException("Unsupported type for parameter " + p.getPath() + " (from " + p.getSource().declaringClass() + "), ensure it is a Class"); @@ -172,8 +172,8 @@ private Class toJavaType(final ParameterMeta p) { if (p.getType().equals(ARRAY) && p.getJavaType() instanceof ParameterizedType parameterizedType) { final Type[] arguments = parameterizedType.getActualTypeArguments(); - if (arguments.length == 1 && arguments[0] instanceof Class) { - return (Class) arguments[0]; + if (arguments.length == 1 && arguments[0] instanceof Class argClass) { + return argClass; } throw new IllegalArgumentException("Unsupported type for parameter " + p.getPath() + " (from " + p.getSource().declaringClass() + "), " + "ensure it is a ParameterizedType with one argument"); diff --git a/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java b/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java index 474b91aedde26..2557c4dd01359 100755 --- a/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java +++ b/component-tools/src/test/java/org/talend/sdk/component/tools/ComponentValidatorTest.java @@ -182,8 +182,9 @@ public void beforeEach(final ExtensionContext context) { public void afterEach(final ExtensionContext context) { final ExtensionContext.Store store = context.getStore(NAMESPACE); final boolean fails = !((ComponentPackage) store.get(ComponentPackage.class.getName())).success(); - final String expectedMessage = ((ExceptionSpec) context.getStore(NAMESPACE).get(ExceptionSpec.class.getName())) - .getMessage(); + final String expectedMessage = + ((ExceptionSpec) context.getStore(NAMESPACE).get(ExceptionSpec.class.getName())) + .getMessage(); try { ((ComponentValidator) store.get(ComponentValidator.class.getName())).run(); if (fails) { diff --git a/documentation/src/main/java/org/talend/runtime/documentation/Generator.java b/documentation/src/main/java/org/talend/runtime/documentation/Generator.java index a75a8aad81a99..2f08828472513 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/Generator.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/Generator.java @@ -373,7 +373,8 @@ private static void generatedScanningExclusions(final File generatedDir) { stream.println("Therefore, the following packages are ignored:"); stream.println(); stream.println("[.talend-filterlist]"); - ((KnownClassesFilter.OptimizedExclusionFilter) ((KnownClassesFilter) KnownClassesFilter.INSTANCE).getDelegateSkip()) + ((KnownClassesFilter.OptimizedExclusionFilter) ((KnownClassesFilter) KnownClassesFilter.INSTANCE) + .getDelegateSkip()) .getIncluded() .stream() .sorted() diff --git a/documentation/src/main/java/org/talend/runtime/documentation/Github.java b/documentation/src/main/java/org/talend/runtime/documentation/Github.java index c38abde6f1c30..78457b75ce99c 100644 --- a/documentation/src/main/java/org/talend/runtime/documentation/Github.java +++ b/documentation/src/main/java/org/talend/runtime/documentation/Github.java @@ -112,8 +112,8 @@ public Collection load() { .collect(toList()))) .get(); } catch (final ExecutionException ee) { - if (ee.getCause() instanceof WebApplicationException) { - final Response response = ((WebApplicationException) ee.getCause()).getResponse(); + if (ee.getCause() instanceof WebApplicationException wae) { + final Response response = wae.getResponse(); if (response != null && response.getEntity() != null) { log.error(response.readEntity(String.class)); } diff --git a/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java b/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java index 45f84f5a4233d..591c2d79022e8 100644 --- a/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java +++ b/singer-parent/component-kitap/src/main/java/org/talend/sdk/component/singer/kitap/RecordJsonMapper.java @@ -58,7 +58,8 @@ public class RecordJsonMapper implements Function { private final Singer singer; - private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), Json.createGeneratorFactory(emptyMap()), + private final RecordService service = (RecordService) new DefaultServiceProvider(null, JsonProvider.provider(), + Json.createGeneratorFactory(emptyMap()), Json.createReaderFactory(emptyMap()), Json.createBuilderFactory(emptyMap()), Json.createParserFactory(emptyMap()), Json.createWriterFactory(emptyMap()), new JsonbConfig(), JsonbProvider.provider(), null, null, emptyList(), t -> new RecordBuilderFactoryImpl("kitap"), null)