This repository has been archived by the owner on Feb 26, 2023. It is now read-only.
/
ValidatorHelper.java
1207 lines (996 loc) · 52.9 KB
/
ValidatorHelper.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 (C) 2010-2013 eBusiness Information, Excilys Group
*
* 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.androidannotations.helper;
import static java.util.Arrays.asList;
import static org.androidannotations.helper.AndroidConstants.LOG_DEBUG;
import static org.androidannotations.helper.AndroidConstants.LOG_ERROR;
import static org.androidannotations.helper.AndroidConstants.LOG_INFO;
import static org.androidannotations.helper.AndroidConstants.LOG_VERBOSE;
import static org.androidannotations.helper.AndroidConstants.LOG_WARN;
import static org.androidannotations.helper.CanonicalNameConstants.CLIENT_HTTP_REQUEST_INTERCEPTOR;
import static org.androidannotations.helper.CanonicalNameConstants.HTTP_MESSAGE_CONVERTER;
import static org.androidannotations.helper.CanonicalNameConstants.INTERNET_PERMISSION;
import static org.androidannotations.helper.ModelConstants.GENERATION_SUFFIX;
import static org.androidannotations.helper.ModelConstants.VALID_ENHANCED_COMPONENT_ANNOTATIONS;
import static org.androidannotations.helper.ModelConstants.VALID_ENHANCED_VIEW_SUPPORT_ANNOTATIONS;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ErrorType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.Delete;
import org.androidannotations.annotations.rest.Get;
import org.androidannotations.annotations.rest.Head;
import org.androidannotations.annotations.rest.Options;
import org.androidannotations.annotations.rest.Post;
import org.androidannotations.annotations.rest.Put;
import org.androidannotations.annotations.rest.Rest;
import org.androidannotations.annotations.sharedpreferences.DefaultBoolean;
import org.androidannotations.annotations.sharedpreferences.DefaultFloat;
import org.androidannotations.annotations.sharedpreferences.DefaultInt;
import org.androidannotations.annotations.sharedpreferences.DefaultLong;
import org.androidannotations.annotations.sharedpreferences.DefaultString;
import org.androidannotations.annotations.sharedpreferences.SharedPref;
import org.androidannotations.api.sharedpreferences.SharedPreferencesHelper;
import org.androidannotations.model.AndroidSystemServices;
import org.androidannotations.model.AnnotationElements;
import org.androidannotations.processing.InstanceStateProcessor;
import org.androidannotations.validation.IsValid;
public class ValidatorHelper {
private static final List<String> ANDROID_SHERLOCK_MENU_ITEM_QUALIFIED_NAMES = asList(CanonicalNameConstants.MENU_ITEM, CanonicalNameConstants.SHERLOCK_MENU_ITEM);
private static final List<String> ANDROID_FRAGMENT_QUALIFIED_NAMES = asList(CanonicalNameConstants.FRAGMENT, CanonicalNameConstants.SUPPORT_V4_FRAGMENT);
private static final String METHOD_NAME_SET_ROOT_URL = "setRootUrl";
private static final List<String> VALID_PREF_RETURN_TYPES = Arrays.asList("int", "boolean", "float", "long", CanonicalNameConstants.STRING);
private static final List<String> INVALID_PREF_METHOD_NAMES = Arrays.asList("edit", "getSharedPreferences", "clear", "getEditor", "apply");
private static final Collection<Integer> VALID_LOG_LEVELS = Arrays.asList(LOG_VERBOSE, LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR);
protected final TargetAnnotationHelper annotationHelper;
public ValidatorHelper(TargetAnnotationHelper targetAnnotationHelper) {
annotationHelper = targetAnnotationHelper;
}
public void isNotFinal(Element element, IsValid valid) {
if (annotationHelper.isFinal(element)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s cannot be used on a final element");
}
}
public void isNotSynchronized(Element element, IsValid valid) {
if (annotationHelper.isSynchronized(element)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s cannot be used on a synchronized element. If you think you shall need to use the synchronized keyword for a specific use case, please post on the mailing list.");
}
}
public void isInterface(TypeElement element, IsValid valid) {
if (!annotationHelper.isInterface(element)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s can only be used on an interface");
}
}
public void isTopLevel(TypeElement element, IsValid valid) {
if (!annotationHelper.isTopLevel(element)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s can only be used on a top level type");
}
}
public void doesNotExtendOtherInterfaces(TypeElement element, IsValid valid) {
if (element.getInterfaces().size() > 0) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s can only be used on an interface that does not extend other interfaces");
}
}
public void doesNotReturnPrimitive(ExecutableElement element, IsValid valid) {
if (element.getReturnType().getKind().isPrimitive()) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s cannot return primitive");
}
}
public void doesNotReturnArray(ExecutableElement element, IsValid valid) {
if (element.getReturnType().getKind() == TypeKind.ARRAY) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s cannot return array");
}
}
public void isNotPrivate(Element element, IsValid valid) {
if (annotationHelper.isPrivate(element)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s cannot be used on a private element");
}
}
public void isPublic(Element element, IsValid valid) {
if (!annotationHelper.isPublic(element)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s cannot be used on a non public element");
}
}
public void enclosingElementHasEBeanAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
Element enclosingElement = element.getEnclosingElement();
hasClassAnnotation(element, enclosingElement, validatedElements, EBean.class, valid);
}
public void enclosingElementHasEActivity(Element element, AnnotationElements validatedElements, IsValid valid) {
Element enclosingElement = element.getEnclosingElement();
hasClassAnnotation(element, enclosingElement, validatedElements, EActivity.class, valid);
}
public void enclosingElementHasEActivityOrEFragment(Element element, AnnotationElements validatedElements, IsValid valid) {
Element enclosingElement = element.getEnclosingElement();
@SuppressWarnings("unchecked")
List<Class<? extends Annotation>> validAnnotations = asList(EActivity.class, EFragment.class);
hasOneOfClassAnnotations(element, enclosingElement, validatedElements, validAnnotations, valid);
}
public void enclosingElementHasEFragment(Element element, AnnotationElements validatedElements, IsValid valid) {
Element enclosingElement = element.getEnclosingElement();
hasClassAnnotation(element, enclosingElement, validatedElements, EFragment.class, valid);
}
public void hasEActivity(Element element, AnnotationElements validatedElements, IsValid valid) {
hasClassAnnotation(element, element, validatedElements, EActivity.class, valid);
}
public void hasEActivityOrEFragment(Element element, AnnotationElements validatedElements, IsValid valid) {
@SuppressWarnings("unchecked")
List<Class<? extends Annotation>> validAnnotations = asList(EActivity.class, EFragment.class);
hasOneOfClassAnnotations(element, element, validatedElements, validAnnotations, valid);
}
public void enclosingElementHasEnhancedViewSupportAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
Element enclosingElement = element.getEnclosingElement();
hasOneOfClassAnnotations(element, enclosingElement, validatedElements, VALID_ENHANCED_VIEW_SUPPORT_ANNOTATIONS, valid);
}
public void enclosingElementHasEnhancedComponentAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
Element enclosingElement = element.getEnclosingElement();
hasOneOfClassAnnotations(element, enclosingElement, validatedElements, VALID_ENHANCED_COMPONENT_ANNOTATIONS, valid);
}
private void hasClassAnnotation(Element reportElement, Element element, AnnotationElements validatedElements, Class<? extends Annotation> validAnnotation, IsValid valid) {
ArrayList<Class<? extends Annotation>> validAnnotations = new ArrayList<Class<? extends Annotation>>();
validAnnotations.add(validAnnotation);
hasOneOfClassAnnotations(reportElement, element, validatedElements, validAnnotations, valid);
}
private void hasOneOfClassAnnotations(Element reportElement, Element element, AnnotationElements validatedElements, List<Class<? extends Annotation>> validAnnotations, IsValid valid) {
boolean foundAnnotation = false;
for (Class<? extends Annotation> validAnnotation : validAnnotations) {
if (element.getAnnotation(validAnnotation) != null) {
Set<? extends Element> layoutAnnotatedElements = validatedElements.getRootAnnotatedElements(validAnnotation.getName());
/*
* This is for the case where the element has the right
* annotation, but that annotation was not validated. We do not
* add any compile error (should already exist on the
* annotation), but we still invalidate this element.
*/
if (!layoutAnnotatedElements.contains(element)) {
valid.invalidate();
}
foundAnnotation = true;
break;
}
}
if (!foundAnnotation) {
valid.invalidate();
annotationHelper.printAnnotationError(reportElement, "%s can only be used in a class annotated with " + getFormattedValidEnhancedBeanAnnotationTypes(validAnnotations) + ".");
}
}
private String getFormattedValidEnhancedBeanAnnotationTypes(List<Class<? extends Annotation>> annotations) {
StringBuilder sb = new StringBuilder();
if (!annotations.isEmpty()) {
sb.append(TargetAnnotationHelper.annotationName(annotations.get(0)));
for (int i = 1; i < annotations.size(); i++) {
sb.append(", ");
sb.append(TargetAnnotationHelper.annotationName(annotations.get(i)));
}
}
return sb.toString();
}
public void hasViewByIdAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
String error = "can only be used with annotation";
elementHasAnnotation(ViewById.class, element, validatedElements, valid, error);
}
public void elementHasRestAnnotationOrEnclosingElementHasRestAnnotationAndElementHasMethodRestAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
String error = "can only be used in an interface annotated with";
elementHasAnnotation(Rest.class, element, validatedElements, valid, error);
if (!valid.isValid()) {
enclosingElementHasRestAnnotation(element, validatedElements, valid);
elementHasMethodRestAnnotation(element, validatedElements, valid);
}
}
public void elementHasMethodRestAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
String error = "can only be used on a method annotated with Rest methods.";
elementHasAnnotationContainsIn(REST_ANNOTATION_CLASSES, element, validatedElements, valid, error);
}
public void enclosingElementHasRestAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
String error = "can only be used in an interface annotated with";
enclosingElementHasAnnotation(Rest.class, element, validatedElements, valid, error);
}
public void enclosingElementHasAnnotation(Class<? extends Annotation> annotation, Element element, AnnotationElements validatedElements, IsValid valid, String error) {
Element enclosingElement = element.getEnclosingElement();
elementHasAnnotation(annotation, enclosingElement, validatedElements, valid, error);
}
public void elementHasAnnotation(Class<? extends Annotation> annotation, Element element, AnnotationElements validatedElements, IsValid valid, String error) {
Set<? extends Element> layoutAnnotatedElements = validatedElements.getRootAnnotatedElements(annotation.getName());
if (!layoutAnnotatedElements.contains(element)) {
valid.invalidate();
if (element.getAnnotation(annotation) == null) {
annotationHelper.printAnnotationError(element, "%s " + error + " " + TargetAnnotationHelper.annotationName(annotation));
}
}
}
public void elementHasAnnotationContainsIn(List<Class<? extends Annotation>> annotations, Element element, AnnotationElements validatedElements, IsValid valid, String error) {
boolean isAnnoted = false;
for (Class<? extends Annotation> annotation : annotations) {
if (elementHasAnnotation(annotation, element, validatedElements)) {
isAnnoted = true;
break;
}
}
if (!isAnnoted) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s " + error);
}
}
public boolean elementHasAnnotation(Class<? extends Annotation> annotation, Element element, AnnotationElements validatedElements) {
Set<? extends Element> layoutAnnotatedElements = validatedElements.getRootAnnotatedElements(annotation.getName());
return layoutAnnotatedElements.contains(element);
}
public void throwsOnlyRestClientException(ExecutableElement element, IsValid valid) {
List<? extends TypeMirror> thrownTypes = element.getThrownTypes();
if (thrownTypes.size() > 0) {
if (thrownTypes.size() > 1 || !thrownTypes.get(0).toString().equals("org.springframework.web.client.RestClientException")) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated methods can only declare throwing a RestClientException");
}
}
}
public void elementHasGetOrPostAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
if (!elementHasAnnotation(Get.class, element) && !elementHasAnnotation(Post.class, element)) {
annotationHelper.printAnnotationError(element, "%s can only be used in an interface annotated with Get or Post annotation");
}
}
public void typeHasAnnotation(Class<? extends Annotation> annotation, Element element, IsValid valid) {
TypeMirror elementType = element.asType();
typeHasAnnotation(annotation, elementType, element, valid);
}
public void typeHasAnnotation(Class<? extends Annotation> annotation, TypeMirror elementType, Element reportingElement, IsValid valid) {
Element typeElement = annotationHelper.getTypeUtils().asElement(elementType);
if (!elementHasAnnotationSafe(annotation, typeElement)) {
valid.invalidate();
annotationHelper.printAnnotationError(reportingElement, "%s can only be used on an element annotated with " + TargetAnnotationHelper.annotationName(annotation));
}
}
public void typeOrTargetValueHasAnnotation(Class<? extends Annotation> annotation, Element element, IsValid valid) {
DeclaredType targetAnnotationClassValue = annotationHelper.extractAnnotationClassParameter(element);
if (targetAnnotationClassValue != null) {
typeHasAnnotation(annotation, targetAnnotationClassValue, element, valid);
if (!annotationHelper.getTypeUtils().isAssignable(targetAnnotationClassValue, element.asType())) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "The value of %s must be assignable into the annotated field");
}
} else {
typeHasAnnotation(annotation, element, valid);
}
}
private boolean elementHasAnnotationSafe(Class<? extends Annotation> annotation, Element element) {
List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (annotationMirror.getAnnotationType().toString().equals(annotation.getName())) {
return true;
}
}
return false;
}
private boolean elementHasAnnotation(Class<? extends Annotation> annotation, Element element) {
return element.getAnnotation(annotation) != null;
}
public void elementHasRestAnnotation(Element element, AnnotationElements validatedElements, IsValid valid) {
String error = "can only be used in an interface annotated with";
elementHasAnnotation(Rest.class, element, validatedElements, valid, error);
}
public void returnTypeNotGenericUnlessResponseEntity(ExecutableElement element, IsValid valid) {
TypeMirror returnType = element.getReturnType();
TypeKind returnKind = returnType.getKind();
if (returnKind == TypeKind.DECLARED) {
DeclaredType declaredReturnType = (DeclaredType) returnType;
if (!declaredReturnType.toString().startsWith("org.springframework.http.ResponseEntity<") && declaredReturnType.getTypeArguments().size() > 0) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated methods cannot return parameterized types, except for ResponseEntity");
}
}
}
public void hasHttpHeadersReturnType(ExecutableElement element, IsValid valid) {
String returnType = element.getReturnType().toString();
if (!returnType.equals("org.springframework.http.HttpHeaders")) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated methods can only return a HttpHeaders, not " + returnType);
}
}
public void hasSetOfHttpMethodReturnType(ExecutableElement element, IsValid valid) {
TypeMirror returnType = element.getReturnType();
String returnTypeString = returnType.toString();
if (!returnTypeString.equals("java.util.Set<org.springframework.http.HttpMethod>")) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated methods can only return a Set of HttpMethod, not " + returnTypeString);
} else {
DeclaredType declaredType = (DeclaredType) returnType;
List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
if (typeArguments.size() != 1) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated methods can only return a parameterized Set (with HttpMethod)");
} else {
TypeMirror typeArgument = typeArguments.get(0);
if (!typeArgument.toString().equals("org.springframework.http.HttpMethod")) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated methods can only return a parameterized Set of HttpMethod, not " + typeArgument.toString());
}
}
}
}
public void urlVariableNamesExistInParameters(ExecutableElement element, List<String> variableNames, IsValid valid) {
List<? extends VariableElement> parameters = element.getParameters();
List<String> parametersName = new ArrayList<String>();
for (VariableElement parameter : parameters) {
parametersName.add(parameter.getSimpleName().toString());
}
for (String variableName : variableNames) {
if (!parametersName.contains(variableName)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated method has an url variable which name could not be found in the method parameters: " + variableName);
return;
}
}
}
public void doesntThrowException(Element element, IsValid valid) {
ExecutableElement executableElement = (ExecutableElement) element;
if (executableElement.getThrownTypes().size() > 0) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated methods should not declare throwing any exception");
}
}
public void returnTypeIsVoidOrBoolean(ExecutableElement executableElement, IsValid valid) {
TypeMirror returnType = executableElement.getReturnType();
TypeKind returnKind = returnType.getKind();
if (returnKind != TypeKind.BOOLEAN && returnKind != TypeKind.VOID && !returnType.toString().equals(CanonicalNameConstants.BOOLEAN)) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with a boolean or a void return type");
}
}
public void returnTypeIsVoid(ExecutableElement executableElement, IsValid valid) {
TypeMirror returnType = executableElement.getReturnType();
if (returnType.getKind() != TypeKind.VOID) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with a void return type");
}
}
public void returnTypeIsNotVoid(ExecutableElement executableElement, IsValid valid) {
TypeMirror returnType = executableElement.getReturnType();
if (returnType.getKind() == TypeKind.VOID) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with a return type non void");
}
}
public void zeroOrOneParameter(ExecutableElement executableElement, IsValid valid) {
List<? extends VariableElement> parameters = executableElement.getParameters();
if (parameters.size() > 1) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with zero or one parameter, instead of " + parameters.size());
}
}
public void zeroParameter(ExecutableElement executableElement, IsValid valid) {
List<? extends VariableElement> parameters = executableElement.getParameters();
if (parameters.size() > 0) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with zero parameter, instead of " + parameters.size());
}
}
public void zeroOrOneViewParameters(ExecutableElement executableElement, IsValid valid) {
zeroOrOneSpecificParameter(executableElement, CanonicalNameConstants.VIEW, valid);
}
public void zeroOrOneMenuItemParameters(ExecutableElement executableElement, IsValid valid) {
zeroOrOneSpecificParameter(executableElement, ANDROID_SHERLOCK_MENU_ITEM_QUALIFIED_NAMES, valid);
}
public void zeroOrOneSpecificParameter(ExecutableElement executableElement, String parameterTypeQualifiedName, IsValid valid) {
zeroOrOneSpecificParameter(executableElement, Arrays.asList(parameterTypeQualifiedName), valid);
}
public void zeroOrOneSpecificParameter(ExecutableElement executableElement, List<String> parameterTypeQualifiedNames, IsValid valid) {
zeroOrOneParameter(executableElement, valid);
List<? extends VariableElement> parameters = executableElement.getParameters();
if (parameters.size() == 1) {
VariableElement parameter = parameters.get(0);
TypeMirror parameterType = parameter.asType();
if (!parameterTypeQualifiedNames.contains(parameterType.toString())) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with no parameter or a parameter of type " + parameterTypeQualifiedNames + ", not " + parameterType);
}
}
}
public void zeroOrOneBundleParameter(ExecutableElement executableElement, IsValid valid) {
zeroOrOneSpecificParameter(executableElement, CanonicalNameConstants.BUNDLE, valid);
}
public void extendsActivity(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.ACTIVITY, valid);
}
public void extendsFragment(Element element, IsValid valid) {
extendsOneOfTypes(element, ANDROID_FRAGMENT_QUALIFIED_NAMES, valid);
}
public void extendsService(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.SERVICE, valid);
}
public void extendsReceiver(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.BROADCAST_RECEIVER, valid);
}
public void extendsProvider(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.CONTENT_PROVIDER, valid);
}
public void extendsView(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.VIEW, valid);
}
public void extendsTextView(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.TEXT_VIEW, valid);
}
public void extendsViewGroup(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.VIEW_GROUP, valid);
}
public void extendsApplication(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.APPLICATION, valid);
}
public void extendsContext(Element element, IsValid valid) {
extendsType(element, CanonicalNameConstants.CONTEXT, valid);
}
public void extendsOrmLiteDaoWithValidModelParameter(Element element, IsValid valid) {
TypeMirror elementType = element.asType();
TypeMirror modelTypeMirror = annotationHelper.extractAnnotationParameter(element, "model");
TypeElement daoTypeElement = annotationHelper.typeElementFromQualifiedName(CanonicalNameConstants.DAO);
if (daoTypeElement != null) {
TypeMirror wildcardType = annotationHelper.getTypeUtils().getWildcardType(null, null);
DeclaredType daoParameterizedType = annotationHelper.getTypeUtils().getDeclaredType(daoTypeElement, modelTypeMirror, wildcardType);
// Checks that elementType extends Dao<ModelType, ?>
if (!annotationHelper.isSubtype(elementType, daoParameterizedType)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s can only be used on an element that extends " + daoParameterizedType.toString());
}
}
}
public void hasASqlLiteOpenHelperParameterizedType(Element element, IsValid valid) {
TypeMirror helperType = annotationHelper.extractAnnotationParameter(element, "helper");
TypeMirror openHelperType = annotationHelper.typeElementFromQualifiedName(CanonicalNameConstants.SQLLITE_OPEN_HELPER).asType();
if (!annotationHelper.isSubtype(helperType, openHelperType)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s helper() parameter must extend " + CanonicalNameConstants.SQLLITE_OPEN_HELPER);
}
}
public void applicationRegistered(Element element, AndroidManifest manifest, IsValid valid) {
if (manifest.isLibraryProject()) {
return;
}
String applicationClassName = manifest.getApplicationClassName();
if (applicationClassName != null) {
TypeElement typeElement = (TypeElement) element;
String componentQualifiedName = typeElement.getQualifiedName().toString();
String generatedComponentQualifiedName = componentQualifiedName + ModelConstants.GENERATION_SUFFIX;
if (!applicationClassName.equals(generatedComponentQualifiedName)) {
if (applicationClassName.equals(componentQualifiedName)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "The AndroidManifest.xml file contains the original component, and not the AndroidAnnotations generated component. Please register " + generatedComponentQualifiedName + " instead of " + componentQualifiedName);
} else {
annotationHelper.printAnnotationWarning(element, "The component " + generatedComponentQualifiedName + " is not registered in the AndroidManifest.xml file.");
}
}
} else {
valid.invalidate();
annotationHelper.printAnnotationError(element, "No application class registered in the AndroidManifest.xml");
}
}
public void isSharedPreference(Element element, AnnotationElements validatedElements, IsValid valid) {
TypeMirror type = element.asType();
/*
* The type is not available yet because it has just been generated
*/
if (type instanceof ErrorType || type.getKind() == TypeKind.ERROR) {
String elementTypeName = type.toString();
boolean sharedPrefValidatedInRound = false;
if (elementTypeName.endsWith(GENERATION_SUFFIX)) {
String prefTypeName = elementTypeName.substring(0, elementTypeName.length() - GENERATION_SUFFIX.length());
Set<? extends Element> sharedPrefElements = validatedElements.getRootAnnotatedElements(SharedPref.class.getName());
for (Element sharedPrefElement : sharedPrefElements) {
TypeElement sharedPrefTypeElement = (TypeElement) sharedPrefElement;
String sharedPrefQualifiedName = sharedPrefTypeElement.getQualifiedName().toString();
if (sharedPrefQualifiedName.endsWith(prefTypeName)) {
sharedPrefValidatedInRound = true;
break;
}
}
}
if (!sharedPrefValidatedInRound) {
valid.invalidate();
}
} else {
extendsType(element, SharedPreferencesHelper.class.getName(), valid);
}
}
public void extendsOneOfTypes(Element element, List<String> typeQualifiedNames, IsValid valid) {
TypeMirror elementType = element.asType();
for (String typeQualifiedName : typeQualifiedNames) {
TypeElement typeElement = annotationHelper.typeElementFromQualifiedName(typeQualifiedName);
if (typeElement != null) {
TypeMirror expectedType = typeElement.asType();
if (annotationHelper.isSubtype(elementType, expectedType)) {
return;
}
}
}
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s can only be used on an element that extends one of the following classes: " + typeQualifiedNames);
}
public void extendsType(Element element, String typeQualifiedName, IsValid valid) {
TypeMirror elementType = element.asType();
TypeElement typeElement = annotationHelper.typeElementFromQualifiedName(typeQualifiedName);
if (typeElement != null) {
TypeMirror expectedType = typeElement.asType();
if (!annotationHelper.isSubtype(elementType, expectedType)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s can only be used on an element that extends " + typeQualifiedName);
}
}
}
public void hasExactlyOneParameter(ExecutableElement executableElement, IsValid valid) {
List<? extends VariableElement> parameters = executableElement.getParameters();
if (parameters.size() != 1) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with exactly one parameter, instead of " + parameters.size());
}
}
public void hasOneOrTwoParametersAndFirstIsBoolean(ExecutableElement executableElement, IsValid valid) {
List<? extends VariableElement> parameters = executableElement.getParameters();
if (parameters.size() < 1 || parameters.size() > 2) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with 1 or 2 parameter, instead of " + parameters.size());
} else {
VariableElement firstParameter = parameters.get(0);
TypeKind parameterKind = firstParameter.asType().getKind();
if (parameterKind != TypeKind.BOOLEAN && !firstParameter.toString().equals(CanonicalNameConstants.BOOLEAN)) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "the first parameter should be a boolean");
}
}
}
public void allowedType(Element element, IsValid valid, TypeMirror fieldTypeMirror, List<String> allowedTypes) {
String qualifiedName = fieldTypeMirror.toString();
if (!allowedTypes.contains(qualifiedName)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s can only be used on a field which is a " + allowedTypes.toString() + ", not " + qualifiedName);
}
}
public void hasRoboGuiceJars(Element element, IsValid valid) {
Elements elementUtils = annotationHelper.getElementUtils();
if (elementUtils.getTypeElement(CanonicalNameConstants.INJECTOR_PROVIDER) == null) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "Could not find the RoboGuice framework in the classpath, the following class is missing: " + CanonicalNameConstants.INJECTOR_PROVIDER);
}
if (elementUtils.getTypeElement(RoboGuiceConstants.ROBOGUICE_APPLICATION_CLASS) == null) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "Could not find the RoboApplication class in the classpath, are you using RoboGuice 1.1.1 ?");
}
try {
if (elementUtils.getTypeElement(CanonicalNameConstants.INJECTOR) == null) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "Could not find the Guice framework in the classpath, the following class is missing: " + CanonicalNameConstants.INJECTOR);
}
} catch (RuntimeException e) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "Could not find the Guice framework in the classpath, the following class is missing: " + CanonicalNameConstants.INJECTOR);
}
}
public void hasSpringAndroidJars(Element element, IsValid valid) {
Elements elementUtils = annotationHelper.getElementUtils();
if (elementUtils.getTypeElement(CanonicalNameConstants.REST_TEMPLATE) == null) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "Could not find the SpringAndroid framework in the classpath, the following class is missing: " + CanonicalNameConstants.REST_TEMPLATE);
}
}
public void hasOrmLiteJars(Element element, IsValid valid) {
Elements elementUtils = annotationHelper.getElementUtils();
if (elementUtils.getTypeElement(CanonicalNameConstants.DAO) == null) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "Could not find the OrmLite framework in the classpath, the following class is missing: " + CanonicalNameConstants.DAO);
}
}
public void androidService(AndroidSystemServices androidSystemServices, Element element, IsValid valid) {
TypeMirror serviceType = element.asType();
if (!androidSystemServices.contains(serviceType)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "Unknown service type: " + serviceType.toString());
}
}
public void hasOneMotionEventOrTwoMotionEventViewParameters(ExecutableElement executableElement, IsValid valid) {
List<? extends VariableElement> parameters = executableElement.getParameters();
if (parameters.size() < 1 || parameters.size() > 2) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "%s can only be used on a method with 1 (MotionEvent) or 2 (MotionEvent, View) parameters, instead of " + parameters.size());
} else {
VariableElement firstParameter = parameters.get(0);
String firstParameterType = firstParameter.asType().toString();
if (!firstParameterType.equals(CanonicalNameConstants.MOTION_EVENT)) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "the first parameter must be a " + CanonicalNameConstants.MOTION_EVENT + ", not a " + firstParameterType);
}
if (parameters.size() == 2) {
VariableElement secondParameter = parameters.get(1);
String secondParameterType = secondParameter.asType().toString();
if (!secondParameterType.equals(CanonicalNameConstants.VIEW)) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "the second parameter must be a " + CanonicalNameConstants.VIEW + ", not a " + secondParameterType);
}
}
}
}
public void hasOneOrTwoParametersAndFirstIsDb(ExecutableElement executableElement, IsValid valid) {
List<? extends VariableElement> parameters = executableElement.getParameters();
if (parameters.size() < 1) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "There should be at least 1 parameter: a " + CanonicalNameConstants.SQLITE_DATABASE);
} else {
VariableElement firstParameter = parameters.get(0);
String firstParameterType = firstParameter.asType().toString();
if (!firstParameterType.equals(CanonicalNameConstants.SQLITE_DATABASE)) {
valid.invalidate();
annotationHelper.printAnnotationError(executableElement, "the first parameter must be a " + CanonicalNameConstants.SQLITE_DATABASE + ", not a " + firstParameterType);
}
}
}
public void isDeclaredType(Element element, IsValid valid, TypeMirror uiFieldTypeMirror) {
if (!(uiFieldTypeMirror instanceof DeclaredType)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s can only be used on a field which is a declared type");
}
}
public boolean isPrefMethod(Element element) {
if (!element.getKind().equals(ElementKind.METHOD)) {
annotationHelper.printError(element, "Only methods are allowed in an " + annotationHelper.annotationName() + " annotated interface");
} else {
ExecutableElement executableElement = (ExecutableElement) element;
String methodName = executableElement.getSimpleName().toString();
if (executableElement.getParameters().size() > 0) {
annotationHelper.printError(element, "Method " + methodName + " should have no parameters in an " + annotationHelper.annotationName() + " annotated interface");
} else {
String returnType = executableElement.getReturnType().toString();
if (!VALID_PREF_RETURN_TYPES.contains(returnType)) {
annotationHelper.printError(element, "Method " + methodName + " should only return preference simple types in an " + annotationHelper.annotationName() + " annotated interface");
} else {
if (INVALID_PREF_METHOD_NAMES.contains(methodName)) {
annotationHelper.printError(element, "The method name " + methodName + " is forbidden in an " + annotationHelper.annotationName() + " annotated interface");
} else {
return true;
}
}
}
}
return false;
}
public void hasCorrectDefaultAnnotation(ExecutableElement method) {
checkDefaultAnnotation(method, DefaultBoolean.class, "boolean", new TypeKindAnnotationCondition(TypeKind.BOOLEAN));
checkDefaultAnnotation(method, DefaultFloat.class, "float", new TypeKindAnnotationCondition(TypeKind.FLOAT));
checkDefaultAnnotation(method, DefaultInt.class, "int", new TypeKindAnnotationCondition(TypeKind.INT));
checkDefaultAnnotation(method, DefaultLong.class, "long", new TypeKindAnnotationCondition(TypeKind.LONG));
checkDefaultAnnotation(method, DefaultString.class, "String", new DefaultAnnotationCondition() {
@Override
public boolean correctReturnType(TypeMirror returnType) {
return returnType.toString().equals(CanonicalNameConstants.STRING);
}
});
}
private interface DefaultAnnotationCondition {
boolean correctReturnType(TypeMirror returnType);
}
private class TypeKindAnnotationCondition implements DefaultAnnotationCondition {
private final TypeKind typeKind;
public TypeKindAnnotationCondition(TypeKind typeKind) {
this.typeKind = typeKind;
}
@Override
public boolean correctReturnType(TypeMirror returnType) {
return returnType.getKind() == typeKind;
}
}
private <T extends Annotation> void checkDefaultAnnotation(ExecutableElement method, Class<T> annotationClass, String expectedReturnType, DefaultAnnotationCondition condition) {
T defaultAnnotation = method.getAnnotation(annotationClass);
if (defaultAnnotation != null) {
if (!condition.correctReturnType(method.getReturnType())) {
annotationHelper.printAnnotationError(method, annotationClass.getName(), TargetAnnotationHelper.annotationName(annotationClass) + " can only be used on a method that returns a " + expectedReturnType);
}
}
}
@SuppressWarnings("unchecked")
private static final List<Class<? extends Annotation>> REST_ANNOTATION_CLASSES = Arrays.asList(Get.class, Head.class, Options.class, Post.class, Put.class, Delete.class);
public void unannotatedMethodReturnsRestTemplate(TypeElement typeElement, IsValid valid) {
List<? extends Element> enclosedElements = typeElement.getEnclosedElements();
boolean foundGetRestTemplateMethod = false;
boolean foundSetRestTemplateMethod = false;
boolean foundSetRootUrlMethod = false;
for (Element enclosedElement : enclosedElements) {
if (enclosedElement.getKind() != ElementKind.METHOD) {
valid.invalidate();
annotationHelper.printError(enclosedElement, "Only methods are allowed in a " + TargetAnnotationHelper.annotationName(Rest.class) + " annotated interface");
} else {
boolean hasRestAnnotation = false;
for (Class<? extends Annotation> annotationClass : REST_ANNOTATION_CLASSES) {
if (enclosedElement.getAnnotation(annotationClass) != null) {
hasRestAnnotation = true;
break;
}
}
if (!hasRestAnnotation) {
ExecutableElement executableElement = (ExecutableElement) enclosedElement;
TypeMirror returnType = executableElement.getReturnType();
if (returnType.toString().equals(CanonicalNameConstants.REST_TEMPLATE)) {
if (executableElement.getParameters().size() > 0) {
valid.invalidate();
annotationHelper.printError(enclosedElement, "The method returning a RestTemplate should not declare any parameter in a " + TargetAnnotationHelper.annotationName(Rest.class) + " annotated interface");
} else {
if (foundGetRestTemplateMethod) {
valid.invalidate();
annotationHelper.printError(enclosedElement, "Only one method should declare returning a RestTemplate in a " + TargetAnnotationHelper.annotationName(Rest.class) + " annotated interface");
} else {
foundGetRestTemplateMethod = true;
}
}
} else if (returnType.getKind() == TypeKind.VOID) {
List<? extends VariableElement> parameters = executableElement.getParameters();
if (parameters.size() == 1) {
VariableElement firstParameter = parameters.get(0);
if (firstParameter.asType().toString().equals(CanonicalNameConstants.REST_TEMPLATE)) {
if (!foundSetRestTemplateMethod) {
foundSetRestTemplateMethod = true;
} else {
valid.invalidate();
annotationHelper.printError(enclosedElement, "You can only have oneRestTemplate setter method on a " + TargetAnnotationHelper.annotationName(Rest.class) + " annotated interface");
}
} else if (executableElement.getSimpleName().toString().equals(METHOD_NAME_SET_ROOT_URL) && !foundSetRootUrlMethod) {
foundSetRootUrlMethod = true;
} else {
valid.invalidate();
annotationHelper.printError(enclosedElement, "The method to set a RestTemplate should have only one RestTemplate parameter on a " + TargetAnnotationHelper.annotationName(Rest.class) + " annotated interface");
}
} else {
valid.invalidate();
annotationHelper.printError(enclosedElement, "The method to set a RestTemplate should have only one RestTemplate parameter on a " + TargetAnnotationHelper.annotationName(Rest.class) + " annotated interface");
}
} else {
valid.invalidate();
annotationHelper.printError(enclosedElement, "All methods should be annotated in a " + TargetAnnotationHelper.annotationName(Rest.class) + " annotated interface, except the ones that returns or set a RestTemplate");
}
}
}
}
}
public void notAlreadyValidated(Element element, AnnotationElements validatedElements, IsValid valid) {
if (validatedElements.getAllElements().contains(element)) {
valid.invalidate();
annotationHelper.printAnnotationError(element, "%s annotated element cannot be used with the other annotations used on this element.");
}
}
public void hasEmptyOrContextConstructor(Element element, IsValid valid) {
List<ExecutableElement> constructors = ElementFilter.constructorsIn(element.getEnclosedElements());
if (constructors.size() == 1) {
ExecutableElement constructor = constructors.get(0);
if (!annotationHelper.isPrivate(constructor)) {
if (constructor.getParameters().size() > 1) {
annotationHelper.printAnnotationError(element, "%s annotated element should have a constructor with one parameter max, of type " + CanonicalNameConstants.CONTEXT);
valid.invalidate();
} else if (constructor.getParameters().size() == 1) {
VariableElement parameter = constructor.getParameters().get(0);
if (!parameter.asType().toString().equals(CanonicalNameConstants.CONTEXT)) {
annotationHelper.printAnnotationError(element, "%s annotated element should have a constructor with one parameter max, of type " + CanonicalNameConstants.CONTEXT);
valid.invalidate();
}
}
} else {
annotationHelper.printAnnotationError(element, "%s annotated element should not have a private constructor");
valid.invalidate();
}
} else {
annotationHelper.printAnnotationError(element, "%s annotated element should have only one constructor");
valid.invalidate();
}
}
public void hasEmptyConstructor(Element element, IsValid valid) {
List<ExecutableElement> constructors = ElementFilter.constructorsIn(element.getEnclosedElements());
if (constructors.size() == 1) {
ExecutableElement constructor = constructors.get(0);