Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort Support for feign pagination #328

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -42,6 +42,7 @@
import org.springframework.cloud.openfeign.support.PageJacksonModule;
import org.springframework.cloud.openfeign.support.PageableSpringEncoder;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SortJacksonModule;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
Expand Down Expand Up @@ -150,6 +151,12 @@ public Module pageJacksonModule() {
return new PageJacksonModule();
}

@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Page")
public Module sortModule() {
return new SortJacksonModule();
}

private Encoder springEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider) {
AbstractFormWriter formWriter = formWriterProvider.getIfAvailable();

Expand Down
Expand Up @@ -65,9 +65,17 @@ static class SimplePageImpl<T> implements Page<T> {

SimplePageImpl(@JsonProperty("content") List<T> content,
@JsonProperty("number") int number, @JsonProperty("size") int size,
@JsonProperty("totalElements") long totalElements) {
delegate = new PageImpl<>(content, PageRequest.of(number, size),
totalElements);
@JsonProperty("totalElements") long totalElements,
@JsonProperty("sort") Sort sort) {
PageRequest pageRequest;
if (sort != null) {
pageRequest = PageRequest.of(number, size, sort);
}
else {
pageRequest = PageRequest.of(number, size);
}
delegate = new PageImpl<>(content, pageRequest, totalElements);

}

@JsonProperty
Expand Down
@@ -0,0 +1,56 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.openfeign.support;

import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.module.SimpleDeserializers;
import com.fasterxml.jackson.databind.module.SimpleSerializers;

import org.springframework.data.domain.Sort;

/**
* This jackson module provides support to add serialize and deserialize for spring
* {@link Sort} object.
*
* @author canbezmen
*/
public class SortJacksonModule extends Module {

@Override
public String getModuleName() {
return "SortModule";
}

@Override
public Version version() {
return new Version(0, 1, 0, "", null, null);
}

@Override
public void setupModule(SetupContext context) {
SimpleSerializers serializers = new SimpleSerializers();
serializers.addSerializer(Sort.class, new SortJsonComponent.SortSerializer());
context.addSerializers(serializers);

SimpleDeserializers deserializers = new SimpleDeserializers();
deserializers.addDeserializer(Sort.class,
new SortJsonComponent.SortDeserializer());
context.addDeserializers(deserializers);
}

}
@@ -0,0 +1,93 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.openfeign.support;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.node.ArrayNode;

import org.springframework.data.domain.Sort;

/**
* This class provides support to serialize and deserialize spring {@link Sort} object.
*
* @author canbezmen
*/
public class SortJsonComponent {

public static class SortSerializer extends JsonSerializer<Sort> {

@Override
public void serialize(Sort value, JsonGenerator gen,
SerializerProvider serializers) throws IOException {
gen.writeStartArray();
value.iterator().forEachRemaining(v -> {
try {
gen.writeObject(v);
}
catch (IOException e) {
e.printStackTrace();
}
});
gen.writeEndArray();
}

@Override
public Class<Sort> handledType() {
return Sort.class;
}

}

public static class SortDeserializer extends JsonDeserializer<Sort> {

@Override
public Sort deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
if (treeNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) treeNode;
List<Sort.Order> orders = new ArrayList<>();
for (JsonNode jsonNode : arrayNode) {
Sort.Order order = new Sort.Order(
Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
jsonNode.get("property").textValue());
orders.add(order);
}
return Sort.by(orders);
}
return null;
}

@Override
public Class<Sort> handledType() {
return Sort.class;
}

}

}
Expand Up @@ -16,6 +16,8 @@

package org.springframework.cloud.openfeign.encoding;

import java.util.Optional;

import org.junit.Test;
import org.junit.runner.RunWith;

Expand Down Expand Up @@ -78,6 +80,14 @@ public void testPageable() {
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
assertThat(response.getBody().getPageable().getSort()).hasSize(1);
Optional<Sort.Order> optionalOrder = response.getBody().getPageable().getSort()
.get().findFirst();
if (optionalOrder.isPresent()) {
Sort.Order order = optionalOrder.get();
assertThat(order.getDirection()).isEqualTo(Sort.Direction.ASC);
assertThat(order.getProperty()).isEqualTo("sortProperty");
}

}

Expand Down
@@ -0,0 +1,68 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.openfeign.support;

import java.util.Optional;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;

import static org.assertj.core.api.Assertions.assertThat;

/**
* @author canbezmen
*/
class SortJacksonModuleTests {

private static ObjectMapper objectMapper;

@BeforeAll
public static void initialize() {
objectMapper = new ObjectMapper();
objectMapper.registerModules(new PageJacksonModule());
objectMapper.registerModule(new SortJacksonModule());
}

@Test
public void deserializePage() throws JsonProcessingException {
// Given
String pageJson = "{\"content\":[\"A name\"],\"number\":1,\"size\":2,\"totalElements\":3,\"sort\":[{\"direction\":\"ASC\",\"property\":\"field\",\"ignoreCase\":false,\"nullHandling\":\"NATIVE\",\"descending\":false,\"ascending\":true}]}";
// When
Page<?> result = objectMapper.readValue(pageJson, Page.class);
// Then
assertThat(result).isNotNull();
assertThat(result.getTotalElements()).isEqualTo(3);
assertThat(result.getContent()).hasSize(1);
assertThat(result.getPageable()).isNotNull();
assertThat(result.getPageable().getPageSize()).isEqualTo(2);
assertThat(result.getPageable().getPageNumber()).isEqualTo(1);
assertThat(result.getPageable().getSort()).hasSize(1);
Optional<Sort.Order> optionalOrder = result.getPageable().getSort().get()
.findFirst();
if (optionalOrder.isPresent()) {
Sort.Order order = optionalOrder.get();
assertThat(order.getDirection()).isEqualTo(Sort.Direction.ASC);
assertThat(order.getProperty()).isEqualTo("field");
}
}

}