Scene7ImportServiceImpl.java
22.8 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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.day.cq.search.Predicate
* com.day.cq.search.PredicateGroup
* com.day.cq.search.Query
* com.day.cq.search.QueryBuilder
* com.day.cq.search.result.Hit
* com.day.cq.search.result.SearchResult
* javax.jcr.Node
* javax.jcr.NodeIterator
* javax.jcr.RepositoryException
* javax.jcr.Session
* org.apache.commons.lang.StringUtils
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Properties
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.PropertyUnbounded
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.Service
* org.apache.sling.api.resource.PersistableValueMap
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.commons.osgi.OsgiUtil
* org.apache.sling.event.jobs.Job
* org.apache.sling.event.jobs.JobManager
* org.apache.sling.event.jobs.Queue
* org.apache.sling.event.jobs.Statistics
* org.apache.sling.jcr.api.SlingRepository
* org.apache.sling.jcr.resource.JcrResourceResolverFactory
* org.osgi.service.component.ComponentContext
* org.osgi.service.event.EventAdmin
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.dam.scene7.impl.importer;
import com.day.cq.dam.scene7.api.S7Config;
import com.day.cq.dam.scene7.api.Scene7Service;
import com.day.cq.dam.scene7.api.constants.Scene7AssetType;
import com.day.cq.dam.scene7.api.importer.LockAssetUtils;
import com.day.cq.dam.scene7.api.importer.Scene7ImportService;
import com.day.cq.dam.scene7.api.model.Scene7Asset;
import com.day.cq.dam.scene7.impl.importer.ImportJobUtils;
import com.day.cq.search.Predicate;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.Hit;
import com.day.cq.search.result.SearchResult;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.PersistableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.event.jobs.Job;
import org.apache.sling.event.jobs.JobManager;
import org.apache.sling.event.jobs.Queue;
import org.apache.sling.event.jobs.Statistics;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.JcrResourceResolverFactory;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(metatype=1, label="%cq.dam.scene7.importservice.name", description="%cq.dam.scene7.importservice.desc")
@Service
@Properties(value={@Property(name="cq.dam.scene7.importservice.excludeassets", description="%cq.dam.scene7.importservice.excludeassets.description", value={"Fxg"}, unbounded=PropertyUnbounded.ARRAY)})
public class Scene7ImportServiceImpl
implements Scene7ImportService {
private static final Logger LOG = LoggerFactory.getLogger(Scene7ImportServiceImpl.class);
private static final int UNRECOVERABLE_ERROR_STOP_COUNT = 5;
static final String SCR_PROP_NAME_EXCLUDE_ASSETS = "cq.dam.scene7.importservice.excludeassets";
static final String[] SCR_PROP_DEFAULT_EXCLUDE_ASSETS = new String[]{"Fxg"};
private static Map<String, Boolean> importsInProgress = new HashMap<String, Boolean>();
private String[] excludedAssets;
private HashSet<String> excludedAssetsSet;
@Reference
private EventAdmin eventAdmin;
@Reference
private JobManager slingJobManager;
@Reference
private Scene7Service scene7Service;
@Reference
private SlingRepository slingRepository;
@Reference
private JcrResourceResolverFactory resolverFactory;
@Reference
private QueryBuilder queryBuilder;
@Reference
private LockAssetUtils lockAssetUtils;
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@Override
public void importAssets(final S7Config s7Config) {
if (s7Config != null) {
try {
String importQueueTopic = s7Config.get("importQueueTopic");
if (StringUtils.isEmpty((String)importQueueTopic)) {
LOG.error("Cannot find a topic for the Scene7 import queue for configuration " + s7Config.getCloudConfigPath() + ". Exiting import process.");
return;
}
Map<String, Boolean> map = importsInProgress;
synchronized (map) {
block39 : {
Boolean importInProgress = importsInProgress.get(s7Config.getCloudConfigPath());
if (importInProgress == null || !Boolean.TRUE.equals(importInProgress)) break block39;
LOG.warn("Import already in progress!");
return;
}
importsInProgress.put(s7Config.getCloudConfigPath(), Boolean.TRUE);
}
LOG.info("Started Scene7 import process");
String rootPath = s7Config.getRootPath();
List<Scene7Asset> assets = this.scene7Service.searchAssets(rootPath, true, true, null, null, null, null, s7Config);
HashSet<String> ignoredAssetHandles = new HashSet<String>();
ArrayList<Scene7Asset> containerAssets = new ArrayList<Scene7Asset>();
Iterator<Scene7Asset> assetIterator = assets.iterator();
int assetsToImport = 0;
String adhocFolder = s7Config.getAdhocFolder();
if (!adhocFolder.endsWith("/")) {
adhocFolder = adhocFolder + "/";
}
while (assetIterator.hasNext()) {
Scene7Asset asset = assetIterator.next();
if (this.excludedAssetsSet.contains(asset.getAssetType().getValue())) {
assetIterator.remove();
continue;
}
String assetFolder = asset.getFolder();
if (assetFolder != null && assetFolder.startsWith(adhocFolder)) {
assetIterator.remove();
continue;
}
if (asset.getAssetType().equals((Object)Scene7AssetType.MBR_SET)) {
assetIterator.remove();
continue;
}
if (!this.hasAssociatedAssets(asset) || (asset = this.scene7Service.getAssociatedAssets(asset, s7Config)).getSubAssets().size() <= 0) continue;
if (this.importContainerAsset(asset)) {
containerAssets.add(asset);
}
assetIterator.remove();
for (Scene7Asset subAsset : asset.getSubAssets()) {
ignoredAssetHandles.add(subAsset.getAssetHandle());
}
}
LOG.debug("Preparing to import {} assets, out of which {} container assets.", (Object)assetsToImport, (Object)containerAssets.size());
Queue importQueue = ImportJobUtils.getImportJobQueue(s7Config, this.slingJobManager);
if (importQueue != null) {
importQueue.getStatistics().reset();
}
for (Scene7Asset asset2 : containerAssets) {
if (ImportJobUtils.isImportQueueSuspended(s7Config, this.slingJobManager)) break;
assetsToImport = this.importAsset(asset2, s7Config, assetsToImport);
}
for (Scene7Asset asset2 : assets) {
if (ignoredAssetHandles.contains(asset2.getAssetHandle())) continue;
if (ImportJobUtils.isImportQueueSuspended(s7Config, this.slingJobManager)) break;
assetsToImport = this.importAsset(asset2, s7Config, assetsToImport);
}
if (assetsToImport > 0 && !ImportJobUtils.isImportQueueSuspended(s7Config, this.slingJobManager)) {
final int totalAssetsToImport = assetsToImport;
Runnable jobTopicChecker = new Runnable(){
@Override
public void run() {
boolean finished = false;
int errorCount = 0;
while (!finished) {
try {
Queue importQueue = ImportJobUtils.getImportJobQueue(s7Config, Scene7ImportServiceImpl.this.slingJobManager);
long totalJobs = 0;
Statistics queueStatistics = null;
if (importQueue != null && (queueStatistics = importQueue.getStatistics()) != null) {
totalJobs = queueStatistics.getNumberOfProcessedJobs();
}
LOG.debug("Total Processed Jobs={}", (Object)totalJobs);
boolean isSuspended = ImportJobUtils.isImportQueueSuspended(s7Config, Scene7ImportServiceImpl.this.slingJobManager);
Object[] arrobject = new Object[3];
arrobject[0] = totalJobs;
arrobject[1] = importQueue == null;
arrobject[2] = isSuspended;
LOG.debug("Scene7 import queue checker status: totalProcessedJobs={}, null import queue={}, queue suspended={}", arrobject);
if (totalJobs >= (long)totalAssetsToImport || importQueue == null || isSuspended) {
finished = true;
if (importQueue != null) {
importQueue.getStatistics().reset();
}
} else {
Thread.sleep(1000);
}
}
catch (Exception e) {
LOG.error("Error while waiting for the import process to finish!", (Throwable)e);
++errorCount;
}
if (errorCount < 5) continue;
LOG.error("Got more than 5 exceptions while waiting for the import process to finish, terminating waiting thread!");
finished = true;
}
}
};
Thread queueMonitor = new Thread(jobTopicChecker);
queueMonitor.start();
queueMonitor.join();
}
this.deleteUntouchedAssets(s7Config);
this.deleteEmptyFolders(s7Config);
this.unmarkProcessedFlag(s7Config);
}
catch (Exception e) {
LOG.error("Error while performing import finish operations!", (Throwable)e);
}
finally {
Map<String, Boolean> e = importsInProgress;
synchronized (e) {
importsInProgress.put(s7Config.getCloudConfigPath(), Boolean.FALSE);
LOG.info("Finished Scene7 import process");
}
}
}
LOG.error("Null Scene7 configuration provided");
}
private boolean hasAssociatedAssets(Scene7Asset scene7Asset) {
Scene7AssetType s7AssetType = scene7Asset.getAssetType();
return s7AssetType.equals((Object)Scene7AssetType.TEMPLATE) || s7AssetType.equals((Object)Scene7AssetType.VIDEO) || s7AssetType.equals((Object)Scene7AssetType.MASTER_VIDEO) || s7AssetType.equals((Object)Scene7AssetType.CATALOG);
}
private boolean importContainerAsset(Scene7Asset scene7Asset) {
return !scene7Asset.getAssetType().equals((Object)Scene7AssetType.CATALOG);
}
private int importAsset(Scene7Asset asset, S7Config s7Config, int assetsToImport) {
try {
HashMap<String, Object> jobProps = new HashMap<String, Object>();
jobProps.put("scene7Asset", asset);
jobProps.put("scene7Config", s7Config.getCloudConfigPath());
jobProps.put("event.job.retries", 0);
this.slingJobManager.addJob(s7Config.getImportQueueTopic(), jobProps);
++assetsToImport;
}
catch (Exception e) {
LOG.error("Unable to create asset import folder. Skipping import of asset " + asset.getName(), (Throwable)e);
}
return assetsToImport;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
private void unmarkProcessedFlag(S7Config s7Config) {
block19 : {
ResourceResolver rr = null;
Session session = null;
try {
session = this.slingRepository.loginService("scene7assetservice", null);
rr = this.resolverFactory.getResourceResolver(session);
if (session == null) break block19;
HashMap<String, String> map = new HashMap<String, String>();
map.put("path", s7Config.getTargetPath());
map.put("type", "dam:Asset");
Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), session);
SearchResult result = query.getResult();
List hits = result.getHits();
Resource resource = null;
for (Hit hit : hits) {
String resourcePath = null;
try {
resource = hit.getResource();
resourcePath = resource.getPath();
this.lockAssetUtils.lockAsset(resourcePath);
PersistableValueMap properties = (PersistableValueMap)resource.getChild("jcr:content").getChild("metadata").adaptTo(PersistableValueMap.class);
properties.remove((Object)"dam:scene7ImportProcessed");
properties.save();
continue;
}
catch (Exception e) {
LOG.error("Unable to remove dam:scene7ImportProcessed flag from " + resource.getPath(), (Throwable)e);
session.refresh(false);
continue;
}
finally {
try {
this.lockAssetUtils.unlockAsset(resource.getPath());
continue;
}
catch (Exception e) {
LOG.error("Unable to unlock S7 asset lock for " + resourcePath, (Throwable)e);
}
continue;
}
}
}
catch (Exception e) {
LOG.error("Unable to remove dam:scene7ImportProcessed flag from imported assets", (Throwable)e);
}
finally {
if (rr != null) {
rr.close();
}
if (session != null) {
session.logout();
}
}
}
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
private void deleteUntouchedAssets(S7Config s7Config) {
ResourceResolver rr = null;
Session session = null;
try {
session = this.slingRepository.loginService("scene7assetservice", null);
rr = this.resolverFactory.getResourceResolver(session);
if (session != null) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("path", s7Config.getTargetPath());
map.put("type", "dam:Asset");
HashMap<String, String> notProcessedMap = new HashMap<String, String>();
notProcessedMap.put("1_property", "jcr:content/metadata/dam:scene7ImportProcessed");
notProcessedMap.put("1_property.value", "true");
HashMap<String, String> scene7AssetsMap = new HashMap<String, String>();
scene7AssetsMap.put("2_property", "jcr:content/metadata/dam:scene7ID");
scene7AssetsMap.put("2_property.operation", "exists");
PredicateGroup predicateGroup = PredicateGroup.create(map);
PredicateGroup notProcessedPredicate = PredicateGroup.create(notProcessedMap);
notProcessedPredicate.set("not", "true");
predicateGroup.add((Predicate)notProcessedPredicate);
predicateGroup.add((Predicate)PredicateGroup.create(scene7AssetsMap));
session.refresh(true);
Query query = this.queryBuilder.createQuery(predicateGroup, session);
SearchResult result = query.getResult();
List hits = result.getHits();
for (Hit hit : hits) {
try {
String path = hit.getPath();
session.removeItem(path);
session.save();
LOG.info("Removed stale S7 DAM asset {}", (Object)path);
}
catch (RepositoryException e) {
session.refresh(false);
}
}
}
}
catch (Exception e) {
LOG.error("Unable to delete assets no longer existing in Scene7", (Throwable)e);
}
finally {
if (rr != null) {
rr.close();
}
if (session != null) {
session.logout();
}
}
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
private void deleteEmptyFolders(S7Config s7Config) {
ResourceResolver rr = null;
Session session = null;
try {
session = this.slingRepository.loginService("scene7assetservice", null);
rr = this.resolverFactory.getResourceResolver(session);
if (session != null) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("path", s7Config.getTargetPath());
map.put("type", "sling:OrderedFolder");
Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), session);
SearchResult result = query.getResult();
List hits = result.getHits();
for (Hit hit : hits) {
try {
Node node = hit.getNode();
NodeIterator iterator = node.getNodes();
if (iterator.hasNext()) continue;
String path = node.getPath();
session.removeItem(path);
session.save();
LOG.info("Removed stale S7 DAM folder {}", (Object)path);
}
catch (RepositoryException e) {
session.refresh(false);
}
}
}
}
catch (Exception e) {
LOG.error("Unable to remove stale folders", (Throwable)e);
}
finally {
if (rr != null) {
rr.close();
}
if (session != null) {
session.logout();
}
}
}
protected void activate(ComponentContext componentContext) {
Dictionary properties = componentContext.getProperties();
this.excludedAssets = OsgiUtil.toStringArray(properties.get("cq.dam.scene7.importservice.excludeassets"), (String[])SCR_PROP_DEFAULT_EXCLUDE_ASSETS);
this.excludedAssetsSet = new HashSet(this.excludedAssets.length);
for (int i = 0; i < this.excludedAssets.length; ++i) {
this.excludedAssetsSet.add(this.excludedAssets[i]);
}
}
protected void deactivate(ComponentContext componentContext) {
}
protected void bindEventAdmin(EventAdmin eventAdmin) {
this.eventAdmin = eventAdmin;
}
protected void unbindEventAdmin(EventAdmin eventAdmin) {
if (this.eventAdmin == eventAdmin) {
this.eventAdmin = null;
}
}
protected void bindSlingJobManager(JobManager jobManager) {
this.slingJobManager = jobManager;
}
protected void unbindSlingJobManager(JobManager jobManager) {
if (this.slingJobManager == jobManager) {
this.slingJobManager = null;
}
}
protected void bindScene7Service(Scene7Service scene7Service) {
this.scene7Service = scene7Service;
}
protected void unbindScene7Service(Scene7Service scene7Service) {
if (this.scene7Service == scene7Service) {
this.scene7Service = null;
}
}
protected void bindSlingRepository(SlingRepository slingRepository) {
this.slingRepository = slingRepository;
}
protected void unbindSlingRepository(SlingRepository slingRepository) {
if (this.slingRepository == slingRepository) {
this.slingRepository = null;
}
}
protected void bindResolverFactory(JcrResourceResolverFactory jcrResourceResolverFactory) {
this.resolverFactory = jcrResourceResolverFactory;
}
protected void unbindResolverFactory(JcrResourceResolverFactory jcrResourceResolverFactory) {
if (this.resolverFactory == jcrResourceResolverFactory) {
this.resolverFactory = null;
}
}
protected void bindQueryBuilder(QueryBuilder queryBuilder) {
this.queryBuilder = queryBuilder;
}
protected void unbindQueryBuilder(QueryBuilder queryBuilder) {
if (this.queryBuilder == queryBuilder) {
this.queryBuilder = null;
}
}
protected void bindLockAssetUtils(LockAssetUtils lockAssetUtils) {
this.lockAssetUtils = lockAssetUtils;
}
protected void unbindLockAssetUtils(LockAssetUtils lockAssetUtils) {
if (this.lockAssetUtils == lockAssetUtils) {
this.lockAssetUtils = null;
}
}
}