BinaryValueManagerImpl.java
17.1 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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.day.cq.commons.jcr.JcrUtil
* javax.jcr.AccessDeniedException
* javax.jcr.Node
* javax.jcr.NodeIterator
* javax.jcr.PathNotFoundException
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.Value
* javax.jcr.nodetype.NodeType
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Properties
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.Service
* org.apache.sling.api.resource.LoginException
* org.apache.sling.api.resource.NonExistingResource
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ResourceResolverFactory
* org.apache.sling.api.resource.ResourceUtil
* org.apache.sling.api.resource.ValueMap
* org.apache.sling.jcr.resource.JcrResourceUtil
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.wcm.undo.impl;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.wcm.undo.BinaryHandlingException;
import com.day.cq.wcm.undo.BinaryValueManager;
import com.day.cq.wcm.undo.UndoConfigService;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import javax.jcr.AccessDeniedException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.nodetype.NodeType;
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.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.jcr.resource.JcrResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(label="Day CQ WCM Undo Binary Value Manager", immediate=1, metatype=0, description="Manages binary values for CQ's undo facilities.")
@Service(value={BinaryValueManager.class, Runnable.class})
@Properties(value={@Property(name="scheduler.period", longValue={3600}), @Property(name="scheduler.concurrent", boolValue={0}, propertyPrivate=1)})
public class BinaryValueManagerImpl
implements BinaryValueManager,
Runnable {
@Reference
protected UndoConfigService config;
@Reference
private ResourceResolverFactory rrf;
private static final Logger log = LoggerFactory.getLogger(BinaryValueManagerImpl.class);
private static final String UNDO_SERVICE = "undo-service";
private String createBasePath() {
String undoPath = this.config.getConfig("path", String.class);
StringBuilder basePath = new StringBuilder(undoPath.length() + 32);
basePath.append(undoPath).append('/');
long nowSec = System.currentTimeMillis() / 1000;
long firstLevel = nowSec / 3600;
basePath.append(firstLevel).append('/');
long secondLevel = nowSec / 60 % 60;
basePath.append(secondLevel);
return basePath.toString();
}
private Node findNtResource(Node baseNode) throws RepositoryException {
if (baseNode.getPrimaryNodeType().isNodeType("nt:resource")) {
return baseNode;
}
NodeIterator children = baseNode.getNodes();
while (children.hasNext()) {
Node child = children.nextNode();
Node blobNode = this.findNtResource(child);
if (blobNode == null) continue;
return blobNode;
}
return null;
}
private void removeResource(Resource resourceToRemove) throws BinaryHandlingException {
if (resourceToRemove == null) {
return;
}
ResourceResolver resolver = resourceToRemove.getResourceResolver();
Node targetNode = (Node)resourceToRemove.adaptTo(Node.class);
Session session = (Session)resolver.adaptTo(Session.class);
try {
session.refresh(false);
targetNode.remove();
session.save();
}
catch (RepositoryException re) {
throw new BinaryHandlingException("Could not delete binary value", (Throwable)re);
}
}
@Override
public boolean isChanged(Resource par, String subPath, String originalRef) throws BinaryHandlingException {
if (originalRef == null) {
return true;
}
ResourceResolver resolver = par.getResourceResolver();
Resource originalBinary = resolver.getResource(originalRef + "/binary");
if (originalBinary instanceof NonExistingResource) {
originalBinary = null;
}
Resource currentBinary = null;
try {
Node blobNode;
Node subNode;
Node parNode = (Node)par.adaptTo(Node.class);
if (parNode.hasNode(subPath) && (blobNode = this.findNtResource(subNode = parNode.getNode(subPath))) != null) {
currentBinary = resolver.getResource(blobNode.getPath());
}
}
catch (RepositoryException re) {
throw new BinaryHandlingException("Could not detect if BLOB has changed.", (Throwable)re);
}
if (currentBinary == null) {
return originalBinary != null;
}
if (originalBinary == null) {
return true;
}
ValueMap currentProps = ResourceUtil.getValueMap((Resource)currentBinary);
Calendar currentLastModified = (Calendar)currentProps.get("jcr:lastModified", Calendar.class);
ValueMap originalProps = ResourceUtil.getValueMap((Resource)originalBinary);
Calendar originalLastModified = (Calendar)originalProps.get("jcr:lastModified", Calendar.class);
log.debug("Current last modified: {}; original last modified: {}", (Object)(currentLastModified != null ? Long.valueOf(currentLastModified.getTimeInMillis()) : "-"), (Object)(originalLastModified != null ? Long.valueOf(originalLastModified.getTimeInMillis()) : "-"));
if (currentLastModified == null) {
return originalLastModified != null;
}
if (originalLastModified == null) {
return true;
}
return !originalLastModified.equals(currentLastModified);
}
@Override
public String save(Resource par, String subPath) throws BinaryHandlingException {
String path = this.createBasePath();
String uuid = UUID.randomUUID().toString();
String dataPath = path + "/" + uuid;
if (par == null) {
throw new BinaryHandlingException("No paragraph specified.");
}
ResourceResolver resolver = par.getResourceResolver();
if (resolver == null) {
throw new BinaryHandlingException("No resource resolver available.");
}
Session session = (Session)par.getResourceResolver().adaptTo(Session.class);
try {
Node dataNode;
session.refresh(false);
Node parNode = (Node)par.adaptTo(Node.class);
if (!parNode.hasNode(subPath)) {
String string = null;
return string;
}
Node subNode = parNode.getNode(subPath);
Node blobNode = this.findNtResource(subNode);
if (blobNode == null) {
throw new BinaryHandlingException("No binary node found.");
}
StringBuilder rscSubPath = new StringBuilder(64);
Node processingNode = blobNode;
while (!processingNode.getPath().equals(subNode.getPath())) {
rscSubPath.insert(0, processingNode.getName());
rscSubPath.insert(0, '/');
processingNode = processingNode.getParent();
}
rscSubPath.insert(0, subPath);
String[] pathParts = rscSubPath.toString().split("/");
String[] partTypes = new String[pathParts.length];
processingNode = parNode;
int p = 0;
for (String part : pathParts) {
processingNode = processingNode.getNode(part);
partTypes[p++] = processingNode.getPrimaryNodeType().getName();
}
log.debug("Saving BLOB from '{}' to '{}'.", (Object)par.getPath(), (Object)dataPath);
try {
dataNode = JcrResourceUtil.createPath((String)dataPath, (String)"sling:Folder", (String)"nt:unstructured", (Session)session, (boolean)false);
}
catch (PathNotFoundException pnfe) {
throw new AccessDeniedException("Possible permission problem while creating path to '" + dataPath + "'.");
}
dataNode.setProperty("pathParts", pathParts);
dataNode.setProperty("partTypes", partTypes);
JcrUtil.copy((Node)blobNode, (Node)dataNode, (String)"binary");
session.save();
log.debug("BLOB '{}' saved successfully.", (Object)dataPath);
}
catch (RepositoryException re) {
throw new BinaryHandlingException("Could not save binary value", (Throwable)re);
}
finally {
try {
session.refresh(false);
}
catch (RepositoryException re) {}
}
return dataPath;
}
@Override
public void restore(Resource undoData, Resource par, String subPath) throws BinaryHandlingException {
String undoPath = this.config.getConfig("path", String.class);
Session session = (Session)undoData.getResourceResolver().adaptTo(Session.class);
try {
Node parNode;
session.refresh(false);
String undoDataPath = undoData.getPath();
if (!undoDataPath.startsWith(undoPath + "/")) {
throw new BinaryHandlingException("Cannot restore from paths other than '" + undoPath + "'");
}
Node undoNode = (Node)undoData.adaptTo(Node.class);
Node dataNode = undoNode.getNode("binary");
Node processingNode = parNode = (Node)par.adaptTo(Node.class);
Value[] pathParts = undoNode.getProperty("pathParts").getValues();
Value[] partTypes = undoNode.getProperty("partTypes").getValues();
int p = 0;
for (Value part : pathParts) {
String partName = part.getString();
if (!processingNode.hasNode(partName)) {
String nodeType = partTypes[p].getString();
processingNode = processingNode.addNode(partName, nodeType);
} else {
processingNode = processingNode.getNode(partName);
}
++p;
}
String targetName = processingNode.getName();
String targetPath = processingNode.getPath();
Node copiedNode = JcrUtil.copy((Node)dataNode, (Node)processingNode.getParent(), (String)targetName);
if (parNode.isNodeType("cq:Page")) {
parNode = parNode.getNode("jcr:content");
}
Calendar now = Calendar.getInstance();
String userId = parNode.getSession().getUserID();
copiedNode.setProperty("jcr:lastModified", now);
copiedNode.setProperty("jcr:lastModifiedBy", userId);
parNode.setProperty("jcr:lastModified", now);
parNode.setProperty("jcr:lastModifiedBy", userId);
session.save();
log.debug("BLOB restored successfully from '{}' to '{}'", (Object)undoData.getPath(), (Object)targetPath);
}
catch (RepositoryException re) {
throw new BinaryHandlingException("Could not restore binary value", (Throwable)re);
}
finally {
try {
session.refresh(false);
}
catch (RepositoryException re) {}
}
}
@Override
public void delete(Resource par, String subPath, boolean deletePar) throws BinaryHandlingException {
Resource resourceToRemove;
ResourceResolver resolver = par.getResourceResolver();
if (deletePar) {
Resource resourceToCheck = resolver.getResource(par, subPath);
Node nodeToDelete = null;
try {
for (Node nodeToCheck = (Node)resourceToCheck.adaptTo(Node.class); nodeToCheck != null; nodeToCheck = nodeToCheck.getParent()) {
if (nodeToCheck.isNodeType("nt:resource")) {
if (nodeToDelete != null) break;
nodeToDelete = nodeToCheck;
continue;
}
if (!nodeToCheck.isNodeType("nt:file")) continue;
nodeToDelete = nodeToCheck;
break;
}
if (nodeToDelete == null) {
throw new BinaryHandlingException("Could not determine a valid binary node of type nt:resource or nt:file.");
}
String pathToDelete = nodeToDelete.getPath();
log.debug("Removing binary from actual path '{}'", (Object)pathToDelete);
resourceToRemove = resolver.getResource(pathToDelete);
}
catch (RepositoryException re) {
throw new BinaryHandlingException("Could not determine binary node (nt:resource or nt:file) to remove due to an underlying repository problem.", (Throwable)re);
}
} else {
resourceToRemove = resolver.getResource(par, subPath);
}
this.removeResource(resourceToRemove);
}
@Override
public void delete(ResourceResolver resolver, String undoPath) throws BinaryHandlingException {
String basePath = this.config.getConfig("path", String.class);
if (!undoPath.startsWith(basePath + "/")) {
throw new BinaryHandlingException("Cannot delete in paths that don't start with '" + basePath + "'");
}
this.removeResource(resolver.getResource(undoPath));
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@Override
public void run() {
log.debug("Janitor job executing.");
long undoDataValidity = this.config.getConfig("dataValidity", Integer.class).longValue();
String undoPath = this.config.getConfig("path", String.class);
long nowHour = System.currentTimeMillis() / 3600000;
long thresholdHour = nowHour - undoDataValidity;
log.debug("Cleaning for threshold hour {}", (Object)thresholdHour);
ResourceResolver resolver = null;
Session session = null;
try {
resolver = this.rrf.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "undo-service"));
session = (Session)resolver.adaptTo(Session.class);
if (undoPath != null && session.nodeExists(undoPath)) {
Node dataRoot = session.getNode(undoPath);
NodeIterator dataIt = dataRoot.getNodes();
ArrayList<Node> toRemove = new ArrayList<Node>();
while (dataIt.hasNext()) {
Node nodeToCheck = dataIt.nextNode();
log.debug("Checking undo folder '{}' for removal.", (Object)nodeToCheck.getPath());
try {
long nodeHour = Long.parseLong(nodeToCheck.getName());
if (nodeHour >= thresholdHour) continue;
toRemove.add(nodeToCheck);
}
catch (NumberFormatException nfe) {
log.debug("Invalid node name: {}", (Object)nodeToCheck.getName());
}
}
for (Node nodeToRemove : toRemove) {
log.debug("Removing undo data folder '{}'", (Object)nodeToRemove.getPath());
nodeToRemove.remove();
}
session.save();
}
}
catch (LoginException e) {
log.error("Unable to obtain a resource resolver for cleaning up the undo area.", (Throwable)e);
}
catch (RepositoryException re) {
log.warn("Could not cleanup undo data.", (Throwable)re);
}
finally {
if (session != null) {
session.logout();
}
}
}
protected void bindConfig(UndoConfigService undoConfigService) {
this.config = undoConfigService;
}
protected void unbindConfig(UndoConfigService undoConfigService) {
if (this.config == undoConfigService) {
this.config = null;
}
}
protected void bindRrf(ResourceResolverFactory resourceResolverFactory) {
this.rrf = resourceResolverFactory;
}
protected void unbindRrf(ResourceResolverFactory resourceResolverFactory) {
if (this.rrf == resourceResolverFactory) {
this.rrf = null;
}
}
}