1
1
/*
2
- * Copyright 2008-2012 the original author or authors.
2
+ * Copyright 2008-2015 the original author or authors.
3
3
*
4
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
5
* you may not use this file except in compliance with the License.
16
16
package org .springframework .data .repository .query .parser ;
17
17
18
18
import java .util .ArrayList ;
19
+ import java .util .Arrays ;
20
+ import java .util .HashSet ;
19
21
import java .util .List ;
22
+ import java .util .Set ;
20
23
import java .util .regex .Matcher ;
21
24
import java .util .regex .Pattern ;
22
25
36
39
public class OrderBySource {
37
40
38
41
private static final String BLOCK_SPLIT = "(?<=Asc|Desc)(?=\\ p{Lu})" ;
39
- private static final Pattern DIRECTION_SPLIT = Pattern .compile ("(.+)(Asc|Desc)$" );
42
+ private static final Pattern DIRECTION_SPLIT = Pattern .compile ("(.+?)(Asc|Desc)?$" );
43
+ private static final String INVALID_ORDER_SYNTAX = "Invalid order syntax for part %s!" ;
44
+ private static final Set <String > DIRECTION_KEYWORDS = new HashSet <String >(Arrays .asList ("Asc" , "Desc" ));
40
45
41
46
private final List <Order > orders ;
42
47
@@ -47,7 +52,6 @@ public class OrderBySource {
47
52
* @param clause must not be {@literal null}.
48
53
*/
49
54
public OrderBySource (String clause ) {
50
-
51
55
this (clause , null );
52
56
}
53
57
@@ -56,18 +60,30 @@ public OrderBySource(String clause) {
56
60
* type.
57
61
*
58
62
* @param clause must not be {@literal null}.
59
- * @param domainClass
63
+ * @param domainClass can be {@literal null}.
60
64
*/
61
65
public OrderBySource (String clause , Class <?> domainClass ) {
62
66
63
67
this .orders = new ArrayList <Sort .Order >();
68
+
64
69
for (String part : clause .split (BLOCK_SPLIT )) {
70
+
65
71
Matcher matcher = DIRECTION_SPLIT .matcher (part );
72
+
66
73
if (!matcher .find ()) {
67
- throw new IllegalArgumentException (String .format ("Invalid order syntax for part %s!" , part ));
74
+ throw new IllegalArgumentException (String .format (INVALID_ORDER_SYNTAX , part ));
68
75
}
69
- Direction direction = Direction .fromString (matcher .group (2 ));
70
- this .orders .add (createOrder (matcher .group (1 ), direction , domainClass ));
76
+
77
+ String propertyString = matcher .group (1 );
78
+ String directionString = matcher .group (2 );
79
+
80
+ // No property, but only a direction keyword
81
+ if (DIRECTION_KEYWORDS .contains (propertyString ) && directionString == null ) {
82
+ throw new IllegalArgumentException (String .format (INVALID_ORDER_SYNTAX , part ));
83
+ }
84
+
85
+ Direction direction = StringUtils .hasText (directionString ) ? Direction .fromString (directionString ) : null ;
86
+ this .orders .add (createOrder (propertyString , direction , domainClass ));
71
87
}
72
88
}
73
89
0 commit comments