This repository has been archived by the owner on Jan 5, 2022. It is now read-only.
/
EntityManagerImpl.java
2884 lines (2252 loc) · 111 KB
/
EntityManagerImpl.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.usergrid.persistence.cassandra;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;
import org.apache.usergrid.locking.Lock;
import org.apache.usergrid.mq.Message;
import org.apache.usergrid.mq.QueueManager;
import org.apache.usergrid.mq.cassandra.QueueManagerFactoryImpl;
import org.apache.usergrid.persistence.AggregateCounter;
import org.apache.usergrid.persistence.AggregateCounterSet;
import org.apache.usergrid.persistence.CollectionRef;
import org.apache.usergrid.persistence.ConnectedEntityRef;
import org.apache.usergrid.persistence.ConnectionRef;
import org.apache.usergrid.persistence.CounterResolution;
import org.apache.usergrid.persistence.DynamicEntity;
import org.apache.usergrid.persistence.Entity;
import org.apache.usergrid.persistence.EntityFactory;
import org.apache.usergrid.persistence.EntityManager;
import org.apache.usergrid.persistence.EntityRef;
import org.apache.usergrid.persistence.Identifier;
import org.apache.usergrid.persistence.IndexBucketLocator;
import org.apache.usergrid.persistence.Query;
import org.apache.usergrid.persistence.Query.CounterFilterPredicate;
import org.apache.usergrid.persistence.Results;
import org.apache.usergrid.persistence.Results.Level;
import org.apache.usergrid.persistence.RoleRef;
import org.apache.usergrid.persistence.Schema;
import org.apache.usergrid.persistence.SimpleCollectionRef;
import org.apache.usergrid.persistence.SimpleEntityRef;
import org.apache.usergrid.persistence.SimpleRoleRef;
import org.apache.usergrid.persistence.TypedEntity;
import org.apache.usergrid.persistence.cassandra.CounterUtils.AggregateCounterSelection;
import org.apache.usergrid.persistence.cassandra.util.TraceParticipant;
import org.apache.usergrid.persistence.entities.Application;
import org.apache.usergrid.persistence.entities.Event;
import org.apache.usergrid.persistence.entities.Group;
import org.apache.usergrid.persistence.entities.Role;
import org.apache.usergrid.persistence.entities.User;
import org.apache.usergrid.persistence.exceptions.DuplicateUniquePropertyExistsException;
import org.apache.usergrid.persistence.exceptions.EntityNotFoundException;
import org.apache.usergrid.persistence.exceptions.RequiredPropertyNotFoundException;
import org.apache.usergrid.persistence.exceptions.UnexpectedEntityTypeException;
import org.apache.usergrid.persistence.hector.CountingMutator;
import org.apache.usergrid.persistence.schema.CollectionInfo;
import org.apache.usergrid.utils.ClassUtils;
import org.apache.usergrid.utils.CompositeUtils;
import org.apache.usergrid.utils.UUIDUtils;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.yammer.metrics.annotation.Metered;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.ColumnSlice;
import me.prettyprint.hector.api.beans.CounterRow;
import me.prettyprint.hector.api.beans.CounterRows;
import me.prettyprint.hector.api.beans.CounterSlice;
import me.prettyprint.hector.api.beans.DynamicComposite;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.beans.HCounterColumn;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.beans.Rows;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.MultigetSliceCounterQuery;
import me.prettyprint.hector.api.query.QueryResult;
import me.prettyprint.hector.api.query.SliceCounterQuery;
import static java.lang.String.CASE_INSENSITIVE_ORDER;
import static java.util.Arrays.asList;
import static me.prettyprint.hector.api.factory.HFactory.createCounterSliceQuery;
import static org.apache.commons.lang.StringUtils.capitalize;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.usergrid.locking.LockHelper.getUniqueUpdateLock;
import static org.apache.usergrid.persistence.Results.Level.REFS;
import static org.apache.usergrid.persistence.Results.fromEntities;
import static org.apache.usergrid.persistence.Schema.COLLECTION_ROLES;
import static org.apache.usergrid.persistence.Schema.COLLECTION_USERS;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_COLLECTIONS;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_PERMISSIONS;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_PROPERTIES;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_ROLENAMES;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_ROLETIMES;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_SETS;
import static org.apache.usergrid.persistence.Schema.PROPERTY_ASSOCIATED;
import static org.apache.usergrid.persistence.Schema.PROPERTY_CREATED;
import static org.apache.usergrid.persistence.Schema.PROPERTY_INACTIVITY;
import static org.apache.usergrid.persistence.Schema.PROPERTY_MODIFIED;
import static org.apache.usergrid.persistence.Schema.PROPERTY_NAME;
import static org.apache.usergrid.persistence.Schema.PROPERTY_TIMESTAMP;
import static org.apache.usergrid.persistence.Schema.PROPERTY_TYPE;
import static org.apache.usergrid.persistence.Schema.PROPERTY_UUID;
import static org.apache.usergrid.persistence.Schema.TYPE_APPLICATION;
import static org.apache.usergrid.persistence.Schema.TYPE_CONNECTION;
import static org.apache.usergrid.persistence.Schema.TYPE_ENTITY;
import static org.apache.usergrid.persistence.Schema.TYPE_MEMBER;
import static org.apache.usergrid.persistence.Schema.TYPE_ROLE;
import static org.apache.usergrid.persistence.Schema.defaultCollectionName;
import static org.apache.usergrid.persistence.Schema.deserializeEntityProperties;
import static org.apache.usergrid.persistence.Schema.getDefaultSchema;
import static org.apache.usergrid.persistence.SimpleEntityRef.getUuid;
import static org.apache.usergrid.persistence.SimpleEntityRef.ref;
import static org.apache.usergrid.persistence.SimpleRoleRef.getIdForGroupIdAndRoleName;
import static org.apache.usergrid.persistence.SimpleRoleRef.getIdForRoleName;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.APPLICATION_AGGREGATE_COUNTERS;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_COMPOSITE_DICTIONARIES;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_COUNTERS;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_DICTIONARIES;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_ID_SETS;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_PROPERTIES;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_UNIQUE;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.addDeleteToMutator;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.addInsertToMutator;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.addPropertyToMutator;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.batchExecute;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.key;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.toStorableBinaryValue;
import static org.apache.usergrid.persistence.cassandra.CassandraService.ALL_COUNT;
import static org.apache.usergrid.persistence.cassandra.Serializers.be;
import static org.apache.usergrid.persistence.cassandra.Serializers.le;
import static org.apache.usergrid.persistence.cassandra.Serializers.se;
import static org.apache.usergrid.persistence.cassandra.Serializers.ue;
import static org.apache.usergrid.utils.ClassUtils.cast;
import static org.apache.usergrid.utils.ConversionUtils.bytebuffer;
import static org.apache.usergrid.utils.ConversionUtils.getLong;
import static org.apache.usergrid.utils.ConversionUtils.object;
import static org.apache.usergrid.utils.ConversionUtils.string;
import static org.apache.usergrid.utils.ConversionUtils.uuid;
import static org.apache.usergrid.utils.InflectionUtils.singularize;
import static org.apache.usergrid.utils.UUIDUtils.getTimestampInMicros;
import static org.apache.usergrid.utils.UUIDUtils.getTimestampInMillis;
import static org.apache.usergrid.utils.UUIDUtils.isTimeBased;
import static org.apache.usergrid.utils.UUIDUtils.newTimeUUID;
/**
* Cassandra-specific implementation of Datastore
*
* @author edanuff
* @author tnine
*/
public class EntityManagerImpl implements EntityManager {
/** The log4j logger. */
private static final Logger logger = LoggerFactory.getLogger( EntityManagerImpl.class );
public static final String APPLICATION_COLLECTION = "application.collection.";
public static final String APPLICATION_ENTITIES = "application.entities";
public static final long ONE_COUNT = 1L;
@Resource
private EntityManagerFactoryImpl emf;
@Resource
private QueueManagerFactoryImpl qmf;
@Resource
private IndexBucketLocator indexBucketLocator;
@Resource
private QueryExecutorService queryExecutorService;
private UUID applicationId;
private Application application;
@Resource
private CassandraService cass;
@Resource
private CounterUtils counterUtils;
private boolean skipAggregateCounters;
public EntityManagerImpl() {
}
public EntityManagerImpl init( EntityManagerFactoryImpl emf, CassandraService cass, CounterUtils counterUtils,
UUID applicationId, boolean skipAggregateCounters ) {
this.emf = emf;
this.cass = cass;
this.counterUtils = counterUtils;
this.applicationId = applicationId;
this.skipAggregateCounters = skipAggregateCounters;
qmf = ( QueueManagerFactoryImpl ) getApplicationContext().getBean( "queueManagerFactory" );
indexBucketLocator = ( IndexBucketLocator ) getApplicationContext().getBean( "indexBucketLocator" );
// prime the application entity for the EM
try {
getApplication();
}
catch ( Exception ex ) {
ex.printStackTrace();
}
return this;
}
public void setApplicationId( UUID applicationId ) {
this.applicationId = applicationId;
}
public ApplicationContext getApplicationContext() {
return emf.applicationContext;
}
@Override
public EntityRef getApplicationRef() {
return ref( TYPE_APPLICATION, applicationId );
}
@Override
public Application getApplication() throws Exception {
if ( application == null ) {
application = get( applicationId, Application.class );
}
return application;
}
@Override
public void updateApplication( Application app ) throws Exception {
update( app );
this.application = app;
}
@Override
public void updateApplication( Map<String, Object> properties ) throws Exception {
this.updateProperties( applicationId, properties );
this.application = get( applicationId, Application.class );
}
@Override
public RelationManagerImpl getRelationManager( EntityRef entityRef ) {
//RelationManagerImpl rmi = applicationContext.getBean(RelationManagerImpl.class);
RelationManagerImpl rmi = new RelationManagerImpl();
rmi.init( this, cass, queryExecutorService, applicationId, entityRef, indexBucketLocator );
return rmi;
}
/**
* Batch dictionary property.
*
* @param batch The batch to set the property into
* @param entity The entity that owns the property
* @param propertyName the property name
* @param propertyValue the property value
* @param timestampUuid The update timestamp as a uuid
*
* @return batch
*
* @throws Exception the exception
*/
public Mutator<ByteBuffer> batchSetProperty( Mutator<ByteBuffer> batch, EntityRef entity, String propertyName,
Object propertyValue, UUID timestampUuid ) throws Exception {
return this.batchSetProperty( batch, entity, propertyName, propertyValue, false, false, timestampUuid );
}
public Mutator<ByteBuffer> batchSetProperty( Mutator<ByteBuffer> batch, EntityRef entity, String propertyName,
Object propertyValue, boolean force, boolean noRead,
UUID timestampUuid ) throws Exception {
long timestamp = getTimestampInMicros( timestampUuid );
// propertyName = propertyName.toLowerCase();
boolean entitySchemaHasProperty = getDefaultSchema().hasProperty( entity.getType(), propertyName );
propertyValue = getDefaultSchema().validateEntityPropertyValue( entity.getType(), propertyName, propertyValue );
Schema defaultSchema = Schema.getDefaultSchema();
if ( PROPERTY_TYPE.equalsIgnoreCase( propertyName ) && ( propertyValue != null ) ) {
if ( "entity".equalsIgnoreCase( propertyValue.toString() ) || "dynamicentity"
.equalsIgnoreCase( propertyValue.toString() ) ) {
String errorMsg =
"Unable to dictionary entity type to " + propertyValue + " because that is not a valid type.";
logger.error( errorMsg );
throw new IllegalArgumentException( errorMsg );
}
}
if ( entitySchemaHasProperty ) {
if ( !force ) {
if ( !defaultSchema.isPropertyMutable( entity.getType(), propertyName ) ) {
return batch;
}
// Passing null for propertyValue indicates delete the property
// so if required property, exit
if ( ( propertyValue == null ) && defaultSchema.isRequiredProperty( entity.getType(), propertyName ) ) {
return batch;
}
}
/**
* Unique property, load the old value and remove it, check if it's not a duplicate
*/
if ( defaultSchema.getEntityInfo( entity.getType() ).isPropertyUnique( propertyName ) ) {
Lock lock = getUniqueUpdateLock( cass.getLockManager(), applicationId, propertyValue, entity.getType(),
propertyName );
try {
lock.lock();
if ( !isPropertyValueUniqueForEntity( entity.getUuid(), entity.getType(), propertyName,
propertyValue ) ) {
throw new DuplicateUniquePropertyExistsException( entity.getType(), propertyName,
propertyValue );
}
String collectionName = Schema.defaultCollectionName( entity.getType() );
uniquePropertyDelete( batch, collectionName, entity.getType(), propertyName, propertyValue,
entity.getUuid(), timestamp - 1 );
uniquePropertyWrite( batch, collectionName, propertyName, propertyValue, entity.getUuid(),
timestamp );
}
finally {
lock.unlock();
}
}
}
if ( getDefaultSchema().isPropertyIndexed( entity.getType(), propertyName ) ) {
//this call is incorrect. The current entity is NOT the head entity
getRelationManager( entity )
.batchUpdatePropertyIndexes( batch, propertyName, propertyValue, entitySchemaHasProperty, noRead,
timestampUuid );
}
if ( propertyValue != null ) {
// Set the new value
addPropertyToMutator( batch, key( entity.getUuid() ), entity.getType(), propertyName, propertyValue,
timestamp );
if ( !entitySchemaHasProperty ) {
// Make a list of all the properties ever dictionary on this
// entity
addInsertToMutator( batch, ENTITY_DICTIONARIES, key( entity.getUuid(), DICTIONARY_PROPERTIES ),
propertyName, null, timestamp );
}
}
else {
addDeleteToMutator( batch, ENTITY_PROPERTIES, key( entity.getUuid() ), propertyName, timestamp );
}
return batch;
}
/**
* Batch update properties.
*
* @param batch the batch
* @param entity The owning entity reference
* @param properties the properties to set
* @param timestampUuid the timestamp of the update operation as a time uuid
*
* @return batch
*
* @throws Exception the exception
*/
public Mutator<ByteBuffer> batchUpdateProperties( Mutator<ByteBuffer> batch, EntityRef entity,
Map<String, Object> properties, UUID timestampUuid )
throws Exception {
for ( String propertyName : properties.keySet() ) {
Object propertyValue = properties.get( propertyName );
batch = batchSetProperty( batch, entity, propertyName, propertyValue, timestampUuid );
}
return batch;
}
/**
* Batch update set.
*
* @param batch the batch
* @param entity The owning entity
* @param dictionaryName the dictionary name
* @param elementValue the dictionary value
* @param removeFromDictionary True to delete from the dictionary
* @param timestampUuid the timestamp
*
* @return batch
*
* @throws Exception the exception
*/
public Mutator<ByteBuffer> batchUpdateDictionary( Mutator<ByteBuffer> batch, EntityRef entity,
String dictionaryName, Object elementValue,
boolean removeFromDictionary, UUID timestampUuid )
throws Exception {
return batchUpdateDictionary( batch, entity, dictionaryName, elementValue, null, removeFromDictionary,
timestampUuid );
}
public Mutator<ByteBuffer> batchUpdateDictionary( Mutator<ByteBuffer> batch, EntityRef entity,
String dictionaryName, Object elementValue, Object elementCoValue,
boolean removeFromDictionary, UUID timestampUuid )
throws Exception {
long timestamp = getTimestampInMicros( timestampUuid );
// dictionaryName = dictionaryName.toLowerCase();
if ( elementCoValue == null ) {
elementCoValue = ByteBuffer.allocate( 0 );
}
boolean entityHasDictionary = getDefaultSchema().hasDictionary( entity.getType(), dictionaryName );
// Don't index dynamic dictionaries not defined by the schema
if ( entityHasDictionary ) {
getRelationManager( entity )
.batchUpdateSetIndexes( batch, dictionaryName, elementValue, removeFromDictionary, timestampUuid );
}
ApplicationCF dictionary_cf = entityHasDictionary ? ENTITY_DICTIONARIES : ENTITY_COMPOSITE_DICTIONARIES;
if ( elementValue != null ) {
if ( !removeFromDictionary ) {
// Set the new value
elementCoValue = toStorableBinaryValue( elementCoValue, !entityHasDictionary );
addInsertToMutator( batch, dictionary_cf, key( entity.getUuid(), dictionaryName ),
entityHasDictionary ? elementValue : asList( elementValue ), elementCoValue, timestamp );
if ( !entityHasDictionary ) {
addInsertToMutator( batch, ENTITY_DICTIONARIES, key( entity.getUuid(), DICTIONARY_SETS ),
dictionaryName, null, timestamp );
}
}
else {
addDeleteToMutator( batch, dictionary_cf, key( entity.getUuid(), dictionaryName ),
entityHasDictionary ? elementValue : asList( elementValue ), timestamp );
}
}
return batch;
}
/**
* Returns true if the property is unique, and the entity can be saved. If it's not unique, false is returned
*
* @return True if this entity can safely "own" this property name and value unique combination
*/
@Metered( group = "core", name = "EntityManager_isPropertyValueUniqueForEntity" )
public boolean isPropertyValueUniqueForEntity( UUID ownerEntityId, String entityType, String propertyName,
Object propertyValue ) throws Exception {
if ( !getDefaultSchema().isPropertyUnique( entityType, propertyName ) ) {
return true;
}
if ( propertyValue == null ) {
return true;
}
/**
* Doing this in a loop sucks, but we need to account for possibly having more than 1 entry in the index due
* to corruption. We need to allow them to update, otherwise
* both entities will be unable to update and must be deleted
*/
Set<UUID> ownerEntityIds = getUUIDsForUniqueProperty( applicationId, entityType, propertyName, propertyValue );
//if there are no entities for this property, we know it's unique. If there are,
// we have to make sure the one we were passed is in the set. otherwise it belongs
//to a different entity
return ownerEntityIds.size() == 0 || ownerEntityIds.contains( ownerEntityId );
}
/**
* Return all UUIDs that have this unique value
*
* @param ownerEntityId The entity id that owns this entity collection
* @param collectionName The entity collection name
* @param propertyName The name of the unique property
* @param propertyValue The value of the unique property
*/
private Set<UUID> getUUIDsForUniqueProperty( UUID ownerEntityId, String collectionName, String propertyName,
Object propertyValue ) throws Exception {
String collectionNameInternal = defaultCollectionName( collectionName );
Object key = createUniqueIndexKey( ownerEntityId, collectionNameInternal, propertyName, propertyValue );
List<HColumn<ByteBuffer, ByteBuffer>> cols =
cass.getColumns( cass.getApplicationKeyspace( applicationId ), ENTITY_UNIQUE, key, null, null, 2,
false );
//No columns at all, it's unique
if ( cols.size() == 0 ) {
return Collections.emptySet();
}
//shouldn't happen, but it's an error case
if ( cols.size() > 1 ) {
logger.error( "INDEX CORRUPTION: More than 1 unique value exists for entities in ownerId {} of type {} on "
+ "property {} with value {}",
new Object[] { ownerEntityId, collectionNameInternal, propertyName, propertyValue } );
}
/**
* Doing this in a loop sucks, but we need to account for possibly having more than 1 entry in the index due
* to corruption. We need to allow them to update, otherwise
* both entities will be unable to update and must be deleted
*/
Set<UUID> results = new HashSet<UUID>( cols.size() );
for ( HColumn<ByteBuffer, ByteBuffer> col : cols ) {
results.add( ue.fromByteBuffer( col.getName() ) );
}
return results;
}
/** Add this unique index to the delete */
private void uniquePropertyDelete( Mutator<ByteBuffer> m, String collectionName, String entityType,
String propertyName, Object propertyValue, UUID entityId, long timestamp )
throws Exception {
//read the old value and delete it
Object oldValue = getProperty( new SimpleEntityRef( entityType, entityId ), propertyName );
//we have an old value. If the new value is empty, we want to delete the old value. If the new value is
// different we want to delete, otherwise we don't issue the delete
if ( oldValue != null && ( propertyValue == null || !oldValue.equals( propertyValue ) ) ) {
Object key = createUniqueIndexKey( applicationId, collectionName, propertyName, oldValue );
addDeleteToMutator( m, ENTITY_UNIQUE, key, timestamp, entityId );
}
}
/** Add this unique index to the delete */
private void uniquePropertyWrite( Mutator<ByteBuffer> m, String collectionName, String propertyName,
Object propertyValue, UUID entityId, long timestamp ) throws Exception {
Object key = createUniqueIndexKey( applicationId, collectionName, propertyName, propertyValue );
addInsertToMutator( m, ENTITY_UNIQUE, key, entityId, null, timestamp );
}
/**
* Create a row key for the entity of the given type with the name and value in the property. Used for fast unique
* index lookups
*/
private Object createUniqueIndexKey( UUID ownerId, String collectionName, String propertyName, Object value ) {
return key( ownerId, collectionName, propertyName, value );
}
@Override
@Metered( group = "core", name = "EntityManager_getAlias_single" )
public EntityRef getAlias( UUID ownerId, String collectionType, String aliasValue ) throws Exception {
Assert.notNull( ownerId, "ownerId is required" );
Assert.notNull( collectionType, "collectionType is required" );
Assert.notNull( aliasValue, "aliasValue is required" );
Map<String, EntityRef> results = getAlias( ownerId, collectionType, Collections.singletonList( aliasValue ) );
if ( results == null || results.size() == 0 ) {
return null;
}
//add a warn statement so we can see if we have data migration issues.
//TODO When we get an event system, trigger a repair if this is detected
if ( results.size() > 1 ) {
logger.warn(
"More than 1 entity with Owner id '{}' of type '{}' and alias '{}' exists. This is a duplicate "
+ "alias, and needs audited", new Object[] { ownerId, collectionType, aliasValue } );
}
return results.get( aliasValue );
}
@Override
public Map<String, EntityRef> getAlias( String aliasType, List<String> aliases ) throws Exception {
return getAlias( applicationId, aliasType, aliases );
}
@Override
@Metered( group = "core", name = "EntityManager_getAlias_multi" )
public Map<String, EntityRef> getAlias( UUID ownerId, String collectionName, List<String> aliases )
throws Exception {
Assert.notNull( ownerId, "ownerId is required" );
Assert.notNull( collectionName, "collectionName is required" );
Assert.notEmpty( aliases, "aliases are required" );
String propertyName = Schema.getDefaultSchema().aliasProperty( collectionName );
Map<String, EntityRef> results = new HashMap<String, EntityRef>();
for ( String alias : aliases ) {
for ( UUID id : getUUIDsForUniqueProperty( ownerId, collectionName, propertyName, alias ) ) {
results.put( alias, new SimpleEntityRef( collectionName, id ) );
}
}
return results;
}
@SuppressWarnings( "unchecked" )
@Override
public <A extends Entity> A create( String entityType, Class<A> entityClass, Map<String, Object> properties )
throws Exception {
if ( ( entityType != null ) && ( entityType.startsWith( TYPE_ENTITY ) || entityType
.startsWith( "entities" ) ) ) {
throw new IllegalArgumentException( "Invalid entity type" );
}
A e = null;
try {
e = ( A ) create( entityType, ( Class<Entity> ) entityClass, properties, null );
}
catch ( ClassCastException e1 ) {
logger.error( "Unable to create typed entity", e1 );
}
return e;
}
@Override
public Entity create( UUID importId, String entityType, Map<String, Object> properties ) throws Exception {
return create( entityType, null, properties, importId );
}
@SuppressWarnings( "unchecked" )
@Override
public <A extends TypedEntity> A create( A entity ) throws Exception {
return ( A ) create( entity.getType(), entity.getClass(), entity.getProperties() );
}
@Override
@TraceParticipant
public Entity create( String entityType, Map<String, Object> properties ) throws Exception {
return create( entityType, null, properties );
}
/**
* Creates a new entity.
*
* @param entityType the entity type
* @param entityClass the entity class
* @param properties the properties
* @param importId an existing external uuid to use as the id for the new entity
*
* @return new entity
*
* @throws Exception the exception
*/
@Metered( group = "core", name = "EntityManager_create" )
@TraceParticipant
public <A extends Entity> A create( String entityType, Class<A> entityClass, Map<String, Object> properties,
UUID importId ) throws Exception {
UUID timestampUuid = newTimeUUID();
Keyspace ko = cass.getApplicationKeyspace( applicationId );
Mutator<ByteBuffer> m = CountingMutator.createFlushingMutator( ko, be );
A entity = batchCreate( m, entityType, entityClass, properties, importId, timestampUuid );
batchExecute( m, CassandraService.RETRY_COUNT );
return entity;
}
@SuppressWarnings( "unchecked" )
@Metered( group = "core", name = "EntityManager_batchCreate" )
public <A extends Entity> A batchCreate( Mutator<ByteBuffer> m, String entityType, Class<A> entityClass,
Map<String, Object> properties, UUID importId, UUID timestampUuid )
throws Exception {
String eType = Schema.normalizeEntityType( entityType );
Schema schema = getDefaultSchema();
boolean is_application = TYPE_APPLICATION.equals( eType );
if ( ( ( applicationId == null ) || applicationId.equals( UUIDUtils.ZERO_UUID ) ) && !is_application ) {
return null;
}
long timestamp = getTimestampInMicros( timestampUuid );
UUID itemId = null;
if ( is_application ) {
itemId = applicationId;
}
if ( importId != null ) {
itemId = importId;
}
if (itemId == null) {
itemId = UUIDUtils.newTimeUUID();
}
boolean emptyPropertyMap = false;
if ( properties == null ) {
properties = new TreeMap<String, Object>( CASE_INSENSITIVE_ORDER );
}
if ( properties.isEmpty() ) {
emptyPropertyMap = true;
}
if ( importId != null ) {
if ( isTimeBased( importId ) ) {
timestamp = UUIDUtils.getTimestampInMicros( importId );
}
else if ( properties.get( PROPERTY_CREATED ) != null ) {
timestamp = getLong( properties.get( PROPERTY_CREATED ) ) * 1000;
}
}
if ( entityClass == null ) {
entityClass = ( Class<A> ) Schema.getDefaultSchema().getEntityClass( entityType );
}
Set<String> required = schema.getRequiredProperties( entityType );
if ( required != null ) {
for ( String p : required ) {
if ( !PROPERTY_UUID.equals( p ) && !PROPERTY_TYPE.equals( p ) && !PROPERTY_CREATED.equals( p )
&& !PROPERTY_MODIFIED.equals( p ) ) {
Object v = properties.get( p );
if ( schema.isPropertyTimestamp( entityType, p ) ) {
if ( v == null ) {
properties.put( p, timestamp / 1000 );
}
else {
long ts = getLong( v );
if ( ts <= 0 ) {
properties.put( p, timestamp / 1000 );
}
}
continue;
}
if ( v == null ) {
throw new RequiredPropertyNotFoundException( entityType, p );
}
else if ( ( v instanceof String ) && isBlank( ( String ) v ) ) {
throw new RequiredPropertyNotFoundException( entityType, p );
}
}
}
}
// Create collection name based on entity: i.e. "users"
String collection_name = Schema.defaultCollectionName( eType );
// Create collection key based collection name
String bucketId = indexBucketLocator.getBucket(itemId );
Object collection_key = key( applicationId, Schema.DICTIONARY_COLLECTIONS, collection_name, bucketId );
CollectionInfo collection = null;
if ( !is_application ) {
// Add entity to collection
if ( !emptyPropertyMap ) {
addInsertToMutator( m, ENTITY_ID_SETS, collection_key, itemId, null, timestamp );
}
// Add name of collection to dictionary property
// Application.collections
addInsertToMutator( m, ENTITY_DICTIONARIES, key( applicationId, Schema.DICTIONARY_COLLECTIONS ),
collection_name, null, timestamp );
addInsertToMutator( m, ENTITY_COMPOSITE_DICTIONARIES, key( itemId, Schema.DICTIONARY_CONTAINER_ENTITIES ),
asList( TYPE_APPLICATION, collection_name, applicationId ), null, timestamp );
}
if ( emptyPropertyMap ) {
return null;
}
properties.put( PROPERTY_UUID, itemId );
properties.put( PROPERTY_TYPE, Schema.normalizeEntityType( entityType, false ) );
if ( importId != null ) {
if ( properties.get( PROPERTY_CREATED ) == null ) {
properties.put( PROPERTY_CREATED, timestamp / 1000 );
}
if ( properties.get( PROPERTY_MODIFIED ) == null ) {
properties.put( PROPERTY_MODIFIED, timestamp / 1000 );
}
}
else {
properties.put( PROPERTY_CREATED, timestamp / 1000 );
properties.put( PROPERTY_MODIFIED, timestamp / 1000 );
}
// special case timestamp and published properties
// and dictionary their timestamp values if not set
// this is sure to break something for someone someday
if ( properties.containsKey( PROPERTY_TIMESTAMP ) ) {
long ts = getLong( properties.get( PROPERTY_TIMESTAMP ) );
if ( ts <= 0 ) {
properties.put( PROPERTY_TIMESTAMP, timestamp / 1000 );
}
}
A entity = EntityFactory.newEntity( itemId, eType, entityClass );
logger.info( "Entity created of type {}", entity.getClass().getName() );
if ( Event.ENTITY_TYPE.equals( eType ) ) {
Event event = ( Event ) entity.toTypedEntity();
for ( String prop_name : properties.keySet() ) {
Object propertyValue = properties.get( prop_name );
if ( propertyValue != null ) {
event.setProperty( prop_name, propertyValue );
}
}
Message message = storeEventAsMessage( m, event, timestamp );
incrementEntityCollection( "events", timestamp );
entity.setUuid( message.getUuid() );
return entity;
}
for ( String prop_name : properties.keySet() ) {
Object propertyValue = properties.get( prop_name );
if ( propertyValue == null ) {
continue;
}
if ( User.ENTITY_TYPE.equals( entityType ) && "me".equals( prop_name ) ) {
throw new DuplicateUniquePropertyExistsException( entityType, prop_name, propertyValue );
}
entity.setProperty( prop_name, propertyValue );
batchSetProperty( m, entity, prop_name, propertyValue, true, true, timestampUuid );
}
if ( !is_application ) {
incrementEntityCollection( collection_name, timestamp );
}
return entity;
}
private void incrementEntityCollection( String collection_name, long cassandraTimestamp ) {
try {
incrementAggregateCounters( null, null, null, APPLICATION_COLLECTION + collection_name,
ONE_COUNT, cassandraTimestamp );
}
catch ( Exception e ) {
logger.error( "Unable to increment counter application.collection: {}.", new Object[]{ collection_name, e} );
}
try {
incrementAggregateCounters( null, null, null, APPLICATION_ENTITIES, ONE_COUNT, cassandraTimestamp );
}
catch ( Exception e ) {
logger.error( "Unable to increment counter application.entities for collection: {} with timestamp: {}", new Object[]{collection_name, cassandraTimestamp,e} );
}
}
public void decrementEntityCollection( String collection_name ) {
long cassandraTimestamp = cass.createTimestamp();
decrementEntityCollection( collection_name, cassandraTimestamp );
}
public void decrementEntityCollection( String collection_name, long cassandraTimestamp ) {
try {
incrementAggregateCounters( null, null, null, APPLICATION_COLLECTION + collection_name, -ONE_COUNT,
cassandraTimestamp );
}
catch ( Exception e ) {
logger.error( "Unable to decrement counter application.collection: {}.", new Object[]{collection_name, e} );
}
try {
incrementAggregateCounters( null, null, null, APPLICATION_ENTITIES, -ONE_COUNT, cassandraTimestamp );
}
catch ( Exception e ) {
logger.error( "Unable to decrement counter application.entities for collection: {} with timestamp: {}", new Object[]{collection_name, cassandraTimestamp,e} );
}
}
@Metered( group = "core", name = "EntityManager_insertEntity" )
public void insertEntity( String type, UUID entityId ) throws Exception {
Keyspace ko = cass.getApplicationKeyspace( applicationId );
Mutator<ByteBuffer> m = CountingMutator.createFlushingMutator( ko, be );
Object itemKey = key( entityId );
long timestamp = cass.createTimestamp();
addPropertyToMutator( m, itemKey, type, PROPERTY_UUID, entityId, timestamp );
addPropertyToMutator( m, itemKey, type, PROPERTY_TYPE, type, timestamp );
batchExecute( m, CassandraService.RETRY_COUNT );
}
public Message storeEventAsMessage( Mutator<ByteBuffer> m, Event event, long timestamp ) {
counterUtils.addEventCounterMutations( m, applicationId, event, timestamp );
QueueManager q = qmf.getQueueManager( applicationId );
Message message = new Message();
message.setType( "event" );
message.setCategory( event.getCategory() );
message.setStringProperty( "message", event.getMessage() );
message.setTimestamp( timestamp );
q.postToQueue( "events", message );
return message;
}
/**
* Gets the type.
*
* @param entityId the entity id
*
* @return entity type
*
* @throws Exception the exception
*/
@Metered( group = "core", name = "EntityManager_getEntityType" )
public String getEntityType( UUID entityId ) throws Exception {