Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package it.aboutbits.springboot.toolbox.parameter;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

@Slf4j
@ToString
@Accessors(fluent = true)
public final class PageParameter {
@Getter
@Setter
@SuppressWarnings({"checkstyle:StaticVariableName", "java:S3008"})
private static int MAX_PAGE_SIZE = 9999;

@Getter
@Setter
@SuppressWarnings({"checkstyle:StaticVariableName", "java:S3008"})
private static int DEFAULT_PAGE_SIZE = 50;

private record PageInfo(int page, int size, boolean paged) {
}

private final PageInfo pageInfo;

private PageParameter(Integer page, Integer size) {
var actualPage = (page == null) ? 0 : page;
var actualSize = (size == null) ? DEFAULT_PAGE_SIZE : size;

if (actualSize > MAX_PAGE_SIZE) {
log.warn("Page size exceeded maximum [actualSize={}, maxSize={}]", actualSize, MAX_PAGE_SIZE);
}

pageInfo = new PageInfo(
Math.max(0, actualPage),
Math.min(actualSize, MAX_PAGE_SIZE),
true
);
}

private PageParameter() {
pageInfo = new PageInfo(0, Integer.MAX_VALUE, false);
}

public static PageParameter of(Integer page) {
return new PageParameter(page, null);
}

public static PageParameter of(Integer page, Integer size) {
return new PageParameter(page, size);
}

public static PageParameter defaultPage() {
return new PageParameter(null, null);
}

public static PageParameter unpaged() {
return new PageParameter();
}

public int page() {
return pageInfo.page();
}

public int size() {
return pageInfo.size();
}

public boolean isPaged() {
return pageInfo.paged();
}

public boolean isUnpaged() {
return !pageInfo.paged();
}

public PageRequest toPageRequest() {
return PageRequest.of(page(), size());
}

public PageRequest toPageRequest(Sort sort) {
return PageRequest.of(page(), size(), sort);
}

@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj instanceof PageParameter pageParameter) {
return this.pageInfo.equals(pageParameter.pageInfo);
}
return false;
}

@Override
public int hashCode() {
return super.hashCode();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package it.aboutbits.springboot.toolbox.parameter;

import lombok.NonNull;
import org.springframework.data.domain.Sort;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public record SortParameter<T extends Enum<?> & SortParameter.Definition>(List<SortField> sortFields) {
private static final String DEFAULT_SORT_PROPERTY = "id";
private static final Sort DEFAULT_SORT = Sort.by(
Sort.Direction.ASC,
DEFAULT_SORT_PROPERTY
);

public static <T extends Enum<?> & Definition> SortParameter<T> unsorted() {
return new SortParameter<>(Collections.emptyList());
}

@SafeVarargs
public static <T extends Enum<?> & Definition> SortParameter<T> by(
@NonNull T... sortDefinitions
) {
return new SortParameter<>(
Stream.of(sortDefinitions)
.map(sortDefinition -> new SortField(
sortDefinition.name(),
Sort.Direction.ASC,
Sort.NullHandling.NATIVE
)
)
.toList()
);
}

public static <T extends Enum<?> & Definition> SortParameter<T> by(
@NonNull T sortDefinition,
@NonNull Sort.Direction direction,
@NonNull Sort.NullHandling nullHandling
) {
return new SortParameter<>(
List.of(new SortField(
sortDefinition.name(),
direction,
nullHandling
)
)
);
}

public SortParameter<T> or(@NonNull SortParameter<T> fallback) {
return sortFields == null || sortFields.isEmpty() ? fallback : this;
}

public Sort buildSortWithoutDefault(@NonNull Map<T, String> mapping) {
var stringMapping = mapping.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().name(),
Map.Entry::getValue
));

return buildSort(stringMapping, false);
}

public Sort buildSort(@NonNull Map<T, String> mapping) {
var stringMapping = mapping.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().name(),
Map.Entry::getValue
));

return buildSort(stringMapping, true);
}

// SonarLint: Replace this usage of 'Stream.collect(Collectors.toList())' with 'Stream.toList()' and ensure that the list is unmodified.
@SuppressWarnings("java:S6204")
private Sort buildSort(@NonNull Map<String, String> mapping, boolean withDefault) {
if (sortFields == null || sortFields.isEmpty()) {
return withDefault ? DEFAULT_SORT : Sort.unsorted();
}

var additionalSort = Sort.by(
sortFields.stream()
.filter(sortField -> mapping.containsKey(sortField.property()))
.map(sortField -> new Sort.Order(
sortField.direction(),
mapping.get(sortField.property()),
sortField.nullHandling()
))
// We do not use .toList() here as we potentially want to modify the sort list later in the StoreImpl
.collect(Collectors.toList())
);

if (withDefault) {
var includesDefault = additionalSort.getOrderFor(DEFAULT_SORT_PROPERTY) != null;
if (!includesDefault) {
return additionalSort.and(DEFAULT_SORT);
}
}
return additionalSort;
}

