/
SqlRepositoryServiceImpl.java
1665 lines (1401 loc) · 73 KB
/
SqlRepositoryServiceImpl.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-2014 Evolveum
*
* 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 com.evolveum.midpoint.repo.sql;
import com.evolveum.midpoint.common.InternalsConfig;
import com.evolveum.midpoint.common.crypto.CryptoUtil;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.delta.ReferenceDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.*;
import com.evolveum.midpoint.repo.api.LookupTableSearchType;
import com.evolveum.midpoint.repo.api.RepoAddOptions;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.repo.sql.data.common.*;
import com.evolveum.midpoint.repo.sql.data.common.any.RAnyValue;
import com.evolveum.midpoint.repo.sql.data.common.any.RValueType;
import com.evolveum.midpoint.repo.sql.data.common.type.RObjectExtensionType;
import com.evolveum.midpoint.repo.sql.query.QueryEngine;
import com.evolveum.midpoint.repo.sql.query.QueryException;
import com.evolveum.midpoint.repo.sql.query.RQuery;
import com.evolveum.midpoint.repo.sql.util.*;
import com.evolveum.midpoint.schema.*;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.xml.namespace.QName;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;
/**
* @author lazyman
*/
@Repository
public class SqlRepositoryServiceImpl extends SqlBaseService implements RepositoryService {
public static final String PERFORMANCE_LOG_NAME = SqlRepositoryServiceImpl.class.getName() + ".performance";
private static final Trace LOGGER = TraceManager.getTrace(SqlRepositoryServiceImpl.class);
private static final Trace LOGGER_PERFORMANCE = TraceManager.getTrace(PERFORMANCE_LOG_NAME);
private static final int MAX_CONSTRAINT_NAME_LENGTH = 40;
private static final String IMPLEMENTATION_SHORT_NAME = "SQL";
private static final String IMPLEMENTATION_DESCRIPTION = "Implementation that stores data in generic relational" +
" (SQL) databases. It is using ORM (hibernate) on top of JDBC to access the database.";
private static final String DETAILS_TRANSACTION_ISOLATION = "transactionIsolation";
private static final String DETAILS_CLIENT_INFO = "clientInfo.";
private static final String DETAILS_DATA_SOURCE = "dataSource";
private static final String DETAILS_HIBERNATE_DIALECT = "hibernateDialect";
private static final String DETAILS_HIBERNATE_HBM_2_DDL = "hibernateHbm2ddl";
private OrgClosureManager closureManager;
public SqlRepositoryServiceImpl(SqlRepositoryFactory repositoryFactory) {
super(repositoryFactory);
}
// public because of testing
public OrgClosureManager getClosureManager() {
if (closureManager == null) {
closureManager = new OrgClosureManager(getConfiguration());
}
return closureManager;
}
private <T extends ObjectType> PrismObject<T> getObject(Session session, Class<T> type, String oid,
Collection<SelectorOptions<GetOperationOptions>> options,
boolean lockForUpdate)
throws ObjectNotFoundException, SchemaException, DtoTranslationException, QueryException {
boolean lockedForUpdateViaHibernate = false;
boolean lockedForUpdateViaSql = false;
LockOptions lockOptions = new LockOptions();
//todo fix lock for update!!!!!
if (lockForUpdate) {
if (getConfiguration().isLockForUpdateViaHibernate()) {
lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE);
lockedForUpdateViaHibernate = true;
} else if (getConfiguration().isLockForUpdateViaSql()) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Trying to lock object " + oid + " for update (via SQL)");
}
long time = System.currentTimeMillis();
SQLQuery q = session.createSQLQuery("select oid from m_object where oid = ? for update");
q.setString(0, oid);
Object result = q.uniqueResult();
if (result == null) {
return throwObjectNotFoundException(type, oid);
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Locked via SQL (in " + (System.currentTimeMillis() - time) + " ms)");
}
lockedForUpdateViaSql = true;
}
}
if (LOGGER.isTraceEnabled()) {
if (lockedForUpdateViaHibernate) {
LOGGER.trace("Getting object " + oid + " with locking for update (via hibernate)");
} else if (lockedForUpdateViaSql) {
LOGGER.trace("Getting object " + oid + ", already locked for update (via SQL)");
} else {
LOGGER.trace("Getting object " + oid + " without locking for update");
}
}
GetObjectResult fullObject = null;
if (!lockForUpdate) {
Query query = session.getNamedQuery("get.object");
query.setString("oid", oid);
query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
query.setLockOptions(lockOptions);
fullObject = (GetObjectResult) query.uniqueResult();
} else {
// we're doing update after this get, therefore we load full object right now
// (it would be loaded during merge anyway)
// this just loads object to hibernate session, probably will be removed later. Merge after this get
// will be faster. Read and use object only from fullObject column.
// todo remove this later [lazyman]
Criteria criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type));
criteria.add(Restrictions.eq("oid", oid));
criteria.setLockMode(lockOptions.getLockMode());
RObject obj = (RObject) criteria.uniqueResult();
if (obj != null) {
obj.toJAXB(getPrismContext(), null).asPrismObject();
fullObject = new GetObjectResult(obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(),
obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount());
}
}
LOGGER.trace("Got it.");
if (fullObject == null) {
throwObjectNotFoundException(type, oid);
}
LOGGER.trace("Transforming data to JAXB type.");
PrismObject<T> prismObject = updateLoadedObject(fullObject, type, options, session);
validateObjectType(prismObject, type);
return prismObject;
}
private <T extends ObjectType> PrismObject<T> throwObjectNotFoundException(Class<T> type, String oid)
throws ObjectNotFoundException {
throw new ObjectNotFoundException("Object of type '" + type.getSimpleName() + "' with oid '" + oid
+ "' was not found.", null, oid);
}
@Override
public <T extends ObjectType> PrismObject<T> getObject(Class<T> type, String oid,
Collection<SelectorOptions<GetOperationOptions>> options,
OperationResult result)
throws ObjectNotFoundException, SchemaException {
Validate.notNull(type, "Object type must not be null.");
Validate.notEmpty(oid, "Oid must not be null or empty.");
Validate.notNull(result, "Operation result must not be null.");
LOGGER.debug("Getting object '{}' with oid '{}'.", new Object[]{type.getSimpleName(), oid});
final String operation = "getting";
int attempt = 1;
OperationResult subResult = result.createMinorSubresult(GET_OBJECT);
subResult.addParam("type", type.getName());
subResult.addParam("oid", oid);
SqlPerformanceMonitor pm = getPerformanceMonitor();
long opHandle = pm.registerOperationStart("getObject");
try {
while (true) {
try {
return getObjectAttempt(type, oid, options, subResult);
} catch (RuntimeException ex) {
attempt = logOperationAttempt(oid, operation, attempt, ex, subResult);
pm.registerOperationNewTrial(opHandle, attempt);
}
}
} finally {
pm.registerOperationFinish(opHandle, attempt);
}
}
private <T extends ObjectType> PrismObject<T> getObjectAttempt(Class<T> type, String oid,
Collection<SelectorOptions<GetOperationOptions>> options,
OperationResult result)
throws ObjectNotFoundException, SchemaException {
LOGGER_PERFORMANCE.debug("> get object {}, oid={}", type.getSimpleName(), oid);
PrismObject<T> objectType = null;
Session session = null;
try {
session = beginReadOnlyTransaction();
objectType = getObject(session, type, oid, options, false);
session.getTransaction().commit();
} catch (ObjectNotFoundException ex) {
GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options);
rollbackTransaction(session, ex, result, !GetOperationOptions.isAllowNotFound(rootOptions));
throw ex;
} catch (SchemaException ex) {
rollbackTransaction(session, ex, "Schema error while getting object with oid: "
+ oid + ". Reason: " + ex.getMessage(), result, true);
throw ex;
} catch (QueryException | DtoTranslationException | RuntimeException ex) {
handleGeneralException(ex, session, result);
} finally {
cleanupSessionAndResult(session, result);
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Get object:\n{}", new Object[]{(objectType != null ? objectType.debugDump(3) : null)});
}
return objectType;
}
private Session beginReadOnlyTransaction() {
return beginTransaction(getConfiguration().isUseReadOnlyTransactions());
}
@Override
public <F extends FocusType> PrismObject<F> searchShadowOwner(String shadowOid, Collection<SelectorOptions<GetOperationOptions>> options, OperationResult result)
throws ObjectNotFoundException {
Validate.notEmpty(shadowOid, "Oid must not be null or empty.");
Validate.notNull(result, "Operation result must not be null.");
LOGGER.debug("Searching shadow owner for {}", shadowOid);
final String operation = "searching shadow owner";
int attempt = 1;
OperationResult subResult = result.createSubresult(SEARCH_SHADOW_OWNER);
subResult.addParam("shadowOid", shadowOid);
while (true) {
try {
return searchShadowOwnerAttempt(shadowOid, options, subResult);
} catch (RuntimeException ex) {
attempt = logOperationAttempt(shadowOid, operation, attempt, ex, subResult);
}
}
}
private <F extends FocusType> PrismObject<F> searchShadowOwnerAttempt(String shadowOid, Collection<SelectorOptions<GetOperationOptions>> options, OperationResult result)
throws ObjectNotFoundException {
LOGGER_PERFORMANCE.debug("> search shadow owner for oid={}", shadowOid);
PrismObject<F> owner = null;
Session session = null;
try {
session = beginReadOnlyTransaction();
Query query = session.getNamedQuery("searchShadowOwner.getShadow");
query.setString("oid", shadowOid);
if (query.uniqueResult() == null) {
throw new ObjectNotFoundException("Shadow with oid '" + shadowOid + "' doesn't exist.");
}
LOGGER.trace("Selecting account shadow owner for account {}.", new Object[]{shadowOid});
query = session.getNamedQuery("searchShadowOwner.getOwner");
query.setString("oid", shadowOid);
query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
List<GetObjectResult> focuses = query.list();
LOGGER.trace("Found {} focuses, transforming data to JAXB types.",
new Object[]{(focuses != null ? focuses.size() : 0)});
if (focuses == null || focuses.isEmpty()) {
// account shadow owner was not found
return null;
}
if (focuses.size() > 1) {
LOGGER.warn("Found {} owners for shadow oid {}, returning first owner.",
new Object[]{focuses.size(), shadowOid});
}
GetObjectResult focus = focuses.get(0);
owner = updateLoadedObject(focus, (Class<F>) FocusType.class, options, session);
session.getTransaction().commit();
} catch (ObjectNotFoundException ex) {
GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options);
rollbackTransaction(session, ex, result, !GetOperationOptions.isAllowNotFound(rootOptions));
throw ex;
} catch (SchemaException | RuntimeException ex) {
handleGeneralException(ex, session, result);
} finally {
cleanupSessionAndResult(session, result);
}
return owner;
}
@Override
@Deprecated
public PrismObject<UserType> listAccountShadowOwner(String accountOid, OperationResult result)
throws ObjectNotFoundException {
Validate.notEmpty(accountOid, "Oid must not be null or empty.");
Validate.notNull(result, "Operation result must not be null.");
LOGGER.debug("Selecting account shadow owner for account {}.", new Object[]{accountOid});
final String operation = "listing account shadow owner";
int attempt = 1;
OperationResult subResult = result.createSubresult(LIST_ACCOUNT_SHADOW);
subResult.addParam("accountOid", accountOid);
while (true) {
try {
return listAccountShadowOwnerAttempt(accountOid, subResult);
} catch (RuntimeException ex) {
attempt = logOperationAttempt(accountOid, operation, attempt, ex, subResult);
}
}
}
private PrismObject<UserType> listAccountShadowOwnerAttempt(String accountOid, OperationResult result)
throws ObjectNotFoundException {
LOGGER_PERFORMANCE.debug("> list account shadow owner oid={}", accountOid);
PrismObject<UserType> userType = null;
Session session = null;
try {
session = beginReadOnlyTransaction();
Query query = session.getNamedQuery("listAccountShadowOwner.getUser");
query.setString("oid", accountOid);
query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
List<GetObjectResult> users = query.list();
LOGGER.trace("Found {} users, transforming data to JAXB types.",
new Object[]{(users != null ? users.size() : 0)});
if (users == null || users.isEmpty()) {
// account shadow owner was not found
return null;
}
if (users.size() > 1) {
LOGGER.warn("Found {} users for account oid {}, returning first user. [interface change needed]",
new Object[]{users.size(), accountOid});
}
GetObjectResult user = users.get(0);
userType = updateLoadedObject(user, UserType.class, null, session);
session.getTransaction().commit();
} catch (SchemaException | RuntimeException ex) {
handleGeneralException(ex, session, result);
} finally {
cleanupSessionAndResult(session, result);
}
return userType;
}
private void validateName(PrismObject object) throws SchemaException {
PrismProperty name = object.findProperty(ObjectType.F_NAME);
if (name == null || ((PolyString) name.getRealValue()).isEmpty()) {
throw new SchemaException("Attempt to add object without name.");
}
}
@Override
public <T extends ObjectType> String addObject(PrismObject<T> object, RepoAddOptions options, OperationResult result)
throws ObjectAlreadyExistsException, SchemaException {
Validate.notNull(object, "Object must not be null.");
validateName(object);
Validate.notNull(result, "Operation result must not be null.");
if (options == null) {
options = new RepoAddOptions();
}
LOGGER.debug("Adding object type '{}', overwrite={}, allowUnencryptedValues={}",
new Object[]{object.getCompileTimeClass().getSimpleName(), options.isOverwrite(),
options.isAllowUnencryptedValues()}
);
if (InternalsConfig.encryptionChecks && !RepoAddOptions.isAllowUnencryptedValues(options)) {
CryptoUtil.checkEncrypted(object);
}
if (InternalsConfig.consistencyChecks) {
object.checkConsistence(ConsistencyCheckScope.THOROUGH);
} else {
object.checkConsistence(ConsistencyCheckScope.MANDATORY_CHECKS_ONLY);
}
if (LOGGER.isTraceEnabled()) {
// Explicitly log name
PolyStringType namePolyType = object.asObjectable().getName();
LOGGER.trace("NAME: {} - {}", namePolyType.getOrig(), namePolyType.getNorm());
}
OperationResult subResult = result.createSubresult(ADD_OBJECT);
subResult.addParam("object", object);
subResult.addParam("options", options);
final String operation = "adding";
int attempt = 1;
String oid = object.getOid();
while (true) {
try {
return addObjectAttempt(object, options, subResult);
} catch (RuntimeException ex) {
attempt = logOperationAttempt(oid, operation, attempt, ex, subResult);
}
}
}
private <T extends ObjectType> String addObjectAttempt(PrismObject<T> object, RepoAddOptions options,
OperationResult result)
throws ObjectAlreadyExistsException, SchemaException {
LOGGER_PERFORMANCE.debug("> add object {}, oid={}, overwrite={}",
new Object[]{object.getCompileTimeClass().getSimpleName(), object.getOid(), options.isOverwrite()});
String oid = null;
Session session = null;
OrgClosureManager.Context closureContext = null;
// it is needed to keep the original oid for example for import options. if we do not keep it
// and it was null it can bring some error because the oid is set when the object contains orgRef
// or it is org. and by the import we do not know it so it will be trying to delete non-existing object
String originalOid = object.getOid();
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Object\n{}", new Object[]{object.debugDump()});
}
LOGGER.trace("Translating JAXB to data type.");
PrismIdentifierGenerator.Operation operation = options.isOverwrite() ?
PrismIdentifierGenerator.Operation.ADD_WITH_OVERWRITE :
PrismIdentifierGenerator.Operation.ADD;
RObject rObject = createDataObjectFromJAXB(object, operation);
session = beginTransaction();
closureContext = getClosureManager().onBeginTransactionAdd(session, object, options.isOverwrite());
if (options.isOverwrite()) {
oid = overwriteAddObjectAttempt(object, rObject, originalOid, session, closureContext);
} else {
oid = nonOverwriteAddObjectAttempt(object, rObject, originalOid, session, closureContext);
}
session.getTransaction().commit();
LOGGER.trace("Saved object '{}' with oid '{}'", new Object[]{
object.getCompileTimeClass().getSimpleName(), oid});
object.setOid(oid);
} catch (ObjectAlreadyExistsException ex) {
rollbackTransaction(session, ex, result, true);
throw ex;
} catch (ConstraintViolationException ex) {
handleConstraintViolationException(session, ex, result);
rollbackTransaction(session, ex, result, true);
LOGGER.debug("Constraint violation occurred (will be rethrown as ObjectAlreadyExistsException).", ex);
// we don't know if it's only name uniqueness violation, or something else,
// therefore we're throwing it always as ObjectAlreadyExistsException revert
// to the original oid and prevent of unexpected behaviour (e.g. by import with overwrite option)
if (StringUtils.isEmpty(originalOid)) {
object.setOid(null);
}
String constraintName = ex.getConstraintName();
// Breaker to avoid long unreadable messages
if (constraintName != null && constraintName.length() > MAX_CONSTRAINT_NAME_LENGTH) {
constraintName = null;
}
throw new ObjectAlreadyExistsException("Conflicting object already exists"
+ (constraintName == null ? "" : " (violated constraint '" + constraintName + "')"), ex);
} catch (SchemaException ex) {
rollbackTransaction(session, ex, result, true);
throw ex;
} catch (DtoTranslationException | RuntimeException ex) {
handleGeneralException(ex, session, result);
} finally {
cleanupClosureAndSessionAndResult(closureContext, session, result);
}
return oid;
}
private <T extends ObjectType> String overwriteAddObjectAttempt(PrismObject<T> object, RObject rObject,
String originalOid, Session session, OrgClosureManager.Context closureContext)
throws ObjectAlreadyExistsException, SchemaException, DtoTranslationException {
PrismObject<T> oldObject = null;
//check if object already exists, find differences and increment version if necessary
Collection<? extends ItemDelta> modifications = null;
if (originalOid != null) {
try {
oldObject = getObject(session, object.getCompileTimeClass(), originalOid, null, true);
ObjectDelta<T> delta = object.diff(oldObject);
modifications = delta.getModifications();
//we found existing object which will be overwritten, therefore we increment version
Integer version = RUtil.getIntegerFromString(oldObject.getVersion());
version = (version == null) ? 0 : ++version;
rObject.setVersion(version);
} catch (QueryException ex) {
handleGeneralCheckedException(ex, session, null);
} catch (ObjectNotFoundException ex) {
//it's ok that object was not found, therefore we won't be overwriting it
}
}
updateFullObject(rObject, object);
RObject merged = (RObject) session.merge(rObject);
//add and maybe modify
if (getClosureManager().isEnabled()) {
OrgClosureManager.Operation operation;
if (modifications == null) {
operation = OrgClosureManager.Operation.ADD;
modifications = createAddParentRefDelta(object);
} else {
operation = OrgClosureManager.Operation.MODIFY;
}
getClosureManager().updateOrgClosure(oldObject, modifications, session, merged.getOid(), object.getCompileTimeClass(),
operation, closureContext);
}
return merged.getOid();
}
private <T extends ObjectType> void updateFullObject(RObject object, PrismObject<T> savedObject)
throws DtoTranslationException, SchemaException {
LOGGER.debug("Updating full object xml column start.");
savedObject.setVersion(Integer.toString(object.getVersion()));
if (UserType.class.equals(savedObject.getCompileTimeClass())) {
savedObject.removeProperty(UserType.F_JPEG_PHOTO);
}
String xml = getPrismContext().serializeObjectToString(savedObject, PrismContext.LANG_XML);
byte[] fullObject = RUtil.getByteArrayFromXml(xml, getConfiguration().isUseZip());
if (LOGGER.isTraceEnabled()) LOGGER.trace("Storing full object\n{}", xml);
object.setFullObject(fullObject);
LOGGER.debug("Updating full object xml column finish.");
}
private <T extends ObjectType> String nonOverwriteAddObjectAttempt(PrismObject<T> object, RObject rObject,
String originalOid, Session session, OrgClosureManager.Context closureContext)
throws ObjectAlreadyExistsException, SchemaException, DtoTranslationException {
// check name uniqueness (by type)
if (StringUtils.isNotEmpty(originalOid)) {
LOGGER.trace("Checking oid uniqueness.");
//todo improve this table name bullshit
Class hqlType = ClassMapper.getHQLTypeClass(object.getCompileTimeClass());
SQLQuery query = session.createSQLQuery("select count(*) from " + RUtil.getTableName(hqlType)
+ " where oid=:oid");
query.setString("oid", object.getOid());
Number count = (Number) query.uniqueResult();
if (count != null && count.longValue() > 0) {
throw new ObjectAlreadyExistsException("Object '" + object.getCompileTimeClass().getSimpleName()
+ "' with oid '" + object.getOid() + "' already exists.");
}
}
updateFullObject(rObject, object);
LOGGER.trace("Saving object (non overwrite).");
String oid = (String) session.save(rObject);
if (getClosureManager().isEnabled()) {
Collection<ReferenceDelta> modifications = createAddParentRefDelta(object);
getClosureManager().updateOrgClosure(null, modifications, session, oid, object.getCompileTimeClass(),
OrgClosureManager.Operation.ADD, closureContext);
}
return oid;
}
@Override
public <T extends ObjectType> void deleteObject(Class<T> type, String oid, OperationResult result)
throws ObjectNotFoundException {
Validate.notNull(type, "Object type must not be null.");
Validate.notEmpty(oid, "Oid must not be null or empty.");
Validate.notNull(result, "Operation result must not be null.");
LOGGER.debug("Deleting object type '{}' with oid '{}'", new Object[]{type.getSimpleName(), oid});
final String operation = "deleting";
int attempt = 1;
OperationResult subResult = result.createSubresult(DELETE_OBJECT);
subResult.addParam("type", type.getName());
subResult.addParam("oid", oid);
SqlPerformanceMonitor pm = getPerformanceMonitor();
long opHandle = pm.registerOperationStart("deleteObject");
try {
while (true) {
try {
deleteObjectAttempt(type, oid, subResult);
return;
} catch (RuntimeException ex) {
attempt = logOperationAttempt(oid, operation, attempt, ex, subResult);
pm.registerOperationNewTrial(opHandle, attempt);
}
}
} finally {
pm.registerOperationFinish(opHandle, attempt);
}
}
private <T extends ObjectType> List<ReferenceDelta> createAddParentRefDelta(PrismObject<T> object) {
PrismReference parentOrgRef = object.findReference(ObjectType.F_PARENT_ORG_REF);
if (parentOrgRef == null || parentOrgRef.isEmpty()) {
return new ArrayList<>();
}
PrismObjectDefinition def = object.getDefinition();
ReferenceDelta delta = ReferenceDelta.createModificationAdd(new ItemPath(ObjectType.F_PARENT_ORG_REF),
def, parentOrgRef.getClonedValues());
return Arrays.asList(delta);
}
private <T extends ObjectType> void deleteObjectAttempt(Class<T> type, String oid, OperationResult result)
throws ObjectNotFoundException {
LOGGER_PERFORMANCE.debug("> delete object {}, oid={}", new Object[]{type.getSimpleName(), oid});
Session session = null;
OrgClosureManager.Context closureContext = null;
try {
session = beginTransaction();
closureContext = getClosureManager().onBeginTransactionDelete(session, type, oid);
Criteria query = session.createCriteria(ClassMapper.getHQLTypeClass(type));
query.add(Restrictions.eq("oid", oid));
RObject object = (RObject) query.uniqueResult();
if (object == null) {
throw new ObjectNotFoundException("Object of type '" + type.getSimpleName() + "' with oid '" + oid
+ "' was not found.", null, oid);
}
getClosureManager().updateOrgClosure(null, null, session, oid, type, OrgClosureManager.Operation.DELETE, closureContext);
session.delete(object);
session.getTransaction().commit();
} catch (ObjectNotFoundException ex) {
rollbackTransaction(session, ex, result, true);
throw ex;
} catch (RuntimeException ex) {
handleGeneralException(ex, session, result);
} finally {
cleanupClosureAndSessionAndResult(closureContext, session, result);
}
}
@Override
public <T extends ObjectType> int countObjects(Class<T> type, ObjectQuery query, OperationResult result) {
Validate.notNull(type, "Object type must not be null.");
Validate.notNull(result, "Operation result must not be null.");
LOGGER.debug("Counting objects of type '{}', query (on trace level).", new Object[]{type.getSimpleName()});
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Full query\n{}", new Object[]{(query == null ? "undefined" : query.debugDump())});
}
OperationResult subResult = result.createMinorSubresult(COUNT_OBJECTS);
subResult.addParam("type", type.getName());
subResult.addParam("query", query);
if (query != null) {
ObjectFilter filter = query.getFilter();
filter = ObjectQueryUtil.simplify(filter);
if (filter instanceof NoneFilter) {
subResult.recordSuccess();
return 0;
}
query = query.cloneEmpty();
query.setFilter(filter);
}
final String operation = "counting";
int attempt = 1;
while (true) {
try {
return countObjectsAttempt(type, query, subResult);
} catch (RuntimeException ex) {
attempt = logOperationAttempt(null, operation, attempt, ex, subResult);
}
}
}
private <T extends ObjectType> int countObjectsAttempt(Class<T> type, ObjectQuery query, OperationResult result) {
LOGGER_PERFORMANCE.debug("> count objects {}", new Object[]{type.getSimpleName()});
int count = 0;
Session session = null;
try {
Class<? extends RObject> hqlType = ClassMapper.getHQLTypeClass(type);
session = beginReadOnlyTransaction();
Number longCount;
if (query == null || query.getFilter() == null) {
// this is 5x faster than count with 3 inner joins, it can probably improved also for queries which
// filters uses only properties from concrete entities like RUser, RRole by improving interpreter [lazyman]
SQLQuery sqlQuery = session.createSQLQuery("SELECT COUNT(*) FROM " + RUtil.getTableName(hqlType));
longCount = (Number) sqlQuery.uniqueResult();
} else {
QueryEngine engine = new QueryEngine(getConfiguration(), getPrismContext());
RQuery rQuery = engine.interpret(query, type, null, true, session);
longCount = (Number) rQuery.uniqueResult();
}
LOGGER.trace("Found {} objects.", longCount);
count = longCount != null ? longCount.intValue() : 0;
} catch (QueryException | RuntimeException ex) {
handleGeneralException(ex, session, result);
} finally {
cleanupSessionAndResult(session, result);
}
return count;
}
@Override
public <T extends ObjectType> SearchResultList<PrismObject<T>> searchObjects(Class<T> type, ObjectQuery query,
Collection<SelectorOptions<GetOperationOptions>> options,
OperationResult result) throws SchemaException {
Validate.notNull(type, "Object type must not be null.");
Validate.notNull(result, "Operation result must not be null.");
logSearchInputParameters(type, query, false);
OperationResult subResult = result.createSubresult(SEARCH_OBJECTS);
subResult.addParam("type", type.getName());
subResult.addParam("query", query);
// subResult.addParam("paging", paging);
if (query != null) {
ObjectFilter filter = query.getFilter();
filter = ObjectQueryUtil.simplify(filter);
if (filter instanceof NoneFilter) {
subResult.recordSuccess();
return new SearchResultList(new ArrayList<PrismObject<T>>(0));
}
query = query.cloneEmpty();
query.setFilter(filter);
}
SqlPerformanceMonitor pm = getPerformanceMonitor();
long opHandle = pm.registerOperationStart("searchObjects");
final String operation = "searching";
int attempt = 1;
try {
while (true) {
try {
return searchObjectsAttempt(type, query, options, subResult);
} catch (RuntimeException ex) {
attempt = logOperationAttempt(null, operation, attempt, ex, subResult);
pm.registerOperationNewTrial(opHandle, attempt);
}
}
} finally {
pm.registerOperationFinish(opHandle, attempt);
}
}
private <T extends ObjectType> void logSearchInputParameters(Class<T> type, ObjectQuery query, boolean iterative) {
ObjectPaging paging = query != null ? query.getPaging() : null;
LOGGER.debug("Searching objects of type '{}', query (on trace level), offset {}, count {}, iterative {}.",
new Object[]{type.getSimpleName(), (paging != null ? paging.getOffset() : "undefined"),
(paging != null ? paging.getMaxSize() : "undefined"), iterative}
);
if (!LOGGER.isTraceEnabled()) {
return;
}
LOGGER.trace("Full query\n{}\nFull paging\n{}", new Object[]{
(query == null ? "undefined" : query.debugDump()),
(paging != null ? paging.debugDump() : "undefined")});
if (iterative) {
LOGGER.trace("Iterative search by paging: {}, batch size {}",
getConfiguration().isIterativeSearchByPaging(),
getConfiguration().getIterativeSearchByPagingBatchSize());
}
}
private <T extends ObjectType> SearchResultList<PrismObject<T>> searchObjectsAttempt(Class<T> type, ObjectQuery query,
Collection<SelectorOptions<GetOperationOptions>> options,
OperationResult result) throws SchemaException {
LOGGER_PERFORMANCE.debug("> search objects {}", new Object[]{type.getSimpleName()});
List<PrismObject<T>> list = new ArrayList<>();
Session session = null;
try {
session = beginReadOnlyTransaction();
QueryEngine engine = new QueryEngine(getConfiguration(), getPrismContext());
RQuery rQuery = engine.interpret(query, type, options, false, session);
List<GetObjectResult> objects = rQuery.list();
LOGGER.trace("Found {} objects, translating to JAXB.", new Object[]{(objects != null ? objects.size() : 0)});
for (GetObjectResult object : objects) {
PrismObject<T> prismObject = updateLoadedObject(object, type, options, session);
list.add(prismObject);
}
session.getTransaction().commit();
} catch (QueryException | RuntimeException ex) {
handleGeneralException(ex, session, result);
} finally {
cleanupSessionAndResult(session, result);
}
return new SearchResultList(list);
}
/**
* This method provides object parsing from String and validation.
*/
private <T extends ObjectType> PrismObject<T> updateLoadedObject(GetObjectResult result, Class<T> type,
Collection<SelectorOptions<GetOperationOptions>> options,
Session session) throws SchemaException {
String xml = RUtil.getXmlFromByteArray(result.getFullObject(), getConfiguration().isUseZip());
PrismObject<T> prismObject;
try {
prismObject = getPrismContext().parseObject(xml);
} catch (SchemaException e) {
LOGGER.debug("Couldn't parse object because of schema exception ({}):\nObject: {}", e, xml);
throw e;
}
if (UserType.class.equals(prismObject.getCompileTimeClass())) {
if (SelectorOptions.hasToLoadPath(UserType.F_JPEG_PHOTO, options)) {
//todo improve, use user.hasPhoto flag and take options into account [lazyman]
//this is called only when options contains INCLUDE user/jpegPhoto
Query query = session.getNamedQuery("get.userPhoto");
query.setString("oid", prismObject.getOid());
byte[] photo = (byte[]) query.uniqueResult();
if (photo != null) {
PrismProperty property = prismObject.findOrCreateProperty(UserType.F_JPEG_PHOTO);
property.setRealValue(photo);
}
}
} else if (ShadowType.class.equals(prismObject.getCompileTimeClass())) {
//we store it because provisioning now sends it to repo, but it should be transient
prismObject.removeContainer(ShadowType.F_ASSOCIATION);
LOGGER.debug("Loading definitions for shadow attributes.");
Short[] counts = result.getCountProjection();
Class[] classes = GetObjectResult.EXT_COUNT_CLASSES;
for (int i = 0; i < classes.length; i++) {
if (counts[i] == null || counts[i] == 0) {
continue;
}
applyShadowAttributeDefinitions(classes[i], prismObject, session);
}
LOGGER.debug("Definitions for attributes loaded. Counts: {}", Arrays.toString(counts));
}
validateObjectType(prismObject, type);
return prismObject;
}
private void applyShadowAttributeDefinitions(Class<? extends RAnyValue> anyValueType,
PrismObject object, Session session) throws SchemaException {
PrismContainer attributes = object.findContainer(ShadowType.F_ATTRIBUTES);
Query query = session.getNamedQuery("getDefinition." + anyValueType.getSimpleName());
query.setParameter("oid", object.getOid());
query.setParameter("ownerType", RObjectExtensionType.ATTRIBUTES);
List<Object[]> values = query.list();
if (values == null || values.isEmpty()) {
return;
}
for (Object[] value : values) {
ItemDefinition def;
QName name = RUtil.stringToQName((String) value[0]);
QName type = RUtil.stringToQName((String) value[1]);
switch ((RValueType) value[2]) {
case PROPERTY:
def = new PrismPropertyDefinition(name, type, object.getPrismContext());
break;
case REFERENCE:
def = new PrismReferenceDefinition(name, type, object.getPrismContext());
break;
default:
throw new UnsupportedOperationException("Unsupported value type " + value[2]);
}
Item item = attributes.findItem(def.getName());
if (item.getDefinition() == null) {
item.applyDefinition(def, true);
}
}
}
@Override
public <T extends ObjectType> void modifyObject(Class<T> type, String oid,
Collection<? extends ItemDelta> modifications,
OperationResult result)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
Validate.notNull(modifications, "Modifications must not be null.");
Validate.notNull(type, "Object class in delta must not be null.");
Validate.notEmpty(oid, "Oid must not null or empty.");
Validate.notNull(result, "Operation result must not be null.");
OperationResult subResult = result.createSubresult(MODIFY_OBJECT);
subResult.addParam("type", type.getName());
subResult.addParam("oid", oid);
subResult.addCollectionOfSerializablesAsParam("modifications", modifications);
if (modifications.isEmpty()) {
LOGGER.debug("Modification list is empty, nothing was modified.");
subResult.recordStatus(OperationResultStatus.SUCCESS, "Modification list is empty, nothing was modified.");
return;
}
if (InternalsConfig.encryptionChecks) {
CryptoUtil.checkEncrypted(modifications);
}
if (InternalsConfig.consistencyChecks) {
ItemDelta.checkConsistence(modifications, ConsistencyCheckScope.THOROUGH);
} else {
ItemDelta.checkConsistence(modifications, ConsistencyCheckScope.MANDATORY_CHECKS_ONLY);
}
if (LOGGER.isTraceEnabled()) {
for (ItemDelta modification : modifications) {
if (modification instanceof PropertyDelta<?>) {
PropertyDelta<?> propDelta = (PropertyDelta<?>) modification;
if (propDelta.getPath().equivalent(new ItemPath(ObjectType.F_NAME))) {
Collection<PrismPropertyValue<PolyString>> values = propDelta.getValues(PolyString.class);
for (PrismPropertyValue<PolyString> pval : values) {