diff --git a/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/common/CosmosUtils.java b/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/common/CosmosUtils.java index 150f719916..dc29f594a5 100644 --- a/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/common/CosmosUtils.java +++ b/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/common/CosmosUtils.java @@ -49,8 +49,7 @@ public static CosmosAccessException cosmosAccessException(CosmosDiagnosticsProce } // Unwrap the exception in case if it is a reactive exception final Throwable unwrappedThrowable = Exceptions.unwrap(throwable); - if (unwrappedThrowable instanceof CosmosException && cosmosDiagnosticsProcessor != null) { - CosmosException cosmosException = (CosmosException) unwrappedThrowable; + if (unwrappedThrowable instanceof CosmosException cosmosException && cosmosDiagnosticsProcessor != null) { processDiagnostics(cosmosDiagnosticsProcessor, operationName, cosmosException.getDiagnostics(), cosmosException.getActivityId(), cosmosException.getRequestCharge()); } diff --git a/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/operations/CosmosSqlPreparedQuery.java b/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/operations/CosmosSqlPreparedQuery.java index b946d126cd..81c1f57377 100644 --- a/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/operations/CosmosSqlPreparedQuery.java +++ b/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/operations/CosmosSqlPreparedQuery.java @@ -73,8 +73,8 @@ public String getUpdate() { } private CosmosSqlStoredQuery getCosmosSqlStoredQuery(StoredQuery storedQuery) { - if (storedQuery instanceof CosmosSqlStoredQuery) { - return (CosmosSqlStoredQuery) storedQuery; + if (storedQuery instanceof CosmosSqlStoredQuery cosmosSqlStoredQuery) { + return cosmosSqlStoredQuery; } throw new IllegalStateException("Expected for stored query query to be of type: CosmosSqlStoredQuery got: " + sqlStoredQuery.getClass().getName()); } diff --git a/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/operations/DefaultReactiveCosmosRepositoryOperations.java b/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/operations/DefaultReactiveCosmosRepositoryOperations.java index 8bd49d3d00..1fd650b344 100644 --- a/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/operations/DefaultReactiveCosmosRepositoryOperations.java +++ b/data-azure-cosmos/src/main/java/io/micronaut/data/cosmos/operations/DefaultReactiveCosmosRepositoryOperations.java @@ -179,8 +179,8 @@ public StoredQuery decorate(MethodInvocationContext context, defaultCosmosSqlQueryBuilder = new CosmosSqlQueryBuilder(context.getAnnotationMetadata()); } String update = null; - if (storedQuery instanceof QueryResultStoredQuery) { - update = ((QueryResultStoredQuery) storedQuery).getQueryResult().getUpdate(); + if (storedQuery instanceof QueryResultStoredQuery queryResultStoredQuery) { + update = queryResultStoredQuery.getQueryResult().getUpdate(); } RuntimePersistentEntity runtimePersistentEntity = runtimeEntityRegistry.getEntity(storedQuery.getRootEntity()); return new CosmosSqlStoredQuery<>(storedQuery, runtimePersistentEntity, defaultCosmosSqlQueryBuilder, update); @@ -561,15 +561,15 @@ private boolean isRawQuery(@NonNull PreparedQuery preparedQuery) { } private SqlPreparedQuery getSqlPreparedQuery(PreparedQuery preparedQuery) { - if (preparedQuery instanceof SqlPreparedQuery) { - return (SqlPreparedQuery) preparedQuery; + if (preparedQuery instanceof SqlPreparedQuery sqlPreparedQuery) { + return sqlPreparedQuery; } throw new IllegalStateException("Expected for prepared query to be of type: SqlPreparedQuery got: " + preparedQuery.getClass().getName()); } private CosmosSqlPreparedQuery getCosmosSqlPreparedQuery(PreparedQuery preparedQuery) { - if (preparedQuery instanceof CosmosSqlPreparedQuery) { - return (CosmosSqlPreparedQuery) preparedQuery; + if (preparedQuery instanceof CosmosSqlPreparedQuery cosmosSqlPreparedQuery) { + return cosmosSqlPreparedQuery; } throw new IllegalStateException("Expected for prepared query to be of type: CosmosSqlPreparedQuery got: " + preparedQuery.getClass().getName()); } @@ -896,8 +896,7 @@ private void setIfMatchETag(CosmosItemRequestOptions requestOptions, ObjectNode } private Throwable handleCosmosOperationException(String message, Throwable e, String operationName, RuntimePersistentEntity persistentEntity) { - if (e instanceof CosmosException) { - CosmosException cosmosException = (CosmosException) e; + if (e instanceof CosmosException cosmosException) { if (cosmosException.getStatusCode() == HttpResponseStatus.PRECONDITION_FAILED.code()) { CosmosEntity cosmosEntity = CosmosEntity.get(persistentEntity); if (cosmosEntity.getVersionField() != null) { diff --git a/data-document-model/src/main/java/io/micronaut/data/document/model/query/builder/CosmosSqlQueryBuilder.java b/data-document-model/src/main/java/io/micronaut/data/document/model/query/builder/CosmosSqlQueryBuilder.java index bc7a4aecb8..af3a45d39a 100644 --- a/data-document-model/src/main/java/io/micronaut/data/document/model/query/builder/CosmosSqlQueryBuilder.java +++ b/data-document-model/src/main/java/io/micronaut/data/document/model/query/builder/CosmosSqlQueryBuilder.java @@ -396,8 +396,8 @@ private void initializeCriteriaHandlers() { appendPropertyRef(whereClause, ctx.getAnnotationMetadata(), ctx.getPersistentEntity(), propertyPath); whereClause.append(COMMA); Object value = criterion.getValue(); - if (value instanceof BindingParameter) { - ctx.pushParameter((BindingParameter) value, newBindingContext(propertyPath.getPropertyPath())); + if (value instanceof BindingParameter bindingParameter) { + ctx.pushParameter(bindingParameter, newBindingContext(propertyPath.getPropertyPath())); } else { asLiterals(ctx.query(), value); } diff --git a/data-document-model/src/main/java/io/micronaut/data/document/model/query/builder/MongoQueryBuilder.java b/data-document-model/src/main/java/io/micronaut/data/document/model/query/builder/MongoQueryBuilder.java index 0f4f69a4e1..e8a58bd43d 100644 --- a/data-document-model/src/main/java/io/micronaut/data/document/model/query/builder/MongoQueryBuilder.java +++ b/data-document-model/src/main/java/io/micronaut/data/document/model/query/builder/MongoQueryBuilder.java @@ -108,7 +108,7 @@ public final class MongoQueryBuilder implements QueryBuilder { return; } if (criterion instanceof QueryModel.PropertyCriterion || criterion instanceof QueryModel.PropertyComparisonCriterion) { - Map neg = new LinkedHashMap<>(); + var neg = new LinkedHashMap(); handleCriterion(ctx, neg, criterion); if (neg.size() != 1) { throw new IllegalStateException("Expected size of 1"); @@ -174,8 +174,8 @@ public final class MongoQueryBuilder implements QueryBuilder { PersistentPropertyPath propertyPath = context.getRequiredProperty(criterion); Object value = criterion.getValue(); String criterionPropertyName = getCriterionPropertyName(criterion.getProperty(), context); - if (value instanceof Iterable) { - List values = CollectionUtils.iterableToList((Iterable) value); + if (value instanceof Iterable iterable) { + List values = CollectionUtils.iterableToList(iterable); obj.put(criterionPropertyName, singletonMap("$in", values.stream().map(val -> valueRepresentation(context, propertyPath, val)).collect(Collectors.toList()))); } else { obj.put(criterionPropertyName, singletonMap("$in", singletonList(valueRepresentation(context, propertyPath, value)))); @@ -185,8 +185,8 @@ public final class MongoQueryBuilder implements QueryBuilder { PersistentPropertyPath propertyPath = context.getRequiredProperty(criterion); Object value = criterion.getValue(); String criterionPropertyName = getCriterionPropertyName(criterion.getProperty(), context); - if (value instanceof Iterable) { - List values = CollectionUtils.iterableToList((Iterable) value); + if (value instanceof Iterable iterable) { + List values = CollectionUtils.iterableToList(iterable); obj.put(criterionPropertyName, singletonMap("$nin", values.stream().map(val -> valueRepresentation(context, propertyPath, val)).collect(Collectors.toList()))); } else { obj.put(criterionPropertyName, singletonMap("$nin", singletonList(valueRepresentation(context, propertyPath, value)))); @@ -223,8 +223,8 @@ public final class MongoQueryBuilder implements QueryBuilder { Object value = criterion.getValue(); String criterionPropertyName = getCriterionPropertyName(criterion.getProperty(), context); Object criteriaValue; - if (value instanceof Iterable) { - List values = CollectionUtils.iterableToList((Iterable) value); + if (value instanceof Iterable iterable) { + List values = CollectionUtils.iterableToList(iterable); criteriaValue = values.stream().map(val -> valueRepresentation(context, propertyPath, val)).collect(Collectors.toList()); } else { criteriaValue = singletonList(valueRepresentation(context, propertyPath, value)); @@ -275,9 +275,9 @@ private void handleRegexPropertyExpress Map regexCriteria = new HashMap<>(2); regexCriteria.put(OPTIONS, ignoreCase ? "i" : ""); String regexValue; - if (value instanceof BindingParameter) { + if (value instanceof BindingParameter bindingParameter) { int index = context.pushParameter( - (BindingParameter) value, + bindingParameter, newBindingContext(propertyPath, propertyPath) ); regexValue = QUERY_PARAMETER_PLACEHOLDER + ":" + index; @@ -336,15 +336,15 @@ private Object valueRepresentation(CriteriaContext context, PersistentPropertyPath inPropertyPath, PersistentPropertyPath outPropertyPath, Object value) { - if (value instanceof LocalDate) { - return singletonMap(MONGO_DATE_IDENTIFIER, formatDate((LocalDate) value)); + if (value instanceof LocalDate localDate) { + return singletonMap(MONGO_DATE_IDENTIFIER, formatDate(localDate)); } - if (value instanceof LocalDateTime) { - return singletonMap(MONGO_DATE_IDENTIFIER, formatDate((LocalDateTime) value)); + if (value instanceof LocalDateTime localDateTime) { + return singletonMap(MONGO_DATE_IDENTIFIER, formatDate(localDateTime)); } - if (value instanceof BindingParameter) { + if (value instanceof BindingParameter bindingParameter) { int index = context.pushParameter( - (BindingParameter) value, + bindingParameter, newBindingContext(inPropertyPath, outPropertyPath) ); return singletonMap(QUERY_PARAMETER_PLACEHOLDER, index); @@ -378,8 +378,8 @@ operator, asList( } private Object asLiteral(@Nullable Object value) { - if (value instanceof RegexPattern) { - return "'" + Pattern.quote(((RegexPattern) value).value) + "'"; + if (value instanceof RegexPattern regexPattern) { + return "'" + Pattern.quote(regexPattern.value) + "'"; } return value; } @@ -576,19 +576,19 @@ private void addLookups(Collection joins, QueryState queryState) { if (mappedByPath == null) { throw new IllegalStateException("Cannot find mapped path: " + mappedBy); } - if (!(mappedByPath.getProperty() instanceof Association)) { + if (!(mappedByPath.getProperty() instanceof Association associationProperty)) { throw new IllegalStateException("Expected association as a mapped path: " + mappedBy); } - List localMatchFields = new ArrayList<>(); - List foreignMatchFields = new ArrayList<>(); + var localMatchFields = new ArrayList(); + var foreignMatchFields = new ArrayList(); traversePersistentProperties(currentLookup.persistentEntity.getIdentity(), (associations, p) -> { String fieldPath = asPath(associations, p); localMatchFields.add(fieldPath); }); - List mappedAssociations = new ArrayList<>(mappedByPath.getAssociations()); - mappedAssociations.add((Association) mappedByPath.getProperty()); + var mappedAssociations = new ArrayList<>(mappedByPath.getAssociations()); + mappedAssociations.add(associationProperty); traversePersistentProperties(mappedAssociations, currentLookup.persistentEntity.getIdentity(), (associations, p) -> { String fieldPath = asPath(associations, p); @@ -603,11 +603,11 @@ private void addLookups(Collection joins, QueryState queryState) { currentPath) ); } else { - List mappedAssociations = new ArrayList<>(propertyPath.getAssociations()); + var mappedAssociations = new ArrayList<>(propertyPath.getAssociations()); mappedAssociations.add((Association) propertyPath.getProperty()); - List localMatchFields = new ArrayList<>(); - List foreignMatchFields = new ArrayList<>(); + var localMatchFields = new ArrayList(); + var foreignMatchFields = new ArrayList(); PersistentProperty identity = lookupStage.persistentEntity.getIdentity(); if (identity == null) { throw new IllegalStateException("Null identity of persistent entity: " + lookupStage.persistentEntity); @@ -645,7 +645,7 @@ private List resolveJoinTableJoinFields(AnnotationMetadata annotationMet if (!joinColumns.isEmpty()) { return joinColumns; } - List fields = new ArrayList<>(); + var fields = new ArrayList(); traversePersistentProperties(entity.getIdentity(), (associations, property) -> { fields.add(asPath(associations, property)); }); @@ -662,7 +662,7 @@ private List resolveJoinTableAssociatedFields(AnnotationMetadata annotat if (identity == null) { throw new MappingException("Cannot have a foreign key association without an ID on entity: " + entity.getName()); } - List fields = new ArrayList<>(); + var fields = new ArrayList(); traversePersistentProperties(identity, (associations, property) -> { fields.add(asPath(associations, property)); }); @@ -679,7 +679,7 @@ private String asPath(List associations, PersistentProperty propert if (associations.isEmpty()) { return getPropertyPersistName(property); } - StringJoiner joiner = new StringJoiner("."); + var joiner = new StringJoiner("."); for (Association association : associations) { joiner.add(getPropertyPersistName(association)); } @@ -934,9 +934,9 @@ public QueryResult buildUpdate(AnnotationMetadata annotationMetadata, QueryModel for (Map.Entry e : propertiesToUpdate.entrySet()) { PersistentPropertyPath propertyPath = findProperty(queryState, e.getKey(), null); String propertyPersistName = getPropertyPersistName(propertyPath.getProperty()); - if (e.getValue() instanceof BindingParameter) { + if (e.getValue() instanceof BindingParameter bindingParameter) { int index = queryState.pushParameter( - (BindingParameter) e.getValue(), + bindingParameter, newBindingContext(propertyPath) ); sets.put(propertyPersistName, singletonMap(QUERY_PARAMETER_PLACEHOLDER, index)); @@ -1043,11 +1043,11 @@ private void appendMap(StringBuilder sb, Map map) { } private boolean skipValue(Object obj) { - if (obj instanceof Map) { - return ((Map) obj).isEmpty(); + if (obj instanceof Map map) { + return map.isEmpty(); } - if (obj instanceof Collection) { - return ((Collection) obj).isEmpty(); + if (obj instanceof Collection collection) { + return collection.isEmpty(); } return false; } @@ -1065,12 +1065,12 @@ private void appendArray(StringBuilder sb, Collection collection) { } private void append(StringBuilder sb, Object obj) { - if (obj instanceof Map) { - appendMap(sb, (Map) obj); - } else if (obj instanceof Collection) { - appendArray(sb, (Collection) obj); - } else if (obj instanceof RawJsonValue) { - sb.append(((RawJsonValue) obj).value); + if (obj instanceof Map map) { + appendMap(sb, map); + } else if (obj instanceof Collection collection) { + appendArray(sb, collection); + } else if (obj instanceof RawJsonValue rawJsonValue) { + sb.append(rawJsonValue.value); } else if (obj == null) { sb.append("null"); } else if (obj instanceof Boolean) { @@ -1078,9 +1078,7 @@ private void append(StringBuilder sb, Object obj) { } else if (obj instanceof Number) { sb.append(obj); } else { - sb.append("'"); - sb.append(obj); - sb.append("'"); + sb.append('\'').append(obj).append('\''); } } diff --git a/data-document-processor/src/main/java/io/micronaut/data/document/processor/matchers/MongoRawQueryMethodMatcher.java b/data-document-processor/src/main/java/io/micronaut/data/document/processor/matchers/MongoRawQueryMethodMatcher.java index 4e002e8d54..8d74f3cc13 100644 --- a/data-document-processor/src/main/java/io/micronaut/data/document/processor/matchers/MongoRawQueryMethodMatcher.java +++ b/data-document-processor/src/main/java/io/micronaut/data/document/processor/matchers/MongoRawQueryMethodMatcher.java @@ -95,9 +95,9 @@ private void removeAnnotation(AnnotationMetadata annotationMetadata, String anno removeAnnotation(hierarchy.getRootMetadata(), annotation); return; } - if (annotationMetadata instanceof MutableAnnotationMetadata) { - ((MutableAnnotationMetadata) annotationMetadata).removeAnnotation(annotation); - ((MutableAnnotationMetadata) annotationMetadata).removeStereotype(annotation); + if (annotationMetadata instanceof MutableAnnotationMetadata mutableAnnotationMetadata) { + mutableAnnotationMetadata.removeAnnotation(annotation); + mutableAnnotationMetadata.removeStereotype(annotation); } } diff --git a/data-hibernate-jpa/src/main/java/io/micronaut/data/hibernate/operations/AbstractHibernateOperations.java b/data-hibernate-jpa/src/main/java/io/micronaut/data/hibernate/operations/AbstractHibernateOperations.java index 0eef2aa998..467de0fbcf 100644 --- a/data-hibernate-jpa/src/main/java/io/micronaut/data/hibernate/operations/AbstractHibernateOperations.java +++ b/data-hibernate-jpa/src/main/java/io/micronaut/data/hibernate/operations/AbstractHibernateOperations.java @@ -453,8 +453,8 @@ public void bindOne(QueryParameterBinding binding, Object value) { Collection coll; if (value == null) { coll = Collections.emptyList(); - } else if (value instanceof Collection) { - coll = (Collection) value; + } else if (value instanceof Collection collection) { + coll = collection; } else { coll = Arrays.asList((Object[]) value); } @@ -633,8 +633,8 @@ private void bindCriteriaSort(CriteriaQuery criteriaQuery, Root root, } private BindableParametersPreparedQuery getBindableParametersPreparedQuery(PreparedQuery preparedQuery) { - if (preparedQuery instanceof BindableParametersPreparedQuery) { - return (BindableParametersPreparedQuery) preparedQuery; + if (preparedQuery instanceof BindableParametersPreparedQuery bindableParametersPreparedQuery) { + return bindableParametersPreparedQuery; } throw new IllegalStateException("Expected for prepared query to be of type: BindableParametersPreparedQuery"); } diff --git a/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/AbstractSpecificationInterceptor.java b/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/AbstractSpecificationInterceptor.java index b31626743c..655ee1327e 100644 --- a/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/AbstractSpecificationInterceptor.java +++ b/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/AbstractSpecificationInterceptor.java @@ -51,10 +51,10 @@ public abstract class AbstractSpecificationInterceptor extends AbstractPublisher */ protected AbstractSpecificationInterceptor(RepositoryOperations operations) { super(operations); - if (operations instanceof ReactiveCapableRepository) { - ReactiveRepositoryOperations reactive = ((ReactiveCapableRepository) operations).reactive(); - if (reactive instanceof HibernateReactorRepositoryOperations) { - this.operations = (HibernateReactorRepositoryOperations) reactive; + if (operations instanceof ReactiveCapableRepository reactiveCapableRepository) { + ReactiveRepositoryOperations reactive = reactiveCapableRepository.reactive(); + if (reactive instanceof HibernateReactorRepositoryOperations hibernateReactorRepositoryOperations) { + this.operations = hibernateReactorRepositoryOperations; } else { throw new IllegalStateException("Reactive repository operations must be na instance of HibernateReactorRepositoryOperations"); } @@ -70,8 +70,8 @@ protected AbstractSpecificationInterceptor(RepositoryOperations operations) { */ protected Specification getSpecification(MethodInvocationContext context) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof Specification) { - return (Specification) parameterValue; + if (parameterValue instanceof Specification specification) { + return specification; } if (parameterValue == null) { // parameter is nullable diff --git a/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/ReactiveFindAllSpecificationInterceptor.java b/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/ReactiveFindAllSpecificationInterceptor.java index 35e92198d4..62d7f7a72d 100644 --- a/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/ReactiveFindAllSpecificationInterceptor.java +++ b/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/ReactiveFindAllSpecificationInterceptor.java @@ -78,8 +78,7 @@ protected Publisher interceptPublisher(RepositoryMethodKey methodKey, MethodI */ private void addSort(Object sortObject, CriteriaQuery query, Root root, CriteriaBuilder criteriaBuilder) { - if (sortObject instanceof Sort) { - Sort sort = (Sort) sortObject; + if (sortObject instanceof Sort sort) { if (sort.isSorted()) { query.orderBy(getOrders(sort, root, criteriaBuilder)); } diff --git a/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/ReactiveFindPageSpecificationInterceptor.java b/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/ReactiveFindPageSpecificationInterceptor.java index 08a8f10264..4142a959c9 100644 --- a/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/ReactiveFindPageSpecificationInterceptor.java +++ b/data-hibernate-reactive/src/main/java/io/micronaut/data/hibernate/reactive/repository/jpa/intercept/ReactiveFindPageSpecificationInterceptor.java @@ -54,8 +54,8 @@ protected ReactiveFindPageSpecificationInterceptor(@NonNull RepositoryOperations @Override protected final Pageable getPageable(MethodInvocationContext context) { final Object parameterValue = context.getParameterValues()[1]; - if (parameterValue instanceof Pageable) { - return (Pageable) parameterValue; + if (parameterValue instanceof Pageable pageable) { + return pageable; } return Pageable.UNPAGED; } diff --git a/data-jdbc/src/main/java/io/micronaut/data/jdbc/mapper/JdbcQueryStatement.java b/data-jdbc/src/main/java/io/micronaut/data/jdbc/mapper/JdbcQueryStatement.java index a9925d90f8..9a79ccada6 100644 --- a/data-jdbc/src/main/java/io/micronaut/data/jdbc/mapper/JdbcQueryStatement.java +++ b/data-jdbc/src/main/java/io/micronaut/data/jdbc/mapper/JdbcQueryStatement.java @@ -146,12 +146,12 @@ public QueryStatement setTime(PreparedStatement stat @Override public QueryStatement setValue(PreparedStatement statement, Integer index, Object value) throws DataAccessException { try { - if (value instanceof Clob) { - statement.setClob(index, (Clob) value); - } else if (value instanceof Blob) { - statement.setBlob(index, (Blob) value); - } else if (value instanceof Array) { - statement.setArray(index, (Array) value); + if (value instanceof Clob clob) { + statement.setClob(index, clob); + } else if (value instanceof Blob blob) { + statement.setBlob(index, blob); + } else if (value instanceof Array array) { + statement.setArray(index, array); } else if (value != null) { if (value.getClass().isEnum()) { statement.setObject(index, value, Types.OTHER); @@ -310,8 +310,8 @@ public QueryStatement setArray(PreparedStatement sta try { if (array == null) { statement.setNull(name, Types.ARRAY); - } else if (array instanceof Array) { - statement.setArray(name, (Array) array); + } else if (array instanceof Array array1) { + statement.setArray(name, array1); } else { statement.setObject(name, array); } diff --git a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/AbstractSpecificationInterceptor.java b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/AbstractSpecificationInterceptor.java index fda1fa03af..60a52e957e 100644 --- a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/AbstractSpecificationInterceptor.java +++ b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/AbstractSpecificationInterceptor.java @@ -57,8 +57,8 @@ protected AbstractSpecificationInterceptor(RepositoryOperations operations) { */ protected Specification getSpecification(MethodInvocationContext context, boolean nullable) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof Specification) { - return (Specification) parameterValue; + if (parameterValue instanceof Specification specification) { + return specification; } if (parameterValue == null) { if (nullable) { diff --git a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/CountSpecificationInterceptor.java b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/CountSpecificationInterceptor.java index 590a7a9898..76767eb5b9 100644 --- a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/CountSpecificationInterceptor.java +++ b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/CountSpecificationInterceptor.java @@ -50,8 +50,8 @@ public class CountSpecificationInterceptor extends AbstractSpecificationIntercep */ public CountSpecificationInterceptor(@NonNull RepositoryOperations operations) { super(operations); - if (operations instanceof JpaRepositoryOperations) { - this.jpaOperations = (JpaRepositoryOperations) operations; + if (operations instanceof JpaRepositoryOperations jpaRepositoryOperations) { + this.jpaOperations = jpaRepositoryOperations; } else { throw new IllegalStateException("Repository operations must be na instance of JpaRepositoryOperations"); } diff --git a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindAllSpecificationInterceptor.java b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindAllSpecificationInterceptor.java index 35ec809efe..b866399eb6 100644 --- a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindAllSpecificationInterceptor.java +++ b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindAllSpecificationInterceptor.java @@ -48,8 +48,8 @@ public class FindAllSpecificationInterceptor extends AbstractSpecificationInterc */ protected FindAllSpecificationInterceptor(@NonNull RepositoryOperations operations) { super(operations); - if (operations instanceof JpaRepositoryOperations) { - this.jpaOperations = (JpaRepositoryOperations) operations; + if (operations instanceof JpaRepositoryOperations jpaRepositoryOperations) { + this.jpaOperations = jpaRepositoryOperations; } else { throw new IllegalStateException("Repository operations must be na instance of JpaRepositoryOperations"); } @@ -84,8 +84,7 @@ public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext query, Root root, CriteriaBuilder criteriaBuilder) { - if (sortObject instanceof Sort) { - Sort sort = (Sort) sortObject; + if (sortObject instanceof Sort sort) { if (sort.isSorted()) { query.orderBy(getOrders(sort, root, criteriaBuilder)); } diff --git a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindOneSpecificationInterceptor.java b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindOneSpecificationInterceptor.java index 89d2b8f1ae..11706f565d 100644 --- a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindOneSpecificationInterceptor.java +++ b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindOneSpecificationInterceptor.java @@ -52,8 +52,8 @@ public class FindOneSpecificationInterceptor extends AbstractSpecificationInterc */ protected FindOneSpecificationInterceptor(@NonNull RepositoryOperations operations) { super(operations); - if (operations instanceof JpaRepositoryOperations) { - this.jpaOperations = (JpaRepositoryOperations) operations; + if (operations instanceof JpaRepositoryOperations jpaRepositoryOperations) { + this.jpaOperations = jpaRepositoryOperations; } else { throw new IllegalStateException("Repository operations must be na instance of JpaRepositoryOperations"); } diff --git a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindPageSpecificationInterceptor.java b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindPageSpecificationInterceptor.java index 42c98be0b7..505c247604 100644 --- a/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindPageSpecificationInterceptor.java +++ b/data-jpa/src/main/java/io/micronaut/data/jpa/repository/intercept/FindPageSpecificationInterceptor.java @@ -52,8 +52,8 @@ public class FindPageSpecificationInterceptor extends AbstractSpecificationInter */ protected FindPageSpecificationInterceptor(@NonNull RepositoryOperations operations) { super(operations); - if (operations instanceof JpaRepositoryOperations) { - this.jpaOperations = (JpaRepositoryOperations) operations; + if (operations instanceof JpaRepositoryOperations jpaRepositoryOperations) { + this.jpaOperations = jpaRepositoryOperations; } else { throw new IllegalStateException("Repository operations must be na instance of JpaRepositoryOperations"); } @@ -62,8 +62,8 @@ protected FindPageSpecificationInterceptor(@NonNull RepositoryOperations operati @Override protected final Pageable getPageable(MethodInvocationContext context) { final Object parameterValue = context.getParameterValues()[1]; - if (parameterValue instanceof Pageable) { - return (Pageable) parameterValue; + if (parameterValue instanceof Pageable pageable) { + return pageable; } return Pageable.UNPAGED; } diff --git a/data-model/src/main/java/io/micronaut/data/model/Association.java b/data-model/src/main/java/io/micronaut/data/model/Association.java index 94e649b81b..48408f70c4 100644 --- a/data-model/src/main/java/io/micronaut/data/model/Association.java +++ b/data-model/src/main/java/io/micronaut/data/model/Association.java @@ -74,8 +74,8 @@ default Optional getInverseSide() { .stringValue(Relation.class, "mappedBy") .flatMap(s -> { final PersistentProperty persistentProperty = getAssociatedEntity().getPropertyByPath(s).orElse(null); - if (persistentProperty instanceof Association) { - return Optional.of((Association) persistentProperty); + if (persistentProperty instanceof Association association) { + return Optional.of(association); } return Optional.empty(); }); @@ -91,8 +91,8 @@ default Optional getInversePathSide() { .stringValue(Relation.class, "mappedBy") .flatMap(s -> { final PersistentPropertyPath persistentPropertyPath = getAssociatedEntity().getPropertyPath(s); - if (persistentPropertyPath instanceof PersistentAssociationPath) { - return Optional.of((PersistentAssociationPath) persistentPropertyPath); + if (persistentPropertyPath instanceof PersistentAssociationPath persistentAssociationPath) { + return Optional.of(persistentAssociationPath); } return Optional.empty(); }); diff --git a/data-model/src/main/java/io/micronaut/data/model/PersistentEntity.java b/data-model/src/main/java/io/micronaut/data/model/PersistentEntity.java index 6958f48245..b63fbe3176 100644 --- a/data-model/src/main/java/io/micronaut/data/model/PersistentEntity.java +++ b/data-model/src/main/java/io/micronaut/data/model/PersistentEntity.java @@ -234,19 +234,19 @@ default Optional getPath(String camelCasePath) { if (identity != null) { if (identity.getName().equals(name)) { sp = identity; - } else if (identity instanceof Association) { - PersistentEntity idEntity = ((Association) identity).getAssociatedEntity(); + } else if (identity instanceof Association association) { + PersistentEntity idEntity = association.getAssociatedEntity(); sp = idEntity.getPropertyByName(name); } } } if (sp != null) { - if (sp instanceof Association) { + if (sp instanceof Association association) { b.append(name); if (i.hasNext()) { b.append('.'); } - currentEntity = ((Association) sp).getAssociatedEntity(); + currentEntity = association.getAssociatedEntity(); name = null; } else if (!i.hasNext()) { b.append(name); @@ -254,7 +254,7 @@ default Optional getPath(String camelCasePath) { } } - return b.length() == 0 || b.charAt(b.length() - 1) == '.' ? Optional.empty() : Optional.of(b.toString()); + return b.isEmpty() || b.charAt(b.length() - 1) == '.' ? Optional.empty() : Optional.of(b.toString()); } return Optional.empty(); @@ -290,8 +290,8 @@ default Optional getPropertyByPath(String path) { if (identity != null) { if (identity.getName().equals(path)) { pp = identity; - } else if (identity instanceof Embedded) { - PersistentEntity idEntity = ((Embedded) identity).getAssociatedEntity(); + } else if (identity instanceof Embedded embedded) { + PersistentEntity idEntity = embedded.getAssociatedEntity(); pp = idEntity.getPropertyByName(path); } } @@ -311,8 +311,8 @@ default Optional getPropertyByPath(String path) { return Optional.empty(); } } - if (prop instanceof Association) { - startingEntity = ((Association) prop).getAssociatedEntity(); + if (prop instanceof Association association) { + startingEntity = association.getAssociatedEntity(); } } return Optional.ofNullable(prop); @@ -352,8 +352,8 @@ default PersistentPropertyPath getPropertyPath(@NonNull String[] propertyPath) { if (identity != null) { if (identity.getName().equals(propertyName)) { pp = identity; - } else if (identity instanceof Embedded) { - PersistentEntity idEntity = ((Embedded) identity).getAssociatedEntity(); + } else if (identity instanceof Embedded embedded) { + PersistentEntity idEntity = embedded.getAssociatedEntity(); pp = idEntity.getPropertyByName(propertyName); if (pp != null) { return PersistentPropertyPath.of(Collections.singletonList((Embedded) identity), pp, identity.getName() + "." + pp.getName()); diff --git a/data-model/src/main/java/io/micronaut/data/model/PersistentPropertyPath.java b/data-model/src/main/java/io/micronaut/data/model/PersistentPropertyPath.java index 0e3003bad3..d800c18cd6 100644 --- a/data-model/src/main/java/io/micronaut/data/model/PersistentPropertyPath.java +++ b/data-model/src/main/java/io/micronaut/data/model/PersistentPropertyPath.java @@ -81,8 +81,8 @@ public static PersistentPropertyPath of(List associations, @NonNull * @return new instance of {@link PersistentPropertyPath} or {@link PersistentAssociationPath} */ public static PersistentPropertyPath of(List associations, @NonNull PersistentProperty property, @Nullable String path) { - if (property instanceof Association) { - return new PersistentAssociationPath(associations, (Association) property, path); + if (property instanceof Association association) { + return new PersistentAssociationPath(associations, association, path); } return new PersistentPropertyPath(associations, property, path); } @@ -96,10 +96,10 @@ public static PersistentPropertyPath of(List associations, @NonNull * @return The root bean - possibly modified */ public Object setPropertyValue(Object bean, Object value) { - if (!(property instanceof RuntimePersistentProperty)) { + if (!(property instanceof RuntimePersistentProperty runtimeProperty)) { throw new IllegalStateException("Expected runtime property!"); } - return setProperty(associations, (RuntimePersistentProperty) property, bean, value); + return setProperty(associations, runtimeProperty, bean, value); } private Object setProperty(List associations, RuntimePersistentProperty property, Object bean, Object value) { @@ -134,7 +134,7 @@ private X setProperty(BeanProperty beanProperty, X x, Y y) { * @return The value */ public Object getPropertyValue(Object bean) { - if (!(property instanceof RuntimePersistentProperty)) { + if (!(property instanceof RuntimePersistentProperty p)) { throw new IllegalStateException("Expected runtime property!"); } Object value = bean; @@ -146,7 +146,6 @@ public Object getPropertyValue(Object bean) { return null; } } - RuntimePersistentProperty p = (RuntimePersistentProperty) property; if (value != null) { BeanProperty beanProperty = p.getProperty(); value = beanProperty.get(value); diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaDelete.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaDelete.java index c8a406e44c..05aeae3535 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaDelete.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaDelete.java @@ -66,15 +66,13 @@ public QueryModel getQueryModel() { } QueryModel qm = QueryModel.from(entityRoot.getPersistentEntity()); Joiner joiner = new Joiner(); - if (predicate instanceof PredicateVisitable) { - PredicateVisitable predicate = (PredicateVisitable) this.predicate; - predicate.accept(createPredicateVisitor(qm)); - predicate.accept(joiner); + if (predicate instanceof PredicateVisitable predicateVisitable) { + predicateVisitable.accept(createPredicateVisitor(qm)); + predicateVisitable.accept(joiner); } - if (returning instanceof SelectionVisitable) { - SelectionVisitable selection = (SelectionVisitable) this.returning; - selection.accept(new QueryModelSelectionVisitor(qm, false)); - selection.accept(joiner); + if (returning instanceof SelectionVisitable selectionVisitable) { + selectionVisitable.accept(new QueryModelSelectionVisitor(qm, false)); + selectionVisitable.accept(joiner); } for (Map.Entry e : joiner.getJoins().entrySet()) { qm.join(e.getKey(), Optional.ofNullable(e.getValue().getType()).orElse(Join.Type.DEFAULT), e.getValue().getAlias()); diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaQuery.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaQuery.java index 69d34912b9..2aab0476e7 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaQuery.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaQuery.java @@ -95,15 +95,13 @@ public QueryModel getQueryModel() { } QueryModel qm = QueryModel.from(entityRoot.getPersistentEntity()); Joiner joiner = new Joiner(); - if (predicate instanceof PredicateVisitable) { - PredicateVisitable predicate = (PredicateVisitable) this.predicate; - predicate.accept(createPredicateVisitor(qm)); - predicate.accept(joiner); + if (predicate instanceof PredicateVisitable predicateVisitable) { + predicateVisitable.accept(createPredicateVisitor(qm)); + predicateVisitable.accept(joiner); } - if (selection instanceof SelectionVisitable) { - SelectionVisitable selection = (SelectionVisitable) this.selection; - selection.accept(new QueryModelSelectionVisitor(qm, distinct)); - selection.accept(joiner); + if (selection instanceof SelectionVisitable selectionVisitable) { + selectionVisitable.accept(new QueryModelSelectionVisitor(qm, distinct)); + selectionVisitable.accept(joiner); SelectionVisitable entityRoot = (SelectionVisitable) this.entityRoot; entityRoot.accept(joiner); } else { diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaUpdate.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaUpdate.java index 479f027171..65f6e1bb76 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaUpdate.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityCriteriaUpdate.java @@ -82,15 +82,13 @@ public QueryModel getQueryModel() { } QueryModel qm = QueryModel.from(entityRoot.getPersistentEntity()); Joiner joiner = new Joiner(); - if (predicate instanceof PredicateVisitable) { - PredicateVisitable predicate = (PredicateVisitable) this.predicate; - predicate.accept(createPredicateVisitor(qm)); - predicate.accept(joiner); + if (predicate instanceof PredicateVisitable predicateVisitable) { + predicateVisitable.accept(createPredicateVisitor(qm)); + predicateVisitable.accept(joiner); } - if (returning instanceof SelectionVisitable) { - SelectionVisitable selection = (SelectionVisitable) this.returning; - selection.accept(new QueryModelSelectionVisitor(qm, false)); - selection.accept(joiner); + if (returning instanceof SelectionVisitable selectionVisitable) { + selectionVisitable.accept(new QueryModelSelectionVisitor(qm, false)); + selectionVisitable.accept(joiner); } for (Map.Entry e : joiner.getJoins().entrySet()) { qm.join(e.getKey(), Optional.ofNullable(e.getValue().getType()).orElse(Join.Type.DEFAULT), e.getValue().getAlias()); diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityJoinSupport.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityJoinSupport.java index 3e9d70057f..5943fd04fd 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityJoinSupport.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/AbstractPersistentEntityJoinSupport.java @@ -75,11 +75,11 @@ protected abstract PersistentAssociationPath createJoinAssociation( private PersistentAssociationPath getJoin(String attributeName, io.micronaut.data.annotation.Join.Type type, String alias) { PersistentProperty persistentProperty = getPersistentEntity().getPropertyByName(attributeName); - if (!(persistentProperty instanceof Association)) { + if (!(persistentProperty instanceof Association association)) { throw new IllegalStateException("Expected an association for attribute name: " + attributeName); } - PersistentAssociationPath path = joins.computeIfAbsent(attributeName, a -> createJoinAssociation((Association) persistentProperty, type, alias)); + PersistentAssociationPath path = joins.computeIfAbsent(attributeName, a -> createJoinAssociation(association, type, alias)); if (type != null && type != io.micronaut.data.annotation.Join.Type.DEFAULT) { path.setAssociationJoinType(type); @@ -92,26 +92,26 @@ private PersistentAssociationPath getJoin(String attributeName, io. private PersistentCollectionAssociationPath getCollectionJoin(String attributeName, io.micronaut.data.annotation.Join.Type type, String alias) { PersistentAssociationPath join = getJoin(attributeName, type, alias); - if (!(join instanceof PersistentCollectionAssociationPath)) { + if (!(join instanceof PersistentCollectionAssociationPath persistentCollectionAssociationPath)) { throw new IllegalStateException("Join is not a Collection!"); } - return (PersistentCollectionAssociationPath) join; + return persistentCollectionAssociationPath; } private PersistentSetAssociationPath getSetJoin(String attributeName, io.micronaut.data.annotation.Join.Type type, String alias) { PersistentAssociationPath join = getJoin(attributeName, type, alias); - if (!(join instanceof PersistentSetAssociationPath)) { + if (!(join instanceof PersistentSetAssociationPath persistentSetAssociationPath)) { throw new IllegalStateException("Join is not a Set!"); } - return (PersistentSetAssociationPath) join; + return persistentSetAssociationPath; } private PersistentListAssociationPath getListJoin(String attributeName, io.micronaut.data.annotation.Join.Type type, String alias) { PersistentAssociationPath join = getJoin(attributeName, type, alias); - if (!(join instanceof PersistentListAssociationPath)) { + if (!(join instanceof PersistentListAssociationPath persistentListAssociationPath)) { throw new IllegalStateException("Join is not a List!"); } - return (PersistentListAssociationPath) join; + return persistentListAssociationPath; } @Override diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/CriteriaUtils.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/CriteriaUtils.java index 3efdebb2fb..0d5300e9e2 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/CriteriaUtils.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/CriteriaUtils.java @@ -67,8 +67,7 @@ public static List> requireBoolExpressions(Iterable requireBoolExpression(Expression exp) { - if (exp instanceof IExpression) { - IExpression expression = (IExpression) exp; + if (exp instanceof IExpression expression) { if (!expression.isBoolean()) { throw new IllegalStateException("Expected a boolean expression! Got: " + exp); } @@ -78,8 +77,7 @@ public static IExpression requireBoolExpression(Expression exp) { } public static PersistentPropertyPath requireBoolProperty(Expression exp) { - if (exp instanceof PersistentPropertyPath) { - PersistentPropertyPath propertyPath = (PersistentPropertyPath) exp; + if (exp instanceof PersistentPropertyPath propertyPath) { if (!propertyPath.isBoolean()) { throw new IllegalStateException("Expected a boolean expression property! Got: " + exp); } @@ -120,8 +118,8 @@ public static Expression requireComparablePropertyParameterOrLiteral(Expr // TODO: validation return exp; } - if (exp instanceof LiteralExpression) { - if (((LiteralExpression) exp).getValue() instanceof Comparable) { + if (exp instanceof LiteralExpression tLiteralExpression) { + if (tLiteralExpression.getValue() instanceof Comparable) { return exp; } throw new IllegalStateException("Expected a comparable expression property! Got: " + exp); @@ -149,15 +147,15 @@ public static Expression requireNumericPropertyParameterOrLiteral(Express } public static ParameterExpression requireParameter(Expression exp) { - if (exp instanceof ParameterExpression) { - return (ParameterExpression) exp; + if (exp instanceof ParameterExpression parameterExpression) { + return parameterExpression; } throw new IllegalStateException("Expression is expected to be a parameter! Got: " + exp); } public static PersistentPropertyPath requireProperty(Expression exp) { - if (exp instanceof PersistentPropertyPath) { - return (PersistentPropertyPath) exp; + if (exp instanceof PersistentPropertyPath persistentPropertyPath) { + return persistentPropertyPath; } throw new IllegalStateException("Expression is expected to be a property path! Got: " + exp); } @@ -212,13 +210,13 @@ public static Set> extractPredicateParameters(Expression< private static void extractPredicateParameters(Expression predicate, Set> parameters) { if (predicate instanceof PersistentPropertyBinaryPredicate pp) { - if (pp.getExpression() instanceof ParameterExpression) { - parameters.add((ParameterExpression) pp.getExpression()); + if (pp.getExpression() instanceof ParameterExpression parameterExpression) { + parameters.add(parameterExpression); } } else if (predicate instanceof PersistentPropertyInValuesPredicate pp) { for (Expression expression : pp.getValues()) { - if (expression instanceof ParameterExpression) { - parameters.add((ParameterExpression) expression); + if (expression instanceof ParameterExpression parameterExpression) { + parameters.add(parameterExpression); } } } else if (predicate instanceof ConjunctionPredicate conjunctionPredicate) { diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/predicate/NegatedPredicate.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/predicate/NegatedPredicate.java index f5ce27d324..ffe3efe369 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/predicate/NegatedPredicate.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/predicate/NegatedPredicate.java @@ -46,8 +46,8 @@ public boolean isNegated() { @Override public Predicate not() { - if (negated instanceof Predicate) { - return ((Predicate) negated).not(); + if (negated instanceof Predicate predicate) { + return predicate.not(); } throw new IllegalStateException("Cannot negate predicate: " + negated); } diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/query/QueryModelPredicateVisitor.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/query/QueryModelPredicateVisitor.java index 51ff39a77d..6da1f11f3a 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/query/QueryModelPredicateVisitor.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/query/QueryModelPredicateVisitor.java @@ -64,8 +64,8 @@ public QueryModelPredicateVisitor(QueryModel queryModel) { } private void visit(IExpression expression) { - if (expression instanceof PredicateVisitable) { - ((PredicateVisitable) expression).accept(this); + if (expression instanceof PredicateVisitable predicateVisitable) { + predicateVisitable.accept(this); } else if (expression instanceof PersistentPropertyPath propertyPath) { // TODO add(Restrictions.isTrue(getPropertyPath(propertyPath))); @@ -135,18 +135,18 @@ public void visit(PersistentPropertyBinaryPredicate propertyToExpressionOp) { } private void visitPropertyPathPredicate(PersistentPropertyPath propertyPath, Expression expression, PredicateBinaryOp op) { - if (expression instanceof PersistentPropertyPath) { + if (expression instanceof PersistentPropertyPath persistentPropertyPath) { add(getPropertyToPropertyRestriction(op, propertyPath, - (PersistentPropertyPath) expression)); + persistentPropertyPath)); } else if (expression instanceof ParameterExpression) { add(getPropertyToValueRestriction(op, propertyPath, expression)); - } else if (expression instanceof LiteralExpression) { + } else if (expression instanceof LiteralExpression literalExpression) { add(getPropertyToValueRestriction(op, propertyPath, - ((LiteralExpression) expression).getValue())); + literalExpression.getValue())); } else { throw new IllegalStateException("Unsupported expression: " + expression); } @@ -156,8 +156,8 @@ private void visitPropertyPathPredicate(PersistentPropertyPath propertyPath, public void visit(ExpressionBinaryPredicate expressionBinaryPredicate) { Expression left = expressionBinaryPredicate.getLeft(); PredicateBinaryOp op = expressionBinaryPredicate.getOp(); - if (left instanceof PersistentPropertyPath) { - visitPropertyPathPredicate((PersistentPropertyPath) left, + if (left instanceof PersistentPropertyPath persistentPropertyPath) { + visitPropertyPathPredicate(persistentPropertyPath, expressionBinaryPredicate.getRight(), op); } else if (left instanceof IdExpression) { @@ -334,8 +334,8 @@ public void visit(PersistentPropertyInValuesPredicate inValues) { } private Object asValue(Object value) { - if (value instanceof LiteralExpression) { - return ((LiteralExpression) value).getValue(); + if (value instanceof LiteralExpression literalExpression) { + return literalExpression.getValue(); } return value; } diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/query/QueryModelSelectionVisitor.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/query/QueryModelSelectionVisitor.java index 21e42c2f8c..fbc38b3bfb 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/query/QueryModelSelectionVisitor.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/query/QueryModelSelectionVisitor.java @@ -99,8 +99,8 @@ private QueryModel.Projection getProjection(AggregateExpression aggregateE case COUNT_DISTINCT -> { if (expression instanceof PersistentEntityRoot) { return Projections.countDistinctRoot(); - } else if (expression instanceof PersistentPropertyPath) { - return Projections.countDistinct(((PersistentPropertyPath) expression).getPathAsString()); + } else if (expression instanceof PersistentPropertyPath persistentPropertyPath) { + return Projections.countDistinct(persistentPropertyPath.getPathAsString()); } else { throw new IllegalStateException("Illegal expression: " + expression + " for count distinct selection!"); } @@ -167,8 +167,8 @@ public void visit(AliasedSelection aliasedSelection) { } private void addProjection(QueryModel.Projection projection) { - if (projection instanceof QueryModel.PropertyProjection && alias != null) { - ((QueryModel.PropertyProjection) projection).setAlias(alias); + if (projection instanceof QueryModel.PropertyProjection propertyProjection && alias != null) { + propertyProjection.setAlias(alias); } queryModel.projections().add(projection); } diff --git a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/util/Joiner.java b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/util/Joiner.java index c382a81bef..adea808dc0 100644 --- a/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/util/Joiner.java +++ b/data-model/src/main/java/io/micronaut/data/model/jpa/criteria/impl/util/Joiner.java @@ -151,16 +151,16 @@ private void visitJoins(Set> j } private void visitPredicateExpression(Expression expression) { - if (expression instanceof PredicateVisitable) { - ((PredicateVisitable) expression).accept(this); - } else if (expression instanceof PersistentPropertyPath) { - joinIfNeeded((PersistentPropertyPath) expression, true); + if (expression instanceof PredicateVisitable predicateVisitable) { + predicateVisitable.accept(this); + } else if (expression instanceof PersistentPropertyPath persistentPropertyPath) { + joinIfNeeded(persistentPropertyPath, true); } } private void visitSelectionExpression(Expression expression) { - if (expression instanceof PersistentPropertyPath) { - joinIfNeeded((PersistentPropertyPath) expression, false); + if (expression instanceof PersistentPropertyPath persistentPropertyPath) { + joinIfNeeded(persistentPropertyPath, false); } } @@ -182,8 +182,8 @@ public void visit(AliasedSelection aliasedSelection) { @Override public void visit(CompoundSelection compoundSelection) { for (Selection selection : compoundSelection.getCompoundSelectionItems()) { - if (selection instanceof SelectionVisitable) { - ((SelectionVisitable) selection).accept(this); + if (selection instanceof SelectionVisitable selectionVisitable) { + selectionVisitable.accept(this); } else { throw new IllegalStateException("Unknown selection object: " + selection); } diff --git a/data-model/src/main/java/io/micronaut/data/model/naming/NamingStrategy.java b/data-model/src/main/java/io/micronaut/data/model/naming/NamingStrategy.java index da368ad287..13828037df 100644 --- a/data-model/src/main/java/io/micronaut/data/model/naming/NamingStrategy.java +++ b/data-model/src/main/java/io/micronaut/data/model/naming/NamingStrategy.java @@ -94,8 +94,8 @@ public interface NamingStrategy { */ default @NonNull String mappedName(@NonNull PersistentProperty property) { ArgumentUtils.requireNonNull("property", property); - if (property instanceof Association) { - return mappedName((Association) property); + if (property instanceof Association association) { + return mappedName(association); } else { return property.getAnnotationMetadata() .stringValue(MappedProperty.class) diff --git a/data-model/src/main/java/io/micronaut/data/model/query/DefaultQuery.java b/data-model/src/main/java/io/micronaut/data/model/query/DefaultQuery.java index cb8c76b422..71138c6775 100644 --- a/data-model/src/main/java/io/micronaut/data/model/query/DefaultQuery.java +++ b/data-model/src/main/java/io/micronaut/data/model/query/DefaultQuery.java @@ -272,8 +272,7 @@ public QueryModel sort(@NonNull Sort sort) { * @return This query instance */ @Override - public @NonNull - DefaultQuery eq(@NonNull String property, @NonNull Object parameter) { + public @NonNull DefaultQuery eq(@NonNull String property, @NonNull Object parameter) { criteria.add(Restrictions.eq(property, parameter)); return this; } @@ -285,12 +284,10 @@ DefaultQuery eq(@NonNull String property, @NonNull Object parameter) { * @return This query instance */ @Override - public @NonNull - DefaultQuery allEq(@NonNull Map values) { + public @NonNull DefaultQuery allEq(@NonNull Map values) { QueryModel.Junction conjunction = conjunction(); - for (String property : values.keySet()) { - Object value = values.get(property); - conjunction.add(Restrictions.eq(property, value)); + for (var entry : values.entrySet()) { + conjunction.add(Restrictions.eq(entry.getKey(), entry.getValue())); } return this; } diff --git a/data-model/src/main/java/io/micronaut/data/model/query/builder/AbstractSqlLikeQueryBuilder.java b/data-model/src/main/java/io/micronaut/data/model/query/builder/AbstractSqlLikeQueryBuilder.java index 60a1e5f5b7..60b02b235f 100644 --- a/data-model/src/main/java/io/micronaut/data/model/query/builder/AbstractSqlLikeQueryBuilder.java +++ b/data-model/src/main/java/io/micronaut/data/model/query/builder/AbstractSqlLikeQueryBuilder.java @@ -75,7 +75,7 @@ * @author graemerocher * @since 1.0.0 */ -@SuppressWarnings("checkstyle:FileLength") +@SuppressWarnings("FileLength") public abstract class AbstractSqlLikeQueryBuilder implements QueryBuilder { public static final String ORDER_BY_CLAUSE = " ORDER BY "; protected static final String SELECT_CLAUSE = "SELECT "; @@ -260,8 +260,8 @@ public abstract class AbstractSqlLikeQueryBuilder implements QueryBuilder { appendPropertyRef(whereClause, ctx.getAnnotationMetadata(), ctx.getPersistentEntity(), propertyPath); whereClause.append(" IN ("); Object value = inQuery.getValue(); - if (value instanceof BindingParameter) { - ctx.pushParameter((BindingParameter) value, newBindingContext(propertyPath.propertyPath).expandable()); + if (value instanceof BindingParameter bindingParameter) { + ctx.pushParameter(bindingParameter, newBindingContext(propertyPath.propertyPath).expandable()); } else { asLiterals(ctx.query(), value); } @@ -274,8 +274,8 @@ public abstract class AbstractSqlLikeQueryBuilder implements QueryBuilder { appendPropertyRef(whereClause, ctx.getAnnotationMetadata(), ctx.getPersistentEntity(), propertyPath); whereClause.append(" NOT IN ("); Object value = inQuery.getValue(); - if (value instanceof BindingParameter) { - ctx.pushParameter((BindingParameter) value, newBindingContext(propertyPath.propertyPath).expandable()); + if (value instanceof BindingParameter bindingParameter) { + ctx.pushParameter(bindingParameter, newBindingContext(propertyPath.propertyPath).expandable()); } else { asLiterals(ctx.query(), value); } @@ -332,14 +332,14 @@ protected void asLiterals(StringBuilder sb, @Nullable Object value) { */ @NonNull protected String asLiteral(@Nullable Object value) { - if (value instanceof LiteralExpression) { - value = ((LiteralExpression) value).getValue(); + if (value instanceof LiteralExpression literalExpression) { + value = literalExpression.getValue(); } if (value == null) { return "NULL"; } - if (value instanceof Number) { - return Long.toString(((Number) value).longValue()); + if (value instanceof Number number) { + return Long.toString(number.longValue()); } if (value instanceof Boolean) { return value.toString().toUpperCase(Locale.ROOT); @@ -551,14 +551,14 @@ public String getAliasName(JoinPath joinPath) { @NonNull protected String getPathOnlyAliasName(JoinPath joinPath) { return joinPath.getAlias().orElseGet(() -> { - String p = ""; + var p = new StringBuilder(); for (Association ass : joinPath.getAssociationPath()) { - p += ass.getAliasName(); + p.append(ass.getAliasName()); if (ass.hasDeclaredAliasName() && ass != joinPath.getAssociation()) { - p += "_"; + p.append('_'); } } - return p; + return p.toString(); }); } @@ -752,8 +752,8 @@ protected void buildSelect(AnnotationMetadata annotationMetadata, selectAllColumns(annotationMetadata, queryState, queryString); return; } - if (projection instanceof QueryModel.LiteralProjection) { - queryString.append(asLiteral(((QueryModel.LiteralProjection) projection).getValue())); + if (projection instanceof QueryModel.LiteralProjection literalProjection) { + queryString.append(asLiteral(literalProjection.getValue())); } else if (projection instanceof QueryModel.CountProjection) { appendProjectionRowCount(queryString, tableAlias); } else if (projection instanceof QueryModel.DistinctProjection) { @@ -1498,8 +1498,8 @@ private void appendCaseInsensitiveCriterion(CriteriaContext ctx, } private void appendPlaceholderOrLiteral(CriteriaContext ctx, QueryPropertyPath propertyPath, Object value) { - if (value instanceof BindingParameter) { - ctx.pushParameter((BindingParameter) value, newBindingContext(propertyPath.propertyPath)); + if (value instanceof BindingParameter bindingParameter) { + ctx.pushParameter(bindingParameter, newBindingContext(propertyPath.propertyPath)); return; } ctx.query().append(asLiteral(value)); @@ -1569,7 +1569,7 @@ public int getParameterIndex() { List> update = propertiesToUpdate.entrySet().stream() .map(e -> { QueryPropertyPath propertyPath = findProperty(queryState, e.getKey(), null); - if (propertyPath.getProperty() instanceof Association && ((Association) propertyPath.getProperty()).isForeignKey()) { + if (propertyPath.getProperty() instanceof Association association && association.isForeignKey()) { throw new IllegalArgumentException("Foreign key associations cannot be updated as part of a batch update statement"); } return new AbstractMap.SimpleEntry<>(propertyPath, e.getValue()); @@ -1595,9 +1595,9 @@ public int getParameterIndex() { } queryString.append(propertyPath.getPath()).append('='); } - if (entry.getValue() instanceof BindingParameter) { + if (entry.getValue() instanceof BindingParameter bindingParameter) { appendUpdateSetParameter(queryString, tableAlias, prop, () -> { - queryState.pushParameter((BindingParameter) entry.getValue(), newBindingContext(propertyPath.propertyPath)); + queryState.pushParameter(bindingParameter, newBindingContext(propertyPath.propertyPath)); }); } else { queryString.append(asLiteral(entry.getValue())); @@ -1614,7 +1614,7 @@ public int getParameterIndex() { NamingStrategy namingStrategy = getNamingStrategy(queryState.getEntity()); for (Map.Entry entry : update) { QueryPropertyPath propertyPath = entry.getKey(); - if (entry.getValue() instanceof BindingParameter) { + if (entry.getValue() instanceof BindingParameter bindingParameter) { traversePersistentProperties(propertyPath.getAssociations(), propertyPath.getProperty(), (associations, property) -> { String tableAlias = propertyPath.getTableAlias(); if (tableAlias != null) { @@ -1627,7 +1627,7 @@ public int getParameterIndex() { queryString.append(columnName).append('='); appendUpdateSetParameter(queryString, tableAlias, property, () -> { queryState.pushParameter( - (BindingParameter) entry.getValue(), + bindingParameter, newBindingContext( propertyPath.propertyPath, PersistentPropertyPath.of(associations, property, asPath(associations, property)) @@ -1688,9 +1688,9 @@ protected void appendUpdateSetParameter(StringBuilder sb, String alias, Persiste * @param appendParameter The append parameter action */ protected void appendTransformed(StringBuilder sb, String transformed, Runnable appendParameter) { - int parameterPosition = transformed.indexOf("?"); + int parameterPosition = transformed.indexOf('?'); if (parameterPosition > -1) { - if (transformed.lastIndexOf("?") != parameterPosition) { + if (transformed.lastIndexOf('?') != parameterPosition) { throw new IllegalStateException("Only one parameter placeholder is allowed!"); } sb.append(transformed, 0, parameterPosition); diff --git a/data-model/src/main/java/io/micronaut/data/model/query/builder/sql/SqlQueryBuilder.java b/data-model/src/main/java/io/micronaut/data/model/query/builder/sql/SqlQueryBuilder.java index 639405adfa..c503be6a66 100644 --- a/data-model/src/main/java/io/micronaut/data/model/query/builder/sql/SqlQueryBuilder.java +++ b/data-model/src/main/java/io/micronaut/data/model/query/builder/sql/SqlQueryBuilder.java @@ -59,7 +59,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; +import java.util.EnumMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; @@ -110,7 +110,7 @@ public class SqlQueryBuilder extends AbstractSqlLikeQueryBuilder implements Quer private static final String JDBC_REPO_ANNOTATION = "io.micronaut.data.jdbc.annotation.JdbcRepository"; private final Dialect dialect; - private final Map perDialectConfig = new HashMap<>(3); + private final Map perDialectConfig = new EnumMap<>(Dialect.class); private Pattern positionalParameterPattern; @@ -190,8 +190,8 @@ protected boolean shouldEscape(@NonNull PersistentEntity entity) { @Override protected String asLiteral(Object value) { - if ((dialect == Dialect.SQL_SERVER || dialect == Dialect.ORACLE) && value instanceof Boolean) { - return ((Boolean) value).booleanValue() ? "1" : "0"; + if ((dialect == Dialect.SQL_SERVER || dialect == Dialect.ORACLE) && value instanceof Boolean vBoolean) { + return vBoolean ? "1" : "0"; } return super.asLiteral(value); } @@ -585,11 +585,8 @@ private String addIndex(PersistentEntity entity, IndexConfiguration config) { .map(isUnique -> isUnique ? "UNIQUE " : "") .orElse("")) .append("INDEX "); - indexBuilder.append(indexName).append(" ON " + - Optional.ofNullable(config.tableName) - .orElseThrow(() -> new NullPointerException("Table name cannot be null")) + - " (" + - provideColumnList(config)); + indexBuilder.append(indexName).append(" ON ").append(Optional.ofNullable(config.tableName) + .orElseThrow(() -> new NullPointerException("Table name cannot be null"))).append(" (").append(provideColumnList(config)); if (dialect == Dialect.ORACLE) { indexBuilder.append(")"); @@ -1543,10 +1540,10 @@ private void join(StringBuilder sb, List onRightColumns = new ArrayList<>(); Association association = null; - if (leftProperty instanceof Association) { - association = (Association) leftProperty; - } else if (rightProperty instanceof Association) { - association = (Association) rightProperty; + if (leftProperty instanceof Association associationLeft) { + association = associationLeft; + } else if (rightProperty instanceof Association associationRight) { + association = associationRight; } if (association != null) { Optional inverse = association.getInverseSide().map(Function.identity()); @@ -1559,14 +1556,14 @@ private void join(StringBuilder sb, .stream() .map(ann -> ann.stringValue(isOwner ? "name" : "referencedColumnName").orElse(null)) .filter(Objects::nonNull) - .collect(Collectors.toList()) + .toList() ); onRightColumns.addAll( joinColumnsHolder.getAnnotations(VALUE_MEMBER) .stream() .map(ann -> ann.stringValue(isOwner ? "referencedColumnName" : "name").orElse(null)) .filter(Objects::nonNull) - .collect(Collectors.toList()) + .toList() ); } } diff --git a/data-mongodb/src/main/java/io/micronaut/data/mongodb/init/AbstractMongoCollectionsCreator.java b/data-mongodb/src/main/java/io/micronaut/data/mongodb/init/AbstractMongoCollectionsCreator.java index 5f95f635bf..fe7f6b9fda 100644 --- a/data-mongodb/src/main/java/io/micronaut/data/mongodb/init/AbstractMongoCollectionsCreator.java +++ b/data-mongodb/src/main/java/io/micronaut/data/mongodb/init/AbstractMongoCollectionsCreator.java @@ -66,8 +66,8 @@ public class AbstractMongoCollectionsCreator { protected M getMongoFactory(Class mongoFactoryClass, BeanLocator beanLocator, AbstractMongoConfiguration mongoConfiguration) { if (mongoConfiguration instanceof DefaultMongoConfiguration) { return beanLocator.getBean(mongoFactoryClass); - } else if (mongoConfiguration instanceof NamedMongoConfiguration) { - Qualifier qualifier = Qualifiers.byName(((NamedMongoConfiguration) mongoConfiguration).getServerName()); + } else if (mongoConfiguration instanceof NamedMongoConfiguration namedMongoConfiguration) { + Qualifier qualifier = Qualifiers.byName(namedMongoConfiguration.getServerName()); return beanLocator.getBean(mongoFactoryClass, qualifier); } else { throw new IllegalStateException("Cannot get MongoDB client for unrecognized configuration: " + mongoConfiguration); diff --git a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/AbstractMongoRepositoryOperations.java b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/AbstractMongoRepositoryOperations.java index 8505ef44ad..ccfcf38b8e 100644 --- a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/AbstractMongoRepositoryOperations.java +++ b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/AbstractMongoRepositoryOperations.java @@ -119,15 +119,15 @@ protected final DeleteOptions getDeleteOptions(AnnotationMetadata annotationMeta protected abstract CodecRegistry getCodecRegistry(Dtb database); protected MongoStoredQuery getMongoStoredQuery(StoredQuery storedQuery) { - if (storedQuery instanceof MongoStoredQuery) { - return (MongoStoredQuery) storedQuery; + if (storedQuery instanceof MongoStoredQuery mongoStoredQuery) { + return mongoStoredQuery; } throw new IllegalStateException("Expected for stored query to be of type: MongoStoredQuery"); } protected MongoPreparedQuery getMongoPreparedQuery(PreparedQuery preparedQuery) { - if (preparedQuery instanceof MongoPreparedQuery) { - return (MongoPreparedQuery) preparedQuery; + if (preparedQuery instanceof MongoPreparedQuery mongoPreparedQuery) { + return mongoPreparedQuery; } throw new IllegalStateException("Expected for prepared query to be of type: MongoPreparedQuery"); } diff --git a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoRepositoryOperations.java b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoRepositoryOperations.java index dab68abc97..c0b453c9bb 100644 --- a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoRepositoryOperations.java +++ b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoRepositoryOperations.java @@ -649,8 +649,8 @@ private K triggerPostLoad(AnnotationMetadata annotationMetadata, RuntimePers switch (runtimeAssociation.getKind()) { case MANY_TO_MANY: case ONE_TO_MANY: - if (o instanceof Iterable) { - for (Object value : ((Iterable) o)) { + if (o instanceof Iterable iterable) { + for (Object value : iterable) { triggerPostLoad(value, associatedEntity, annotationMetadata); } } diff --git a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoStoredQuery.java b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoStoredQuery.java index 40e5f263cf..b6e0d2daff 100644 --- a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoStoredQuery.java +++ b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoStoredQuery.java @@ -202,8 +202,8 @@ private int getParameterIndexByName(@Nullable String name) { if (name == null) { return -1; } - if (storedQuery instanceof DefaultStoredQuery) { - String[] argumentNames = ((DefaultStoredQuery) storedQuery).getMethod().getArgumentNames(); + if (storedQuery instanceof DefaultStoredQuery defaultStoredQuery) { + String[] argumentNames = defaultStoredQuery.getMethod().getArgumentNames(); for (int i = 0; i < argumentNames.length; i++) { String argumentName = argumentNames[i]; if (argumentName.equals(name)) { @@ -331,8 +331,8 @@ private boolean needsProcessingValue(BsonValue value) { } private Bson replaceQueryParameters(Bson value, @Nullable InvocationContext invocationContext, @Nullable E entity) { - if (value instanceof BsonDocument) { - return (BsonDocument) replaceQueryParametersInBsonValue(((BsonDocument) value).clone(), invocationContext, entity); + if (value instanceof BsonDocument bsonDocument) { + return (BsonDocument) replaceQueryParametersInBsonValue(bsonDocument.clone(), invocationContext, entity); } throw new IllegalStateException("Unrecognized value: " + value); } @@ -482,25 +482,24 @@ private BsonValue getValue(QueryParameterBinding queryParameterBinding, Object v if (isIdentity && value instanceof String) { return new BsonObjectId(new ObjectId((String) value)); } - if (value instanceof Object[]) { - List valueList = Arrays.asList((Object[]) value); + if (value instanceof Object[] objects) { + List valueList = Arrays.asList(objects); if (isIdentity) { for (ListIterator iterator = valueList.listIterator(); iterator.hasNext(); ) { Object item = iterator.next(); - if (item instanceof String) { - item = new BsonObjectId(new ObjectId((String) item)); + if (item instanceof String string) { + item = new BsonObjectId(new ObjectId(string)); } iterator.set(item); } } value = valueList; } - if (value instanceof Collection) { + if (value instanceof Collection values) { final boolean isIdentityField = isIdentity; - Collection values = (Collection) value; return new BsonArray(values.stream().map(val -> { - if (isIdentityField && val instanceof String) { - return new BsonObjectId(new ObjectId((String) val)); + if (isIdentityField && val instanceof String string) { + return new BsonObjectId(new ObjectId(string)); } return MongoUtils.toBsonValue(conversionService, val, codecRegistry.get()); }).collect(Collectors.toList())); diff --git a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultReactiveMongoRepositoryOperations.java b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultReactiveMongoRepositoryOperations.java index d57c1b155c..cf7a4c66bd 100644 --- a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultReactiveMongoRepositoryOperations.java +++ b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultReactiveMongoRepositoryOperations.java @@ -576,8 +576,8 @@ private K triggerPostLoad(AnnotationMetadata annotationMetadata, RuntimePers switch (runtimeAssociation.getKind()) { case MANY_TO_MANY: case ONE_TO_MANY: - if (o instanceof Iterable) { - for (Object value : ((Iterable) o)) { + if (o instanceof Iterable iterable) { + for (Object value : iterable) { triggerPostLoad(value, associatedEntity, annotationMetadata); } } diff --git a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/MongoUtils.java b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/MongoUtils.java index cd09cb82d3..0846719e53 100644 --- a/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/MongoUtils.java +++ b/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/MongoUtils.java @@ -140,17 +140,17 @@ public static BsonValue toBsonValue(ConversionService conversionService, Object if (value == null) { return BsonNull.VALUE; } - if (value instanceof String) { - return new BsonString((String) value); + if (value instanceof String strValue) { + return new BsonString(strValue); } - if (value instanceof Integer) { - return new BsonInt32((Integer) value); + if (value instanceof Integer intValue) { + return new BsonInt32(intValue); } - if (value instanceof Long) { - return new BsonInt64((Long) value); + if (value instanceof Long longValue) { + return new BsonInt64(longValue); } - if (value instanceof ObjectId) { - return new BsonObjectId((ObjectId) value); + if (value instanceof ObjectId objectId) { + return new BsonObjectId(objectId); } return BsonDocumentWrapper.asBsonDocument(value, codecRegistry).toBsonDocument(); } @@ -160,14 +160,14 @@ static BsonValue toBsonValue(ConversionService conversionService, BsonType bsonT case STRING: return new BsonString(value.toString()); case OBJECT_ID: - if (value instanceof String) { - return new BsonObjectId(new ObjectId((String) value)); + if (value instanceof String strValue) { + return new BsonObjectId(new ObjectId(strValue)); } - if (value instanceof byte[]) { - return new BsonObjectId(new ObjectId((byte[]) value)); + if (value instanceof byte[] bytesValue) { + return new BsonObjectId(new ObjectId(bytesValue)); } - if (value instanceof Date) { - return new BsonObjectId(new ObjectId((Date) value)); + if (value instanceof Date dateValue) { + return new BsonObjectId(new ObjectId(dateValue)); } return new BsonObjectId(conversionService.convertRequired(value, ObjectId.class)); default: diff --git a/data-mongodb/src/main/java/io/micronaut/data/mongodb/serde/DataDecoderContext.java b/data-mongodb/src/main/java/io/micronaut/data/mongodb/serde/DataDecoderContext.java index de5a0e9c25..8b8fa98279 100644 --- a/data-mongodb/src/main/java/io/micronaut/data/mongodb/serde/DataDecoderContext.java +++ b/data-mongodb/src/main/java/io/micronaut/data/mongodb/serde/DataDecoderContext.java @@ -186,10 +186,13 @@ public Object deserialize(Decoder decoder, DecoderContext decoderContext, Argume @Override public Deserializer findDeserializer(Argument type) throws SerdeException { Codec codec = codecRegistry.get(type.getType(), codecRegistry); - if (codec instanceof MappedCodec) { - return ((MappedCodec) codec).deserializer; + if (codec instanceof MappedCodec mappedCodec) { + return mappedCodec.deserializer; } - if (codec != null && !(codec instanceof IterableCodec) && !(Map.class.isAssignableFrom(codec.getEncoderClass())) && !(Collection.class.isAssignableFrom(codec.getEncoderClass()))) { + if (codec != null + && !(codec instanceof IterableCodec) + && !(Map.class.isAssignableFrom(codec.getEncoderClass())) + && !(Collection.class.isAssignableFrom(codec.getEncoderClass()))) { return new CodecBsonDecoder<>((Codec) codec); } return parent.findDeserializer(type); diff --git a/data-mongodb/src/main/java/io/micronaut/data/mongodb/serde/DataEncoderContext.java b/data-mongodb/src/main/java/io/micronaut/data/mongodb/serde/DataEncoderContext.java index 78869809f3..6f7c035d13 100644 --- a/data-mongodb/src/main/java/io/micronaut/data/mongodb/serde/DataEncoderContext.java +++ b/data-mongodb/src/main/java/io/micronaut/data/mongodb/serde/DataEncoderContext.java @@ -170,8 +170,8 @@ public void serialize(Encoder encoder, EncoderContext context, Argument type, @Override public Serializer findSerializer(Argument type) throws SerdeException { Codec codec = codecRegistry.get(type.getType(), codecRegistry); - if (codec instanceof MappedCodec) { - return ((MappedCodec) codec).serializer; + if (codec instanceof MappedCodec mappedCodec) { + return mappedCodec.serializer; } if (codec != null && !(codec instanceof IterableCodec) && !(Map.class.isAssignableFrom(codec.getEncoderClass()))) { return new CodecBsonDecoder<>((Codec) codec); diff --git a/data-processor/src/main/java/io/micronaut/data/processor/model/criteria/impl/SourcePersistentEntityCriteriaUpdateImpl.java b/data-processor/src/main/java/io/micronaut/data/processor/model/criteria/impl/SourcePersistentEntityCriteriaUpdateImpl.java index c76622b621..8ee292498e 100644 --- a/data-processor/src/main/java/io/micronaut/data/processor/model/criteria/impl/SourcePersistentEntityCriteriaUpdateImpl.java +++ b/data-processor/src/main/java/io/micronaut/data/processor/model/criteria/impl/SourcePersistentEntityCriteriaUpdateImpl.java @@ -67,8 +67,8 @@ public PersistentEntityRoot from(PersistentEntity persistentEntity) { @Override protected void setValue(String attributeName, Object value) { - if (value instanceof SourceParameterExpressionImpl) { - ((SourceParameterExpressionImpl) value).setUpdate(true); + if (value instanceof SourceParameterExpressionImpl sourceParameterExpression) { + sourceParameterExpression.setUpdate(true); } super.setValue(attributeName, value); } diff --git a/data-processor/src/main/java/io/micronaut/data/processor/model/criteria/impl/SourcePersistentEntityPath.java b/data-processor/src/main/java/io/micronaut/data/processor/model/criteria/impl/SourcePersistentEntityPath.java index 8170a08e1e..0826832416 100644 --- a/data-processor/src/main/java/io/micronaut/data/processor/model/criteria/impl/SourcePersistentEntityPath.java +++ b/data-processor/src/main/java/io/micronaut/data/processor/model/criteria/impl/SourcePersistentEntityPath.java @@ -48,8 +48,7 @@ default PersistentPropertyPath get(String attributeName) { if (property == null) { throw new IllegalStateException("Cannot query entity [" + getPersistentEntity().getSimpleName() + "] on non-existent property: " + attributeName); } - if (this instanceof PersistentAssociationPath) { - PersistentAssociationPath associationPath = (PersistentAssociationPath) this; + if (this instanceof PersistentAssociationPath associationPath) { List associations = associationPath.getAssociations(); List newAssociations = new ArrayList<>(associations.size() + 1); newAssociations.addAll(associations); diff --git a/data-processor/src/main/java/io/micronaut/data/processor/visitors/RepositoryTypeElementVisitor.java b/data-processor/src/main/java/io/micronaut/data/processor/visitors/RepositoryTypeElementVisitor.java index 46a46c175e..17a9c9eafd 100644 --- a/data-processor/src/main/java/io/micronaut/data/processor/visitors/RepositoryTypeElementVisitor.java +++ b/data-processor/src/main/java/io/micronaut/data/processor/visitors/RepositoryTypeElementVisitor.java @@ -545,16 +545,16 @@ private void bindAdditionalParameters(MatchContext matchContext, } private String addRawQueryParameterPlaceholders(QueryBuilder queryEncoder, String query, List queryParts) { - if (queryEncoder instanceof SqlQueryBuilder) { + if (queryEncoder instanceof SqlQueryBuilder sqlQueryBuilder) { Iterator iterator = queryParts.iterator(); String first = iterator.next(); if (queryParts.size() < 2) { return first; } - StringBuilder sb = new StringBuilder(first); + var sb = new StringBuilder(first); int i = 1; while (iterator.hasNext()) { - sb.append(((SqlQueryBuilder) queryEncoder).formatParameter(i++).getName()); + sb.append(sqlQueryBuilder.formatParameter(i++).getName()); sb.append(iterator.next()); } return sb.toString(); diff --git a/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/AbstractCriteriaMethodMatch.java b/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/AbstractCriteriaMethodMatch.java index 0613adcb02..7c25d27148 100644 --- a/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/AbstractCriteriaMethodMatch.java +++ b/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/AbstractCriteriaMethodMatch.java @@ -629,7 +629,7 @@ protected final io.micronaut.data.model.jpa.criteria.PersistentPropertyPath< path = path.join(association.getName()); } Path exp; - if (pp.getProperty() instanceof Association && ((Association) pp.getProperty()).getKind() != Relation.Kind.EMBEDDED) { + if (pp.getProperty() instanceof Association association && association.getKind() != Relation.Kind.EMBEDDED) { exp = path.join(pp.getProperty().getName()); } else { exp = path.get(pp.getProperty().getName()); diff --git a/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/FindMethodMatcher.java b/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/FindMethodMatcher.java index fa6ad9f249..ce450714dd 100644 --- a/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/FindMethodMatcher.java +++ b/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/FindMethodMatcher.java @@ -68,8 +68,8 @@ protected void apply(MethodMatchContext matchContext, PersistentEntityCriteriaQuery query, SourcePersistentEntityCriteriaBuilder cb) { super.apply(matchContext, root, query, cb); - if (query instanceof AbstractPersistentEntityCriteriaQuery) { - hasIdMatch = ((AbstractPersistentEntityCriteriaQuery) query).hasOnlyIdRestriction(); + if (query instanceof AbstractPersistentEntityCriteriaQuery criteriaQuery) { + hasIdMatch = criteriaQuery.hasOnlyIdRestriction(); } } diff --git a/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/UpdateMethodMatcher.java b/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/UpdateMethodMatcher.java index 18ee0f8ab7..0ca970a04f 100644 --- a/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/UpdateMethodMatcher.java +++ b/data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/UpdateMethodMatcher.java @@ -138,7 +138,7 @@ protected void addPropertiesToUpdate(MethodMatchContext matchContext, } Stream.concat(rootEntity.getPersistentProperties().stream(), Stream.of(rootEntity.getVersion())) - .filter(p -> p != null && !((p instanceof Association) && ((Association) p).isForeignKey()) && !p.isGenerated() && + .filter(p -> p != null && !(p instanceof Association association && association.isForeignKey()) && !p.isGenerated() && p.findAnnotation(AutoPopulated.class).map(ap -> ap.getRequiredValue(AutoPopulated.UPDATEABLE, Boolean.class)).orElse(true)) .forEach(p -> query.set(p.getName(), cb.entityPropertyParameter(entityParam))); diff --git a/data-r2dbc/src/main/java/io/micronaut/data/r2dbc/mapper/ColumnNameR2dbcResultReader.java b/data-r2dbc/src/main/java/io/micronaut/data/r2dbc/mapper/ColumnNameR2dbcResultReader.java index 1f34acff7c..2393921ef5 100644 --- a/data-r2dbc/src/main/java/io/micronaut/data/r2dbc/mapper/ColumnNameR2dbcResultReader.java +++ b/data-r2dbc/src/main/java/io/micronaut/data/r2dbc/mapper/ColumnNameR2dbcResultReader.java @@ -86,8 +86,8 @@ public Object readDynamic(@NonNull Row resultSet, @NonNull String index, @NonNul if (o instanceof Integer) { return o; } - if (o instanceof Number) { - return ((Number) o).intValue(); + if (o instanceof Number number) { + return number.intValue(); } return convertRequired(o, Integer.class); case BOOLEAN: @@ -132,11 +132,11 @@ private byte[] readBlob(@NonNull Row resultSet, @NonNull String index) { if (o instanceof byte[]) { return null; } - if (o instanceof ByteBuffer) { - return ((ByteBuffer) o).array(); + if (o instanceof ByteBuffer byteBuffer) { + return byteBuffer.array(); } - if (o instanceof Blob) { - ByteBuffer byteBuffer = Mono.from(((Blob) o).stream()).block(); + if (o instanceof Blob blob) { + ByteBuffer byteBuffer = Mono.from(blob.stream()).block(); if (byteBuffer == null) { return new byte[0]; } @@ -200,8 +200,8 @@ public String readString(Row resultSet, String name) { if (o == null) { return null; } - if (o instanceof String) { - return (String) o; + if (o instanceof String string) { + return string; } if (o instanceof Clob clob) { CharSequence charSequence = Mono.from(clob.stream()).block(); diff --git a/data-r2dbc/src/main/java/io/micronaut/data/r2dbc/operations/DefaultR2dbcRepositoryOperations.java b/data-r2dbc/src/main/java/io/micronaut/data/r2dbc/operations/DefaultR2dbcRepositoryOperations.java index 7f3ead34b8..40b6b19fdd 100644 --- a/data-r2dbc/src/main/java/io/micronaut/data/r2dbc/operations/DefaultR2dbcRepositoryOperations.java +++ b/data-r2dbc/src/main/java/io/micronaut/data/r2dbc/operations/DefaultR2dbcRepositoryOperations.java @@ -164,6 +164,7 @@ final class DefaultR2dbcRepositoryOperations extends AbstractSqlRepositoryOperat * @param connectionOperations The connection operations */ @Internal + @SuppressWarnings("ParameterNumber") DefaultR2dbcRepositoryOperations( @Parameter String dataSourceName, ConnectionFactory connectionFactory, diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/convert/DataConversionServiceFactory.java b/data-runtime/src/main/java/io/micronaut/data/runtime/convert/DataConversionServiceFactory.java index 4a30e0aac9..a42c227dbc 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/convert/DataConversionServiceFactory.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/convert/DataConversionServiceFactory.java @@ -702,65 +702,65 @@ private void addZonedConvertorsConvertors(DataConversionServiceImpl conversi } private Integer asInteger(Object value, DataConversionService dataConversionService) { - if (value instanceof Integer) { - return (Integer) value; + if (value instanceof Integer intValue) { + return intValue; } - if (value instanceof Number) { - return ((Number) value).intValue(); + if (value instanceof Number number) { + return number.intValue(); } return dataConversionService.convertRequired(value, Integer.class); } private Long asLong(Object value, DataConversionService dataConversionService) { - if (value instanceof Long) { - return (Long) value; + if (value instanceof Long longValue) { + return longValue; } - if (value instanceof Number) { - return ((Number) value).longValue(); + if (value instanceof Number number) { + return number.longValue(); } return dataConversionService.convertRequired(value, Long.class); } private Double asDouble(Object value, DataConversionService dataConversionService) { - if (value instanceof Double) { - return (Double) value; + if (value instanceof Double doubleValue) { + return doubleValue; } - if (value instanceof Number) { - return ((Number) value).doubleValue(); + if (value instanceof Number number) { + return number.doubleValue(); } return dataConversionService.convertRequired(value, Double.class); } private Boolean asBoolean(Object value, DataConversionService dataConversionService) { - if (value instanceof Boolean) { - return (Boolean) value; + if (value instanceof Boolean boolValue) { + return boolValue; } return dataConversionService.convertRequired(value, Boolean.class); } private Float asFloat(Object value, DataConversionService dataConversionService) { - if (value instanceof Float) { - return (Float) value; + if (value instanceof Float floatValue) { + return floatValue; } - if (value instanceof Number) { - return ((Number) value).floatValue(); + if (value instanceof Number number) { + return number.floatValue(); } return dataConversionService.convertRequired(value, Float.class); } private Short asShort(Object value, DataConversionService dataConversionService) { - if (value instanceof Short) { - return (Short) value; + if (value instanceof Short shortValue) { + return shortValue; } - if (value instanceof Number) { - return ((Number) value).shortValue(); + if (value instanceof Number number) { + return number.shortValue(); } return dataConversionService.convertRequired(value, Short.class); } private Character asCharacter(Object value, DataConversionService dataConversionService) { - if (value instanceof Character) { - return (Character) value; + if (value instanceof Character charValue) { + return charValue; } return dataConversionService.convertRequired(value, Character.class); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/LiteralsAsParametersQueryModelPredicateVisitor.java b/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/LiteralsAsParametersQueryModelPredicateVisitor.java index c740bbf746..063bcc6b9b 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/LiteralsAsParametersQueryModelPredicateVisitor.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/LiteralsAsParametersQueryModelPredicateVisitor.java @@ -98,14 +98,13 @@ public void visit(PersistentPropertyInValuesPredicate inValues) { @NotNull private ParameterExpression asParameter(Object exp) { - if (exp instanceof ParameterExpression) { - return (ParameterExpression) exp; + if (exp instanceof ParameterExpression parameterExpression) { + return parameterExpression; } Objects.requireNonNull(exp); Class type; Object value; - if (exp instanceof LiteralExpression) { - LiteralExpression literalExpression = (LiteralExpression) exp; + if (exp instanceof LiteralExpression literalExpression) { type = literalExpression.getJavaType(); value = literalExpression.getValue(); } else if (exp instanceof Expression) { diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/RuntimePersistentEntityPath.java b/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/RuntimePersistentEntityPath.java index f2faa56b14..77ee769151 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/RuntimePersistentEntityPath.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/RuntimePersistentEntityPath.java @@ -40,8 +40,7 @@ default PersistentPropertyPath get(String attributeName) { if (property == null) { throw new IllegalStateException("Cannot query entity [" + getPersistentEntity().getSimpleName() + "] on non-existent property: " + attributeName); } - if (this instanceof PersistentAssociationPath) { - PersistentAssociationPath associationPath = (PersistentAssociationPath) this; + if (this instanceof PersistentAssociationPath associationPath) { List associations = associationPath.getAssociations(); List newAssociations = new ArrayList<>(associations.size() + 1); newAssociations.addAll(associations); diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/metamodel/StaticMetamodelInitializer.java b/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/metamodel/StaticMetamodelInitializer.java index 2729750b08..139ff24c3c 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/metamodel/StaticMetamodelInitializer.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/criteria/metamodel/StaticMetamodelInitializer.java @@ -65,8 +65,8 @@ private synchronized void initializeMetadataInternal(RuntimePersistentEntity try { if (field.get(field.getDeclaringClass()) == null) { RuntimePersistentProperty prop = persistentEntity.getPropertyByName(property); - if (prop instanceof RuntimeAssociation) { - initializeMetadataInternal(((RuntimeAssociation) prop).getAssociatedEntity()); + if (prop instanceof RuntimeAssociation runtimeAssociation) { + initializeMetadataInternal(runtimeAssociation.getAssociatedEntity()); } if (field.getType() == SingularAttribute.class) { ReflectionUtils.setField(field, field.getDeclaringClass(), new RuntimePersistentPropertySingularAttribute<>(persistentEntity, prop)); diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/event/listeners/AutoTimestampEntityEventListener.java b/data-runtime/src/main/java/io/micronaut/data/runtime/event/listeners/AutoTimestampEntityEventListener.java index e082c0691a..613b746b38 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/event/listeners/AutoTimestampEntityEventListener.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/event/listeners/AutoTimestampEntityEventListener.java @@ -98,8 +98,8 @@ public Object populate(RuntimePersistentProperty property, @Nullable Object p private Object truncate(Object now, ChronoUnit truncateToValue) { if (truncateToValue != null) { - if (now instanceof OffsetDateTime) { - now = ((OffsetDateTime) now).truncatedTo(truncateToValue); + if (now instanceof OffsetDateTime offsetDateTime) { + now = offsetDateTime.truncatedTo(truncateToValue); } else { now = conversionService.convertRequired(now, Instant.class).truncatedTo(truncateToValue); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/AbstractQueryInterceptor.java b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/AbstractQueryInterceptor.java index 293aca5171..5ff821774a 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/AbstractQueryInterceptor.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/AbstractQueryInterceptor.java @@ -113,14 +113,14 @@ protected AbstractQueryInterceptor(@NonNull RepositoryOperations operations) { ArgumentUtils.requireNonNull("operations", operations); this.conversionService = operations.getConversionService(); this.operations = operations; - this.storedQueryResolver = operations instanceof StoredQueryResolver ? (StoredQueryResolver) operations : new DefaultStoredQueryResolver() { + this.storedQueryResolver = operations instanceof StoredQueryResolver sQueryResolver ? sQueryResolver : new DefaultStoredQueryResolver() { @Override protected HintsCapableRepository getHintsCapableRepository() { return operations; } }; - if (operations instanceof MethodContextAwareStoredQueryDecorator) { - storedQueryDecorator = (MethodContextAwareStoredQueryDecorator) operations; + if (operations instanceof MethodContextAwareStoredQueryDecorator methodDecorator) { + storedQueryDecorator = methodDecorator; } else if (operations instanceof StoredQueryDecorator decorator) { storedQueryDecorator = new MethodContextAwareStoredQueryDecorator() { @Override @@ -136,19 +136,19 @@ public StoredQuery decorate(MethodInvocationContext context, } }; } - this.preparedQueryResolver = operations instanceof PreparedQueryResolver ? (PreparedQueryResolver) operations : new DefaultPreparedQueryResolver() { + this.preparedQueryResolver = operations instanceof PreparedQueryResolver resolver ? resolver : new DefaultPreparedQueryResolver() { @Override protected ConversionService getConversionService() { return operations.getConversionService(); } }; - this.preparedQueryDecorator = operations instanceof PreparedQueryDecorator ? (PreparedQueryDecorator) operations : new PreparedQueryDecorator() { + this.preparedQueryDecorator = operations instanceof PreparedQueryDecorator decorator ? decorator : new PreparedQueryDecorator() { @Override public PreparedQuery decorate(PreparedQuery preparedQuery) { return preparedQuery; } }; - this.pagedQueryResolver = operations instanceof PagedQueryResolver ? (PagedQueryResolver) operations : new DefaultPagedQueryResolver(); + this.pagedQueryResolver = operations instanceof PagedQueryResolver resolver ? resolver : new DefaultPagedQueryResolver(); } /** @@ -758,8 +758,8 @@ protected final void validateNullArguments(MethodInvocationContext context * @return the size */ protected int count(Iterable iterable) { - if (iterable instanceof Collection) { - return ((Collection) iterable).size(); + if (iterable instanceof Collection collection) { + return collection.size(); } Iterator iterator = iterable.iterator(); int i = 0; diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractAsyncInterceptor.java b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractAsyncInterceptor.java index 33dc231310..86c57bc569 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractAsyncInterceptor.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractAsyncInterceptor.java @@ -49,8 +49,8 @@ public abstract class AbstractAsyncInterceptor extends AbstractQueryInterc */ protected AbstractAsyncInterceptor(@NonNull RepositoryOperations datastore) { super(datastore); - if (datastore instanceof AsyncCapableRepository) { - this.asyncDatastoreOperations = ((AsyncCapableRepository) datastore).async(); + if (datastore instanceof AsyncCapableRepository asyncCapableRepository) { + this.asyncDatastoreOperations = asyncCapableRepository.async(); } else { throw new DataAccessException("Datastore of type [" + datastore.getClass() + "] does not support asynchronous operations"); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractAsyncInterceptor2.java b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractAsyncInterceptor2.java index 5ef726156f..2cce6c923c 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractAsyncInterceptor2.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractAsyncInterceptor2.java @@ -48,8 +48,8 @@ abstract sealed class AbstractAsyncInterceptor2 extends AbstractQueryInter */ protected AbstractAsyncInterceptor2(@NonNull RepositoryOperations datastore) { super(datastore); - if (datastore instanceof AsyncCapableRepository) { - this.asyncDatastoreOperations = ((AsyncCapableRepository) datastore).async(); + if (datastore instanceof AsyncCapableRepository asyncCapableRepository) { + this.asyncDatastoreOperations = asyncCapableRepository.async(); } else { throw new DataAccessException("Datastore of type [" + datastore.getClass() + "] does not support asynchronous operations"); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractCountConvertCompletionStageInterceptor.java b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractCountConvertCompletionStageInterceptor.java index deab1ccfa4..f1c1f46a23 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractCountConvertCompletionStageInterceptor.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/async/AbstractCountConvertCompletionStageInterceptor.java @@ -59,8 +59,8 @@ public CompletionStage intercept(RepositoryMethodKey methodKey, MethodIn } return cs.thenApply(it -> { if (isNumber(csValueArgument.getType())) { - if (it instanceof Iterable) { - it = count((Iterable) it); + if (it instanceof Iterable iterable) { + it = count(iterable); } else if (!(it instanceof Number)) { it = it == null ? 0 : 1; } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/criteria/AbstractSpecificationInterceptor.java b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/criteria/AbstractSpecificationInterceptor.java index 04fecee188..3a516b2fed 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/criteria/AbstractSpecificationInterceptor.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/criteria/AbstractSpecificationInterceptor.java @@ -63,7 +63,6 @@ import jakarta.persistence.criteria.Root; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; @@ -128,7 +127,7 @@ public StoredQuery decorate(MethodInvocationContext context, } }; } - preparedQueryDecorator = operations instanceof PreparedQueryDecorator ? (PreparedQueryDecorator) operations : new PreparedQueryDecorator() { + preparedQueryDecorator = operations instanceof PreparedQueryDecorator decorator ? decorator : new PreparedQueryDecorator() { @Override public PreparedQuery decorate(PreparedQuery preparedQuery) { return preparedQuery; @@ -232,8 +231,8 @@ protected final PreparedQuery preparedQueryForCriteria(Repository private Pageable findPageable(MethodInvocationContext context) { Pageable pageable = Pageable.UNPAGED; for (Object param : context.getParameterValues()) { - if (param instanceof Pageable) { - pageable = (Pageable) param; + if (param instanceof Pageable pageableParam) { + pageable = pageableParam; break; } } @@ -383,11 +382,11 @@ protected final CriteriaQuery buildQuery(MethodInvocationContext co @Nullable protected QuerySpecification getQuerySpecification(MethodInvocationContext context) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof QuerySpecification) { - return (QuerySpecification) parameterValue; + if (parameterValue instanceof QuerySpecification querySpecification) { + return querySpecification; } - if (parameterValue instanceof PredicateSpecification) { - return QuerySpecification.where((PredicateSpecification) parameterValue); + if (parameterValue instanceof PredicateSpecification predicateSpecification) { + return QuerySpecification.where(predicateSpecification); } Argument parameterArgument = context.getArguments()[0]; if (parameterArgument.isAssignableFrom(QuerySpecification.class) || parameterArgument.isAssignableFrom(PredicateSpecification.class)) { @@ -408,8 +407,8 @@ protected QuerySpecification getQuerySpecification(MethodInvocationContex @NonNull protected CriteriaQueryBuilder getCriteriaQueryBuilder(MethodInvocationContext context, Set joinPaths) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof CriteriaQueryBuilder) { - return (CriteriaQueryBuilder) parameterValue; + if (parameterValue instanceof CriteriaQueryBuilder criteriaQueryBuilder) { + return criteriaQueryBuilder; } return criteriaBuilder -> { Class rootEntity = getRequiredRootEntity(context); @@ -464,11 +463,11 @@ private Set mergeJoinPaths(Set joinPaths, Collection DeleteSpecification getDeleteSpecification(MethodInvocationContext context) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof DeleteSpecification) { - return (DeleteSpecification) parameterValue; + if (parameterValue instanceof DeleteSpecification deleteSpecification) { + return deleteSpecification; } - if (parameterValue instanceof PredicateSpecification) { - return DeleteSpecification.where((PredicateSpecification) parameterValue); + if (parameterValue instanceof PredicateSpecification predicateSpecification) { + return DeleteSpecification.where(predicateSpecification); } Argument parameterArgument = context.getArguments()[0]; if (parameterArgument.isAssignableFrom(DeleteSpecification.class) || parameterArgument.isAssignableFrom(PredicateSpecification.class)) { @@ -488,8 +487,8 @@ protected DeleteSpecification getDeleteSpecification(MethodInvocationCont @NonNull protected CriteriaDeleteBuilder getCriteriaDeleteBuilder(MethodInvocationContext context) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof CriteriaDeleteBuilder) { - return (CriteriaDeleteBuilder) parameterValue; + if (parameterValue instanceof CriteriaDeleteBuilder criteriaDeleteBuilder) { + return criteriaDeleteBuilder; } return criteriaBuilder -> { Class rootEntity = getRequiredRootEntity(context); @@ -516,8 +515,8 @@ protected CriteriaDeleteBuilder getCriteriaDeleteBuilder(MethodInvocation @Nullable protected UpdateSpecification getUpdateSpecification(MethodInvocationContext context) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof UpdateSpecification) { - return (UpdateSpecification) parameterValue; + if (parameterValue instanceof UpdateSpecification updateSpecification) { + return updateSpecification; } Argument parameterArgument = context.getArguments()[0]; if (parameterArgument.isAssignableFrom(UpdateSpecification.class) || parameterArgument.isAssignableFrom(PredicateSpecification.class)) { @@ -537,8 +536,8 @@ protected UpdateSpecification getUpdateSpecification(MethodInvocationCont @NonNull protected CriteriaUpdateBuilder getCriteriaUpdateBuilder(MethodInvocationContext context) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof CriteriaUpdateBuilder) { - return (CriteriaUpdateBuilder) parameterValue; + if (parameterValue instanceof CriteriaUpdateBuilder criteriaUpdateBuilder) { + return criteriaUpdateBuilder; } return criteriaBuilder -> { Class rootEntity = getRequiredRootEntity(context); diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/criteria/reactive/AbstractReactiveSpecificationInterceptor.java b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/criteria/reactive/AbstractReactiveSpecificationInterceptor.java index 3bee09d65f..0e50b10d84 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/criteria/reactive/AbstractReactiveSpecificationInterceptor.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/criteria/reactive/AbstractReactiveSpecificationInterceptor.java @@ -53,8 +53,8 @@ public abstract class AbstractReactiveSpecificationInterceptor extends Abs */ protected AbstractReactiveSpecificationInterceptor(RepositoryOperations operations) { super(operations); - if (operations instanceof ReactiveCapableRepository) { - this.reactiveOperations = ((ReactiveCapableRepository) operations).reactive(); + if (operations instanceof ReactiveCapableRepository reactiveCapableRepository) { + this.reactiveOperations = reactiveCapableRepository.reactive(); } else { throw new DataAccessException("Datastore of type [" + operations.getClass() + "] does not support reactive operations"); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/reactive/AbstractReactiveInterceptor.java b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/reactive/AbstractReactiveInterceptor.java index 095a64e434..f8759d0ef5 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/reactive/AbstractReactiveInterceptor.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/intercept/reactive/AbstractReactiveInterceptor.java @@ -44,8 +44,8 @@ public abstract class AbstractReactiveInterceptor extends AbstractQueryInt */ protected AbstractReactiveInterceptor(@NonNull RepositoryOperations operations) { super(operations); - if (operations instanceof ReactiveCapableRepository) { - this.reactiveOperations = ((ReactiveCapableRepository) operations).reactive(); + if (operations instanceof ReactiveCapableRepository reactiveCapableRepository) { + this.reactiveOperations = reactiveCapableRepository.reactive(); } else { throw new DataAccessException("Datastore of type [" + operations.getClass() + "] does not support reactive operations"); } @@ -59,8 +59,8 @@ protected AbstractReactiveInterceptor(@NonNull RepositoryOperations operations) */ protected Publisher count(Publisher publisher) { return Flux.from(publisher).map(v -> { - if (v instanceof Number) { - return ((Number) v).longValue(); + if (v instanceof Number number) { + return number.longValue(); } return 1L; }).reduce(0L, Long::sum).map(Long::intValue); diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/BeanIntrospectionMapper.java b/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/BeanIntrospectionMapper.java index 6d0a5557c2..a4f5d8f94e 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/BeanIntrospectionMapper.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/BeanIntrospectionMapper.java @@ -92,7 +92,7 @@ R map(@NonNull D object, @NonNull Class type) throws InstantiationException { } else if (Iterable.class.isAssignableFrom(property.getType())) { if (v instanceof Collection) { property.set(instance, v); - } else if (v instanceof Iterable iterable) { + } else if (v instanceof Iterable iterable) { List list = new ArrayList<>(CollectionUtils.iterableToList(iterable)); property.set(instance, convert(list, property.asArgument())); } else { diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/MapperUtils.java b/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/MapperUtils.java index 37defe43c6..3fcd28ec66 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/MapperUtils.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/MapperUtils.java @@ -47,17 +47,17 @@ static Collection toCollection(Object value) { return null; } Collection collection; - if (value instanceof Collection) { - collection = (Collection) value; - } else if (value instanceof Iterable iterable) { + if (value instanceof Collection aCollection) { + collection = aCollection; + } else if (value instanceof Iterable iterable) { collection = new ArrayList<>(CollectionUtils.iterableToList(iterable)); } else if (value.getClass().isArray()) { Object[] arr = (Object[]) value; collection = Arrays.asList(arr); - } else if (value instanceof Array) { + } else if (value instanceof Array arrayValue) { Object[] arr; try { - arr = (Object[]) ((Array) value).getArray(); + arr = (Object[]) arrayValue.getArray(); } catch (SQLException e) { throw new DataAccessException("Unable to read SQL array", e); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/QueryStatement.java b/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/QueryStatement.java index 23d32a7f41..09db30b420 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/QueryStatement.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/QueryStatement.java @@ -75,8 +75,8 @@ default QueryStatement setDynamic( } return setString(statement, index, str); case INTEGER: - if (value instanceof Number) { - return setInt(statement, index, ((Number) value).intValue()); + if (value instanceof Number number) { + return setInt(statement, index, number.intValue()); } else { Integer integer = convertRequired(value, Integer.class); if (integer != null) { @@ -86,8 +86,8 @@ default QueryStatement setDynamic( } } case BOOLEAN: - if (value instanceof Boolean) { - return setBoolean(statement, index, ((Boolean) value)); + if (value instanceof Boolean bool) { + return setBoolean(statement, index, bool); } else { Boolean b = convertRequired(value, Boolean.class); if (b != null) { @@ -97,8 +97,8 @@ default QueryStatement setDynamic( } } case DATE: - if (value instanceof Date) { - return setDate(statement, index, ((Date) value)); + if (value instanceof Date date) { + return setDate(statement, index, date); } else { return setDate(statement, index, convertRequired(value, Date.class)); } @@ -106,17 +106,17 @@ default QueryStatement setDynamic( Instant instant; if (value == null) { instant = null; - } else if (value instanceof ZonedDateTime) { - instant = ((ZonedDateTime) value).toInstant(); - } else if (value instanceof Instant) { - instant = ((Instant) value); + } else if (value instanceof ZonedDateTime zonedDateTime) { + instant = zonedDateTime.toInstant(); + } else if (value instanceof Instant instantVal) { + instant = instantVal; } else { instant = convertRequired(value, Instant.class); } return setTimestamp(statement, index, instant); case TIME: - if (value instanceof Time) { - return setTime(statement, index, (Time) value); + if (value instanceof Time time) { + return setTime(statement, index, time); } else { throw new DataAccessException("Invalid time: " + value); } @@ -130,8 +130,8 @@ default QueryStatement setDynamic( throw new DataAccessException("Invalid UUID: " + value); } case DOUBLE: - if (value instanceof Number) { - return setDouble(statement, index, ((Number) value).doubleValue()); + if (value instanceof Number number) { + return setDouble(statement, index, number.doubleValue()); } else { Double d = convertRequired(value, Double.class); if (d != null) { @@ -141,22 +141,22 @@ default QueryStatement setDynamic( } } case BYTE_ARRAY: - if (value instanceof byte[]) { - return setBytes(statement, index, ((byte[]) value)); + if (value instanceof byte[] byteArray) { + return setBytes(statement, index, byteArray); } else { return setBytes(statement, index, convertRequired(value, byte[].class)); } case BIGDECIMAL: - if (value instanceof BigDecimal) { - return setBigDecimal(statement, index, (BigDecimal) value); - } else if (value instanceof Number) { - return setBigDecimal(statement, index, BigDecimal.valueOf(((Number) value).doubleValue())); + if (value instanceof BigDecimal decimal) { + return setBigDecimal(statement, index, decimal); + } else if (value instanceof Number number) { + return setBigDecimal(statement, index, BigDecimal.valueOf(number.doubleValue())); } else { return setBigDecimal(statement, index, convertRequired(value, BigDecimal.class)); } case LONG: - if (value instanceof Number) { - return setLong(statement, index, ((Number) value).longValue()); + if (value instanceof Number number) { + return setLong(statement, index, number.longValue()); } else { Long l = convertRequired(value, Long.class); if (l != null) { @@ -166,8 +166,8 @@ default QueryStatement setDynamic( } } case CHARACTER: - if (value instanceof Character) { - return setChar(statement, index, (Character) value); + if (value instanceof Character character) { + return setChar(statement, index, character); } else { Character c = convertRequired(value, Character.class); if (c != null) { @@ -177,8 +177,8 @@ default QueryStatement setDynamic( } } case FLOAT: - if (value instanceof Number) { - return setFloat(statement, index, ((Number) value).floatValue()); + if (value instanceof Number number) { + return setFloat(statement, index, number.floatValue()); } else { Float f = convertRequired(value, Float.class); if (f != null) { @@ -188,8 +188,8 @@ default QueryStatement setDynamic( } } case SHORT: - if (value instanceof Number) { - return setShort(statement, index, ((Number) value).shortValue()); + if (value instanceof Number number) { + return setShort(statement, index, number.shortValue()); } else { Short s = convertRequired(value, Short.class); if (s != null) { @@ -199,8 +199,8 @@ default QueryStatement setDynamic( } } case BYTE: - if (value instanceof Number) { - return setByte(statement, index, ((Number) value).byteValue()); + if (value instanceof Number number) { + return setByte(statement, index, number.byteValue()); } else { Byte n = convertRequired(value, Byte.class); if (n != null) { diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/sql/SqlResultEntityTypeMapper.java b/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/sql/SqlResultEntityTypeMapper.java index 13ee84a028..ed00f8d8d3 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/sql/SqlResultEntityTypeMapper.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/mapper/sql/SqlResultEntityTypeMapper.java @@ -524,8 +524,8 @@ private K readEntity(RS rs, MappingContext ctx, @Nullable Object parent, } BeanProperty property = rpp.getProperty(); if (rpp instanceof RuntimeAssociation entityAssociation) { - if (rpp instanceof Embedded) { - Object value = readEntity(rs, ctx.embedded((Embedded) rpp), parent == null ? entity : parent, null); + if (rpp instanceof Embedded embedded) { + Object value = readEntity(rs, ctx.embedded(embedded), parent == null ? entity : parent, null); entity = setProperty(property, entity, value); } else { final boolean isInverse = parent != null && entityAssociation.getKind().isSingleEnded() && isAssociation && ctx.association.getOwner() == entityAssociation.getAssociatedEntity(); @@ -624,8 +624,8 @@ private Object readEntityId(RS rs, MappingContext ctx) { if (identity == null) { return null; } - if (identity instanceof Embedded) { - return readEntity(rs, ctx.embedded((Embedded) identity), null, null); + if (identity instanceof Embedded embedded) { + return readEntity(rs, ctx.embedded(embedded), null, null); } return readProperty(rs, ctx, identity); } @@ -636,9 +636,9 @@ private K convertAndSetWithValue(K entity, RuntimePersistentProperty rpp, private Object convert(RuntimePersistentProperty rpp, Object v) { Class propertyType = rpp.getType(); - if (v instanceof Array) { + if (v instanceof Array array) { try { - v = ((Array) v).getArray(); + v = array.getArray(); } catch (SQLException e) { throw new DataAccessException("Error getting an array value: " + e.getMessage(), e); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/AbstractRepositoryOperations.java b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/AbstractRepositoryOperations.java index c894758d0a..c0c2aba2a2 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/AbstractRepositoryOperations.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/AbstractRepositoryOperations.java @@ -157,8 +157,8 @@ protected boolean isOnlySingleEndedJoins(RuntimePersistentEntity rootPersiste if (propertyPath == null) { return Stream.empty(); } - if (propertyPath.getProperty() instanceof Association) { - return Stream.concat(propertyPath.getAssociations().stream(), Stream.of((Association) propertyPath.getProperty())); + if (propertyPath.getProperty() instanceof Association association) { + return Stream.concat(propertyPath.getAssociations().stream(), Stream.of(association)); } return propertyPath.getAssociations().stream(); }) diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/AbstractSyncEntitiesOperations.java b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/AbstractSyncEntitiesOperations.java index 0eb63cc3e2..e53f01faa1 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/AbstractSyncEntitiesOperations.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/AbstractSyncEntitiesOperations.java @@ -80,8 +80,8 @@ protected AbstractSyncEntitiesOperations(Ctx ctx, this.hasGeneratedId = insert && persistentEntity.getIdentity() != null && persistentEntity.getIdentity().isGenerated(); Objects.requireNonNull(entities, "Entities cannot be null"); Stream stream; - if (entities instanceof Collection) { - stream = ((Collection) entities).stream(); + if (entities instanceof Collection collection) { + stream = collection.stream(); } else { stream = CollectionUtils.iterableToList(entities).stream(); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/query/DefaultBindableParametersPreparedQuery.java b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/query/DefaultBindableParametersPreparedQuery.java index cfdb1ca995..abf0ac9128 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/query/DefaultBindableParametersPreparedQuery.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/query/DefaultBindableParametersPreparedQuery.java @@ -60,8 +60,8 @@ public DefaultBindableParametersPreparedQuery(PreparedQuery preparedQuery, } private static BindableParametersStoredQuery unwrap(StoredQuery storedQuery) { - if (storedQuery instanceof BindableParametersStoredQuery) { - return (BindableParametersStoredQuery) storedQuery; + if (storedQuery instanceof BindableParametersStoredQuery bindableParametersStoredQuery) { + return bindableParametersStoredQuery; } if (storedQuery instanceof DelegateStoredQuery) { return unwrap(storedQuery); diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/query/DefaultBindableParametersStoredQuery.java b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/query/DefaultBindableParametersStoredQuery.java index 2edbdbd05b..2384b86fee 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/query/DefaultBindableParametersStoredQuery.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/query/DefaultBindableParametersStoredQuery.java @@ -224,14 +224,14 @@ private List expandValue(Object value, @Nullable DataType dataType) { if (value == null || dataType != null && dataType.isArray() && dataType != DataType.BYTE_ARRAY || value instanceof byte[]) { // not expanded return null; - } else if (value instanceof Iterable) { - return (List) CollectionUtils.iterableToList((Iterable) value); + } else if (value instanceof Iterable iterable) { + return (List) CollectionUtils.iterableToList(iterable); } else if (value.getClass().isArray()) { int len = Array.getLength(value); if (len == 0) { return Collections.emptyList(); } else { - List list = new ArrayList<>(len); + var list = new ArrayList<>(len); for (int j = 0; j < len; j++) { Object o = Array.get(value, j); list.add(o); diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/sql/AbstractSqlRepositoryOperations.java b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/sql/AbstractSqlRepositoryOperations.java index c8ebe576be..2427ec05c6 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/sql/AbstractSqlRepositoryOperations.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/sql/AbstractSqlRepositoryOperations.java @@ -361,7 +361,7 @@ protected SqlStoredQuery resolveEntityUpdate(AnnotationMetadata annota .idEq(new QueryParameter(idName)); List updateProperties = persistentEntity.getPersistentProperties() .stream().filter(p -> - !((p instanceof Association) && ((Association) p).isForeignKey()) && + !(p instanceof Association association && association.isForeignKey()) && p.getAnnotationMetadata().booleanValue(AutoPopulated.class, "updateable").orElse(true) ) .map(PersistentProperty::getName) @@ -467,8 +467,8 @@ private Stream> idPropertiesWithValues(Per } protected final SqlPreparedQuery getSqlPreparedQuery(PreparedQuery preparedQuery) { - if (preparedQuery instanceof SqlPreparedQuery) { - return (SqlPreparedQuery) preparedQuery; + if (preparedQuery instanceof SqlPreparedQuery sqlPreparedQuery) { + return sqlPreparedQuery; } throw new IllegalStateException("Expected for prepared query to be of type: SqlPreparedQuery got: " + preparedQuery.getClass().getName()); } diff --git a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/sql/DefaultSqlPreparedQuery.java b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/sql/DefaultSqlPreparedQuery.java index 8ac04d8af9..64d0d0aae5 100644 --- a/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/sql/DefaultSqlPreparedQuery.java +++ b/data-runtime/src/main/java/io/micronaut/data/runtime/operations/internal/sql/DefaultSqlPreparedQuery.java @@ -35,7 +35,6 @@ import java.lang.reflect.Array; import java.util.Collection; -import java.util.Iterator; import java.util.Map; /** @@ -225,13 +224,11 @@ protected int sizeOf(Object value) { if (value == null) { return 1; } - if (value instanceof Collection) { - return ((Collection) value).size(); - } else if (value instanceof Iterable) { + if (value instanceof Collection collection) { + return collection.size(); + } else if (value instanceof Iterable iterable) { int i = 0; - Iterator iterator = ((Iterable) value).iterator(); - while (iterator.hasNext()) { - iterator.next(); + for (Object o : iterable) { i++; } return i; diff --git a/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/CountSpecificationInterceptor.java b/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/CountSpecificationInterceptor.java index 2e00a49efd..18a9973430 100644 --- a/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/CountSpecificationInterceptor.java +++ b/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/CountSpecificationInterceptor.java @@ -42,8 +42,7 @@ public final class CountSpecificationInterceptor extends io.micronaut.data.jpa.r @Override protected io.micronaut.data.jpa.repository.criteria.Specification getSpecification(MethodInvocationContext context, boolean nullable) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof Specification) { - Specification springSpecification = (Specification) parameterValue; + if (parameterValue instanceof Specification springSpecification) { return (root, query, criteriaBuilder) -> springSpecification.toPredicate(root, query, criteriaBuilder); } return super.getSpecification(context, false); diff --git a/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindAllSpecificationInterceptor.java b/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindAllSpecificationInterceptor.java index cfb215f626..0b0af5d386 100644 --- a/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindAllSpecificationInterceptor.java +++ b/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindAllSpecificationInterceptor.java @@ -50,8 +50,7 @@ public final class FindAllSpecificationInterceptor extends io.micronaut.data.jpa @Override protected io.micronaut.data.jpa.repository.criteria.Specification getSpecification(MethodInvocationContext context, boolean nullable) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof Specification) { - Specification springSpecification = (Specification) parameterValue; + if (parameterValue instanceof Specification springSpecification) { return (root, query, criteriaBuilder) -> springSpecification.toPredicate(root, query, criteriaBuilder); } return super.getSpecification(context, false); @@ -59,8 +58,7 @@ protected io.micronaut.data.jpa.repository.criteria.Specification getSpecificati @Override protected void addSort(Object sortObject, CriteriaQuery query, Root root, CriteriaBuilder criteriaBuilder) { - if (sortObject instanceof Sort) { - Sort sort = (Sort) sortObject; + if (sortObject instanceof Sort sort) { if (sort.isSorted()) { final List orders = QueryUtils.toOrders(sort, root, criteriaBuilder); query.orderBy(orders); diff --git a/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindOneSpecificationInterceptor.java b/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindOneSpecificationInterceptor.java index 96ffb5487b..f9ba126d3c 100644 --- a/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindOneSpecificationInterceptor.java +++ b/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindOneSpecificationInterceptor.java @@ -42,8 +42,7 @@ public final class FindOneSpecificationInterceptor extends io.micronaut.data.jpa @Override protected io.micronaut.data.jpa.repository.criteria.Specification getSpecification(MethodInvocationContext context, boolean nullable) { final Object parameterValue = context.getParameterValues()[0]; - if (parameterValue instanceof Specification) { - Specification springSpecification = (Specification) parameterValue; + if (parameterValue instanceof Specification springSpecification) { return (root, query, criteriaBuilder) -> springSpecification.toPredicate(root, query, criteriaBuilder); } return super.getSpecification(context, false); diff --git a/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindPageSpecificationInterceptor.java b/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindPageSpecificationInterceptor.java index 3ab626c075..b6976879a4 100644 --- a/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindPageSpecificationInterceptor.java +++ b/data-spring-jpa/src/main/java/io/micronaut/data/spring/jpa/intercept/FindPageSpecificationInterceptor.java @@ -54,8 +54,8 @@ public final class FindPageSpecificationInterceptor extends AbstractQueryInterce */ FindPageSpecificationInterceptor(@NonNull RepositoryOperations operations) { super(operations); - if (operations instanceof JpaRepositoryOperations) { - this.jpaOperations = (JpaRepositoryOperations) operations; + if (operations instanceof JpaRepositoryOperations jpaRepositoryOperations) { + this.jpaOperations = jpaRepositoryOperations; } else { throw new IllegalStateException("Repository operations must be na instance of JpaRepositoryOperations"); } @@ -69,8 +69,7 @@ public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext query = criteriaBuilder.createQuery(getRequiredRootEntity(context)); @@ -81,8 +80,7 @@ public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext orders = QueryUtils.toOrders(sort, root, criteriaBuilder); diff --git a/data-tx-hibernate/src/main/java/io/micronaut/transaction/hibernate/HibernateTransactionManager.java b/data-tx-hibernate/src/main/java/io/micronaut/transaction/hibernate/HibernateTransactionManager.java index 3c24b2885b..6bcfc95fce 100644 --- a/data-tx-hibernate/src/main/java/io/micronaut/transaction/hibernate/HibernateTransactionManager.java +++ b/data-tx-hibernate/src/main/java/io/micronaut/transaction/hibernate/HibernateTransactionManager.java @@ -276,15 +276,15 @@ public boolean hasConnection() { * @see org.hibernate.ConnectionReleaseMode#ON_CLOSE */ private boolean isSameConnectionForEntireSession(Session session) { - if (!(session instanceof SessionImplementor)) { + if (!(session instanceof SessionImplementor sessionImplementor)) { // The best we can do is to assume we're safe. return true; } PhysicalConnectionHandlingMode releaseMode = - ((SessionImplementor) session).getJdbcCoordinator() + sessionImplementor.getJdbcCoordinator() .getLogicalConnection() .getConnectionHandlingMode(); - return PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_HOLD.equals(releaseMode); + return PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_HOLD == releaseMode; } /** @@ -296,11 +296,11 @@ private boolean isSameConnectionForEntireSession(Session session) { * @see #isSameConnectionForEntireSession(Session) */ private boolean isPhysicallyConnected(Session session) { - if (!(session instanceof SessionImplementor)) { + if (!(session instanceof SessionImplementor sessionImplementor)) { // The best we can do is to check whether we're logically connected. return session.isConnected(); } - return ((SessionImplementor) session).getJdbcCoordinator().getLogicalConnection().isPhysicallyConnected(); + return sessionImplementor.getJdbcCoordinator().getLogicalConnection().isPhysicallyConnected(); } private Connection getConnection(Session session) { diff --git a/data-tx/build.gradle b/data-tx/build.gradle index 992faea1c8..b499e4d1e1 100644 --- a/data-tx/build.gradle +++ b/data-tx/build.gradle @@ -33,14 +33,11 @@ dependencies { testImplementation mnSql.micronaut.jdbc testImplementation mnReactor.micronaut.reactor testImplementation mnTest.micronaut.test.junit5 + testImplementation "javax.transaction:javax.transaction-api:1.3" testRuntimeOnly mnSql.h2 testRuntimeOnly mnSql.micronaut.jdbc.tomcat - - testImplementation(libs.jupiter.api) testRuntimeOnly(libs.jupiter.engine) - - testImplementation "javax.transaction:javax.transaction-api:1.3" } test { diff --git a/doc-examples/jdbc-multitenancy-datasource-example-java/src/test/java/example/BookJdbcDatasourceMultiTenancySpec.java b/doc-examples/jdbc-multitenancy-datasource-example-java/src/test/java/example/BookJdbcDatasourceMultiTenancySpec.java index d4cab9f39b..69e1be0847 100644 --- a/doc-examples/jdbc-multitenancy-datasource-example-java/src/test/java/example/BookJdbcDatasourceMultiTenancySpec.java +++ b/doc-examples/jdbc-multitenancy-datasource-example-java/src/test/java/example/BookJdbcDatasourceMultiTenancySpec.java @@ -1,5 +1,6 @@ package example; +import io.micronaut.data.connection.jdbc.advice.DelegatingDataSource; import io.micronaut.http.annotation.Header; import io.micronaut.http.client.annotation.Client; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; @@ -74,7 +75,7 @@ void testRest() throws SQLException { } private long getBooksCount(DataSource ds) throws SQLException { - if (ds instanceof io.micronaut.data.connection.jdbc.advice.DelegatingDataSource delegatingDataSource) { + if (ds instanceof DelegatingDataSource delegatingDataSource) { ds = delegatingDataSource.getTargetDataSource(); } try (Connection connection = ds.getConnection()) { diff --git a/doc-examples/jdbc-multitenancy-schema-example-java/src/test/java/example/BookJdbcSchemaMultiTenancySpec.java b/doc-examples/jdbc-multitenancy-schema-example-java/src/test/java/example/BookJdbcSchemaMultiTenancySpec.java index e0c7659080..29fbf20c35 100644 --- a/doc-examples/jdbc-multitenancy-schema-example-java/src/test/java/example/BookJdbcSchemaMultiTenancySpec.java +++ b/doc-examples/jdbc-multitenancy-schema-example-java/src/test/java/example/BookJdbcSchemaMultiTenancySpec.java @@ -73,8 +73,8 @@ void testRest() throws SQLException { } private long getBooksCount(String schemaName) throws SQLException { - if (dataSource instanceof DelegatingDataSource) { - dataSource = ((DelegatingDataSource) dataSource).getTargetDataSource(); + if (dataSource instanceof DelegatingDataSource delegatingDataSource) { + dataSource = delegatingDataSource.getTargetDataSource(); } try (Connection connection = dataSource.getConnection()) { jdbcSchemaHandler.useSchema(connection, Dialect.H2, schemaName);