forked from grails/grails-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DefaultUrlMappingEvaluator.java
1023 lines (861 loc) · 48.1 KB
/
DefaultUrlMappingEvaluator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2004-2005 Graeme Rocher
*
* 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
*
* http://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.codehaus.groovy.grails.web.mapping;
import groovy.lang.Binding;
import groovy.lang.Closure;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyObjectSupport;
import groovy.lang.Script;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.GrailsMetaClassUtils;
import org.codehaus.groovy.grails.plugins.GrailsPluginManager;
import org.codehaus.groovy.grails.plugins.PluginManagerAware;
import org.codehaus.groovy.grails.plugins.support.aware.ClassLoaderAware;
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import org.codehaus.groovy.grails.validation.ConstrainedPropertyBuilder;
import org.codehaus.groovy.grails.web.mapping.exceptions.UrlMappingException;
import org.codehaus.groovy.grails.web.plugins.support.WebMetaUtils;
import org.codehaus.groovy.runtime.IOGroovyMethods;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* <p>A UrlMapping evaluator that evaluates Groovy scripts that are in the form:</p>
* <p/>
* <pre>
* <code>
* mappings {
* /$post/$year?/$month?/$day?" {
* controller = "blog"
* action = "show"
* constraints {
* year(matches:/\d{4}/)
* month(matches:/\d{2}/)
* }
* }
* }
* </code>
* </pre>
*
* @author Graeme Rocher
* @since 0.5
*/
public class DefaultUrlMappingEvaluator implements UrlMappingEvaluator, ClassLoaderAware, PluginManagerAware {
public static final String ACTION_CREATE = "create";
public static final String ACTION_INDEX = "index";
public static final String ACTION_SHOW = "show";
public static final String ACTION_EDIT = "edit";
public static final String ACTION_UPDATE = "update";
public static final String ACTION_DELETE = "delete";
public static final String ACTION_SAVE = "save";
public static final List<String> DEFAULT_RESOURCES_INCLUDES = Arrays.asList(ACTION_INDEX, ACTION_CREATE, ACTION_SAVE,ACTION_SHOW,ACTION_EDIT, ACTION_UPDATE, ACTION_DELETE);
public static final List<String> DEFAULT_RESOURCE_INCLUDES = Arrays.asList(ACTION_CREATE,ACTION_SAVE,ACTION_SHOW, ACTION_EDIT, ACTION_UPDATE, ACTION_DELETE);
private static final Log LOG = LogFactory.getLog(UrlMappingBuilder.class);
private GroovyClassLoader classLoader = new GroovyClassLoader();
private UrlMappingParser urlParser = new DefaultUrlMappingParser();
private ServletContext servletContext;
private static final String EXCEPTION = "exception";
private static final String PARSE_REQUEST = "parseRequest";
private static final String RESOURCE = "resource";
private static final String RESOURCES = "resources";
private GrailsPluginManager pluginManager;
private WebApplicationContext applicationContext;
/**
* @deprecated Used DefaultUrLMappingsEvaluator(ApplicationContext) instead
* @param servletContext The servlet context
*/
@Deprecated
public DefaultUrlMappingEvaluator(ServletContext servletContext) {
this.servletContext = servletContext;
}
public DefaultUrlMappingEvaluator(WebApplicationContext applicationContext) {
if (applicationContext != null) {
this.servletContext = applicationContext.getServletContext();
}
this.applicationContext = applicationContext;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public List evaluateMappings(Resource resource) {
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
return evaluateMappings(classLoader.parseClass(IOGroovyMethods.getText(inputStream, "UTF-8")));
}
catch (IOException e) {
throw new UrlMappingException("Unable to read mapping file [" + resource.getFilename() + "]: " + e.getMessage(), e);
}
finally {
IOUtils.closeQuietly(inputStream);
}
}
@SuppressWarnings({"unchecked","rawtypes"})
public List<UrlMapping> evaluateMappings(Class theClass) {
GroovyObject obj = (GroovyObject) BeanUtils.instantiateClass(theClass);
if (obj instanceof Script) {
Script script = (Script) obj;
Binding b = new Binding();
MappingCapturingClosure closure = new MappingCapturingClosure(script);
b.setVariable("mappings", closure);
script.setBinding(b);
script.run();
Closure mappings = closure.getMappings();
Binding binding = script.getBinding();
return evaluateMappings(script, mappings, binding);
}
throw new UrlMappingException("Unable to configure URL mappings for class [" + theClass +
"]. A URL mapping must be an instance of groovy.lang.Script.");
}
private List<UrlMapping> evaluateMappings(GroovyObject go, Closure<?> mappings, Binding binding) {
UrlMappingBuilder builder = new UrlMappingBuilder(binding, servletContext);
mappings.setDelegate(builder);
mappings.call();
builder.urlDefiningMode = false;
configureUrlMappingDynamicObjects(go);
return builder.getUrlMappings();
}
@SuppressWarnings("rawtypes")
public List<UrlMapping> evaluateMappings(Closure closure) {
UrlMappingBuilder builder = new UrlMappingBuilder(null, servletContext);
closure.setDelegate(builder);
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
if (closure.getParameterTypes().length == 0) {
closure.call();
}
else {
closure.call(applicationContext);
}
builder.urlDefiningMode = false;
configureUrlMappingDynamicObjects(closure);
return builder.getUrlMappings();
}
private void configureUrlMappingDynamicObjects(Object object) {
if (pluginManager != null) {
WebMetaUtils.registerCommonWebProperties(GrailsMetaClassUtils.getExpandoMetaClass(object.getClass()), null);
}
}
public void setClassLoader(ClassLoader classLoader) {
Assert.isInstanceOf(GroovyClassLoader.class, classLoader,
"Property [classLoader] must be an instance of GroovyClassLoader");
this.classLoader = (GroovyClassLoader) classLoader;
}
public void setPluginManager(GrailsPluginManager pluginManager) {
this.pluginManager = pluginManager;
}
/**
* A Closure that captures a call to a method that accepts a single closure
*/
@SuppressWarnings("rawtypes")
class MappingCapturingClosure extends Closure {
private static final long serialVersionUID = 2108155626252742722L;
private Closure<?> mappings;
public Closure<?> getMappings() {
return mappings;
}
public MappingCapturingClosure(Object o) {
super(o);
}
@Override
public Object call(Object... args) {
if (args.length > 0 && (args[0] instanceof Closure)) {
mappings = (Closure<?>) args[0];
}
return null;
}
}
/**
* <p>A modal builder that constructs a UrlMapping instances by executing a closure. The class overrides
* getProperty(name) and allows the substitution of GString values with the * wildcard.
* <p/>
* <p>invokeMethod(methodName, args) is also overriden for the creation of each UrlMapping instance
*/
@SuppressWarnings("rawtypes")
class UrlMappingBuilder extends GroovyObjectSupport {
private static final String CAPTURING_WILD_CARD = UrlMapping.CAPTURED_WILDCARD;
private static final String SLASH = "/";
private static final String CONSTRAINTS = "constraints";
private boolean urlDefiningMode = true;
private List<ConstrainedProperty> previousConstraints = new ArrayList<ConstrainedProperty>();
private List<UrlMapping> urlMappings = new ArrayList<UrlMapping>();
private Map<String, Object> parameterValues = new HashMap<String, Object>();
private Binding binding;
private Object actionName = null;
private Object pluginName = null;
private Object namespace = null;
private Object controllerName = null;
private Object viewName = null;
private String httpMethod;
private ServletContext sc;
private Object exception;
private Object parseRequest;
private Object uri;
private Object redirectInfo;
private Deque<ParentResource> parentResources = new ArrayDeque<ParentResource>();
public UrlMappingBuilder(Binding binding, ServletContext servletContext) {
this.binding = binding;
sc = servletContext;
}
public List<UrlMapping> getUrlMappings() {
return urlMappings;
}
public ServletContext getServletContext() {
return sc;
}
public ApplicationContext getApplicationContext() {
return WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
}
public GrailsApplication getGrailsApplication() {
return getApplicationContext().getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);
}
@Override
public Object getProperty(String name) {
if (urlDefiningMode) {
getParentConstraints().add(new ConstrainedProperty(UrlMapping.class, name, String.class));
return CAPTURING_WILD_CARD;
}
return super.getProperty(name);
}
public Object getException() {
return exception;
}
public void setException(Object exception) {
this.exception = exception;
}
public Object getUri() {
return uri;
}
public void setUri(Object uri) {
this.uri = uri;
}
public void setAction(Object action) {
actionName = action;
}
public Object getAction() {
return actionName;
}
public void setController(Object controller) {
controllerName = controller;
}
public Object getController() {
return controllerName;
}
public void setRedirectInfo(Object redirectInfo) {
this.redirectInfo = redirectInfo;
}
public Object getRedirectInfo() {
return redirectInfo;
}
public void setPlugin(Object plugin) {
pluginName = plugin;
}
public Object getPlugin() {
return pluginName;
}
public void setNamespace(Object namespace) {
this.namespace = namespace;
}
public Object getNamespace() {
return namespace;
}
public Object getView() {
return viewName;
}
public void setView(String viewName) {
this.viewName = viewName;
}
public void name(Map<String, UrlMapping> m) {
for (Map.Entry<String, UrlMapping> entry: m.entrySet()) {
entry.getValue().setMappingName(entry.getKey());
}
}
/**
* Define a group
*
* @param uri The URI
* @param mappings The mappings
*/
public void group(String uri, Closure mappings) {
try {
parentResources.push(new ParentResource(null, uri,previousConstraints, true));
mappings.call();
} finally {
parentResources.pop();
}
}
@Override
public Object invokeMethod(String methodName, Object arg) {
if (binding == null) {
return invokeMethodClosure(methodName, arg);
}
return invokeMethodScript(methodName, arg);
}
private Object invokeMethodScript(String methodName, Object arg) {
return _invoke(methodName, arg, null);
}
private Object invokeMethodClosure(String methodName, Object arg) {
return _invoke(methodName, arg, this);
}
void propertyMissing(String name, Object value) {
parameterValues.put(name, value);
}
Object propertyMissing(String name) {
return parameterValues.get(name);
}
private Object _invoke(String methodName, Object arg, Object delegate) {
Object[] args = (Object[]) arg;
List<ConstrainedProperty> currentConstraints = new ArrayList<ConstrainedProperty>();
List<ConstrainedProperty> parentConstraints = getParentConstraints();
if(parentConstraints != null) {
currentConstraints.addAll(parentConstraints);
}
String mappedURI = establishFullURI(methodName, currentConstraints);
final boolean isResponseCode = isResponseCode(mappedURI);
if (mappedURI.startsWith(SLASH) || isResponseCode) {
// Create a new parameter map for this mapping.
parameterValues = new HashMap<String, Object>();
Map variables = binding != null ? binding.getVariables() : null;
try {
urlDefiningMode = false;
args = args != null && args.length > 0 ? args : new Object[]{Collections.EMPTY_MAP};
if (args[0] instanceof Closure) {
UrlMappingData urlData = createUrlMappingData(mappedURI, isResponseCode);
Closure callable = (Closure) args[0];
if (delegate != null) {
callable.setDelegate(delegate);
}
callable.call();
Object controllerName;
Object actionName;
Object pluginName;
String httpMethod = null;
String version = null;
Object namespace;
Object viewName;
Object uri;
Object redirectInfo = null;
if (binding != null) {
controllerName = variables.get(GrailsControllerClass.CONTROLLER);
actionName = variables.get(GrailsControllerClass.ACTION);
viewName = variables.get(GrailsControllerClass.VIEW);
uri = variables.get(UrlMapping.URI);
pluginName = variables.get(UrlMapping.PLUGIN);
namespace = variables.get(UrlMapping.NAMESPACE);
if (variables.containsKey(UrlMapping.HTTP_METHOD)) {
httpMethod = variables.get(UrlMapping.HTTP_METHOD).toString();
}
} else {
controllerName = this.controllerName;
redirectInfo = this.redirectInfo;
actionName = this.actionName;
pluginName = this.pluginName;
namespace = this.namespace;
viewName = this.viewName;
uri = this.uri;
httpMethod = this.httpMethod;
}
ConstrainedProperty[] constraints = currentConstraints.toArray(new ConstrainedProperty[currentConstraints.size()]);
UrlMapping urlMapping;
if (uri != null) {
try {
urlMapping = new RegexUrlMapping(urlData, new URI(uri.toString()), constraints, sc);
} catch (URISyntaxException e) {
throw new UrlMappingException("Cannot map to invalid URI: " + e.getMessage(), e);
}
} else {
urlMapping = createURLMapping(urlData, isResponseCode, redirectInfo, controllerName, actionName, namespace, pluginName, viewName, httpMethod, version,constraints);
}
if (binding != null) {
Map bindingVariables = variables;
Object parse = getParseRequest(Collections.EMPTY_MAP, bindingVariables);
if (parse instanceof Boolean) {
urlMapping.setParseRequest((Boolean) parse);
}
}
configureUrlMapping(urlMapping);
return urlMapping;
}
if (args[0] instanceof Map) {
Map namedArguments = (Map) args[0];
String uri = mappedURI;
String version = null;
if (namedArguments.containsKey(UrlMapping.VERSION)) {
version = namedArguments.get(UrlMapping.VERSION).toString();
}
if (namedArguments.containsKey(UrlMapping.NAMESPACE)) {
namespace = namedArguments.get(UrlMapping.NAMESPACE).toString();
}
UrlMappingData urlData = createUrlMappingData(uri, isResponseCode);
if (namedArguments.containsKey(RESOURCE)) {
Object controller = namedArguments.get(RESOURCE);
String controllerName = controller.toString();
parentResources.push(new ParentResource(controllerName, uri, currentConstraints, true));
try {
invokeLastArgumentIfClosure(args);
} finally {
parentResources.pop();
}
if (controller != null) {
createSingleResourceRestfulMappings(controllerName, pluginName, namespace, version, urlData, currentConstraints, calculateIncludes(namedArguments, DEFAULT_RESOURCE_INCLUDES));
}
} else if (namedArguments.containsKey(RESOURCES)) {
Object controller = namedArguments.get(RESOURCES);
String controllerName = controller.toString();
parentResources.push(new ParentResource(controllerName, uri, currentConstraints, false));
try {
invokeLastArgumentIfClosure(args);
} finally {
parentResources.pop();
}
if (controller != null) {
createResourceRestfulMappings(controllerName, pluginName, namespace,version,urlData, currentConstraints, calculateIncludes(namedArguments, DEFAULT_RESOURCES_INCLUDES));
}
} else {
invokeLastArgumentIfClosure(args);
UrlMapping urlMapping = getURLMappingForNamedArgs(namedArguments, urlData, mappedURI, isResponseCode, currentConstraints);
configureUrlMapping(urlMapping);
return urlMapping;
}
}
return null;
} finally {
if (binding != null) {
variables.clear();
} else {
controllerName = null;
redirectInfo = null;
actionName = null;
viewName = null;
pluginName = null;
namespace = null;
}
if (parentResources.isEmpty()) {
previousConstraints.clear();
urlDefiningMode = true;
}
}
} else if (!urlDefiningMode && CONSTRAINTS.equals(mappedURI)) {
ConstrainedPropertyBuilder builder = new ConstrainedPropertyBuilder(this);
if (args.length > 0 && (args[0] instanceof Closure)) {
Closure callable = (Closure) args[0];
callable.setDelegate(builder);
for (ConstrainedProperty constrainedProperty : currentConstraints) {
builder.getConstrainedProperties().put(constrainedProperty.getPropertyName(), constrainedProperty);
}
callable.call();
}
return builder.getConstrainedProperties();
} else {
return super.invokeMethod(mappedURI, arg);
}
}
private List<String> calculateIncludes(Map namedArguments, List<String> defaultResourcesIncludes) {
List<String> includes = new ArrayList<String>(defaultResourcesIncludes);
Object excludesObject = namedArguments.get("excludes");
if (excludesObject != null ) {
if (excludesObject instanceof List) {
List excludeList = (List) excludesObject;
for (Object exc : excludeList) {
if (exc != null) {
String excStr = exc.toString().toLowerCase();
includes.remove(excStr);
}
}
}
else {
includes.remove(excludesObject.toString());
}
}
Object includesObject = namedArguments.get("includes");
if (includesObject != null) {
if (includesObject instanceof List) {
List includeList = (List) includesObject;
includes.clear();
for (Object inc : includeList) {
if (inc != null) {
String incStr = inc.toString().toLowerCase();
includes.add(incStr);
}
}
}
else {
includes.clear();
includes.add(includesObject.toString());
}
}
return includes;
}
private String establishFullURI(String uri, List<ConstrainedProperty> currentConstraints) {
if (parentResources.isEmpty()) {
return uri;
}
StringBuilder uriBuilder = new StringBuilder();
ParentResource parentResource = parentResources.peek();
if (parentResource.isSingle) {
uriBuilder.append(parentResource.uri);
}
else {
if (parentResource.controllerName != null) {
uriBuilder.append(parentResource.uri).append(SLASH).append(CAPTURING_WILD_CARD);
currentConstraints.add(new ConstrainedProperty(UrlMapping.class, parentResource.controllerName + "Id", String.class));
}
}
uriBuilder.append(uri);
return uriBuilder.toString();
}
private void invokeLastArgumentIfClosure(Object[] args) {
if (args.length > 1 && args[1] instanceof Closure) {
((Closure) args[1]).call();
}
}
protected void createResourceRestfulMappings(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints, List<String> includes) {
ConstrainedProperty[] constraintArray = previousConstraints.toArray(new ConstrainedProperty[previousConstraints.size()]);
if (includes.contains(ACTION_INDEX)) {
// GET /$controller -> action:'index'
UrlMapping listUrlMapping = createIndexActionResourcesRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(listUrlMapping);
}
if (includes.contains(ACTION_CREATE)) {
// GET /$controller/create -> action:'create'
UrlMapping createUrlMapping = createCreateActionResourcesRestfulMapping(controllerName, pluginName,namespace, version, urlData, constraintArray);
configureUrlMapping(createUrlMapping);
}
if (includes.contains(ACTION_SAVE)) {
// POST /$controller -> action:'save'
UrlMapping saveUrlMapping = createSaveActionResourcesRestfulMapping(controllerName, pluginName, namespace,version, urlData, previousConstraints);
configureUrlMapping(saveUrlMapping);
}
if (includes.contains(ACTION_SHOW)) {
// GET /$controller/$id -> action:'show'
UrlMapping showUrlMapping = createShowActionResourcesRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(showUrlMapping);
}
if (includes.contains(ACTION_EDIT)) {
// GET /$controller/$id/edit -> action:'edit'
UrlMapping editUrlMapping = createEditActionResourcesRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(editUrlMapping);
}
if (includes.contains(ACTION_UPDATE)) {
// PUT /$controller/$id -> action:'update'
UrlMapping updateUrlMapping = createUpdateActionResourcesRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(updateUrlMapping);
}
if (includes.contains(ACTION_DELETE)) {
// DELETE /$controller/$id -> action:'delete'
UrlMapping deleteUrlMapping = createDeleteActionResourcesRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(deleteUrlMapping);
}
}
protected UrlMapping createDeleteActionResourcesRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints) {
UrlMappingData deleteUrlMappingData = createRelativeUrlDataWithIdAndFormat(urlData);
List<ConstrainedProperty> deleteUrlMappingConstraints = createConstraintsWithIdAndFormat(previousConstraints);
return new RegexUrlMapping(deleteUrlMappingData,controllerName, ACTION_DELETE, namespace, pluginName, null, HttpMethod.DELETE.toString(), version,deleteUrlMappingConstraints.toArray(new ConstrainedProperty[deleteUrlMappingConstraints.size()]) , servletContext);
}
protected UrlMapping createUpdateActionResourcesRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints) {
UrlMappingData updateUrlMappingData = createRelativeUrlDataWithIdAndFormat(urlData);
List<ConstrainedProperty> updateUrlMappingConstraints = createConstraintsWithIdAndFormat(previousConstraints);
return new RegexUrlMapping(updateUrlMappingData,controllerName, ACTION_UPDATE, namespace, pluginName, null, HttpMethod.PUT.toString(),version,updateUrlMappingConstraints.toArray(new ConstrainedProperty[updateUrlMappingConstraints.size()]) , servletContext);
}
protected UrlMapping createEditActionResourcesRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints) {
UrlMappingData editUrlMappingData = urlData.createRelative('/' + CAPTURING_WILD_CARD + "/edit");
List<ConstrainedProperty> editUrlMappingConstraints = new ArrayList<ConstrainedProperty>(previousConstraints);
editUrlMappingConstraints.add(new ConstrainedProperty(UrlMapping.class, "id", String.class));
return new RegexUrlMapping(editUrlMappingData,controllerName, ACTION_EDIT, namespace, pluginName, null, HttpMethod.GET.toString(), version,editUrlMappingConstraints.toArray(new ConstrainedProperty[editUrlMappingConstraints.size()]) , servletContext);
}
protected UrlMapping createShowActionResourcesRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints) {
UrlMappingData showUrlMappingData = createRelativeUrlDataWithIdAndFormat(urlData);
List<ConstrainedProperty> showUrlMappingConstraints = createConstraintsWithIdAndFormat(previousConstraints);
return new RegexUrlMapping(showUrlMappingData,controllerName, ACTION_SHOW, namespace, pluginName, null, HttpMethod.GET.toString(), version,showUrlMappingConstraints.toArray(new ConstrainedProperty[showUrlMappingConstraints.size()]) , servletContext);
}
private List<ConstrainedProperty> createConstraintsWithIdAndFormat(List<ConstrainedProperty> previousConstraints) {
List<ConstrainedProperty> showUrlMappingConstraints = new ArrayList<ConstrainedProperty>(previousConstraints);
showUrlMappingConstraints.add(new ConstrainedProperty(UrlMapping.class, "id", String.class));
ConstrainedProperty cp = new ConstrainedProperty(UrlMapping.class, "format", String.class);
cp.setNullable(true);
showUrlMappingConstraints.add(cp);
return showUrlMappingConstraints;
}
private UrlMappingData createRelativeUrlDataWithIdAndFormat(UrlMappingData urlData) {
return urlData.createRelative('/' + CAPTURING_WILD_CARD + UrlMapping.OPTIONAL_EXTENSION_WILDCARD + UrlMapping.QUESTION_MARK);
}
private UrlMappingData createFormatOnlyUrlMappingData(UrlMappingData urlData) {
return urlData.createRelative(UrlMapping.OPTIONAL_EXTENSION_WILDCARD + UrlMapping.QUESTION_MARK);
}
protected UrlMapping createSaveActionResourcesRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> constraints) {
UrlMappingData saveActionUrlMappingData = urlData.createRelative(UrlMapping.OPTIONAL_EXTENSION_WILDCARD + UrlMapping.QUESTION_MARK);
List<ConstrainedProperty> saveUrlMappingConstraints = createFormatOnlyConstraints(constraints);
return new RegexUrlMapping(saveActionUrlMappingData,controllerName, ACTION_SAVE, namespace, pluginName, null, HttpMethod.POST.toString(),version,saveUrlMappingConstraints.toArray(new ConstrainedProperty[saveUrlMappingConstraints.size()]), servletContext);
}
protected UrlMapping createCreateActionResourcesRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, ConstrainedProperty[] constraintArray) {
UrlMappingData createMappingData = urlData.createRelative("/create");
return new RegexUrlMapping(createMappingData,controllerName, ACTION_CREATE, namespace, pluginName, null, HttpMethod.GET.toString(), version,constraintArray, servletContext);
}
protected UrlMapping createIndexActionResourcesRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> constraints) {
UrlMappingData indexActionUrlMappingData = urlData.createRelative(UrlMapping.OPTIONAL_EXTENSION_WILDCARD + UrlMapping.QUESTION_MARK);
List<ConstrainedProperty> indexUrlMappingConstraints = createFormatOnlyConstraints(constraints);
return new RegexUrlMapping(indexActionUrlMappingData, controllerName, ACTION_INDEX, namespace, pluginName, null, HttpMethod.GET.toString(), version,indexUrlMappingConstraints.toArray(new ConstrainedProperty[indexUrlMappingConstraints.size()]), servletContext);
}
private List<ConstrainedProperty> createFormatOnlyConstraints(List<ConstrainedProperty> constraints) {
List<ConstrainedProperty> indexUrlMappingConstraints = new ArrayList<ConstrainedProperty>(constraints);
ConstrainedProperty cp = new ConstrainedProperty(UrlMapping.class, "format", String.class);
cp.setNullable(true);
indexUrlMappingConstraints.add(cp);
return indexUrlMappingConstraints;
}
/**
* Takes a controller and creates the necessary URL mappings for a singular RESTful resource
*
* @param controllerName The controller name
* @param pluginName The name of the plugin
* @param namespace
* @param version
* @param urlData The urlData instance
* @param previousConstraints Any constraints
* @param includes
*/
protected void createSingleResourceRestfulMappings(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints, List<String> includes) {
ConstrainedProperty[] constraintArray = previousConstraints.toArray(new ConstrainedProperty[previousConstraints.size()]);
if (includes.contains(ACTION_CREATE)) {
// GET /$controller/create -> action: 'create'
UrlMapping createUrlMapping = createCreateActionResourcesRestfulMapping(controllerName, pluginName, namespace,version, urlData, constraintArray);
configureUrlMapping(createUrlMapping);
}
if (includes.contains(ACTION_SAVE)) {
// POST /$controller -> action:'save'
UrlMapping saveUrlMapping = createSaveActionResourcesRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(saveUrlMapping);
}
if (includes.contains(ACTION_SHOW)) {
// GET /$controller -> action:'show'
UrlMapping showUrlMapping = createShowActionResourceRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(showUrlMapping);
}
if (includes.contains(ACTION_EDIT)) {
// GET /$controller/edit -> action:'edit'
UrlMapping editUrlMapping = createEditctionResourceRestfulMapping(controllerName, pluginName, namespace,version,urlData, constraintArray);
configureUrlMapping(editUrlMapping);
}
if (includes.contains(ACTION_UPDATE)) {
// PUT /$controller -> action:'update'
UrlMapping updateUrlMapping = createUpdateActionResourceRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(updateUrlMapping);
}
if (includes.contains(ACTION_DELETE)) {
// DELETE /$controller -> action:'delete'
UrlMapping deleteUrlMapping = createDeleteActionResourceRestfulMapping(controllerName, pluginName, namespace,version,urlData, previousConstraints);
configureUrlMapping(deleteUrlMapping);
}
}
protected UrlMapping createDeleteActionResourceRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints) {
UrlMappingData deleteUrlMappingData = createFormatOnlyUrlMappingData(urlData);
List<ConstrainedProperty> deleteUrlMappingConstraints = createFormatOnlyConstraints(previousConstraints);
return new RegexUrlMapping(deleteUrlMappingData,controllerName, ACTION_DELETE, null, pluginName, null, HttpMethod.DELETE.toString(), version, deleteUrlMappingConstraints.toArray(new ConstrainedProperty[deleteUrlMappingConstraints.size()]) , servletContext);
}
protected UrlMapping createUpdateActionResourceRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints) {
UrlMappingData updateUrlMappingData = createFormatOnlyUrlMappingData(urlData);
List<ConstrainedProperty> updateUrlMappingConstraints = createFormatOnlyConstraints(previousConstraints);
return new RegexUrlMapping(updateUrlMappingData,controllerName, ACTION_UPDATE, null, pluginName, null, HttpMethod.PUT.toString(),version, updateUrlMappingConstraints.toArray(new ConstrainedProperty[updateUrlMappingConstraints.size()]) , servletContext);
}
protected UrlMapping createEditctionResourceRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, ConstrainedProperty[] constraintArray) {
UrlMappingData editMappingData = urlData.createRelative("/edit");
return new RegexUrlMapping(editMappingData,controllerName,ACTION_EDIT, null, pluginName, null, HttpMethod.GET.toString(),version, constraintArray, servletContext);
}
protected UrlMapping createShowActionResourceRestfulMapping(String controllerName, Object pluginName, Object namespace, String version, UrlMappingData urlData, List<ConstrainedProperty> previousConstraints) {
UrlMappingData showUrlMappingData = createFormatOnlyUrlMappingData(urlData);
List<ConstrainedProperty> showUrlMappingConstraints = createFormatOnlyConstraints(previousConstraints);
return new RegexUrlMapping(showUrlMappingData,controllerName, ACTION_SHOW,null, pluginName, null, HttpMethod.GET.toString(), version, showUrlMappingConstraints.toArray(new ConstrainedProperty[showUrlMappingConstraints.size()]) , servletContext);
}
@SuppressWarnings("unchecked")
private void configureUrlMapping(UrlMapping urlMapping) {
if (binding != null) {
Map<String, Object> vars = binding.getVariables();
for (String key : vars.keySet()) {
if (isNotCoreMappingKey(key)) {
parameterValues.put(key, vars.get(key));
}
}
binding.getVariables().clear();
}
// Add the controller and action to the params map if
// they are set. This ensures consistency of behaviour
// for the application, i.e. "controller" and "action"
// parameters will always be available to it.
if (urlMapping.getControllerName() != null) {
parameterValues.put("controller", urlMapping.getControllerName());
}
if (urlMapping.getActionName() != null) {
parameterValues.put("action", urlMapping.getActionName());
}
urlMapping.setParameterValues(parameterValues);
urlMappings.add(urlMapping);
}
private boolean isNotCoreMappingKey(Object key) {
return !GrailsControllerClass.ACTION.equals(key) &&
!GrailsControllerClass.CONTROLLER.equals(key) &&
!GrailsControllerClass.VIEW.equals(key);
}
private UrlMappingData createUrlMappingData(String methodName, boolean responseCode) {
if (!responseCode) {
return urlParser.parse(methodName);
}
return new ResponseCodeMappingData(methodName);
}
private boolean isResponseCode(String s) {
for (int count = s.length(), i = 0; i < count; i++) {
if (!Character.isDigit(s.charAt(i))) return false;
}
return true;
}
private UrlMapping getURLMappingForNamedArgs(Map namedArguments,
UrlMappingData urlData, String mapping, boolean isResponseCode, List<ConstrainedProperty> currentConstraints) {
Object controllerName;
Object actionName;
final Map bindingVariables = binding != null ? binding.getVariables() : null;
controllerName = getControllerName(namedArguments, bindingVariables);
actionName = getActionName(namedArguments, bindingVariables);
Object pluginName = getPluginName(namedArguments, bindingVariables);
Object httpMethod = getHttpMethod(namedArguments, bindingVariables);
Object version = getVersion(namedArguments, bindingVariables);
Object namespace = getNamespace(namedArguments, bindingVariables);
Object redirectInfo = getRedirectInfo(namedArguments, bindingVariables);
Object viewName = getViewName(namedArguments, bindingVariables);
if (actionName != null && viewName != null) {
viewName = null;
LOG.warn("Both [action] and [view] specified in URL mapping [" + mapping + "]. The action takes precendence!");
}
Object uri = getURI(namedArguments, bindingVariables);
ConstrainedProperty[] constraints = currentConstraints.toArray(new ConstrainedProperty[currentConstraints.size()]);
UrlMapping urlMapping;
if (uri != null) {
try {
urlMapping = new RegexUrlMapping(urlData, new URI(uri.toString()), constraints, sc);
}
catch (URISyntaxException e) {
throw new UrlMappingException("Cannot map to invalid URI: " + e.getMessage(), e);
}
}
else {
urlMapping = createURLMapping(urlData, isResponseCode, redirectInfo, controllerName, actionName, namespace, pluginName, viewName, httpMethod != null ? httpMethod.toString() : null, version != null ? version.toString() : null, constraints);
}
Object exceptionArg = getException(namedArguments, bindingVariables);
if (isResponseCode && exceptionArg != null) {
if (exceptionArg instanceof Class) {
Class exClass = (Class) exceptionArg;
if (Throwable.class.isAssignableFrom(exClass)) {
((ResponseCodeUrlMapping)urlMapping).setExceptionType(exClass);
}
else {
LOG.error("URL mapping argument [exception] with value ["+ exceptionArg +"] must be a subclass of java.lang.Throwable");
}
}
else {
LOG.error("URL mapping argument [exception] with value [" + exceptionArg + "] must be a valid class");
}
}
Object parseRequest = getParseRequest(namedArguments,bindingVariables);
if (parseRequest instanceof Boolean) {
urlMapping.setParseRequest((Boolean) parseRequest);
}
return urlMapping;
}
private Object getVariableFromNamedArgsOrBinding(Map namedArguments, Map bindingVariables, String variableName, Object defaultValue) {
Object returnValue;
returnValue = namedArguments.get(variableName);
if (returnValue == null) {
returnValue = binding != null ? bindingVariables.get(variableName) : defaultValue;
}
return returnValue;
}
private Object getActionName(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables,GrailsControllerClass.ACTION, actionName);
}
private Object getParseRequest(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables,PARSE_REQUEST, parseRequest);
}
private Object getControllerName(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables,GrailsControllerClass.CONTROLLER, controllerName);
}
private Object getPluginName(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables, UrlMapping.PLUGIN, pluginName);
}
private Object getHttpMethod(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables, UrlMapping.HTTP_METHOD, pluginName);
}
private Object getRedirectInfo(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables, UrlMapping.REDIRECT_INFO, redirectInfo);
}
private Object getVersion(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables, UrlMapping.VERSION, pluginName);
}
private Object getNamespace(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables, UrlMapping.NAMESPACE, namespace);
}
private Object getViewName(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables,GrailsControllerClass.VIEW, viewName);
}
private Object getURI(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables, UrlMapping.URI, uri);
}
private Object getException(Map namedArguments, Map bindingVariables) {
return getVariableFromNamedArgsOrBinding(namedArguments, bindingVariables,EXCEPTION, exception);
}
private UrlMapping createURLMapping(UrlMappingData urlData, boolean isResponseCode, Object redirectInfo,
Object controllerName, Object actionName, Object namespace, Object pluginName,
Object viewName, String httpMethod, String version, ConstrainedProperty[] constraints) {
if (!isResponseCode) {
return new RegexUrlMapping(redirectInfo, urlData, controllerName, actionName, namespace, pluginName, viewName, httpMethod, version, constraints, sc);
}
return new ResponseCodeUrlMapping(urlData, controllerName, actionName, namespace, pluginName, viewName,