DefaultJcrStorageProviderImpl.java
45.2 KB
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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.aemds.guide.storage.api.ArchiveResult
* com.adobe.aemds.guide.storage.api.PurgeMode
* com.adobe.aemds.guide.storage.api.PurgeResult
* com.adobe.aemds.guide.storage.api.ResolveResult
* com.adobe.aemds.guide.storage.api.StorageProvider
* com.adobe.aemds.guide.storage.api.StoreResult
* com.adobe.aemds.guide.storage.exception.NodeManipulationException
* com.adobe.aemds.guide.storage.exception.QueryCreationException
* com.adobe.aemds.guide.storage.exception.QueryExecutionException
* com.adobe.aemds.guide.storage.exception.ResolveException
* com.adobe.aemds.guide.storage.exception.SessionUnavailableException
* com.adobe.aemds.guide.storage.exception.StoreException
* com.adobe.aemfd.docmanager.Document
* javax.jcr.Binary
* javax.jcr.Node
* javax.jcr.NodeIterator
* javax.jcr.PathNotFoundException
* javax.jcr.Property
* javax.jcr.PropertyIterator
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.Value
* javax.jcr.ValueFactory
* javax.jcr.Workspace
* javax.jcr.query.Query
* javax.jcr.query.QueryManager
* javax.jcr.query.QueryResult
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.Service
* org.apache.sling.jcr.api.SlingRepository
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.aemds.guide.storage.impl;
import com.adobe.aemds.guide.storage.api.ArchiveResult;
import com.adobe.aemds.guide.storage.api.PurgeMode;
import com.adobe.aemds.guide.storage.api.PurgeResult;
import com.adobe.aemds.guide.storage.api.ResolveResult;
import com.adobe.aemds.guide.storage.api.StorageProvider;
import com.adobe.aemds.guide.storage.api.StoreResult;
import com.adobe.aemds.guide.storage.exception.NodeManipulationException;
import com.adobe.aemds.guide.storage.exception.QueryCreationException;
import com.adobe.aemds.guide.storage.exception.QueryExecutionException;
import com.adobe.aemds.guide.storage.exception.ResolveException;
import com.adobe.aemds.guide.storage.exception.SessionUnavailableException;
import com.adobe.aemds.guide.storage.exception.StoreException;
import com.adobe.aemfd.docmanager.Document;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.jcr.api.SlingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(immediate=1, metatype=1, label="Default JCR-based Storage Provider", description="JCR-based storage provider service for batch generator.")
@Service(value={StorageProvider.class})
public class DefaultJcrStorageProviderImpl
implements StorageProvider {
public static final String BATCH_STORAGE_ROOT = "/content/fd/batch";
private static final String UNKNOWN_ID = "<Unknown ID>";
private static final String QUERY_TOKEN_SCAN_ROOT = "_ADBE_SCAN_ROOT_";
private static final String BATCH_MARKER_PROPERTY = "_adbe_batch_";
private static final String JCR_CONTENT_NODE = "jcr:content";
private static final String JCR_CREATED_PROPERTY = "jcr:created";
private static final String JCR_DATA_PROPERTY = "jcr:data";
private static final String NODE_TYPE_SLING_FOLDER = "sling:Folder";
private static final Calendar DISTANT_FUTURE = new GregorianCalendar(2099, 11, 31);
private static final long DEFAULT_MAX_QUERY_RESULTS = 10000;
@Reference
protected SlingRepository slingRepository;
protected Map<String, Object> providerConfig = new HashMap<String, Object>();
protected String[] excludedProperties = new String[]{"_adbe_batch_"};
protected String SP_STORAGE_ROOT;
protected String SP_STORAGE_CURRENT;
protected String SP_STORAGE_ARCHIVE;
protected String SP_STORAGE_TRASH;
protected int MAX_CHILD_NODES = 1000;
protected int MAX_NODES_PER_SAVE = 1000;
protected int MAX_NODES_PER_READ = 1000;
protected long DEFAULT_MAX_ARCHIVE_QUERY_RESULTS = 10000;
protected long DEFAULT_MAX_PURGE_QUERY_RESULTS = 10000;
private Logger logger = LoggerFactory.getLogger(DefaultJcrStorageProviderImpl.class);
public DefaultJcrStorageProviderImpl() {
this.SP_STORAGE_ROOT = "/content/fd/batch/" + this.getClass().getSimpleName();
this.initProvider();
}
public DefaultJcrStorageProviderImpl(String storageRoot) {
this.SP_STORAGE_ROOT = "/content/fd/batch/" + storageRoot;
this.initProvider();
}
private void initProvider() {
this.SP_STORAGE_CURRENT = this.SP_STORAGE_ROOT + "/current";
this.SP_STORAGE_ARCHIVE = this.SP_STORAGE_ROOT + "/archive";
this.SP_STORAGE_TRASH = this.SP_STORAGE_ROOT + "/trash";
}
public void configure(Map<String, Object> providerConfig) {
this.providerConfig = providerConfig;
}
public String store(Document doc, Map<String, String> metaData) throws StoreException {
return this.store(doc, metaData, null, true);
}
private String store(Document doc, Map<String, String> metaData, Session jcrSession, boolean autoSave) throws StoreException {
if (doc == null) {
return null;
}
boolean sessionOwner = false;
String storageId = null;
try {
if (jcrSession == null) {
if (autoSave) {
jcrSession = this.getSession();
sessionOwner = true;
} else {
throw new StoreException("Auto-save disabled but no JCR session supplied");
}
}
String pathPrefix = null;
String pathSuffix = null;
String absolutePath = null;
if (metaData != null) {
pathPrefix = metaData.get("PROVIDER_META_DATA_PATH_PREFIX");
pathSuffix = metaData.get("PROVIDER_META_DATA_PATH_SUFFIX");
absolutePath = metaData.get("PROVIDER_META_DATA_ABSOLUTE_PATH");
}
StringBuilder nodePath = new StringBuilder();
if (!this.isEmpty(absolutePath)) {
nodePath.append(absolutePath);
} else {
nodePath.append(this.SP_STORAGE_CURRENT).append("/");
if (!this.isEmpty(pathPrefix)) {
nodePath.append(pathPrefix).append("/");
}
nodePath.append(this.getUniqueRelativePath());
if (!this.isEmpty(pathSuffix)) {
nodePath.append("/").append(pathSuffix);
}
}
storageId = this.saveToNode(doc, metaData, nodePath.toString(), jcrSession, autoSave);
}
catch (Exception ex) {
throw new StoreException(ex);
}
finally {
if (sessionOwner) {
this.logoutSilently(jcrSession);
}
}
return storageId;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public StoreResult store(List<Document> documents, Map<Document, Map<String, String>> metaData) {
LinkedHashMap<Document, String> failedDocuments;
boolean saveSuccessful;
LinkedHashMap<Document, String> storedDocuments;
if (documents == null || documents.size() == 0) {
return null;
}
this.checkAndCompact(documents);
Session jcrSession = this.getSession();
storedDocuments = new LinkedHashMap<Document, String>(documents.size());
failedDocuments = new LinkedHashMap<Document, String>();
saveSuccessful = true;
try {
for (int i = 0; i < documents.size(); i += this.MAX_NODES_PER_SAVE) {
int chunkSize = Math.min(this.MAX_NODES_PER_SAVE, documents.size() - i);
Document[] documentChunk = new Document[chunkSize];
documents.subList(i, i + chunkSize).toArray((T[])documentChunk);
if (i > 0) {
this.logger.debug("Renewing JCR session to store {} documents", (Object)chunkSize);
jcrSession = this.renewSession(jcrSession);
}
saveSuccessful = true;
for (Document doc : documentChunk) {
if (doc == null) continue;
String storageId = null;
String failureReason = null;
try {
storageId = this.store(doc, metaData != null ? metaData.get((Object)doc) : null, jcrSession, false);
}
catch (Exception ex) {
failureReason = ex.toString();
this.logger.warn(failureReason, (Throwable)ex);
}
if (storageId != null) {
storedDocuments.put(doc, storageId);
continue;
}
if (failureReason == null) continue;
failedDocuments.put(doc, failureReason);
}
try {
if (!this.isActive(jcrSession)) continue;
jcrSession.save();
continue;
}
catch (Exception ex) {
saveSuccessful = false;
for (Document doc2 : documentChunk) {
if (failedDocuments.containsKey((Object)doc2)) continue;
failedDocuments.put(doc2, ex.toString());
}
this.logger.error("Exception while saving session, all pending changes will be discarded", (Throwable)ex);
try {
if (!this.isActive(jcrSession)) continue;
jcrSession.refresh(false);
continue;
}
catch (RepositoryException re) {
this.logger.error("Exception while discarding pending changes, the repository may be in an inconsistent state", (Throwable)re);
}
}
}
}
catch (SessionUnavailableException sue) {
this.logger.error("Session unavailable while doing bulk store", (Throwable)sue);
if (documents.size() > storedDocuments.size() + failedDocuments.size()) {
this.logger.error("Session unavailable while doing bulk store, only {}/{} documents were saved to repository", (Object)storedDocuments.size(), (Object)documents.size());
for (Document doc : documents) {
if (doc == null || storedDocuments.containsKey((Object)doc) || failedDocuments.containsKey((Object)doc)) continue;
failedDocuments.put(doc, sue.toString());
}
}
}
finally {
this.logoutSilently(jcrSession);
}
if (!saveSuccessful) {
storedDocuments.clear();
}
StoreResult storeResult = new StoreResult();
storeResult.setStoredDocuments(storedDocuments);
storeResult.setFailedDocuments(failedDocuments);
return storeResult;
}
public boolean isProviderOwned(String storageId) {
return !this.isEmpty(storageId) && this.startsWith(storageId, new String[]{this.SP_STORAGE_CURRENT, this.SP_STORAGE_ARCHIVE});
}
public Document resolve(String storageId, boolean searchArchive) throws ResolveException {
return this.resolve(storageId, searchArchive, null);
}
private Document resolve(String storageId, boolean searchArchive, Session jcrSession) throws ResolveException {
Document resolvedDoc;
block16 : {
if (this.isEmpty(storageId)) {
return null;
}
if (!this.isProviderOwned(storageId)) {
throw new ResolveException("storageId " + storageId + " does not belong to this storage provider");
}
boolean sessionOwner = false;
if (jcrSession == null) {
jcrSession = this.getSession();
sessionOwner = true;
}
storageId = storageId.trim();
resolvedDoc = null;
try {
Node storageNode = jcrSession.getNode(storageId);
resolvedDoc = new Document(storageId + "/" + "jcr:content");
PropertyIterator propertyIterator = storageNode.getProperties();
while (propertyIterator.hasNext()) {
Property property = propertyIterator.nextProperty();
if (property == null || this.isExcludedProperty(property.getName()) || property.getType() != 1 || this.isEmpty(property.getString())) continue;
resolvedDoc.setAttribute(property.getName(), (Object)property.getString());
this.logger.debug("Copied property {} from node {} to resolved document", (Object)property.getName(), (Object)storageId);
}
}
catch (PathNotFoundException pnfe) {
if (searchArchive) {
if (storageId.startsWith(this.SP_STORAGE_ARCHIVE)) {
throw new ResolveException((Exception)pnfe);
}
String archiveStorageId = storageId.replace(this.SP_STORAGE_CURRENT, this.SP_STORAGE_ARCHIVE);
try {
resolvedDoc = this.resolve(archiveStorageId, false, jcrSession);
break block16;
}
catch (Exception ex) {
throw new ResolveException(ex);
}
}
throw new ResolveException((Exception)pnfe);
}
catch (RepositoryException re) {
throw new ResolveException((Exception)re);
}
finally {
if (sessionOwner) {
this.logoutSilently(jcrSession);
}
}
}
return resolvedDoc;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public ResolveResult resolve(List<String> storageIDs, boolean searchArchive) {
LinkedHashMap<String, Document> resolvedIDs;
LinkedHashMap<String, String> failedIDs;
if (storageIDs == null || storageIDs.size() == 0) {
return null;
}
this.checkAndCompact(storageIDs);
Session jcrSession = this.getSession();
resolvedIDs = new LinkedHashMap<String, Document>(storageIDs.size());
failedIDs = new LinkedHashMap<String, String>();
try {
for (int i = 0; i < storageIDs.size(); i += this.MAX_NODES_PER_READ) {
int chunkSize = Math.min(this.MAX_NODES_PER_READ, storageIDs.size() - i);
String[] storageIdChunk = new String[chunkSize];
storageIDs.subList(i, i + chunkSize).toArray(storageIdChunk);
if (i > 0) {
this.logger.debug("Renewing JCR session to resolve {} storage IDs", (Object)chunkSize);
jcrSession = this.renewSession(jcrSession);
}
for (String storageId : storageIdChunk) {
if (this.isEmpty(storageId)) continue;
Document resolvedDoc = null;
String failureReason = null;
try {
resolvedDoc = this.resolve(storageId, searchArchive, jcrSession);
}
catch (Exception ex) {
failureReason = ex.toString();
this.logger.warn(failureReason, (Throwable)ex);
}
if (resolvedDoc != null) {
resolvedIDs.put(storageId, resolvedDoc);
continue;
}
if (failureReason == null) continue;
failedIDs.put(storageId, failureReason);
}
}
}
catch (SessionUnavailableException sue) {
this.logger.error("Session unavailable while doing bulk resolve", (Throwable)sue);
if (storageIDs.size() > resolvedIDs.size() + failedIDs.size()) {
this.logger.error("Session unavailable while doing bulk resolve, only {}/{} documents were read from repository", (Object)resolvedIDs.size(), (Object)storageIDs.size());
for (String storageId : storageIDs) {
if (this.isEmpty(storageId) || resolvedIDs.containsKey(storageId) || failedIDs.containsKey(storageId)) continue;
failedIDs.put(storageId, sue.toString());
}
}
}
finally {
this.logoutSilently(jcrSession);
}
ResolveResult resolveResult = new ResolveResult();
resolveResult.setResolvedIDs(resolvedIDs);
resolveResult.setFailedIDs(failedIDs);
return resolveResult;
}
public ArchiveResult archive(String batchId, Query query) {
String[] queryFeatures = this.getQueryFeatures(query);
return this.archive(batchId, queryFeatures[0], queryFeatures[1], false);
}
public ArchiveResult archive(String batchId, Calendar cutoff) {
String jcrQuery = null;
try {
jcrQuery = this.createQuery(cutoff);
}
catch (QueryCreationException qce) {
this.logger.error("Exception while creating query, aborted archival for batch: " + batchId + " with cutoff: " + cutoff, (Throwable)qce);
}
if (jcrQuery == null) {
ArchiveResult archiveResult = new ArchiveResult();
archiveResult.setBatchId(batchId);
archiveResult.setArchivedIDs(new HashMap(0));
archiveResult.setFailedIDs(new HashMap(0));
return archiveResult;
}
ArchiveResult archiveResult = this.archive(batchId, jcrQuery, "JCR-SQL2", true);
return archiveResult;
}
private ArchiveResult archive(String batchId, String jcrQuery, String queryLanguage, boolean resolveQuery) {
String scanRoot = batchId == null ? this.SP_STORAGE_CURRENT : this.SP_STORAGE_CURRENT + "/" + batchId;
List<Map<String, String>> moveResult = this.doMove(batchId, jcrQuery, queryLanguage, resolveQuery, new String[]{scanRoot}, this.SP_STORAGE_ARCHIVE);
ArchiveResult archiveResult = new ArchiveResult();
archiveResult.setBatchId(batchId);
archiveResult.setArchivedIDs(moveResult.get(0));
archiveResult.setFailedIDs(moveResult.get(1));
return archiveResult;
}
public PurgeResult purge(String batchId, Query query, PurgeMode purgeMode) {
String[] queryFeatures = this.getQueryFeatures(query);
return this.purge(batchId, queryFeatures[0], queryFeatures[1], false, purgeMode);
}
public PurgeResult purge(String batchId, Calendar cutoff, PurgeMode purgeMode) {
PurgeResult purgeResult;
String jcrQuery = null;
try {
jcrQuery = this.createQuery(cutoff);
}
catch (QueryCreationException qce) {
this.logger.error("Exception while creating query, aborted purge for batch: " + batchId + " with cutoff: " + cutoff, (Throwable)qce);
}
if (jcrQuery == null) {
purgeResult = new PurgeResult();
purgeResult.setBatchId(batchId);
purgeResult.setPurgedIDs(new ArrayList(0));
purgeResult.setFailedIDs(new HashMap(0));
} else {
purgeResult = this.purge(batchId, jcrQuery, "JCR-SQL2", true, purgeMode);
}
return purgeResult;
}
private PurgeResult purge(String batchId, String jcrQuery, String queryLanguage, boolean resolveQuery, PurgeMode purgeMode) {
String[] scanRoots = new String[]{};
if (purgeMode == null) {
purgeMode = PurgeMode.ARCHIVE_ONLY;
}
switch (purgeMode) {
case CURRENT_ONLY: {
String[] arrstring = new String[1];
arrstring[0] = this.SP_STORAGE_CURRENT + (batchId == null ? "" : new StringBuilder().append("/").append(batchId).toString());
scanRoots = arrstring;
break;
}
case ARCHIVE_ONLY: {
String[] arrstring = new String[1];
arrstring[0] = this.SP_STORAGE_ARCHIVE + (batchId == null ? "" : new StringBuilder().append("/").append(batchId).toString());
scanRoots = arrstring;
break;
}
case CURRENT_AND_ARCHIVE: {
String[] arrstring = new String[2];
arrstring[0] = this.SP_STORAGE_CURRENT + (batchId == null ? "" : new StringBuilder().append("/").append(batchId).toString());
arrstring[1] = this.SP_STORAGE_ARCHIVE + (batchId == null ? "" : new StringBuilder().append("/").append(batchId).toString());
scanRoots = arrstring;
}
}
List<Map<String, String>> moveResult = this.doMove(batchId, jcrQuery, queryLanguage, resolveQuery, scanRoots, this.SP_STORAGE_TRASH);
PurgeResult purgeResult = new PurgeResult();
purgeResult.setBatchId(batchId);
purgeResult.setPurgedIDs(new ArrayList<String>(moveResult.get(0).keySet()));
purgeResult.setFailedIDs(moveResult.get(1));
return purgeResult;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
private List<Map<String, String>> doMove(String batchId, String jcrQuery, String queryLanguage, boolean resolveQuery, String[] scanRoots, String destination) {
String OPERATION;
long providerMaxQueryResults;
block44 : {
Object maxQueryResults;
OPERATION = null;
providerMaxQueryResults = -1;
if (!this.isEmpty(destination) && destination.equalsIgnoreCase(this.SP_STORAGE_ARCHIVE)) {
OPERATION = "archive";
providerMaxQueryResults = this.DEFAULT_MAX_ARCHIVE_QUERY_RESULTS;
maxQueryResults = this.providerConfig.get("PROVIDER_MAX_ARCHIVE_QUERY_RESULTS");
if (maxQueryResults != null) {
try {
if (maxQueryResults instanceof Integer) {
providerMaxQueryResults = ((Integer)maxQueryResults).intValue();
break block44;
}
if (maxQueryResults instanceof Long) {
providerMaxQueryResults = (Long)maxQueryResults;
break block44;
}
if (maxQueryResults instanceof String) {
providerMaxQueryResults = Long.valueOf((String)maxQueryResults);
break block44;
}
this.logger.info("Invalid value specified for MAX_ARCHIVE_QUERY_RESULTS, defaulting to: " + this.DEFAULT_MAX_ARCHIVE_QUERY_RESULTS);
}
catch (NumberFormatException nfe) {
this.logger.info("Invalid value specified for MAX_ARCHIVE_QUERY_RESULTS, defaulting to: " + this.DEFAULT_MAX_ARCHIVE_QUERY_RESULTS);
}
}
} else if (!this.isEmpty(destination) && destination.equalsIgnoreCase(this.SP_STORAGE_TRASH)) {
OPERATION = "purge";
providerMaxQueryResults = this.DEFAULT_MAX_PURGE_QUERY_RESULTS;
maxQueryResults = this.providerConfig.get("PROVIDER_MAX_PURGE_QUERY_RESULTS");
if (maxQueryResults != null) {
try {
if (maxQueryResults instanceof Integer) {
providerMaxQueryResults = ((Integer)maxQueryResults).intValue();
break block44;
}
if (maxQueryResults instanceof Long) {
providerMaxQueryResults = (Long)maxQueryResults;
break block44;
}
if (maxQueryResults instanceof String) {
providerMaxQueryResults = Long.valueOf((String)maxQueryResults);
break block44;
}
this.logger.info("Invalid value specified for MAX_PURGE_QUERY_RESULTS, defaulting to: " + this.DEFAULT_MAX_PURGE_QUERY_RESULTS);
}
catch (NumberFormatException nfe) {
this.logger.info("Invalid value specified for MAX_PURGE_QUERY_RESULTS, defaulting to: " + this.DEFAULT_MAX_PURGE_QUERY_RESULTS);
}
}
} else {
throw new IllegalStateException("Invalid move destination: " + destination);
}
}
LinkedHashMap movedIDs = new LinkedHashMap();
LinkedHashMap failedIDs = new LinkedHashMap();
boolean moveSuccessful = true;
String moveQuery = null;
Session jcrSession = null;
for (String scanRoot : scanRoots) {
moveQuery = jcrQuery;
if (resolveQuery) {
HashMap<String, Object> tokenReplacements = new HashMap<String, Object>();
tokenReplacements.put("_ADBE_SCAN_ROOT_", scanRoot);
try {
moveQuery = this.resolveQuery(moveQuery, tokenReplacements);
}
catch (QueryCreationException qce) {
this.logger.error("Exception while resolving query, aborting " + OPERATION + " of batch " + batchId + " with query '" + moveQuery + "'", (Throwable)qce);
continue;
}
}
boolean exhausted = false;
long nodesRemaining = providerMaxQueryResults;
int chunkId = 0;
while (!exhausted && nodesRemaining > 0) {
Object[] arrobject = new Object[]{OPERATION, batchId, moveQuery, ++chunkId};
this.logger.debug("Processing {} of batch {} with query {}, chunk:{}", arrobject);
LinkedHashMap<String, String> chunkMovedIDs = new LinkedHashMap<String, String>();
LinkedHashMap<String, String> chunkFailedIDs = new LinkedHashMap<String, String>();
try {
StringBuilder logMessage;
jcrSession = jcrSession == null ? this.getSession() : this.renewSession(jcrSession);
NodeIterator selectedNodes = this.executeQuery(moveQuery, queryLanguage, Math.min(nodesRemaining, 10000), jcrSession);
int movedNodeCount = 0;
int selectedNodeCount = 0;
while (selectedNodes.hasNext()) {
Node selectedNode = selectedNodes.nextNode();
++selectedNodeCount;
if (!resolveQuery && (selectedNode.getPath().indexOf(scanRoot) == -1 || !selectedNode.hasProperty("_adbe_batch_"))) continue;
String selectedPath = null;
String movedPath = null;
try {
selectedPath = selectedNode.getPath();
Node movedNode = this.moveNode(selectedNode, destination, jcrSession);
movedPath = movedNode.getPath();
chunkMovedIDs.put(selectedPath, movedPath);
}
catch (Exception ex) {
chunkFailedIDs.put(selectedPath == null ? this.getRandomID() : selectedPath, ex.toString());
this.logger.error("Error while moving selected node to destination path", (Throwable)ex);
}
if (++movedNodeCount < this.MAX_NODES_PER_SAVE) continue;
if (this.isActive(jcrSession)) {
jcrSession.save();
continue;
}
this.logger.error("Session invalidated before pending changes could be saved, aborting {} of chunk {} of batch {} with query '{}'.", new Object[]{OPERATION, chunkId, batchId, moveQuery});
moveSuccessful = false;
break;
}
if (selectedNodeCount > 0) {
logMessage = new StringBuilder();
logMessage.append("Query '").append(moveQuery).append("' returned ").append(selectedNodeCount).append(" nodes, of which ").append(movedNodeCount).append(moveSuccessful ? " will be moved to the specified destination." : " were to be moved to the specified destination but will not be processed further because the session has been invalidated.");
if ((nodesRemaining -= (long)selectedNodeCount) > 0) {
logMessage.append(" It will be executed again to process at most ").append(nodesRemaining).append(" remaining nodes.");
} else {
logMessage.append(" It will not be executed again as ").append(providerMaxQueryResults).append(" nodes have already been processed.");
}
this.logger.debug(logMessage.toString());
} else {
logMessage = new StringBuilder();
logMessage.append("Query '").append(moveQuery).append("' returned no results,");
if (nodesRemaining > 0) {
logMessage.append(" therefore it will not be executed again even though there are ").append(nodesRemaining).append(" nodes remaining.");
} else {
logMessage.append(" and it will not be executed again as ").append(providerMaxQueryResults).append(" nodes have already been processed.");
}
this.logger.debug(logMessage.toString());
exhausted = true;
}
if (moveSuccessful) {
if (this.isActive(jcrSession)) {
jcrSession.save();
} else {
this.logger.error("Session invalidated before pending changes could be saved, aborting {} of chunk {} of batch {} with query '{}'", new Object[]{OPERATION, chunkId, batchId, moveQuery});
moveSuccessful = false;
}
} else {
this.logger.debug("Processing of chunk {} of batch {} has already been marked unsuccessful due to prior failures while saving pending changes.", new Object[]{chunkId, batchId});
}
}
catch (QueryExecutionException qee) {
this.logger.error("Exception while executing query, aborting " + OPERATION + "of chunk " + chunkId + " of batch " + batchId + " with query '" + moveQuery + "'", (Throwable)qee);
moveSuccessful = false;
}
catch (Exception ex) {
this.logger.error("Unexpected exception, aborting " + OPERATION + "of chunk " + chunkId + " of batch " + batchId + " with query '" + moveQuery + "'", (Throwable)ex);
moveSuccessful = false;
}
try {
if (moveSuccessful) {
movedIDs.putAll(chunkMovedIDs);
failedIDs.putAll(chunkFailedIDs);
continue;
}
this.logger.error("Processing of chunk {} of batch {} unsuccessful, discarding all pending changes", (Object)chunkId, (Object)batchId);
if (!this.isActive(jcrSession)) continue;
jcrSession.refresh(false);
continue;
}
catch (RepositoryException re) {
this.logger.error("Exception while discarding pending changes in chunk " + chunkId + " of batch " + batchId + ", the repository may be in an inconsistent state", (Throwable)re);
continue;
}
finally {
this.logoutSilently(jcrSession);
continue;
}
}
}
ArrayList<Map<String, String>> moveResult = new ArrayList<Map<String, String>>(2);
moveResult.add(movedIDs);
moveResult.add(failedIDs);
return moveResult;
}
protected boolean isExcludedProperty(String propertyName) {
if (this.isEmpty(propertyName)) {
return true;
}
return this.startsWith(propertyName, this.excludedProperties);
}
private String[] getQueryFeatures(Query query) {
String[] queryFeatures = new String[2];
if (query == null) {
queryFeatures[0] = "";
queryFeatures[1] = "JCR-SQL2";
} else {
queryFeatures[0] = query.getStatement();
queryFeatures[1] = query.getLanguage();
}
return queryFeatures;
}
private String createQuery(Calendar cutoff) throws QueryCreationException {
return this.createQuery(cutoff, true);
}
private String createQuery(Calendar cutoff, boolean selectOlder) throws QueryCreationException {
if (cutoff == null) {
cutoff = DISTANT_FUTURE;
}
StringBuilder query = new StringBuilder().append("SELECT * FROM [nt:unstructured] AS NODE ").append("WHERE ISDESCENDANTNODE('_ADBE_SCAN_ROOT_') ").append("AND NODE._adbe_batch_ IS NOT null AND ").append("[jcr:created]");
if (selectOlder) {
query.append(" <= ");
} else {
query.append(" > ");
}
Session jcrSession = null;
try {
jcrSession = this.getSession();
Value value = jcrSession.getValueFactory().createValue(cutoff);
query.append("CAST('" + value.getString() + "' AS DATE)");
String string = query.toString();
return string;
}
catch (Exception ex) {
throw new QueryCreationException(ex);
}
finally {
this.logoutSilently(jcrSession);
}
}
private String resolveQuery(String jcrQuery, Map<String, Object> tokenReplacements) throws QueryCreationException {
if (this.isEmpty(jcrQuery)) {
throw new QueryCreationException("Invalid query to resolve using parameters: " + tokenReplacements);
}
if (tokenReplacements == null || tokenReplacements.size() == 0) {
return jcrQuery;
}
String scanRoot = (String)tokenReplacements.get("_ADBE_SCAN_ROOT_");
if (!this.isEmpty(scanRoot)) {
jcrQuery = jcrQuery.replaceAll("_ADBE_SCAN_ROOT_", scanRoot);
}
return jcrQuery;
}
private NodeIterator executeQuery(String jcrQuery, String queryLanguage, long maxQueryResults, Session jcrSession) throws QueryExecutionException {
if (this.isEmpty(jcrQuery)) {
throw new QueryExecutionException("Cannot execute null or empty query");
}
if (this.isEmpty(queryLanguage)) {
queryLanguage = "JCR-SQL2";
}
try {
QueryManager queryManager = jcrSession.getWorkspace().getQueryManager();
Query query = queryManager.createQuery(jcrQuery, queryLanguage);
query.setLimit(maxQueryResults);
QueryResult queryResult = query.execute();
return queryResult.getNodes();
}
catch (Exception ex) {
throw new QueryExecutionException(ex);
}
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
private Node moveNode(Node node, String destination, Session jcrSession) throws NodeManipulationException {
if (node == null) return null;
if (this.isEmpty(destination)) {
return null;
}
boolean sessionOwner = false;
boolean moveSuccessful = true;
Node targetNode = null;
try {
String srcNodePath = node.getPath();
String srcNodeName = node.getName();
if (jcrSession == null) {
this.logger.info("Session not provided, getting new session to move node {}" + srcNodePath);
jcrSession = this.getSession();
sessionOwner = true;
}
Node srcParentNode = node.getParent();
String srcParentNodePath = srcParentNode.getPath();
String targetParentNodePath = null;
if (srcParentNodePath.indexOf(this.SP_STORAGE_CURRENT) != -1) {
targetParentNodePath = srcParentNodePath.replace(this.SP_STORAGE_CURRENT, destination);
} else if (srcParentNodePath.indexOf(this.SP_STORAGE_ARCHIVE) != -1) {
targetParentNodePath = srcParentNodePath.replace(this.SP_STORAGE_ARCHIVE, destination);
}
if (targetParentNodePath == null) throw new NodeManipulationException("Invalid destination: " + targetParentNodePath + " for node: " + srcNodePath);
if (targetParentNodePath.equals(srcParentNodePath)) {
throw new NodeManipulationException("Invalid destination: " + targetParentNodePath + " for node: " + srcNodePath);
}
if (!this.makePath(targetParentNodePath, jcrSession)) {
throw new NodeManipulationException("Error creating destination path: " + targetParentNodePath + " for node: " + srcNodePath);
}
String targetNodePath = targetParentNodePath + "/" + srcNodeName;
jcrSession.move(srcNodePath, targetNodePath);
targetNode = jcrSession.getNode(targetNodePath);
this.removeIfEmpty(srcParentNode, jcrSession);
if (!sessionOwner) return targetNode;
if (this.isActive(jcrSession)) {
jcrSession.save();
return targetNode;
}
this.logger.error("Session invalidated before pending changes could be saved, aborting move of node: {}", (Object)srcNodePath);
moveSuccessful = false;
return targetNode;
}
catch (NodeManipulationException ex) {
moveSuccessful = false;
throw ex;
}
catch (Exception ex) {
moveSuccessful = false;
throw new NodeManipulationException(ex);
}
finally {
if (sessionOwner) {
try {
if (!moveSuccessful) {
jcrSession.refresh(false);
}
}
catch (RepositoryException re) {
this.logger.error("Exception while discarding pending changes, the repository may be in an inconsistent state", (Throwable)re);
}
finally {
this.logoutSilently(jcrSession);
}
}
}
}
private boolean makePath(String absPath, Session jcrSession) throws RepositoryException {
if (this.isEmpty(absPath)) {
return false;
}
this.logger.debug("Making path: {}", (Object)absPath);
if (absPath.startsWith("/")) {
absPath = absPath.substring(1);
}
String[] subPaths = absPath.split("/");
Node currentNode = jcrSession.getRootNode();
for (String subPath : subPaths) {
if (!currentNode.hasNode(subPath)) {
this.logger.debug("Create child node: {}", (Object)subPath);
currentNode = currentNode.addNode(subPath, "sling:Folder");
continue;
}
this.logger.debug("Child node: {} already exists", (Object)subPath);
currentNode = currentNode.getNode(subPath);
}
return true;
}
private void removeIfEmpty(Node node, Session jcrSession) throws RepositoryException {
if (!node.getNodes().hasNext()) {
Node parentNode = node.getParent();
jcrSession.removeItem(node.getPath());
this.removeIfEmpty(parentNode, jcrSession);
}
}
private String saveToNode(Document doc, Map<String, String> metaData, String nodePath, Session jcrSession, boolean autoSave) throws Exception {
if (doc == null || nodePath == null || nodePath.trim().length() == 0) {
return null;
}
int lastPathSepIndex = nodePath.lastIndexOf("/");
String desiredParentPath = nodePath.substring(0, lastPathSepIndex);
String desiredNodeName = nodePath.substring(lastPathSepIndex + 1);
if (!this.makePath(desiredParentPath, jcrSession)) {
throw new NodeManipulationException("Error creating path: " + desiredParentPath);
}
Node parentNode = jcrSession.getNode(desiredParentPath);
Node desiredNode = parentNode.addNode(desiredNodeName, "{http://www.jcp.org/jcr/nt/1.0}unstructured");
desiredNode.setProperty("jcr:created", Calendar.getInstance());
for (String excludedProperty : this.excludedProperties) {
desiredNode.setProperty(excludedProperty, "");
}
if (metaData != null) {
for (Map.Entry<String, String> entry : metaData.entrySet()) {
desiredNode.setProperty(entry.getKey(), entry.getValue());
}
}
Node resourceNode = desiredNode.addNode("jcr:content", "{http://www.jcp.org/jcr/nt/1.0}resource");
Binary documentData = jcrSession.getValueFactory().createBinary(doc.getInputStream());
resourceNode.setProperty("jcr:data", documentData);
if (autoSave) {
jcrSession.save();
}
this.logger.debug("Default storage provider saved document to {}", (Object)nodePath);
return nodePath;
}
private Session getSession() {
Session jcrSession = null;
try {
jcrSession = this.slingRepository.loginService(null, null);
}
catch (RepositoryException re) {
this.logger.error("Exception while getting a session", (Throwable)re);
throw new SessionUnavailableException((Exception)re);
}
return jcrSession;
}
private Session renewSession(Session oldSession) {
this.logoutSilently(oldSession);
return this.getSession();
}
private boolean isActive(Session jcrSession) {
return jcrSession != null && jcrSession.isLive();
}
private boolean isEmpty(String s) {
return s == null || s.trim().length() == 0;
}
private void logoutSilently(Session jcrSession) {
try {
if (this.isActive(jcrSession)) {
jcrSession.logout();
this.logger.debug("Logged out of session " + (Object)jcrSession);
} else {
this.logger.info("Cannot log out of invalid session");
}
}
catch (Exception ex) {
this.logger.error("Exception while logging out of session, check for session leaks", (Throwable)ex);
}
}
private String getUniqueRelativePath() {
Calendar calendar = Calendar.getInstance();
StringBuilder uniqueRelativePath = new StringBuilder().append(calendar.get(1)).append("/").append(calendar.get(2) + 1).append("/").append(calendar.get(5)).append("/").append(calendar.get(11)).append("/").append(calendar.get(12)).append("/").append(calendar.get(13)).append("/").append(calendar.get(14)).append("/").append(UUID.randomUUID());
return uniqueRelativePath.toString();
}
private boolean startsWith(String s, String[] prefixes) {
if (this.isEmpty(s)) {
return false;
}
if (prefixes == null || prefixes.length == 0) {
return true;
}
for (String prefix : prefixes) {
if (prefix == null) {
return true;
}
if (!s.startsWith(prefix)) continue;
return true;
}
return false;
}
private <T> List<T> checkAndCompact(List<T> list) {
if (list == null) {
return null;
}
for (int i = 0; i < list.size(); ++i) {
T element = list.get(i);
if (element != null && (!(element instanceof String) || !this.isEmpty((String)element))) continue;
list.remove(i);
}
return list;
}
private String getRandomID() {
return "<Unknown ID>_" + UUID.randomUUID();
}
protected void bindSlingRepository(SlingRepository slingRepository) {
this.slingRepository = slingRepository;
}
protected void unbindSlingRepository(SlingRepository slingRepository) {
if (this.slingRepository == slingRepository) {
this.slingRepository = null;
}
}
}