public record SortField(
@NonNull String property,
@NonNull Sort.Direction direction,
@NonNull Sort.NullHandling nullHandling
) {
}

public interface Definition {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package it.aboutbits.springboot.toolbox.persistence;

import it.aboutbits.springboot.toolbox.parameter.SortParameter;
import lombok.NonNull;

import java.util.HashMap;

public final class SortMappings<T extends Enum<?> & SortParameter.Definition> extends HashMap<T, String> {
private SortMappings() {
super();
}

public static <T extends Enum<?> & SortParameter.Definition> Mapping<T> map(
@NonNull T property,
@NonNull String column
) {
return new Mapping<>(property, column);
}

@SafeVarargs
public static <T extends Enum<?> & SortParameter.Definition> SortMappings<T> of(
@NonNull Mapping<T>... mappings
) {
var sortMappings = new SortMappings<T>();

for (var mapping : mappings) {
sortMappings.put(mapping.property(), mapping.column());
}

return sortMappings;
}

public record Mapping<T extends Enum<?> & SortParameter.Definition>(@NonNull T property, @NonNull String column) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.StringSchema;
import lombok.RequiredArgsConstructor;
import it.aboutbits.springboot.toolbox.parameter.SortParameter;
import org.springdoc.core.customizers.OpenApiCustomizer;

@RequiredArgsConstructor
public class SortParameterCustomizer implements OpenApiCustomizer {
private final Class<?> sortParameterSortFieldClass;
private final String nameToMatch = "." + SortParameter.class.getSimpleName();

@Override
public void customise(OpenAPI openApi) {
Expand All @@ -29,7 +28,7 @@ public void customise(OpenAPI openApi) {
continue;
}

if (parameter.getSchema().get$ref().endsWith(".SortParameter")) {
if (parameter.getSchema().get$ref().endsWith(nameToMatch)) {
parameter.required(false);
parameter.description(
"""
Expand Down Expand Up @@ -85,7 +84,7 @@ public void customise(OpenAPI openApi) {
);
var itemSchema = new StringSchema()._default("property:asc:last");
itemSchema.setDescription(
"{\"originalTypeFqn\": \"%s\"}".formatted(sortParameterSortFieldClass.getName())
"{\"originalTypeFqn\": \"%s\"}".formatted(SortParameter.class.getName())
);

parameter.setSchema(new ArraySchema().items(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package it.aboutbits.springboot.toolbox.web;

import it.aboutbits.springboot.toolbox.parameter.SortParameter;
import lombok.NonNull;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.ArrayList;
import java.util.Objects;

public class SortParameterResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return SortParameter.class.isAssignableFrom(parameter.getParameterType());
}

@Override
public Object resolveArgument(
@NonNull MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory
) throws IllegalArgumentException {
var sorts = webRequest.getParameterValues(
Objects.requireNonNull(parameter.getParameterName())
);

// Allow empty order list
if (sorts == null) {
return SortParameter.unsorted();
}

var sortFields = new ArrayList<SortParameter.SortField>(sorts.length);
for (var order : sorts) {
var parts = order.split(":");
if (parts.length == 1) {
sortFields.add(new SortParameter.SortField(
parts[0],
org.springframework.data.domain.Sort.DEFAULT_DIRECTION,
org.springframework.data.domain.Sort.NullHandling.NATIVE
));
} else if (parts.length == 2) {
sortFields.add(new SortParameter.SortField(
parts[0],
org.springframework.data.domain.Sort.Direction.fromString(parts[1]),
org.springframework.data.domain.Sort.NullHandling.NATIVE
));
} else if (parts.length == 3) {
sortFields.add(new SortParameter.SortField(
parts[0],
org.springframework.data.domain.Sort.Direction.fromString(parts[1]),
nullHandlingFromString(parts[2])
));
} else {
throw new IllegalArgumentException(
"Invalid sort order, only a maximum of two semicolons are allowed in format <property>[:asc|desc][:native|first|last] -> Your input " + order
);
}
}

return new SortParameter<>(sortFields);
}

private org.springframework.data.domain.Sort.NullHandling nullHandlingFromString(@NonNull String value) {
return switch (value.toLowerCase()) {
case "first":
yield org.springframework.data.domain.Sort.NullHandling.NULLS_FIRST;
case "last":
yield org.springframework.data.domain.Sort.NullHandling.NULLS_LAST;
case "native":
yield org.springframework.data.domain.Sort.NullHandling.NATIVE;
default:
throw new IllegalArgumentException(
"Only native, first or last are allowed as null handling strategy -> Your input " + value
);
};
}
}
Loading