How to manually create Pageable object from a string












2















I didn't find anywhere whether it's possible to create pageable manually from string, let assume that we have the following service method



public <T> List<T> findAnything(final int page, final int size, final String sort) { // e.g. id,desc&username,asc

final Pageable pageable = new PageRequest(page, size, null);
return null;
}


my question is how can i instantiate an object of




org.springframework.data.domain.Sort




from a given string of format, important note that these parameters are chagned dynamically, so more likely i need a path to the spring parser, in my example im passing null instead the object




id,desc&username,asc




EDIT



A little bit more details I'm looking for a mechanism of how spring converts the 'sort' string(with the rest of default parameters) that's coming to the rest endpoint as a query param to Pageable object










share|improve this question

























  • what does the given format mean? id,desc,username,asc Did you probably mean sort=id,desc&sort=username,asc? It's how Spring recognises a Sort object

    – Andrew Tobilko
    Nov 15 '18 at 14:47













  • thanks in my case these params come as id,desc&username,asc string, updated the format, sorry for confusions

    – Stressedout
    Nov 15 '18 at 15:37
















2















I didn't find anywhere whether it's possible to create pageable manually from string, let assume that we have the following service method



public <T> List<T> findAnything(final int page, final int size, final String sort) { // e.g. id,desc&username,asc

final Pageable pageable = new PageRequest(page, size, null);
return null;
}


my question is how can i instantiate an object of




org.springframework.data.domain.Sort




from a given string of format, important note that these parameters are chagned dynamically, so more likely i need a path to the spring parser, in my example im passing null instead the object




id,desc&username,asc




EDIT



A little bit more details I'm looking for a mechanism of how spring converts the 'sort' string(with the rest of default parameters) that's coming to the rest endpoint as a query param to Pageable object










share|improve this question

























  • what does the given format mean? id,desc,username,asc Did you probably mean sort=id,desc&sort=username,asc? It's how Spring recognises a Sort object

    – Andrew Tobilko
    Nov 15 '18 at 14:47













  • thanks in my case these params come as id,desc&username,asc string, updated the format, sorry for confusions

    – Stressedout
    Nov 15 '18 at 15:37














2












2








2


0






I didn't find anywhere whether it's possible to create pageable manually from string, let assume that we have the following service method



public <T> List<T> findAnything(final int page, final int size, final String sort) { // e.g. id,desc&username,asc

final Pageable pageable = new PageRequest(page, size, null);
return null;
}


my question is how can i instantiate an object of




org.springframework.data.domain.Sort




from a given string of format, important note that these parameters are chagned dynamically, so more likely i need a path to the spring parser, in my example im passing null instead the object




id,desc&username,asc




EDIT



A little bit more details I'm looking for a mechanism of how spring converts the 'sort' string(with the rest of default parameters) that's coming to the rest endpoint as a query param to Pageable object










share|improve this question
















I didn't find anywhere whether it's possible to create pageable manually from string, let assume that we have the following service method



public <T> List<T> findAnything(final int page, final int size, final String sort) { // e.g. id,desc&username,asc

final Pageable pageable = new PageRequest(page, size, null);
return null;
}


my question is how can i instantiate an object of




org.springframework.data.domain.Sort




from a given string of format, important note that these parameters are chagned dynamically, so more likely i need a path to the spring parser, in my example im passing null instead the object




id,desc&username,asc




EDIT



A little bit more details I'm looking for a mechanism of how spring converts the 'sort' string(with the rest of default parameters) that's coming to the rest endpoint as a query param to Pageable object







java spring






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 15:35







Stressedout

















asked Nov 15 '18 at 14:18









StressedoutStressedout

8119




8119













  • what does the given format mean? id,desc,username,asc Did you probably mean sort=id,desc&sort=username,asc? It's how Spring recognises a Sort object

    – Andrew Tobilko
    Nov 15 '18 at 14:47













  • thanks in my case these params come as id,desc&username,asc string, updated the format, sorry for confusions

    – Stressedout
    Nov 15 '18 at 15:37



















  • what does the given format mean? id,desc,username,asc Did you probably mean sort=id,desc&sort=username,asc? It's how Spring recognises a Sort object

    – Andrew Tobilko
    Nov 15 '18 at 14:47













  • thanks in my case these params come as id,desc&username,asc string, updated the format, sorry for confusions

    – Stressedout
    Nov 15 '18 at 15:37

















