AppCacheManagerImpl.java
22.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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.day.cq.commons.jcr.JcrUtil
* com.day.cq.contentsync.ContentSyncManager
* com.day.cq.contentsync.config.Config
* com.day.cq.replication.ReplicationActionType
* com.day.cq.replication.ReplicationException
* com.day.cq.replication.Replicator
* com.day.jcr.vault.packaging.Packaging
* javax.jcr.Binary
* javax.jcr.Node
* javax.jcr.NodeIterator
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.ValueFactory
* org.apache.commons.lang.StringUtils
* org.apache.sling.api.resource.LoginException
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolverFactory
* org.apache.sling.commons.json.JSONArray
* org.apache.sling.commons.json.JSONException
* org.apache.sling.commons.json.JSONObject
* org.apache.sling.jcr.api.SlingRepository
* org.osgi.service.cm.ConfigurationAdmin
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.cq.mobile.appcache.impl;
import com.adobe.cq.mobile.appcache.impl.AppCacheException;
import com.adobe.cq.mobile.appcache.impl.AppCacheManager;
import com.adobe.cq.mobile.appcache.impl.AppCacheUtil;
import com.adobe.cq.mobile.appcache.impl.CacheUpdate;
import com.adobe.cq.mobile.appcache.impl.CacheUpdateImpl;
import com.adobe.cq.mobile.appcache.impl.ConfigUtil;
import com.adobe.cq.mobile.appcache.impl.PackageHelper;
import com.adobe.cq.mobile.platform.impl.utils.MobileUtil;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.contentsync.ContentSyncManager;
import com.day.cq.contentsync.config.Config;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.Replicator;
import com.day.jcr.vault.packaging.Packaging;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AppCacheManagerImpl
implements AppCacheManager {
private static final Logger LOGGER = LoggerFactory.getLogger(AppCacheManagerImpl.class);
private static final String PACKAGE_NAME_PREFIX = "mobileapp-update-";
private ContentSyncManager contentSyncManager;
private Session userSession = null;
private Packaging packagingService;
private ConfigurationAdmin configurationAdmin;
private SlingRepository repository;
private ResourceResolverFactory resourceResolverFactory;
private Replicator replicator;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public AppCacheManagerImpl(Session userSession, ContentSyncManager contentSyncManager, Replicator replicator, Packaging packagingService, ConfigurationAdmin configurationAdmin, SlingRepository repository, ResourceResolverFactory resourceResolverFactory) {
this.userSession = userSession;
this.contentSyncManager = contentSyncManager;
this.replicator = replicator;
this.packagingService = packagingService;
this.configurationAdmin = configurationAdmin;
this.repository = repository;
this.resourceResolverFactory = resourceResolverFactory;
}
@Override
public boolean updateCache(Config config, String title, String desc) throws AppCacheException {
try {
boolean updateRequired = this.fillCache(config);
this.lock.writeLock().lock();
if (!updateRequired) {
Long lastFill = this.getLastFill(config);
CacheUpdate latestUpdate = this.getLastUpdate(config);
if (latestUpdate == null) {
if (lastFill != null && lastFill > new Date(0).getTime()) {
updateRequired = true;
}
} else if (lastFill != null && lastFill > latestUpdate.getCreated().getTimeInMillis()) {
updateRequired = true;
}
}
if (updateRequired) {
long lastUpdateTS = this.updateTimestamps(config, title, desc);
String cachePath = ConfigUtil.configToCachePath(config, this.userSession);
Node cacheFolder = this.userSession.getNode(cachePath);
this.addTimestampFile(lastUpdateTS, cacheFolder);
}
boolean lastUpdateTS = updateRequired;
return lastUpdateTS;
}
catch (Exception ex) {
throw new AppCacheException("Failed update", ex);
}
finally {
this.lock.writeLock().unlock();
}
}
private void addTimestampFile(long timestamp, Node cacheFolder) throws RepositoryException, JSONException {
String filePath = cacheFolder.getPath() + "/www/" + "pge-package-update.json";
JcrUtil.createPath((String)filePath, (String)"sling:Folder", (String)"nt:file", (Session)this.userSession, (boolean)false);
Node cacheContentNode = JcrUtil.createPath((String)(filePath + "/jcr:content"), (String)"nt:resource", (Session)this.userSession);
JSONObject fileListing = new JSONObject();
fileListing.put("lastModified", timestamp);
cacheContentNode.setProperty("jcr:data", this.userSession.getValueFactory().createBinary((InputStream)new ByteArrayInputStream(fileListing.toString(3).getBytes())));
cacheContentNode.setProperty("jcr:lastModified", timestamp);
this.userSession.save();
}
private long updateTimestamps(Config config, String title, String desc) throws AppCacheException {
try {
String userId = this.userSession.getUserID();
Long ts = this.contentSyncManager.getLatestTimestamp(config, this.userSession);
String nodeName = String.valueOf(ts);
String updateMetadataPath = ConfigUtil.configToMetadataCachePath(config, this.userSession);
String targetNodePath = updateMetadataPath + "/" + nodeName;
if (this.userSession.itemExists(targetNodePath)) {
throw new AppCacheException("Node already exists at path " + targetNodePath);
}
boolean metadataPreexisted = this.userSession.itemExists(updateMetadataPath);
Node metadataNode = JcrUtil.createPath((String)targetNodePath, (String)"nt:unstructured", (Session)this.userSession);
metadataNode.setProperty("jcr:title", title);
metadataNode.setProperty("jcr:description", desc);
metadataNode.setProperty("jcr:createdBy", userId);
Calendar tsCal = Calendar.getInstance();
tsCal.setTimeInMillis(ts);
metadataNode.setProperty("jcr:created", tsCal);
this.userSession.save();
if (!metadataPreexisted) {
String authorizable = AppCacheUtil.getAuthorizable(this.configurationAdmin, config);
AppCacheUtil.setupCacheACLs(this.resourceResolverFactory, config, this.userSession, false, true, true, authorizable);
}
return ts;
}
catch (RepositoryException ex) {
throw new AppCacheException("Failed to update cache metadata", (Throwable)ex);
}
catch (LoginException ex) {
throw new AppCacheException("Login failed while trying to set up ACLs", (Throwable)ex);
}
}
@Override
public boolean fillCache(Config config) throws AppCacheException {
try {
boolean updated = this.contentSyncManager.updateCache(config, this.userSession);
return updated;
}
catch (Exception ex) {
throw new AppCacheException("Failed update", ex);
}
}
@Override
public void clearCache(Config config) throws AppCacheException {
try {
this.contentSyncManager.clearCache(config, this.userSession);
this.lock.writeLock().lock();
String updateMetadataPath = ConfigUtil.configToMetadataCachePath(config, this.userSession);
if (this.userSession.nodeExists(updateMetadataPath)) {
this.userSession.getNode(updateMetadataPath).remove();
this.userSession.save();
}
}
catch (Exception ex) {
throw new AppCacheException("Failed to clear cache", ex);
}
finally {
this.lock.writeLock().unlock();
}
}
@Override
public boolean hasUpdates(Config config, Date ifModifiedSince) throws AppCacheException {
boolean hasUpdate = false;
try {
Node configNode = this.userSession.getNode(config.getPath());
CacheUpdate lastCacheUpdate = this.getLastUpdate(config);
if (lastCacheUpdate != null) {
hasUpdate = lastCacheUpdate.getCreated().getTimeInMillis() > ifModifiedSince.getTime();
}
}
catch (RepositoryException ex) {
throw new AppCacheException("Failed update check", (Throwable)ex);
}
return hasUpdate;
}
@Override
public Long getLastFill(Config config) {
Long lastFill = null;
long csLastestTimestamp = this.contentSyncManager.getLatestTimestamp(config, this.userSession);
if (new Date(0).getTime() != csLastestTimestamp) {
lastFill = csLastestTimestamp;
}
return lastFill;
}
@Override
public CacheUpdate getLastPublishedUpdate(Config config) throws AppCacheException {
CacheUpdate lastPublished = null;
try {
List<CacheUpdate> updates = this.getUpdates(config);
for (CacheUpdate update : updates) {
if (update.getLastPublished() == null) continue;
lastPublished = update;
}
}
catch (AppCacheException ex) {
LOGGER.warn("Error extracting last published update.", (Throwable)ex);
}
return lastPublished;
}
@Override
public CacheUpdate getLastUpdate(Config config) {
CacheUpdate lastUpdate = null;
try {
List<CacheUpdate> updates = this.getUpdates(config);
if (!updates.isEmpty()) {
lastUpdate = updates.get(updates.size() - 1);
}
}
catch (AppCacheException ex) {
LOGGER.warn("Error extracting last update.", (Throwable)ex);
}
return lastUpdate;
}
@Override
public boolean buildZips(Config config) throws AppCacheException {
LOGGER.info("Build mobile app content zips: " + config.getPath());
boolean zipsBuilt = false;
try {
List<CacheUpdate> cacheUpdateList = this.getUpdates(config);
if (cacheUpdateList.size() == 0) {
LOGGER.warn("No zips to build. No updates found for config. " + config.getPath() + ".");
} else {
Resource configResource = MobileUtil.getResourceResolver(this.resourceResolverFactory, this.userSession).getResource(config.getPath());
String zipPath = this.contentSyncManager.getZip(configResource, null, this.userSession);
LOGGER.info("Built full zip " + zipPath + " for " + config.getPath());
for (CacheUpdate cacheUpdate : cacheUpdateList) {
LOGGER.info("Requesting build of zip for " + config.getPath() + " @" + cacheUpdate.getCreated().getTimeInMillis());
zipPath = this.contentSyncManager.getZip(configResource, cacheUpdate.getCreated().getTime(), this.userSession);
if (zipPath == null) {
LOGGER.info("Skipping zip build, timestamp at latest for " + config.getPath() + " @" + cacheUpdate.getCreated().getTimeInMillis());
continue;
}
LOGGER.info("Built zip " + zipPath + " for " + config.getPath() + " @" + cacheUpdate.getCreated().getTimeInMillis());
zipsBuilt = true;
}
}
}
catch (Exception ex) {
throw new AppCacheException("Failed to build zips", ex);
}
return zipsBuilt;
}
@Override
public boolean transferZips(Config config, String title, String description) throws AppCacheException {
boolean zipsTransferred;
block6 : {
LOGGER.info("Transfer mobile cache " + config.getPath());
zipsTransferred = false;
try {
String cachePath = ConfigUtil.configToCachePath(config, this.userSession);
String zipsCachePath = cachePath + "-zips";
String cacheMetadataPath = ConfigUtil.configToMetadataCachePath(config, this.userSession);
if (this.userSession.nodeExists(cachePath) && this.userSession.nodeExists(zipsCachePath)) {
Node zipCacheNode = this.userSession.getNode(zipsCachePath);
Node cacheMetadataNode = this.userSession.getNode(cacheMetadataPath);
PackageHelper packageHelper = new PackageHelper(this.packagingService);
String packageName = this.getPackageName(config);
String packagePath = packageHelper.createZipPackage(this.userSession, packageName, cacheMetadataNode, zipCacheNode);
this.replicate(this.userSession, config.getPath());
this.replicate(this.userSession, packagePath);
zipsTransferred = true;
this.tagPublishedUpdateAndPruneUnPublished(config);
if (title != null || description != null) {
String metadataPath = null;
try {
metadataPath = this.getLastUpdate(config).getPath();
Node metadataNode = this.userSession.getNode(metadataPath);
metadataNode.setProperty("jcr:title", title);
metadataNode.setProperty("jcr:description", description);
}
catch (Exception ex) {
LOGGER.warn("Failed to update metadata for " + metadataPath);
}
}
LOGGER.info("Transferred config " + config.getPath() + " and package of zips " + packagePath);
break block6;
}
LOGGER.warn("No zips found. Could not transfer config " + config.getPath() + " and package of zips.");
}
catch (Exception ex) {
throw new AppCacheException("Failed to create and replicate zip package", ex);
}
}
return zipsTransferred;
}
private void tagPublishedUpdateAndPruneUnPublished(Config config) {
try {
List<CacheUpdate> cacheUpdateList = this.getUpdates(config);
int pos = 0;
for (CacheUpdate update : cacheUpdateList) {
boolean ispub;
boolean bl = ispub = update.getLastPublished() != null;
if (pos == cacheUpdateList.size() - 1) {
Node lastUpdate = this.userSession.getNode(update.getPath());
LOGGER.debug("Setting published to true for update: " + (Object)lastUpdate);
lastUpdate.setProperty("lastPublished", Calendar.getInstance());
lastUpdate.setProperty("lastPublishedBy", this.userSession.getUserID());
} else if (!ispub) {
Node updateToPrune = this.userSession.getNode(update.getPath());
LOGGER.debug("Removing unpublished update (since last published update and current published update): " + (Object)updateToPrune);
updateToPrune.remove();
}
++pos;
}
}
catch (Exception ex) {
throw new AppCacheException("Failed to retrieve updates", ex);
}
}
private String getPackageName(Config config) throws RepositoryException {
String name = config.getName();
Node configNode = this.userSession.getNode(config.getPath());
if (configNode.hasProperty("jcr:title")) {
String title = configNode.getProperty("jcr:title").getString();
title = JcrUtil.createValidName((String)title);
name = name + "-" + title;
}
return "mobileapp-update-" + name;
}
@Override
public List<CacheUpdate> getUpdates(Config config) throws AppCacheException {
try {
ArrayList<CacheUpdate> updates = new ArrayList<CacheUpdate>();
String updateMetadataPath = ConfigUtil.configToMetadataCachePath(config, this.userSession);
if (this.userSession.nodeExists(updateMetadataPath)) {
Node updateMetadataNode = this.userSession.getNode(updateMetadataPath);
NodeIterator nodeIterator = updateMetadataNode.getNodes();
while (nodeIterator.hasNext()) {
Node updateNode = nodeIterator.nextNode();
CacheUpdate cacheUpdate = this.adaptToCacheUpdate(updateNode);
if (cacheUpdate != null) {
updates.add(cacheUpdate);
continue;
}
LOGGER.debug("Invalid cache update node " + updateNode.getPath());
}
}
Collections.sort(updates, new Comparator<CacheUpdate>(){
@Override
public int compare(CacheUpdate o1, CacheUpdate o2) {
return o1.getCreated().compareTo(o2.getCreated());
}
});
return updates;
}
catch (Exception ex) {
throw new AppCacheException("Failed to retrieve updates", ex);
}
}
@Override
public JSONArray getZips(Config config) throws AppCacheException {
LOGGER.info("Get zips for config " + config.getPath());
try {
JSONArray zips = new JSONArray();
String cachePath = ConfigUtil.configToCachePath(config, this.userSession);
String zipsCachePath = cachePath + "-zips";
if (this.userSession.nodeExists(zipsCachePath)) {
Node zipCacheNode = this.userSession.getNode(zipsCachePath);
NodeIterator zipNodesIter = zipCacheNode.getNodes();
while (zipNodesIter.hasNext()) {
Node zipNode = zipNodesIter.nextNode();
String configName = config.getName();
String name = zipNode.getName();
if (!name.startsWith(configName) || !name.endsWith(".zip")) continue;
JSONObject zipJSON = new JSONObject();
String[] nameTokens = StringUtils.split((String)name, (String)".");
int tsCount = nameTokens.length - 2;
zipJSON.put("name", (Object)name);
zipJSON.put("path", (Object)zipNode.getPath());
if (tsCount == 1) {
zipJSON.put("fromTS", (Object)nameTokens[1]);
} else if (tsCount == 2) {
zipJSON.put("fromTS", (Object)nameTokens[1]);
zipJSON.put("toTS", (Object)nameTokens[2]);
}
long size = zipNode.getProperty("jcr:content/jcr:data").getLength();
zipJSON.put("size", size);
zips.put((Object)zipJSON);
}
}
return zips;
}
catch (Exception ex) {
throw new AppCacheException("Failed to create and replicate zip package", ex);
}
}
private void replicate(Session session, String path) throws ReplicationException {
LOGGER.info("Replicating: " + path);
this.replicator.replicate(session, ReplicationActionType.ACTIVATE, path);
}
private CacheUpdate adaptToCacheUpdate(Node node) {
CacheUpdateImpl impl = null;
try {
Calendar updateTS = null;
if (node.hasProperty("jcr:created")) {
updateTS = node.getProperty("jcr:created").getDate();
}
String updateUserId = null;
if (node.hasProperty("jcr:createdBy")) {
updateUserId = node.getProperty("jcr:createdBy").getString();
}
String title = null;
if (node.hasProperty("jcr:title")) {
title = node.getProperty("jcr:title").getString();
}
String description = null;
if (node.hasProperty("jcr:description")) {
description = node.getProperty("jcr:description").getString();
}
Calendar lastPublished = null;
if (node.hasProperty("lastPublished")) {
lastPublished = node.getProperty("lastPublished").getDate();
}
String lastPublishedBy = null;
if (node.hasProperty("lastPublishedBy")) {
lastPublishedBy = node.getProperty("lastPublishedBy").getString();
}
if (node.hasProperty("user")) {
updateTS = Calendar.getInstance();
updateTS.setTimeInMillis(Long.parseLong(node.getName()));
lastPublished = updateTS;
updateUserId = node.getProperty("user").getString();
}
if (updateTS != null) {
impl = new CacheUpdateImpl(updateTS, updateUserId, title, description, lastPublished, lastPublishedBy, node.getPath());
}
}
catch (Exception ex) {
LOGGER.debug("Invalid CacheUpdate node : " + String.valueOf((Object)node));
}
return impl;
}
}