Skip to content

Commit

Permalink
Fix Sonar bugs (#1355)
Browse files Browse the repository at this point in the history
  • Loading branch information
dstepanov committed Feb 25, 2022
1 parent f2dad95 commit 1df4cd8
Show file tree
Hide file tree
Showing 23 changed files with 92 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ public QueryResult buildQuery(AnnotationMetadata annotationMetadata, QueryModel
ArgumentUtils.requireNonNull("annotationMetadata", annotationMetadata);
ArgumentUtils.requireNonNull("query", query);

QueryState queryState = new QueryState(query, true, false);
QueryState queryState = new QueryState(query, true);

Map<String, Object> predicateObj = new LinkedHashMap<>();
Map<String, Object> group = new LinkedHashMap<>();
Expand Down Expand Up @@ -436,7 +436,8 @@ private void addLookups(Collection<JoinPath> joins, QueryState queryState) {
} else {
String currentPath = asPath(propertyPath.getAssociations(), propertyPath.getProperty());
if (association.isForeignKey()) {
String mappedBy = association.getAnnotationMetadata().stringValue(Relation.class, "mappedBy").get();
String mappedBy = association.getAnnotationMetadata().stringValue(Relation.class, "mappedBy")
.orElseThrow(IllegalStateException::new);
PersistentPropertyPath mappedByPath = association.getAssociatedEntity().getPropertyPath(mappedBy);
if (mappedByPath == null) {
throw new IllegalStateException("Cannot find mapped path: " + mappedBy);
Expand Down Expand Up @@ -693,10 +694,10 @@ private void addProjection(Map<String, Object> groupBy, QueryModel.PropertyProje

@NonNull
private PersistentPropertyPath findProperty(QueryState queryState, String name, Class criterionType) {
return findPropertyInternal(queryState, queryState.getEntity(), queryState.getRootAlias(), name, criterionType);
return findPropertyInternal(queryState, queryState.getEntity(), name, criterionType);
}

private PersistentPropertyPath findPropertyInternal(QueryState queryState, PersistentEntity entity, String tableAlias, String name, Class criterionType) {
private PersistentPropertyPath findPropertyInternal(QueryState queryState, PersistentEntity entity, String name, Class criterionType) {
PersistentPropertyPath propertyPath = entity.getPropertyPath(name);
if (propertyPath != null) {
if (propertyPath.getAssociations().isEmpty()) {
Expand Down Expand Up @@ -786,7 +787,7 @@ public QueryResult buildUpdate(AnnotationMetadata annotationMetadata, QueryModel
ArgumentUtils.requireNonNull("query", query);
ArgumentUtils.requireNonNull("propertiesToUpdate", propertiesToUpdate);

QueryState queryState = new QueryState(query, true, false);
QueryState queryState = new QueryState(query, true);

QueryModel.Junction criteria = query.getCriteria();

Expand Down Expand Up @@ -849,7 +850,7 @@ public QueryResult buildDelete(AnnotationMetadata annotationMetadata, QueryModel
ArgumentUtils.requireNonNull("annotationMetadata", annotationMetadata);
ArgumentUtils.requireNonNull("query", query);

QueryState queryState = new QueryState(query, true, false);
QueryState queryState = new QueryState(query, true);

QueryModel.Junction criteria = query.getCriteria();

Expand Down Expand Up @@ -1089,7 +1090,6 @@ private LookupsStage(PersistentEntity persistentEntity) {
*/
@Internal
protected final class QueryState implements PropertyParameterCreator {
private final String rootAlias;
private final Set<String> joinPaths = new TreeSet<>();
private final AtomicInteger position = new AtomicInteger(0);
private final Map<String, String> additionalRequiredParameters = new LinkedHashMap<>();
Expand All @@ -1099,22 +1099,13 @@ protected final class QueryState implements PropertyParameterCreator {

private final LookupsStage rootLookups;

private QueryState(QueryModel query, boolean allowJoins, boolean useAlias) {
private QueryState(QueryModel query, boolean allowJoins) {
this.allowJoins = allowJoins;
this.entity = query.getPersistentEntity();
this.rootAlias = useAlias ? null : null;
this.parameterBindings = new ArrayList<>(entity.getPersistentPropertyNames().size());
this.rootLookups = new LookupsStage(entity);
}

/**
* @return The root alias
*/
public @Nullable
String getRootAlias() {
return rootAlias;
}

/**
* @return The entity
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ private void buildRawQuery(@NonNull MethodMatchContext matchContext,
persistentEntity = matchContext.getEntity(entityParameter.getGenericType());
} else if (entitiesParameter != null) {
entityParam = entitiesParameter;
persistentEntity = matchContext.getEntity(entitiesParameter.getGenericType().getFirstTypeArgument().get());
persistentEntity = matchContext.getEntity(entitiesParameter.getGenericType().getFirstTypeArgument()
.orElseThrow(IllegalStateException::new));
}

QueryResult queryResult;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,9 @@ public void createSchema(BeanLocator beanLocator) {
if (DataSettings.QUERY_LOG.isDebugEnabled()) {
DataSettings.QUERY_LOG.debug("Dropping Tables: \n{}", sql);
}
PreparedStatement ps = connection.prepareStatement(sql);
ps.executeUpdate();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.executeUpdate();
}
} catch (SQLException e) {
if (DataSettings.QUERY_LOG.isTraceEnabled()) {
DataSettings.QUERY_LOG.trace("Drop Unsuccessful: " + e.getMessage());
Expand All @@ -114,8 +115,9 @@ public void createSchema(BeanLocator beanLocator) {
if (DataSettings.QUERY_LOG.isDebugEnabled()) {
DataSettings.QUERY_LOG.debug("Creating Tables: \n{}", sql);
}
PreparedStatement ps = connection.prepareStatement(sql);
ps.executeUpdate();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.executeUpdate();
}
break;
default:
// do nothing
Expand All @@ -130,8 +132,9 @@ public void createSchema(BeanLocator beanLocator) {
if (DataSettings.QUERY_LOG.isDebugEnabled()) {
DataSettings.QUERY_LOG.debug("Dropping Table: \n{}", sql);
}
PreparedStatement ps = connection.prepareStatement(sql);
ps.executeUpdate();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.executeUpdate();
}
}
} catch (SQLException e) {
if (DataSettings.QUERY_LOG.isTraceEnabled()) {
Expand All @@ -148,8 +151,9 @@ public void createSchema(BeanLocator beanLocator) {
DataSettings.QUERY_LOG.debug("Executing CREATE statement: \n{}", stmt);
}
try {
PreparedStatement ps = connection.prepareStatement(stmt);
ps.executeUpdate();
try (PreparedStatement ps = connection.prepareStatement(stmt)) {
ps.executeUpdate();
}
} catch (SQLException e) {
if (DataSettings.QUERY_LOG.isWarnEnabled()) {
DataSettings.QUERY_LOG.warn("CREATE Statement Unsuccessful: " + e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
Expand Down Expand Up @@ -818,33 +819,43 @@ public <T> Stream<T> entityStream(@NonNull ResultSet resultSet, @Nullable String
ArgumentUtils.requireNonNull("rootEntity", rootEntity);
TypeMapper<ResultSet, T> mapper = new SqlResultEntityTypeMapper<>(prefix, getEntity(rootEntity), columnNameResultSetReader, jsonCodec, conversionService);
Iterable<T> iterable = () -> new Iterator<T>() {
boolean nextCalled = false;
boolean fetched = false;
boolean end = false;

@Override
public boolean hasNext() {
if (fetched) {
return true;
}
if (end) {
return false;
}
try {
if (!nextCalled) {
nextCalled = true;
return resultSet.next();
if (resultSet.next()) {
fetched = true;
} else {
return nextCalled;
end = true;
}
} catch (SQLException e) {
throw new DataAccessException("Error retrieving next JDBC result: " + e.getMessage(), e);
}
return !end;
}

@Override
public T next() {
nextCalled = false;
if (!hasNext()) {
throw new NoSuchElementException();
}
fetched = false;
return mapper.map(resultSet, rootEntity);
}
};
return StreamSupport.stream(iterable.spliterator(), false);
}

@NonNull
protected ResultConsumer.Context<ResultSet> newMappingContext(ResultSet rs) {
private ResultConsumer.Context<ResultSet> newMappingContext(ResultSet rs) {
return new ResultConsumer.Context<ResultSet>() {
@Override
public ResultSet getResultSet() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1942,7 +1942,7 @@ public NamingStrategy getNamingStrategy() {
* @return should escape
*/
public boolean shouldEscape() {
return AbstractSqlLikeQueryBuilder.this.shouldEscape(propertyPath.findPropertyOwner().get());
return AbstractSqlLikeQueryBuilder.this.shouldEscape(propertyPath.findPropertyOwner().orElse(propertyPath.getProperty().getOwner()));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1402,18 +1402,6 @@ private void join(StringBuilder sb,
List<Association> rightPropertyAssociations,
PersistentProperty rightProperty) {

if (!computePropertyPaths()) {
join(sb,
queryState.getQueryModel(),
joinType,
getTableName(associatedEntity),
leftTableAlias,
rightTableAlias,
asPath(leftPropertyAssociations, leftProperty),
asPath(rightPropertyAssociations, rightProperty)
);
return;
}
final boolean escape = shouldEscape(associationOwner);
List<String> onLeftColumns = new ArrayList<>();
List<String> onRightColumns = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
Expand Down Expand Up @@ -237,9 +238,14 @@ protected <R> R convertResult(CodecRegistry codecRegistry,
if (result == null) {
value = BsonNull.VALUE;
} else if (result.size() == 1) {
value = result.values().iterator().next().asNumber();
value = result.values().iterator().next();
} else if (result.size() == 2) {
value = result.entrySet().stream().filter(f -> !f.getKey().equals("_id")).findFirst().get().getValue();
Optional<Map.Entry<String, BsonValue>> id = result.entrySet().stream().filter(f -> !f.getKey().equals("_id")).findFirst();
if (id.isPresent()) {
value = id.get().getValue();
} else {
value = result.values().iterator().next();
}
} else if (isDtoProjection) {
Object dtoResult = MongoUtils.toValue(result.asDocument(), resultType, codecRegistry);
if (resultType.isInstance(dtoResult)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ final class DefaultMongoStoredQuery<E, R, Dtb> implements DelegateStoredQuery<E,
conversionService,
persistentEntity,
database,
storedQuery.getAnnotationMetadata().enumValue(DataMethod.NAME, DataMethod.META_MEMBER_OPERATION_TYPE, DataMethod.OperationType.class).get(),
storedQuery.getAnnotationMetadata().enumValue(DataMethod.NAME, DataMethod.META_MEMBER_OPERATION_TYPE, DataMethod.OperationType.class)
.orElseThrow(IllegalStateException::new),
storedQuery.getAnnotationMetadata().stringValue(Query.class, "update").orElse(null));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,10 @@ public Object deserialize(Decoder decoder, DecoderContext decoderContext, Argume

@Override
public Deserializer<Object> createSpecific(DecoderContext decoderContext, Argument<? super Object> type) throws SerdeException {
Class<?> converterClass = type.getAnnotationMetadata().classValue(MappedProperty.class, "converter").get();
Class<Object> converterPersistedType = type.getAnnotationMetadata().classValue(MappedProperty.class, "converterPersistedType").get();
Class<?> converterClass = type.getAnnotationMetadata().classValue(MappedProperty.class, "converter")
.orElseThrow(IllegalStateException::new);
Class<Object> converterPersistedType = type.getAnnotationMetadata().classValue(MappedProperty.class, "converterPersistedType")
.orElseThrow(IllegalStateException::new);
Argument<Object> convertedType = Argument.of(converterPersistedType);
AttributeConverter<Object, Object> converter = attributeConverterRegistry.getConverter(converterClass);
Deserializer<?> deserializer = findDeserializer(convertedType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,10 @@ public void serialize(Encoder encoder, EncoderContext context, Argument<?> type,
CustomConverterSerializer customConverterSerializer = new CustomConverterSerializer() {
@Override
public Serializer<Object> createSpecific(EncoderContext encoderContext, Argument<?> type) throws SerdeException {
Class<?> converterClass = type.getAnnotationMetadata().classValue(MappedProperty.class, "converter").get();
Class<Object> converterPersistedType = type.getAnnotationMetadata().classValue(MappedProperty.class, "converterPersistedType").get();
Class<?> converterClass = type.getAnnotationMetadata().classValue(MappedProperty.class, "converter")
.orElseThrow(IllegalStateException::new);
Class<Object> converterPersistedType = type.getAnnotationMetadata().classValue(MappedProperty.class, "converterPersistedType")
.orElseThrow(IllegalStateException::new);
Argument<Object> convertedType = Argument.of(converterPersistedType);
Serializer<? super Object> serializer = findSerializer(convertedType);
AttributeConverter<Object, Object> converter = attributeConverterRegistry.getConverter(converterClass);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ public boolean isExpandable() {
}
};
}
if (outgoingQueryParameterProperty == null) {
throw new IllegalStateException("Outgoing query parameter property is required!");
}
boolean autopopulated = propertyPath.getProperty()
.findAnnotation(AutoPopulated.class)
.map(ap -> ap.getRequiredValue(AutoPopulated.UPDATEABLE, Boolean.class))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ public Optional<NamingStrategy> apply(String s) {
}

private DataType getDataTypeFromConverter(ClassElement type, String converter, Map<String, DataType> dataTypes, VisitorContext context) {
ClassElement classElement = context.getClassElement(converter).get();
ClassElement classElement = context.getClassElement(converter).orElseThrow(IllegalStateException::new);
ClassElement genericType = classElement.getGenericType();

Map<String, ClassElement> typeArguments = genericType.getTypeArguments(AttributeConverter.class.getName());
Expand Down Expand Up @@ -310,7 +310,7 @@ private DataType getDataTypeFromConverter(ClassElement type, String converter, M
}

private ClassElement getPersistedClassFromConverter(String converter, VisitorContext context) {
ClassElement classElement = context.getClassElement(converter).get();
ClassElement classElement = context.getClassElement(converter).orElseThrow(IllegalStateException::new);
ClassElement genericType = classElement.getGenericType();

Map<String, ClassElement> typeArguments = genericType.getTypeArguments(AttributeConverter.class.getName());
Expand Down

0 comments on commit 1df4cd8

Please sign in to comment.