what does the given format mean? id,desc,username,asc Did you probably mean sort=id,desc&sort=username,asc? It's how Spring recognises a Sort object

– Andrew Tobilko
Nov 15 '18 at 14:47







what does the given format mean? id,desc,username,asc Did you probably mean sort=id,desc&sort=username,asc? It's how Spring recognises a Sort object

– Andrew Tobilko
Nov 15 '18 at 14:47















thanks in my case these params come as id,desc&username,asc string, updated the format, sorry for confusions

– Stressedout
Nov 15 '18 at 15:37





thanks in my case these params come as id,desc&username,asc string, updated the format, sorry for confusions

– Stressedout
Nov 15 '18 at 15:37












2 Answers
2






active

oldest

votes


















5














You can do :



private Sort orderBy() {
return new Sort(Sort.Direction.DESC, "ID")
.and(new Sort(Sort.Direction.ASC, "username"));
}


I think this is helpful



Sort class has static nested class Order :



public static class Order{
private final Direction direction;
private final String property;
private final boolean ignoreCase;
private final NullHandling nullHandling;
}


and then you can use :



public static Sort by(List<Order> orders)


where you create your Order from String like simply splitting.






share|improve this answer


























  • this parameters are changed dynamically as you can see from the method signature, so that's actually not what im looking for

    – Stressedout
    Nov 15 '18 at 14:21






  • 1





    This answer actually gives you everything you need. You sure do know how to pass a String parameter to a method. Well then, pass it into the orderBy method.

    – ygor
    Nov 15 '18 at 14:23






  • 1





    seems like you do not quite understand the problem

    – Stressedout
    Nov 15 '18 at 14:24













  • You can convert your String to Map and then populate from map Sort elements Map<String,Sort.Direction> where id would be the column name and value order

    – Mykhailo Moskura
    Nov 15 '18 at 14:27








  • 1





    @MykhailoMoskura Now, it makes much more sense. Considering that the format id,desc,username,asc isn't regular, building a List<Order> is a good option. Actually, that's what SortHandlerMethodArgumentResolver does. Upvoted.

    – Andrew Tobilko
    Nov 15 '18 at 14:59





















1














For that purpose I've written something similar to what spring has, i'd be happy if spring exposes SortHandlerMethodArgumentResolver.parseParameterIntoSort for usage outside the package but so far it's not



private Sort parseMultipleSortQueries(final String query) {

final String queries = query.split("&");
return parseSortQuery(queries, ",");
}

private Sort parseSortQuery(final String query, String delimiter) {

final List<Sort.Order> orders = new ArrayList<>();
for (String q : query) {

if (q == null) {
continue;
}

final String parts = q.split(delimiter);
final Sort.Direction direction = parts.length == 0 ? null : Sort.Direction.fromStringOrNull(parts[parts.length - 1]);
for (int i = 0; i < parts.length; i++) {

if (i == parts.length - 1 && direction != null) {
continue;
}

final String property = parts[i];
if (!StringUtils.hasText(property)) {
continue;
}
orders.add(new Sort.Order(direction, property));
}
}
return orders.isEmpty() ? null : new Sort(orders);
}


and here is the test



