/
AnnotationMetadataProvider.java
1498 lines (1324 loc) · 52.4 KB
/
AnnotationMetadataProvider.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
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2013, Red Hat, Inc. and/or its affiliates or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat, Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.search.engine.metadata.impl;
import static org.hibernate.search.engine.impl.AnnotationProcessingHelper.getFieldName;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Field;
import org.hibernate.search.annotations.ProvidedId;
import org.hibernate.search.bridge.builtin.impl.TwoWayString2FieldBridgeAdaptor;
import org.hibernate.search.engine.service.classloading.spi.ClassLoadingException;
import org.hibernate.search.exception.AssertionFailure;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XAnnotatedElement;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XMember;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.search.util.StringHelper;
import org.hibernate.search.SearchException;
import org.hibernate.search.analyzer.Discriminator;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.AnalyzerDef;
import org.hibernate.search.annotations.AnalyzerDefs;
import org.hibernate.search.annotations.AnalyzerDiscriminator;
import org.hibernate.search.annotations.Boost;
import org.hibernate.search.annotations.ClassBridge;
import org.hibernate.search.annotations.ClassBridges;
import org.hibernate.search.annotations.ContainedIn;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.hibernate.search.annotations.Latitude;
import org.hibernate.search.annotations.Longitude;
import org.hibernate.search.annotations.Norms;
import org.hibernate.search.annotations.NumericField;
import org.hibernate.search.annotations.NumericFields;
import org.hibernate.search.annotations.Spatial;
import org.hibernate.search.annotations.Spatials;
import org.hibernate.search.annotations.Store;
import org.hibernate.search.annotations.TermVector;
import org.hibernate.search.bridge.FieldBridge;
import org.hibernate.search.bridge.StringBridge;
import org.hibernate.search.bridge.TwoWayFieldBridge;
import org.hibernate.search.bridge.builtin.impl.DefaultStringBridge;
import org.hibernate.search.bridge.builtin.impl.NullEncodingFieldBridge;
import org.hibernate.search.bridge.builtin.impl.NullEncodingTwoWayFieldBridge;
import org.hibernate.search.bridge.impl.BridgeFactory;
import org.hibernate.search.engine.BoostStrategy;
import org.hibernate.search.engine.impl.AnnotationProcessingHelper;
import org.hibernate.search.engine.impl.DefaultBoostStrategy;
import org.hibernate.search.impl.ConfigContext;
import org.hibernate.search.spatial.Coordinates;
import org.hibernate.search.util.impl.ClassLoaderHelper;
import org.hibernate.search.util.impl.ReflectionHelper;
import org.hibernate.search.util.logging.impl.Log;
import org.hibernate.search.util.logging.impl.LoggerFactory;
/**
* A metadata provider which extracts the required information from annotations.
*
* @author Hardy Ferentschik
*/
public class AnnotationMetadataProvider implements MetadataProvider {
private static final Log log = LoggerFactory.make();
private static final StringBridge NULL_EMBEDDED_STRING_BRIDGE = DefaultStringBridge.INSTANCE;
private static final String UNKNOWN_MAPPED_BY_ROLE = "";
private static final String EMPTY_PREFIX = "";
private final ReflectionManager reflectionManager;
private final ConfigContext configContext;
private final BridgeFactory bridgeFactory;
public AnnotationMetadataProvider(ReflectionManager reflectionManager, ConfigContext configContext) {
this.reflectionManager = reflectionManager;
this.configContext = configContext;
this.bridgeFactory = new BridgeFactory( configContext.getServiceManager() );
}
@Override
public TypeMetadata getTypeMetadataFor(Class<?> clazz) {
XClass xClass = reflectionManager.toXClass( clazz );
TypeMetadata.Builder typeMetadataBuilder = new TypeMetadata.Builder( clazz, configContext )
.boost( getBoost( xClass ) )
.boostStrategy( AnnotationProcessingHelper.getDynamicBoost( xClass ) )
.analyzer( configContext.getDefaultAnalyzer() );
ParseContext parseContext = new ParseContext();
parseContext.processingClass( xClass );
parseContext.setCurrentClass( xClass );
initializeClass(
typeMetadataBuilder,
true,
EMPTY_PREFIX,
parseContext,
configContext,
false,
null
);
return typeMetadataBuilder.build();
}
@Override
public boolean containsSearchMetadata(Class<?> clazz) {
XClass xClass = reflectionManager.toXClass( clazz );
return ReflectionHelper.containsSearchAnnotations( xClass );
}
private void checkDocumentId(XProperty member,
TypeMetadata.Builder typeMetadataBuilder,
boolean isRoot,
String prefix,
ConfigContext configContext,
PathsContext pathsContext,
ParseContext parseContext) {
Annotation idAnnotation = getIdAnnotation( member, typeMetadataBuilder, configContext );
NumericField numericFieldAnn = member.getAnnotation( NumericField.class );
if ( idAnnotation != null ) {
String attributeName = getIdAttributeName( member, idAnnotation );
if ( pathsContext != null ) {
pathsContext.markEncounteredPath( prefix + attributeName );
}
if ( isRoot ) {
if ( parseContext.isExplicitDocumentId() ) {
if ( idAnnotation instanceof DocumentId ) {
throw log.duplicateDocumentIdFound( typeMetadataBuilder.getIndexedType().getName() );
}
else {
//If it's not a DocumentId it's a JPA @Id: ignore it as we already have a @DocumentId
return;
}
}
if ( idAnnotation instanceof DocumentId ) {
parseContext.setExplicitDocumentId( true );
}
FieldBridge idBridge = bridgeFactory.guessType( null, numericFieldAnn, member, reflectionManager, configContext.getServiceManager() );
if ( !( idBridge instanceof TwoWayFieldBridge ) ) {
throw new SearchException(
"Bridge for document id does not implement TwoWayFieldBridge: " + member.getName()
);
}
Field.TermVector termVector = AnnotationProcessingHelper.getTermVector( TermVector.NO );
DocumentFieldMetadata fieldMetadata =
new DocumentFieldMetadata.Builder(
prefix + attributeName,
Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS,
termVector
)
.id()
.boost( AnnotationProcessingHelper.getBoost( member, null ) )
.fieldBridge( idBridge )
.build();
PropertyMetadata idPropertyMetadata = new PropertyMetadata.Builder( member )
.addDocumentField( fieldMetadata )
.build();
typeMetadataBuilder.idProperty( idPropertyMetadata );
}
else {
//component should index their document id
String fieldName = prefix + attributeName;
Field.Index index = AnnotationProcessingHelper.getIndex( Index.YES, Analyze.NO, Norms.YES );
Field.TermVector termVector = AnnotationProcessingHelper.getTermVector( TermVector.NO );
FieldBridge fieldBridge = bridgeFactory.guessType( null, null, member, reflectionManager, configContext.getServiceManager() );
DocumentFieldMetadata fieldMetadata =
new DocumentFieldMetadata.Builder( fieldName, Store.YES, index, termVector )
.boost( AnnotationProcessingHelper.getBoost( member, null ) )
.fieldBridge( fieldBridge )
.idInEmbedded()
.build();
PropertyMetadata propertyMetadata = new PropertyMetadata.Builder( member )
.addDocumentField( fieldMetadata )
.dynamicBoostStrategy( AnnotationProcessingHelper.getDynamicBoost( member ) )
.build();
typeMetadataBuilder.addProperty( propertyMetadata );
// property > entity analyzer (no field analyzer)
Analyzer analyzer = AnnotationProcessingHelper.getAnalyzer(
member.getAnnotation( org.hibernate.search.annotations.Analyzer.class ),
configContext
);
if ( analyzer == null ) {
analyzer = typeMetadataBuilder.getAnalyzer();
}
if ( analyzer == null ) {
throw new AssertionFailure( "Analyzer should not be undefined" );
}
typeMetadataBuilder.addToScopedAnalyzer( fieldName, analyzer, index );
}
}
}
/**
* Checks whether the specified property contains an annotation used as document id.
* This can either be an explicit <code>@DocumentId</code> or if no <code>@DocumentId</code> is specified a
* JPA <code>@Id</code> annotation. The check for the JPA annotation is indirectly to avoid a hard dependency
* to Hibernate Annotations.
*
* @param member the property to check for the id annotation.
* @param context Handle to default configuration settings.
*
* @return the annotation used as document id or <code>null</code> if id annotation is specified on the property.
*/
private Annotation getIdAnnotation(XProperty member, TypeMetadata.Builder typeMetadataBuilder, ConfigContext context) {
Annotation idAnnotation = null;
// check for explicit DocumentId
DocumentId documentIdAnnotation = member.getAnnotation( DocumentId.class );
if ( documentIdAnnotation != null ) {
idAnnotation = documentIdAnnotation;
}
// check for JPA @Id
if ( context.isJpaPresent() ) {
Annotation jpaId;
try {
@SuppressWarnings("unchecked")
Class<? extends Annotation> jpaIdClass =
ClassLoaderHelper.classForName( "javax.persistence.Id", configContext.getServiceManager() );
jpaId = member.getAnnotation( jpaIdClass );
}
catch (ClassLoadingException e) {
throw new SearchException( "Unable to load @Id.class even though it should be present ?!" );
}
if ( jpaId != null ) {
typeMetadataBuilder.jpaProperty( member );
if ( documentIdAnnotation == null ) {
log.debug( "Found JPA id and using it as document id" );
idAnnotation = jpaId;
}
}
}
return idAnnotation;
}
private void initializeProvidedIdMetadata(ProvidedId providedId, XClass clazz, TypeMetadata.Builder typeMetadataBuilder) {
PropertyMetadata propertyMetadata;
FieldBridge providedIdFieldBridge;
String providedIdFieldName;
if ( providedId != null ) {
providedIdFieldBridge = bridgeFactory.extractTwoWayType( providedId.bridge(), clazz, reflectionManager );
providedIdFieldName = providedId.name();
}
else {
providedIdFieldBridge = new TwoWayString2FieldBridgeAdaptor( org.hibernate.search.bridge.builtin.StringBridge.INSTANCE );
providedIdFieldName = ProvidedId.defaultFieldName;
}
DocumentFieldMetadata fieldMetadata =
new DocumentFieldMetadata.Builder(
providedIdFieldName,
Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO
)
.fieldBridge( providedIdFieldBridge )
.boost( 1.0f )
.build();
propertyMetadata = new PropertyMetadata.Builder( null )
.addDocumentField( fieldMetadata )
.build();
typeMetadataBuilder.idProperty( propertyMetadata );
}
/**
* Determines the property name for the document id. It is either the name of the property itself or the
* value of the name attribute of the <code>idAnnotation</code>.
*
* @param member the property used as id property.
* @param idAnnotation the id annotation
*
* @return property name to be used as document id.
*/
private String getIdAttributeName(XProperty member, Annotation idAnnotation) {
String name = null;
try {
Method m = idAnnotation.getClass().getMethod( "name" );
name = (String) m.invoke( idAnnotation );
}
catch (Exception e) {
// ignore
}
return ReflectionHelper.getAttributeName( member, name );
}
private float getBoost(XClass element) {
float boost = 1.0f;
if ( element == null ) {
return boost;
}
Boost boostAnnotation = element.getAnnotation( Boost.class );
if ( boostAnnotation != null ) {
boost = boostAnnotation.value();
}
return boost;
}
private void initializeClass(TypeMetadata.Builder typeMetadataBuilder,
boolean isRoot,
String prefix,
ParseContext parseContext,
ConfigContext configContext,
boolean disableOptimizationsArg,
PathsContext pathsContext) {
List<XClass> hierarchy = ReflectionHelper.createXClassHierarchy( parseContext.getCurrentClass() );
// Iterate the class hierarchy top down. This allows to override the default analyzer for the properties if the class holds one
ProvidedId explicitProvidedIdAnnotation = null;
XClass providedIdHostingClass = null;
for ( XClass currentClass : hierarchy ) {
if ( currentClass.getAnnotation( ProvidedId.class ) != null ) {
explicitProvidedIdAnnotation = currentClass.getAnnotation( ProvidedId.class );
providedIdHostingClass = currentClass;
}
parseContext.setCurrentClass( currentClass );
initializeClassLevelAnnotations( typeMetadataBuilder, prefix, configContext, parseContext );
initializeClassBridgeInstances( typeMetadataBuilder, prefix, configContext, currentClass );
}
boolean isProvidedId = false;
if ( explicitProvidedIdAnnotation != null || configContext.isProvidedIdImplicit() ) {
initializeProvidedIdMetadata( explicitProvidedIdAnnotation, providedIdHostingClass, typeMetadataBuilder );
isProvidedId = true;
}
// if optimizations are enabled, we allow for state in indexed embedded objects which are not
// explicitly indexed to skip index update triggering.
// we don't allow this if the reference is reachable via a custom Field- or ClassBridge,
// as state changes from values out of our control could affect the index.
boolean disableOptimizations = disableOptimizationsArg
|| !stateInspectionOptimizationsEnabled( typeMetadataBuilder );
// iterate again for the properties and fields
for ( XClass currentClass : hierarchy ) {
parseContext.setCurrentClass( currentClass );
// rejecting non properties (ie regular methods) because the object is loaded from Hibernate,
// so indexing a non property does not make sense
List<XProperty> methods = currentClass.getDeclaredProperties( XClass.ACCESS_PROPERTY );
for ( XProperty method : methods ) {
initializeMemberLevelAnnotations(
prefix,
method,
typeMetadataBuilder,
disableOptimizations,
isRoot,
isProvidedId,
configContext,
pathsContext,
parseContext
);
}
List<XProperty> fields = currentClass.getDeclaredProperties( XClass.ACCESS_FIELD );
for ( XProperty field : fields ) {
initializeMemberLevelAnnotations(
prefix,
field,
typeMetadataBuilder,
disableOptimizations,
isRoot,
isProvidedId,
configContext,
pathsContext,
parseContext
);
}
// Indexed collection roles are collected in the parse context while traversing the hierarchy.
// We add all the collection roles of the parent classes and the current class to the current class
// so that we can work around the fact that for @MappedSuperClass the collection role is considered
// attached to the first @Entity sub class by ORM.
// While it is not quite right, it's the best solution we have found to fix HSEARCH-1583 as there is no
// reliable way to unqualify a collection role at the moment.
// This might change in ORM 5 and we might reconsider this decision then.
for ( String unqualifiedCollectionRole : parseContext.getCollectedUnqualifiedCollectionRoles() ) {
typeMetadataBuilder.addCollectionRole(
StringHelper.qualify(
parseContext.getCurrentClass().getName(), unqualifiedCollectionRole
)
);
}
}
}
/**
* Check and initialize class level annotations.
*
* @param typeMetadataBuilder The meta data holder.
* @param prefix The current prefix used for the <code>Document</code> field names.
* @param configContext Handle to default configuration settings.
*/
private void initializeClassLevelAnnotations(TypeMetadata.Builder typeMetadataBuilder,
String prefix,
ConfigContext configContext,
ParseContext parseContext) {
XClass clazz = parseContext.getCurrentClass();
// check for a class level specified analyzer
Analyzer analyzer = AnnotationProcessingHelper.getAnalyzer(
clazz.getAnnotation( org.hibernate.search.annotations.Analyzer.class ),
configContext
);
if ( analyzer != null ) {
typeMetadataBuilder.analyzer( analyzer );
}
// check for AnalyzerDefs annotations
checkForAnalyzerDefs( clazz, configContext );
// Check for any ClassBridges annotation.
ClassBridges classBridgesAnnotation = clazz.getAnnotation( ClassBridges.class );
if ( classBridgesAnnotation != null ) {
ClassBridge[] classBridges = classBridgesAnnotation.value();
for ( ClassBridge cb : classBridges ) {
bindClassBridgeAnnotation( prefix, typeMetadataBuilder, cb, clazz, configContext );
}
}
// Check for any ClassBridge style of annotations.
ClassBridge classBridgeAnnotation = clazz.getAnnotation( ClassBridge.class );
if ( classBridgeAnnotation != null ) {
bindClassBridgeAnnotation( prefix, typeMetadataBuilder, classBridgeAnnotation, clazz, configContext );
}
//Check for Spatial annotation on class level
Spatial spatialAnnotation = clazz.getAnnotation( Spatial.class );
if ( spatialAnnotation != null ) {
bindSpatialAnnotation( spatialAnnotation, prefix, typeMetadataBuilder, parseContext );
}
Spatials spatialsAnnotation = clazz.getAnnotation( Spatials.class );
if ( spatialsAnnotation != null ) {
Spatial[] spatials = spatialsAnnotation.value();
for ( Spatial innerSpatialAnnotation : spatials ) {
bindSpatialAnnotation( innerSpatialAnnotation, prefix, typeMetadataBuilder, parseContext );
}
}
checkForAnalyzerDiscriminator( clazz, typeMetadataBuilder, configContext );
}
/**
* Initializes metadata contributed by class bridge instances set up through the programmatic config API.
*/
private void initializeClassBridgeInstances(TypeMetadata.Builder typeMetadataBuilder,
String prefix,
ConfigContext configContext,
XClass clazz) {
Map<FieldBridge, ClassBridge> classBridgeInstances = configContext.getClassBridgeInstances( reflectionManager.toClass( clazz ) );
for ( Entry<FieldBridge, ClassBridge> classBridge : classBridgeInstances.entrySet() ) {
FieldBridge instance = classBridge.getKey();
ClassBridge configuration = classBridge.getValue();
bindClassBridgeAnnotation( prefix, typeMetadataBuilder, configuration, instance, configContext );
}
}
private void bindClassBridgeAnnotation(String prefix,
TypeMetadata.Builder typeMetadataBuilder,
ClassBridge classBridgeAnnotation,
XClass clazz,
ConfigContext configContext) {
FieldBridge fieldBridge = bridgeFactory.extractType( classBridgeAnnotation, reflectionManager.toClass( clazz ) );
bindClassBridgeAnnotation( prefix, typeMetadataBuilder, classBridgeAnnotation, fieldBridge, configContext );
}
private void bindClassBridgeAnnotation(String prefix,
TypeMetadata.Builder typeMetadataBuilder,
ClassBridge classBridgeAnnotation,
FieldBridge fieldBridge,
ConfigContext configContext) {
bridgeFactory.injectParameters( classBridgeAnnotation, fieldBridge );
String fieldName = prefix + classBridgeAnnotation.name();
Store store = classBridgeAnnotation.store();
Field.Index index = AnnotationProcessingHelper.getIndex(
classBridgeAnnotation.index(),
classBridgeAnnotation.analyze(),
classBridgeAnnotation.norms()
);
Field.TermVector termVector = AnnotationProcessingHelper.getTermVector( classBridgeAnnotation.termVector() );
DocumentFieldMetadata fieldMetadata = new DocumentFieldMetadata.Builder( fieldName, store, index, termVector )
.boost( classBridgeAnnotation.boost().value() )
.fieldBridge( fieldBridge )
.build();
typeMetadataBuilder.addClassBridgeField( fieldMetadata );
Analyzer analyzer = AnnotationProcessingHelper.getAnalyzer( classBridgeAnnotation.analyzer(), configContext );
typeMetadataBuilder.addToScopedAnalyzer( fieldName, analyzer, index );
}
private void bindSpatialAnnotation(Spatial spatialAnnotation,
String prefix,
XProperty member,
TypeMetadata.Builder typeMetadataBuilder,
ParseContext parseContext) {
if ( parseContext.isSpatialNameUsed( spatialAnnotation.name() ) ) {
throw log.cannotHaveTwoSpatialsWithDefaultOrSameName( member.getType().getName() );
}
parseContext.markSpatialNameAsUsed( spatialAnnotation.name() );
String fieldName = prefix + ReflectionHelper.getAttributeName( member, spatialAnnotation.name() );
Store store = spatialAnnotation.store();
Field.Index index = AnnotationProcessingHelper.getIndex( Index.YES, Analyze.NO, Norms.NO );
Field.TermVector termVector = Field.TermVector.NO;
FieldBridge fieldBridge = bridgeFactory.guessType(
null,
null,
member,
reflectionManager,
configContext.getServiceManager()
);
DocumentFieldMetadata fieldMetadata = new DocumentFieldMetadata.Builder( fieldName, store, index, termVector )
.boost( AnnotationProcessingHelper.getBoost( member, spatialAnnotation ) )
.fieldBridge( fieldBridge )
.build();
PropertyMetadata propertyMetadata = new PropertyMetadata.Builder( member )
.addDocumentField( fieldMetadata )
.build();
typeMetadataBuilder.addProperty( propertyMetadata );
if ( member.isCollection() ) {
parseContext.collectUnqualifiedCollectionRole( member.getName() );
}
}
private void bindSpatialAnnotation(Spatial spatialAnnotation,
String prefix,
TypeMetadata.Builder typeMetadataBuilder,
ParseContext parseContext) {
String fieldName;
if ( !spatialAnnotation.name().isEmpty() ) {
fieldName = prefix + spatialAnnotation.name();
}
else {
fieldName = Spatial.COORDINATES_DEFAULT_FIELD;
}
if ( parseContext.isSpatialNameUsed( spatialAnnotation.name() ) ) {
throw log.cannotHaveTwoSpatialsWithDefaultOrSameName( parseContext.getCurrentClass().getName() );
}
parseContext.markSpatialNameAsUsed( spatialAnnotation.name() );
Store store = spatialAnnotation.store();
Field.Index index = AnnotationProcessingHelper.getIndex( Index.YES, Analyze.NO, Norms.NO );
Field.TermVector termVector = AnnotationProcessingHelper.getTermVector( TermVector.NO );
FieldBridge spatialBridge = determineSpatialFieldBridge( spatialAnnotation, parseContext );
DocumentFieldMetadata fieldMetadata = new DocumentFieldMetadata.Builder( fieldName, store, index, termVector )
.boost( spatialAnnotation.boost().value() )
.fieldBridge( spatialBridge )
.build();
typeMetadataBuilder.addClassBridgeField( fieldMetadata );
Analyzer analyzer = typeMetadataBuilder.getAnalyzer();
if ( analyzer == null ) {
throw new AssertionFailure( "Analyzer should not be undefined" );
}
}
private FieldBridge determineSpatialFieldBridge(Spatial spatialAnnotation, ParseContext parseContext) {
final FieldBridge spatialBridge;
XClass clazz = parseContext.getCurrentClass();
if ( reflectionManager.toXClass( Coordinates.class ).isAssignableFrom( clazz ) ) {
spatialBridge = bridgeFactory.buildSpatialBridge( spatialAnnotation, clazz, null, null );
}
else {
String latitudeField = null;
String longitudeField = null;
List<XProperty> fieldList = clazz.getDeclaredProperties( XClass.ACCESS_FIELD );
for ( XProperty property : fieldList ) {
if ( property.isAnnotationPresent( Latitude.class ) && ( property.getAnnotation( Latitude.class ) ).of()
.equals( spatialAnnotation.name() ) ) {
if ( latitudeField != null ) {
throw log.ambiguousLatitudeDefinition( clazz.getName(), latitudeField, property.getName() );
}
latitudeField = property.getName();
}
if ( property.isAnnotationPresent( Longitude.class ) && ( property.getAnnotation( Longitude.class ) ).of()
.equals( spatialAnnotation.name() ) ) {
if ( longitudeField != null ) {
throw log.ambiguousLongitudeDefinition(
clazz.getName(),
longitudeField,
property.getName()
);
}
longitudeField = property.getName();
}
}
List<XProperty> propertyList = clazz.getDeclaredProperties( XClass.ACCESS_PROPERTY );
for ( XProperty property : propertyList ) {
if ( property.isAnnotationPresent( Latitude.class ) && ( property.getAnnotation( Latitude.class ) ).of()
.equals( spatialAnnotation.name() ) ) {
if ( latitudeField != null ) {
throw log.ambiguousLatitudeDefinition( clazz.getName(), latitudeField, property.getName() );
}
latitudeField = property.getName();
}
if ( property.isAnnotationPresent( Longitude.class ) && ( property.getAnnotation( Longitude.class ) ).of()
.equals( spatialAnnotation.name() ) ) {
if ( longitudeField != null ) {
throw log.ambiguousLongitudeDefinition(
clazz.getName(),
longitudeField,
property.getName()
);
}
longitudeField = property.getName();
}
}
if ( latitudeField != null && longitudeField != null ) {
spatialBridge = bridgeFactory.buildSpatialBridge(
spatialAnnotation,
clazz,
latitudeField,
longitudeField
);
}
else {
spatialBridge = null;
}
}
if ( spatialBridge == null ) {
throw log.cannotFindCoordinatesNorLatLongForSpatial(
spatialAnnotation.name()
.isEmpty() ? "default" : spatialAnnotation.name(), clazz.getName()
);
}
return spatialBridge;
}
private void initializeMemberLevelAnnotations(String prefix,
XProperty member,
TypeMetadata.Builder typeMetadataBuilder,
boolean disableOptimizations,
boolean isRoot,
boolean isProvidedId,
ConfigContext configContext,
PathsContext pathsContext,
ParseContext parseContext) {
if ( !isProvidedId ) {
checkDocumentId( member, typeMetadataBuilder, isRoot, prefix, configContext, pathsContext, parseContext );
}
checkForField( member, typeMetadataBuilder, prefix, configContext, pathsContext, parseContext );
checkForFields( member, typeMetadataBuilder, prefix, configContext, pathsContext, parseContext );
checkForSpatial( member, typeMetadataBuilder, prefix, pathsContext, parseContext );
checkForSpatialsAnnotation( member, typeMetadataBuilder, prefix, pathsContext, parseContext );
checkForAnalyzerDefs( member, configContext );
checkForAnalyzerDiscriminator( member, typeMetadataBuilder, configContext );
checkForIndexedEmbedded(
member,
prefix,
disableOptimizations,
typeMetadataBuilder,
configContext,
pathsContext,
parseContext
);
checkForContainedIn( member, typeMetadataBuilder, parseContext );
}
private void checkForContainedIn(XProperty member, TypeMetadata.Builder typeMetadataBuilder, ParseContext parseContext) {
ContainedIn containedInAnnotation = member.getAnnotation( ContainedIn.class );
if ( containedInAnnotation == null ) {
return;
}
updateContainedInMaxDepths( member, typeMetadataBuilder );
parseContext.collectUnqualifiedCollectionRole( member.getName() );
}
private void updateContainedInMaxDepths(XProperty member, TypeMetadata.Builder typeMetadataBuilder) {
updateContainedInMaxDepth( member, typeMetadataBuilder, XClass.ACCESS_FIELD );
updateContainedInMaxDepth( member, typeMetadataBuilder, XClass.ACCESS_PROPERTY );
}
private void updateContainedInMaxDepth(XMember memberWithContainedIn, TypeMetadata.Builder typeMetadataBuilder, String accessType) {
XClass memberReturnedType = memberWithContainedIn.getElementClass();
String mappedBy = mappedBy( memberWithContainedIn );
List<XProperty> returnedTypeProperties = memberReturnedType.getDeclaredProperties( accessType );
for ( XProperty property : returnedTypeProperties ) {
if ( isCorrespondingIndexedEmbedded( mappedBy, property ) ) {
updateDepthProperties( memberWithContainedIn, typeMetadataBuilder, property );
break;
}
}
}
private boolean isCorrespondingIndexedEmbedded(String mappedBy, XProperty property) {
if ( !property.isAnnotationPresent( IndexedEmbedded.class ) ) {
return false;
}
if ( mappedBy.isEmpty() ) {
return true;
}
if ( mappedBy.equals( property.getName() ) ) {
return true;
}
return false;
}
private void updateDepthProperties(XMember memberWithContainedIn,
TypeMetadata.Builder typeMetadataBuilder,
XProperty property) {
int depth = property.getAnnotation( IndexedEmbedded.class ).depth();
typeMetadataBuilder.addContainedIn( new ContainedInMetadata( memberWithContainedIn, depth ) );
}
private String mappedBy(XMember member) {
Annotation[] annotations = member.getAnnotations();
for ( Annotation annotation : annotations ) {
String mappedBy = mappedBy( annotation );
if ( StringHelper.isNotEmpty( mappedBy ) ) {
return mappedBy;
}
}
return UNKNOWN_MAPPED_BY_ROLE;
}
private String mappedBy(Annotation annotation) {
try {
Method declaredMethod = annotation.annotationType().getDeclaredMethod( "mappedBy" );
return (String) declaredMethod.invoke( annotation );
}
catch (SecurityException e) {
return UNKNOWN_MAPPED_BY_ROLE;
}
catch (NoSuchMethodException e) {
return UNKNOWN_MAPPED_BY_ROLE;
}
catch (IllegalArgumentException e) {
return UNKNOWN_MAPPED_BY_ROLE;
}
catch (IllegalAccessException e) {
return UNKNOWN_MAPPED_BY_ROLE;
}
catch (InvocationTargetException e) {
return UNKNOWN_MAPPED_BY_ROLE;
}
}
private void checkForField(XProperty member,
TypeMetadata.Builder typeMetadataBuilder,
String prefix,
ConfigContext configContext,
PathsContext pathsContext,
ParseContext parseContext) {
org.hibernate.search.annotations.Field fieldAnnotation =
member.getAnnotation( org.hibernate.search.annotations.Field.class );
NumericField numericFieldAnnotation = member.getAnnotation( NumericField.class );
DocumentId idAnn = member.getAnnotation( DocumentId.class );
if ( fieldAnnotation != null ) {
if ( isFieldInPath( fieldAnnotation, member, pathsContext, prefix ) || !parseContext.isMaxLevelReached() ) {
PropertyMetadata.Builder propertyMetadataBuilder = new PropertyMetadata.Builder( member )
.dynamicBoostStrategy( AnnotationProcessingHelper.getDynamicBoost( member ) );
bindFieldAnnotation(
prefix,
fieldAnnotation,
numericFieldAnnotation,
typeMetadataBuilder,
propertyMetadataBuilder,
configContext,
parseContext
);
typeMetadataBuilder.addProperty( propertyMetadataBuilder.build() );
}
}
if ( ( fieldAnnotation == null && idAnn == null ) && numericFieldAnnotation != null ) {
throw new SearchException( "@NumericField without a @Field on property '" + member.getName() + "'" );
}
}
private void bindFieldAnnotation(
String prefix,
org.hibernate.search.annotations.Field fieldAnnotation,
NumericField numericFieldAnnotation,
TypeMetadata.Builder typeMetadataBuilder,
PropertyMetadata.Builder propertyMetadataBuilder,
ConfigContext configContext,
ParseContext parseContext) {
XProperty member = propertyMetadataBuilder.getPropertyAccessor();
if ( isPropertyTransient( member, configContext ) ) {
//If the indexed values are derived from a Transient field, we can't rely on dirtyness of properties.
//Only applies on JPA mapped entities.
typeMetadataBuilder.disableStateInspectionOptimization();
}
String fieldName = prefix + ReflectionHelper.getAttributeName( member, fieldAnnotation.name() );
Store store = fieldAnnotation.store();
Field.Index index = AnnotationProcessingHelper.getIndex(
fieldAnnotation.index(),
fieldAnnotation.analyze(),
fieldAnnotation.norms()
);
Field.TermVector termVector = AnnotationProcessingHelper.getTermVector( fieldAnnotation.termVector() );
FieldBridge fieldBridge = bridgeFactory.guessType(
fieldAnnotation,
numericFieldAnnotation,
member,
reflectionManager,
configContext.getServiceManager()
);
String nullToken = determineNullToken( fieldAnnotation, configContext );
if ( nullToken != null && fieldBridge instanceof TwoWayFieldBridge ) {
fieldBridge = new NullEncodingTwoWayFieldBridge( (TwoWayFieldBridge) fieldBridge, nullToken );
}
Analyzer analyzer = determineAnalyzer( fieldAnnotation, member, configContext );
// adjust the type analyzer
analyzer = typeMetadataBuilder.addToScopedAnalyzer(
fieldName,
analyzer,
index
);
DocumentFieldMetadata.Builder fieldMetadataBuilder = new DocumentFieldMetadata.Builder(
fieldName,
store,
index,
termVector
)
.boost( AnnotationProcessingHelper.getBoost( member, fieldAnnotation ) )
.fieldBridge( fieldBridge )
.analyzer( analyzer )
.indexNullAs( nullToken );
if ( numericFieldAnnotation != null ) {
fieldMetadataBuilder.numeric()
.precisionStep( AnnotationProcessingHelper.getPrecisionStep( numericFieldAnnotation ) );
}
DocumentFieldMetadata fieldMetadata = fieldMetadataBuilder.build();
propertyMetadataBuilder.addDocumentField( fieldMetadata );
// keep track of collection role names for ORM integration optimization based on collection update events
parseContext.collectUnqualifiedCollectionRole( member.getName() );
}
private String determineNullToken(org.hibernate.search.annotations.Field fieldAnnotation, ConfigContext context) {
if ( fieldAnnotation == null ) {
return null;
}
String indexNullAs = fieldAnnotation.indexNullAs();
if ( indexNullAs.equals( org.hibernate.search.annotations.Field.DO_NOT_INDEX_NULL ) ) {
indexNullAs = null;
}
else if ( indexNullAs.equals( org.hibernate.search.annotations.Field.DEFAULT_NULL_TOKEN ) ) {
indexNullAs = context.getDefaultNullToken();
}
return indexNullAs;
}
private Analyzer determineAnalyzer(org.hibernate.search.annotations.Field fieldAnnotation,
XProperty member,
ConfigContext context) {
Analyzer analyzer = null;
// check for a nested @Analyzer annotation with @Field
if ( fieldAnnotation != null ) {
analyzer = AnnotationProcessingHelper.getAnalyzer( fieldAnnotation.analyzer(), context );
}
// if there was no analyzer specified as part of @Field, try a stand alone @Analyzer annotation
if ( analyzer == null ) {
analyzer = AnnotationProcessingHelper.getAnalyzer(
member.getAnnotation( org.hibernate.search.annotations.Analyzer.class ),
context
);
}
return analyzer;
}
private boolean isPropertyTransient(XProperty member, ConfigContext context) {
if ( !context.isJpaPresent() ) {
return false;
}
else {
Annotation transientAnnotation;
try {
@SuppressWarnings("unchecked")
Class<? extends Annotation> transientAnnotationClass =
ClassLoaderHelper.classForName(
"javax.persistence.Transient",
configContext.getServiceManager()
);
transientAnnotation = member.getAnnotation( transientAnnotationClass );
}
catch (ClassLoadingException e) {
throw new SearchException( "Unable to load @Transient.class even though it should be present ?!" );
}
return transientAnnotation != null;
}
}
private void checkForSpatialsAnnotation(XProperty member,
TypeMetadata.Builder typeMetadataBuilder,
String prefix,
PathsContext pathsContext,
ParseContext parseContext) {
org.hibernate.search.annotations.Spatials spatialsAnnotation = member.getAnnotation( org.hibernate.search.annotations.Spatials.class );
if ( spatialsAnnotation != null ) {
for ( org.hibernate.search.annotations.Spatial spatialAnnotation : spatialsAnnotation.value() ) {
if ( isFieldInPath(
spatialAnnotation,
member,
pathsContext,
prefix
) || !parseContext.isMaxLevelReached() ) {
bindSpatialAnnotation(
spatialAnnotation,
prefix,
member,
typeMetadataBuilder,
parseContext
);
}
}
}
}
private void checkForSpatial(XProperty member,
TypeMetadata.Builder typeMetadataBuilder,
String prefix,
PathsContext pathsContext,
ParseContext parseContext) {
Spatial spatialAnnotation = member.getAnnotation( Spatial.class );
if ( spatialAnnotation != null ) {
if ( isFieldInPath(
spatialAnnotation,
member,
pathsContext,
prefix
) || !parseContext.isMaxLevelReached() ) {
bindSpatialAnnotation( spatialAnnotation, prefix, member, typeMetadataBuilder, parseContext );
}
}