Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform PageRequest object to query string?

I'm writing an RESTful API which consumes another RESTful Data API, and I'm using Spring Data.

The client side send the page request using query params like:
http://api.mysite.com/products?page=1&size=20&sort=id,asc&sort=name,desc

And I transform the params to PageRequest object and transfer it to the Service Layer.

In the service, I would like to use TestTemplate to interact with the Data API which use a URL, and How can I transform the PageRequest object to a query string like

page=1&size=20&sort=id,asc&sort=name,desc

then I can request data like:

restTemplate.getForEntity("http://data.mysite.com/products?page=1&size=20&sort=id,asc&sort=name,desc",String.class)                    
like image 993
Harry Avatar asked Sep 11 '25 13:09

Harry


2 Answers

I know I am a bit late on this answer, but I too was not able to found an already implemented way to do this. I ended up developing my own routine for doing this:

public static String encodeURLComponent(String component){
    try {
        return URLEncoder.encode(component, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("You are dumm enough that you cannot spell UTF-8, are you?");
    }
}

public static String queryStringFromPageable(Pageable p){
    StringBuilder ans = new StringBuilder();
    ans.append("page=");
    ans.append(encodeURLComponent(p.getPageNumber() + ""));

    // No sorting
    if (p.getSort() == null)
        return ans.toString();

    // Sorting is specified
    for(Sort.Order o : p.getSort()){
        ans.append("&sort=");
        ans.append(encodeURLComponent(o.getProperty()));
        ans.append(",");
        ans.append(encodeURLComponent(o.getDirection().name()));
    }

    return ans.toString();
}

It is not complete, there probably are a couple of details that I am missing, but for my user case (and I think for most of them) this works.

like image 180
Shalen Avatar answered Sep 13 '25 05:09

Shalen


UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl("http://data.mysite.com/products");
                
addRequestParam(uriComponentsBuilder, "page", pageable.getPageNumber());
addRequestParam(uriComponentsBuilder, "size", pageable.getPageSize());
        
String uri = uriComponentsBuilder.toUriString() + sortToString(pageable.getSort());

addRequestParam method:

private static void addRequestParam(UriComponentsBuilder uriBuilder, String parameterName, Object parameter) {
    if (parameter != null) {
        uriBuilder.queryParam(parameterName, parameter);
    }
}

implement sortToString(Sort sort) method as @Shalen. You have to obtain something like this: &sort=name,asc&sort=name2,desc. Return "" if Sort is null;

like image 32
Valeriy K. Avatar answered Sep 13 '25 06:09

Valeriy K.