@Test
public void testParseQuery() {
System.out.println(parseMultipleSortQueries("firstName,asc&lastName,desc")); //firstName: ASC,lastName: DESC
}





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53321455%2fhow-to-manually-create-pageable-object-from-a-string%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    5














    You can do :



    private Sort orderBy() {
    return new Sort(Sort.Direction.DESC, "ID")
    .and(new Sort(Sort.Direction.ASC, "username"));
    }


    I think this is helpful



    Sort class has static nested class Order :



    public static class Order{
    private final Direction direction;
    private final String property;
    private final boolean ignoreCase;
    private final NullHandling nullHandling;
    }


    and then you can use :



    public static Sort by(List<Order> orders)


    where you create your Order from String like simply splitting.






    share|improve this answer


























    • this parameters are changed dynamically as you can see from the method signature, so that's actually not what im looking for

      – Stressedout
      Nov 15 '18 at 14:21






    • 1





      This answer actually gives you everything you need. You sure do know how to pass a String parameter to a method. Well then, pass it into the orderBy method.

      – ygor
      Nov 15 '18 at 14:23






    • 1





      seems like you do not quite understand the problem

      – Stressedout
      Nov 15 '18 at 14:24













    • You can convert your String to Map and then populate from map Sort elements Map<String,Sort.Direction> where id would be the column name and value order

      – Mykhailo Moskura
      Nov 15 '18 at 14:27








    • 1





      @MykhailoMoskura Now, it makes much more sense. Considering that the format id,desc,username,asc isn't regular, building a List<Order> is a good option. Actually, that's what SortHandlerMethodArgumentResolver does. Upvoted.

      – Andrew Tobilko
      Nov 15 '18 at 14:59


















    5














    You can do :



    private Sort orderBy() {
    return new Sort(Sort.Direction.DESC, "ID")
    .and(new Sort(Sort.Direction.ASC, "username"));
    }


    I think this is helpful



    Sort class has static nested class Order :



    public static class Order{
    private final Direction direction;
    private final String property;
    private final boolean ignoreCase;
    private final NullHandling nullHandling;
    }


    and then you can use :



    public static Sort by(List<Order> orders)


    where you create your Order from String like simply splitting.






    share|improve this answer


























    • this parameters are changed dynamically as you can see from the method signature, so that's actually not what im looking for

      – Stressedout
      Nov 15 '18 at 14:21






    • 1





      This answer actually gives you everything you need. You sure do know how to pass a String parameter to a method. Well then, pass it into the orderBy method.

      – ygor
      Nov 15 '18 at 14:23






    • 1





      seems like you do not quite understand the problem

      – Stressedout
      Nov 15 '18 at 14:24













    • You can convert your String to Map and then populate from map Sort elements Map<String,Sort.Direction> where id would be the column name and value order

      – Mykhailo Moskura
      Nov 15 '18 at 14:27








    • 1





      @MykhailoMoskura Now, it makes much more sense. Considering that the format id,desc,username,asc isn't regular, building a List<Order> is a good option. Actually, that's what SortHandlerMethodArgumentResolver does. Upvoted.

      – Andrew Tobilko
      Nov 15 '18 at 14:59
















    5












    5








    5







    You can do :



    private Sort orderBy() {
    return new Sort(Sort.Direction.DESC, "ID")
    .and(new Sort(Sort.Direction.ASC, "username"));
    }


    I think this is helpful



    Sort class has static nested class Order :



    public static class Order{
    private final Direction direction;
    private final String property;
    private final boolean ignoreCase;
    private final NullHandling nullHandling;
    }


    and then you can use :



    public static Sort by(List<Order> orders)


    where you create your Order from String like simply splitting.






    share|improve this answer















    You can do :



    private Sort orderBy() {
    return new Sort(Sort.Direction.DESC, "ID")
    .and(new Sort(Sort.Direction.ASC, "username"));
    }


    I think this is helpful



    Sort class has static nested class Order :



    public static class Order{
    private final Direction direction;
    private final String property;
    private final boolean ignoreCase;
    private final NullHandling nullHandling;
    }


    and then you can use :



    public static Sort by(List<Order> orders)


    where you create your Order from String like simply splitting.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 15 '18 at 14:54

























    answered Nov 15 '18 at 14:21









    Mykhailo MoskuraMykhailo Moskura

    867214




    867214













    • this parameters are changed dynamically as you can see from the method signature, so that's actually not what im looking for

      – Stressedout
      Nov 15 '18 at 14:21






    • 1





      This answer actually gives you everything you need. You sure do know how to pass a String parameter to a method. Well then, pass it into the orderBy method.

      – ygor
      Nov 15 '18 at 14:23






    • 1





      seems like you do not quite understand the problem

      – Stressedout
      Nov 15 '18 at 14:24













    • You can convert your String to Map and then populate from map Sort elements Map<String,Sort.Direction> where id would be the column name and value order

      – Mykhailo Moskura
      Nov 15 '18 at 14:27








    • 1





      @MykhailoMoskura Now, it makes much more sense. Considering that the format id,desc,username,asc isn't regular, building a List<Order> is a good option. Actually, that's what SortHandlerMethodArgumentResolver does. Upvoted.

      – Andrew Tobilko
      Nov 15 '18 at 14:59





















    • this parameters are changed dynamically as you can see from the method signature, so that's actually not what im looking for

      – Stressedout
      Nov 15 '18 at 14:21






    • 1





      This answer actually gives you everything you need. You sure do know how to pass a String parameter to a method. Well then, pass it into the orderBy method.

      – ygor
      Nov 15 '18 at 14:23






    • 1





      seems like you do not quite understand the problem

      – Stressedout
      Nov 15 '18 at 14:24













    • You can convert your String to Map and then populate from map Sort elements Map<String,Sort.Direction> where id would be the column name and value order

      – Mykhailo Moskura
      Nov 15 '18 at 14:27








    • 1





      @MykhailoMoskura Now, it makes much more sense. Considering that the format id,desc,username,asc isn't regular, building a List<Order> is a good option. Actually, that's what SortHandlerMethodArgumentResolver does. Upvoted.

      – Andrew Tobilko
      Nov 15 '18 at 14:59



















    this parameters are changed dynamically as you can see from the method signature, so that's actually not what im looking for

    – Stressedout
    Nov 15 '18 at 14:21





    this parameters are changed dynamically as you can see from the method signature, so that's actually not what im looking for

    – Stressedout
    Nov 15 '18 at 14:21




    1




    1





    This answer actually gives you everything you need. You sure do know how to pass a String parameter to a method. Well then, pass it into the orderBy method.

    – ygor
    Nov 15 '18 at 14:23





    This answer actually gives you everything you need. You sure do know how to pass a String parameter to a method. Well then, pass it into the orderBy method.

    – ygor
    Nov 15 '18 at 14:23




    1




    1





    seems like you do not quite understand the problem

    – Stressedout
    Nov 15 '18 at 14:24







    seems like you do not quite understand the problem

    – Stressedout
    Nov 15 '18 at 14:24















    You can convert your String to Map and then populate from map Sort elements Map<String,Sort.Direction> where id would be the column name and value order

    – Mykhailo Moskura
    Nov 15 '18 at 14:27







    You can convert your String to Map and then populate from map Sort elements Map<String,Sort.Direction> where id would be the column name and value order

    – Mykhailo Moskura
    Nov 15 '18 at 14:27






    1




    1





    @MykhailoMoskura Now, it makes much more sense. Considering that the format id,desc,username,asc isn't regular, building a List<Order> is a good option. Actually, that's what SortHandlerMethodArgumentResolver does. Upvoted.

    – Andrew Tobilko
    Nov 15 '18 at 14:59







    @MykhailoMoskura Now, it makes much more sense. Considering that the format id,desc,username,asc isn't regular, building a List<Order> is a good option. Actually, that's what SortHandlerMethodArgumentResolver does. Upvoted.

    – Andrew Tobilko
    Nov 15 '18 at 14:59















    1














    For that purpose I've written something similar to what spring has, i'd be happy if spring exposes SortHandlerMethodArgumentResolver.parseParameterIntoSort for usage outside the package but so far it's not



    private Sort parseMultipleSortQueries(final String query) {

    final String queries = query.split("&");
    return parseSortQuery(queries, ",");
    }

    private Sort parseSortQuery(final String query, String delimiter) {

    final List<Sort.Order> orders = new ArrayList<>();
    for (String q : query) {

    if (q == null) {
    continue;
    }

    final String parts = q.split(delimiter);
    final Sort.Direction direction = parts.length == 0 ? null : Sort.Direction.fromStringOrNull(parts[parts.length - 1]);
    for (int i = 0; i < parts.length; i++) {

    if (i == parts.length - 1 && direction != null) {
    continue;
    }

    final String property = parts[i];
    if (!StringUtils.hasText(property)) {
    continue;
    }
    orders.add(new Sort.Order(direction, property));
    }
    }
    return orders.isEmpty() ? null : new Sort(orders);
    }


    and here is the test



    @Test
    public void testParseQuery() {
    System.out.println(parseMultipleSortQueries("firstName,asc&lastName,desc")); //firstName: ASC,lastName: DESC
    }





    share|improve this answer






























      1














      For that purpose I've written something similar to what spring has, i'd be happy if spring exposes SortHandlerMethodArgumentResolver.parseParameterIntoSort for usage outside the package but so far it's not



      private Sort parseMultipleSortQueries(final String query) {

      final String queries = query.split("&");
      return parseSortQuery(queries, ",");
      }

      private Sort parseSortQuery(final String query, String delimiter) {

      final List<Sort.Order> orders = new ArrayList<>();
      for (String q : query) {

      if (q == null) {
      continue;
      }

      final String parts = q.split(delimiter);
      final Sort.Direction direction = parts.length == 0 ? null : Sort.Direction.fromStringOrNull(parts[parts.length - 1]);
      for (int i = 0; i < parts.length; i++) {

      if (i == parts.length - 1 && direction != null) {
      continue;
      }

      final String property = parts[i];
      if (!StringUtils.hasText(property)) {
      continue;
      }
      orders.add(new Sort.Order(direction, property));
      }
      }
      return orders.isEmpty() ? null : new Sort(orders);
      }


      and here is the test



      @Test
      public void testParseQuery() {
      System.out.println(parseMultipleSortQueries("firstName,asc&lastName,desc")); //firstName: ASC,lastName: DESC
      }





      share|improve this answer




























        1












        1








        1







        For that purpose I've written something similar to what spring has, i'd be happy if spring exposes SortHandlerMethodArgumentResolver.parseParameterIntoSort for usage outside the package but so far it's not



        private Sort parseMultipleSortQueries(final String query) {

        final String queries = query.split("&");
        return parseSortQuery(queries, ",");
        }

        private Sort parseSortQuery(final String query, String delimiter) {

        final List<Sort.Order> orders = new ArrayList<>();
        for (String q : query) {

        if (q == null) {
        continue;
        }

        final String parts = q.split(delimiter);
        final Sort.Direction direction = parts.length == 0 ? null : Sort.Direction.fromStringOrNull(parts[parts.length - 1]);
        for (int i = 0; i < parts.length; i++) {

        if (i == parts.length - 1 && direction != null) {
        continue;
        }

        final String property = parts[i];
        if (!StringUtils.hasText(property)) {
        continue;
        }
        orders.add(new Sort.Order(direction, property));
        }
        }
        return orders.isEmpty() ? null : new Sort(orders);
        }


        and here is the test



        @Test
        public void testParseQuery() {
        System.out.println(parseMultipleSortQueries("firstName,asc&lastName,desc")); //firstName: ASC,lastName: DESC
        }





        share|improve this answer















        For that purpose I've written something similar to what spring has, i'd be happy if spring exposes SortHandlerMethodArgumentResolver.parseParameterIntoSort for usage outside the package but so far it's not



        private Sort parseMultipleSortQueries(final String query) {

        final String queries = query.split("&");
        return parseSortQuery(queries, ",");
        }

        private Sort parseSortQuery(final String query, String delimiter) {

        final List<Sort.Order> orders = new ArrayList<>();
        for (String q : query) {

        if (q == null) {
        continue;
        }

        final String parts = q.split(delimiter);
        final Sort.Direction direction = parts.length == 0 ? null : Sort.Direction.fromStringOrNull(parts[parts.length - 1]);
        for (int i = 0; i < parts.length; i++) {

        if (i == parts.length - 1 && direction != null) {
        continue;
        }

        final String property = parts[i];
        if (!StringUtils.hasText(property)) {
        continue;
        }
        orders.add(new Sort.Order(direction, property));
        }
        }
        return orders.isEmpty() ? null : new Sort(orders);
        }


        and here is the test



        @Test
        public void testParseQuery() {
        System.out.println(parseMultipleSortQueries("firstName,asc&lastName,desc")); //firstName: ASC,lastName: DESC
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 15:31

























        answered Nov 15 '18 at 15:12









        StressedoutStressedout

        8119




        8119






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53321455%2fhow-to-manually-create-pageable-object-from-a-string%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            The Sandy Post

            Danny Elfman

            Pages that link to "Head v. Amoskeag Manufacturing Co."