StaticContentBuilder.java
15.5 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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.day.text.GlobPattern
* javax.jcr.Credentials
* javax.jcr.Item
* javax.jcr.Node
* javax.jcr.Repository
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.SimpleCredentials
* javax.jcr.Workspace
* javax.jcr.security.AccessControlException
* org.apache.commons.httpclient.HttpClient
* org.apache.commons.httpclient.HttpConnectionManager
* org.apache.commons.httpclient.HttpException
* org.apache.commons.httpclient.HttpMethod
* org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
* org.apache.commons.httpclient.methods.GetMethod
* org.apache.commons.io.IOUtils
* org.apache.felix.scr.annotations.Activate
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Deactivate
* org.apache.felix.scr.annotations.Modified
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.Service
* org.apache.jackrabbit.util.Text
* org.apache.sling.api.resource.ValueMap
* org.apache.sling.commons.osgi.PropertiesUtil
*/
package com.day.cq.replication.impl.content;
import com.day.cq.replication.AgentConfig;
import com.day.cq.replication.ContentBuilder;
import com.day.cq.replication.ReplicationAction;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationContent;
import com.day.cq.replication.ReplicationContentFactory;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.ReplicationLog;
import com.day.text.GlobPattern;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.jcr.Credentials;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;
import javax.jcr.security.AccessControlException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.osgi.PropertiesUtil;
@Component(name="com.day.cq.replication.content.StaticContentBuilder", metatype=1, label="%static.builder.name", description="%static.builder.description")
@Service(value={ContentBuilder.class})
public class StaticContentBuilder
implements ContentBuilder {
@Property(name="name", propertyPrivate=1)
private static final String NAME = "static";
private static final String DEFAULT_HOST = "localhost";
@Property(value={"localhost"})
private static final String PROP_HOST = "host";
private static final int DEFAULT_PORT = 4502;
@Property(intValue={4502})
private static final String PROP_PORT = "port";
private static final String TITLE = "Static Content Builder";
private static final String MT_ZIP = "application/zip";
private static final String REPO_DESC_ID = "crx.repository.systemid";
private static final String REPO_DESC_CLUSTER_ID = "crx.cluster.id";
private HttpClient httpClient;
private String serverHost;
private int serverPort;
@Reference
private Repository repository;
private String repositoryId;
private Map<String, String> tokenMap = new HashMap<String, String>();
private String name;
@Activate
private void activate(Map<String, Object> configuration) {
this.name = PropertiesUtil.toString((Object)configuration.get("name"), (String)"static");
MultiThreadedHttpConnectionManager conMgr = new MultiThreadedHttpConnectionManager();
this.httpClient = new HttpClient((HttpConnectionManager)conMgr);
this.serverHost = PropertiesUtil.toString((Object)configuration.get("host"), (String)"localhost");
this.serverPort = PropertiesUtil.toInteger((Object)configuration.get("port"), (int)4502);
this.repositoryId = this.repository.getDescriptor("crx.cluster.id");
if (this.repositoryId == null) {
this.repositoryId = this.repository.getDescriptor("crx.repository.systemid");
}
}
@Modified
private void modified(Map<String, Object> configuration) {
this.deactivate(configuration);
this.activate(configuration);
}
@Deactivate
private void deactivate(Map<String, Object> configuration) {
if (this.httpClient != null) {
((MultiThreadedHttpConnectionManager)this.httpClient.getHttpConnectionManager()).shutdown();
this.httpClient = null;
}
this.tokenMap.clear();
}
private Rule[] parseRules(String s, ReplicationLog log) {
String[] lines;
ArrayList<Rule> rules = new ArrayList<Rule>();
for (String line : lines = Text.explode((String)s, (int)10)) {
String[] rule = Text.explode((String)line, (int)32);
if (rule.length != 2) {
log.warn(String.format("Rule invalid: %s, should consist of two elements separated by spaces.", line));
continue;
}
rules.add(new Rule(rule[0], rule[1]));
}
Rule[] result = new Rule[rules.size()];
rules.toArray(result);
return result;
}
private String createTokenCookie(Session session) throws ReplicationException {
if (this.repositoryId == null) {
throw new ReplicationException("Unable to obtain repository id.");
}
Session s1 = null;
try {
SimpleCredentials c = new SimpleCredentials(session.getUserID(), new char[0]);
c.setAttribute(".token", (Object)"");
s1 = session.impersonate((Credentials)c);
String value = Text.escape((String)String.format("%s:%s:%s", this.repositoryId, c.getAttribute(".token"), session.getWorkspace().getName()));
String string = String.format("login-token=%s", value);
return string;
}
catch (RepositoryException e) {
throw new ReplicationException("Unable to impersonate same user", (Exception)e);
}
finally {
if (s1 != null) {
s1.logout();
}
}
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
private String getOrCreateTokenCookie(Session session, boolean create) throws ReplicationException {
String tokenCookie;
Map<String, String> map;
if (!create) {
map = this.tokenMap;
synchronized (map) {
tokenCookie = this.tokenMap.get(session.getUserID());
if (tokenCookie != null) {
return tokenCookie;
}
}
}
tokenCookie = this.createTokenCookie(session);
map = this.tokenMap;
synchronized (map) {
this.tokenMap.put(session.getUserID(), tokenCookie);
}
return tokenCookie;
}
@Override
public ReplicationContent create(Session session, ReplicationAction action, ReplicationContentFactory factory) throws ReplicationException {
if (action.getType() != ReplicationActionType.ACTIVATE) {
return ReplicationContent.VOID;
}
AgentConfig config = action.getConfig();
if (config == null) {
throw new ReplicationException("No agent configuration found.");
}
ReplicationLog log = action.getLog();
if (log == null) {
throw new ReplicationException("No replication log found.");
}
String s = (String)config.getProperties().get("definition", String.class);
if (s == null || s.length() == 0) {
log.info(String.format("No rules definition found in agent %s", config.getName()));
return ReplicationContent.VOID;
}
Rule[] rules = this.parseRules(s, log);
if (rules.length == 0) {
log.info(String.format("Rules definition in agent %s did not contain a valid rule", config.getName()));
return ReplicationContent.VOID;
}
try {
Node node = (Node)session.getItem(action.getPath());
return this.create(rules, factory, node, log);
}
catch (AccessControlException e) {
log.error(String.format("Agent cannot access %s: %s", action.getPath(), e.getMessage()));
throw new ReplicationException("Agent is unable to access " + action.getPath(), (Exception)e);
}
catch (RepositoryException e) {
log.error(String.format("Repository exception occurred during serialization of content %s.", action.getPath()));
throw new ReplicationException("RepositoryException during serialization", (Exception)e);
}
catch (IOException e) {
log.error(String.format("I/O error occurred during serialization of content %s", action.getPath()));
throw new ReplicationException("I/O error during serialization", e);
}
}
@Override
public ReplicationContent create(Session session, ReplicationAction action, ReplicationContentFactory factory, Map<String, Object> parameters) throws ReplicationException {
return this.create(session, action, factory);
}
private ReplicationContent create(Rule[] rules, ReplicationContentFactory factory, Node node, ReplicationLog log) throws ReplicationException, RepositoryException, IOException {
HashMap<String, byte[]> binaries = new HashMap<String, byte[]>();
String path = node.getPath();
for (Rule rule : rules) {
byte[] data;
log.debug(String.format("Checking rule (%s) against node path %s", rule, path));
String urlPath = rule.replace(path);
if (urlPath == null) {
log.debug(String.format("Rule (%s) did not match.", rule));
continue;
}
try {
data = this.getContent(urlPath, node.getSession(), log);
}
catch (ReplicationException e) {
log.warn(String.format("Unable to retrieve content: %s", e.getMessage()));
continue;
}
int query = urlPath.indexOf(63);
if (query != -1) {
urlPath = urlPath.substring(0, query);
}
binaries.put(urlPath, data);
}
if (binaries.size() == 0) {
log.debug(String.format("No rule did match for node path %s.", path));
return ReplicationContent.VOID;
}
File file = this.createZip(binaries);
try {
return factory.create("application/zip", file, true);
}
catch (IOException e) {
boolean deleted = file.delete();
log.debug("file {} deleted : {}", file.getAbsolutePath(), deleted);
throw new ReplicationException(e);
}
}
private byte[] getContent(String path, Session session, ReplicationLog log) throws RepositoryException, ReplicationException {
int query;
StringBuilder sb = new StringBuilder("http://");
sb.append(this.serverHost);
if (this.serverPort != 80) {
sb.append(':').append(this.serverPort);
}
if ((query = path.indexOf(63)) != -1) {
sb.append(Text.escapePath((String)path.substring(0, query)));
sb.append('?');
sb.append(path.substring(query + 1));
} else {
sb.append(Text.escapePath((String)path));
}
String url = sb.toString();
log.debug(String.format("Requesting %s", url));
boolean create = false;
do {
GetMethod getReq = new GetMethod(url);
getReq.setFollowRedirects(true);
getReq.setRequestHeader("Cookie", this.getOrCreateTokenCookie(session, create));
try {
int status = this.httpClient.executeMethod((HttpMethod)getReq);
if (status == 200) {
byte[] arrby = getReq.getResponseBody();
return arrby;
}
if (!(status != 404 && status != 401 || create)) {
create = true;
continue;
}
try {
throw new ReplicationException("Unable to fetch content from " + url + " : " + status);
}
catch (HttpException e) {
throw new ReplicationException((Exception)e);
}
catch (IOException e) {
throw new ReplicationException(e);
}
}
finally {
getReq.releaseConnection();
continue;
}
break;
} while (true);
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
private File createZip(Map<String, byte[]> files) throws IOException {
File tmpFile = File.createTempFile("cq5", ".zip");
ZipOutputStream out = null;
boolean successful = false;
try {
out = new ZipOutputStream(new FileOutputStream(tmpFile));
for (Map.Entry<String, byte[]> entry : files.entrySet()) {
out.putNextEntry(new ZipEntry(entry.getKey()));
out.write(entry.getValue());
}
successful = true;
File file = tmpFile;
return file;
}
finally {
IOUtils.closeQuietly((OutputStream)out);
if (!successful && !tmpFile.delete()) {
throw new IOException("tmp zip file could not be deleted");
}
}
}
@Override
public String getName() {
return this.name;
}
@Override
public String getTitle() {
return "Static Content Builder";
}
protected void bindRepository(Repository repository) {
this.repository = repository;
}
protected void unbindRepository(Repository repository) {
if (this.repository == repository) {
this.repository = null;
}
}
private static class Rule {
private final GlobPattern pattern;
private final String replacement;
public Rule(String pattern, String replacement) {
this.pattern = new GlobPattern(pattern);
this.replacement = replacement;
}
public String replace(String input) {
if (this.pattern.matches(input)) {
Properties p = new Properties();
p.setProperty("path", input);
return Text.replaceVariables((Properties)p, (String)this.replacement, (boolean)false);
}
return null;
}
public String toString() {
return this.pattern.toString() + " -> " + this.replacement;
}
}
}