PlatformServerServlet.java
18.3 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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.day.cq.commons.Externalizer
* com.scene7.is.sleng.ipp.ImageAnchorFactory
* com.scene7.is.util.callbacks.ExecutionUtil
* com.scene7.is.util.callbacks.Func1
* com.scene7.is.util.callbacks.Functions
* com.scene7.is.util.callbacks.Funx0
* com.scene7.is.util.callbacks.Option
* com.scene7.is.util.callbacks.Prox0
* com.scene7.is.util.callbacks.Prox2
* com.scene7.is.util.collections.CollectionUtil
* javax.jcr.Session
* javax.servlet.ServletConfig
* javax.servlet.ServletContext
* javax.servlet.ServletException
* javax.servlet.http.HttpServletRequest
* javax.servlet.http.HttpServletRequestWrapper
* javax.servlet.http.HttpServletResponse
* org.apache.felix.scr.annotations.Activate
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.sling.SlingServlet
* org.apache.sling.api.SlingHttpServletRequest
* org.apache.sling.api.SlingHttpServletResponse
* org.apache.sling.api.adapter.Adaptable
* org.apache.sling.api.request.RequestPathInfo
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.servlets.SlingSafeMethodsServlet
* org.apache.sling.jcr.api.SlingRepository
* org.apache.sling.settings.SlingSettingsService
* org.osgi.framework.BundleContext
* org.osgi.service.component.ComponentContext
* org.slf4j.Logger
* org.slf4j.LoggerFactory
* org.springframework.context.ApplicationContext
* org.springframework.context.ConfigurableApplicationContext
* scala.Function0
*/
package com.adobe.cq.dam.s7imaging.impl.ps;
import com.adobe.cq.dam.s7imaging.impl.auth.MemoryTokenService;
import com.adobe.cq.dam.s7imaging.impl.catalog.JcrCatalogAccessor;
import com.adobe.cq.dam.s7imaging.impl.catalog.JcrCatalogAccessorImpl;
import com.adobe.cq.dam.s7imaging.impl.catalog.JcrUtil;
import com.adobe.cq.dam.s7imaging.impl.gfx.LoopbackConfig;
import com.adobe.cq.dam.s7imaging.impl.is.ImageServerComponent;
import com.adobe.cq.dam.s7imaging.impl.ps.ApplicationContextFactory;
import com.adobe.cq.dam.s7imaging.impl.ps.ContentRequestHandler;
import com.adobe.cq.dam.s7imaging.impl.ps.JcrResourceAccessor;
import com.adobe.cq.dam.s7imaging.impl.ps.PsRequestHandler;
import com.adobe.cq.dam.s7imaging.impl.ps.RequestHandler;
import com.adobe.cq.dam.s7imaging.impl.ps.access_log.AccessLog;
import com.day.cq.commons.Externalizer;
import com.scene7.is.sleng.ipp.ImageAnchorFactory;
import com.scene7.is.util.callbacks.ExecutionUtil;
import com.scene7.is.util.callbacks.Func1;
import com.scene7.is.util.callbacks.Functions;
import com.scene7.is.util.callbacks.Funx0;
import com.scene7.is.util.callbacks.Option;
import com.scene7.is.util.callbacks.Prox0;
import com.scene7.is.util.callbacks.Prox2;
import com.scene7.is.util.collections.CollectionUtil;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jcr.Session;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.adapter.Adaptable;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import scala.Function0;
@SlingServlet(resourceTypes={"dam/scene7/imageserving_virtual_tree"}, methods={"GET", "POST"}, label="Adobe CQ Scene7 PlatformServer", description="Adobe CQ Scene7 PlatformServer", metatype=1)
public class PlatformServerServlet
extends SlingSafeMethodsServlet {
@Property(boolValue={1}, label="Cache enabled", description="Whether or not response cache is enabled (boolean)")
public static final String CacheEnable = "cache.enable";
@Property(value={"/etc/dam/imageserver/configuration/jcr:content/settings"}, label="Catalog root", description="JCR path pointing to the catalog root settings")
public static final String CatalogRoot = "catalog-root";
@Property(value={"cache"}, cardinality=10, label="Cache roots", description="One or more paths to response cache directories. Relative paths are resolved against internal s7imaging bundle directory")
public static final String CacheRootPaths = "cache.rootPaths";
@Property(longValue={200000000}, label="Cache Max Size", description="Maximum size of response cache in bytes")
public static final String CacheMaxSize = "cache.maxSize";
@Property(longValue={100000}, label="Cache Max Entries", description="Maximum number of entries in cache")
public static final String CacheMaxEntries = "cache.maxEntries";
@Property(label="Image root path", description="When defined, specifies the location of image files for ImageServer access")
public static final String RootPath = "rootPath";
@Reference
private AccessLog accessLogger;
@Reference
private SlingRepository repo;
@Reference
private ImageServerComponent imageServer;
@Reference
private MemoryTokenService tokenService;
@Reference
private SlingSettingsService slingSettings;
@Reference
private Externalizer externalizer;
private File psHome = null;
private String catalogRoot = null;
private Option<File> rootPath = Option.none();
private JcrResourceAccessor resourceAccessor = ApplicationContextFactory.resourceAccessor;
private JcrCatalogAccessor catalogAccessor = null;
private ConfigurableApplicationContext applicationContext = null;
private RequestHandler imageHandler = null;
private RequestHandler contentHandler = null;
private Map<String, String> psConfig = Collections.emptyMap();
private Option<URL> loopbackUrl = Option.none();
private static final Pattern ImagePath = Pattern.compile("^/is/image(/(.*))?");
private static final Pattern ContentPath = Pattern.compile("^/is/content(/(.*))?");
private static final Logger LOGGER = LoggerFactory.getLogger(PlatformServerServlet.class);
@Activate
protected void activate(ComponentContext ctx) {
LOGGER.info("Activating " + this.getClass().getName());
assert (this.imageServer != null);
assert (this.repo != null);
this.psHome = ctx.getBundleContext().getDataFile("platform-server");
this.catalogRoot = ctx.getProperties().get("catalog-root").toString();
Iterator i$ = Option.some(ctx.getProperties().get("rootPath")).iterator();
while (i$.hasNext()) {
Object rootPath = i$.next();
rootPath = rootPath.toString();
}
this.psConfig = PlatformServerServlet.buildPsConfig(ctx);
this.loopbackUrl = Option.some((Object)LoopbackConfig.createLoopbackUrl(ctx, this.externalizer));
LOGGER.info("Repo: " + (Object)this.repo);
LOGGER.info("psHome: " + this.psHome);
LOGGER.info("catalogRoot: " + this.catalogRoot);
if (this.loopbackUrl.isDefined()) {
LOGGER.info("loopbackUrl: " + this.loopbackUrl.get());
} else {
LOGGER.warn("loopbackUrl: not configured");
}
LOGGER.info(CollectionUtil.mkString(this.psConfig.entrySet(), (String)"PS config: {", (String)"\n", (String)"}"));
}
public void init(ServletConfig config) throws ServletException {
Thread thread = Thread.currentThread();
ClassLoader savedClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader(this.getClass().getClassLoader());
try {
this.init1(config);
}
catch (IOException e) {
throw new ServletException(e.getMessage(), (Throwable)e);
}
finally {
thread.setContextClassLoader(savedClassLoader);
}
}
private void init1(ServletConfig config) throws IOException {
assert (config != null);
if (this.imageServer.isEnabled()) {
this.catalogAccessor = JcrCatalogAccessorImpl.jcrCatalogAccessor(this.rootPath, Option.some((Object)new File(this.slingSettings.getSlingHomePath())));
this.applicationContext = ApplicationContextFactory.apply(this.psHome, this.catalogAccessor, this.imageServer, config.getServletContext(), this.psConfig);
this.imageHandler = PsRequestHandler.apply((ApplicationContext)this.applicationContext);
this.contentHandler = ContentRequestHandler.apply((ApplicationContext)this.applicationContext);
}
}
public void destroy() {
if (this.imageServer.isEnabled()) {
ExecutionUtil.doQuietly((Prox0)new Prox0<IOException>(){
public void run() throws IOException {
PlatformServerServlet.this.imageHandler.close();
}
}, (Prox0)new Prox0<IOException>(){
public void run() throws IOException {
PlatformServerServlet.this.contentHandler.close();
}
}, (Prox0[])new Prox0[]{new Prox0<Exception>(){
public void run() {
PlatformServerServlet.this.catalogAccessor.dispose();
}
}, new Prox0<Exception>(){
public void run() {
PlatformServerServlet.this.applicationContext.close();
}
}});
}
}
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
if (!this.imageServer.isEnabled()) {
PlatformServerServlet.handleDisabled(response);
} else if ("req=ping".equals(request.getQueryString())) {
PlatformServerServlet.handlePing(response);
} else {
ResourceResolver resolver = request.getResourceResolver();
String resourcePath = request.getRequestPathInfo().getResourcePath();
this.handleRequest((HttpServletRequest)request, (HttpServletResponse)response, resolver, resourcePath);
}
}
public void handleRequest(final HttpServletRequest req, final HttpServletResponse resp, final ResourceResolver resolver, final String resourcePath) throws IOException {
ExecutionUtil.withClassLoader((ClassLoader)this.getClass().getClassLoader(), (Prox0)new Prox0<IOException>(){
protected void run() throws IOException {
PlatformServerServlet.this.handleRequest1(req, resp, resolver, resourcePath);
}
});
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
void handleRequest1(final HttpServletRequest req, final HttpServletResponse resp, final ResourceResolver resolver, final String resourcePath) throws MalformedURLException {
Session session = JcrUtil.as(Session.class, (Adaptable)resolver);
String token = this.tokenService.createToken(session);
try {
String headerName = this.tokenService.getHttpHeaderName();
ImageAnchorFactory.withJcrCredentials((String)headerName, (String)token, (Function0)Functions.scalaFunc((Prox0)new Prox0<Exception>(){
public void run() throws Exception {
PlatformServerServlet.this.handleRequest2(req, resp, resolver, resourcePath);
}
}));
}
finally {
this.tokenService.removeToken(token);
}
}
void handleRequest2(final HttpServletRequest req, final HttpServletResponse resp, final ResourceResolver resolver, final String resourcePath) throws Exception {
URL baseUrl = this.resolveBaseUrl(req);
final String urlStr = URLEncoder.encode(baseUrl.toString(), "UTF-8");
this.catalogAccessor.withContext(new Func1<String, String>(){
public String call(String path) {
return "/jcr-storage:/" + urlStr + '/' + this.encodePath(path);
}
private String encodePath(String path) {
assert (path.startsWith("/"));
try {
return URLEncoder.encode(path.substring(1), "UTF-8").replace("+", "%20");
}
catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
}, resolver, new Prox0<Exception>(){
public void run() throws Exception {
PlatformServerServlet.this.handleRequest3(req, resp, resolver, resourcePath);
}
});
}
void handleRequest3(final HttpServletRequest req, final HttpServletResponse resp, final ResourceResolver resolver, final String resourcePath) throws Exception {
this.resourceAccessor.withContext(resolver, new Prox0<Exception>(){
public void run() throws Exception {
PlatformServerServlet.this.handleRequest4(req, resp, resolver, resourcePath);
}
});
}
void handleRequest4(HttpServletRequest req, HttpServletResponse resp, ResourceResolver resolver, String resourcePath) throws Exception {
String mappedPath = resolver.map(resourcePath);
RequestHandler handler = null;
if (ImagePath.matcher(mappedPath).matches()) {
handler = this.imageHandler;
} else if (ContentPath.matcher(mappedPath).matches()) {
handler = this.contentHandler;
}
if (handler != null) {
final RequestHandler h = handler;
this.accessLogger.invoke(new Prox2<HttpServletRequest, HttpServletResponse, Exception>(){
public void run(HttpServletRequest req, HttpServletResponse res) throws Exception {
h.handleRequest(req, res);
}
}, req, resp);
}
}
private static void handleDisabled(SlingHttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.setStatus(404);
resp.getWriter().println("Dynamic Media is disabled");
}
private static void handlePing(SlingHttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("OK");
}
private static HttpServletRequest translate(final String path, HttpServletRequest req) {
return new HttpServletRequestWrapper(req){
public String getServletPath() {
return path;
}
};
}
private static Map<String, String> buildPsConfig(ComponentContext ctx) {
Dictionary props = ctx.getProperties();
Map result = CollectionUtil.map();
result.put("cache.rootPaths", PlatformServerServlet.prop(props, "cache.rootPaths"));
result.put("cache.maxSize", PlatformServerServlet.prop(props, "cache.maxSize"));
result.put("cache.maxEntries", PlatformServerServlet.prop(props, "cache.maxEntries"));
result.put("cache.enable", PlatformServerServlet.prop(props, "cache.enable"));
return result;
}
private URL resolveBaseUrl(HttpServletRequest req) throws MalformedURLException {
Iterator i$ = this.loopbackUrl.iterator();
if (i$.hasNext()) {
URL u = (URL)i$.next();
return u;
}
URL reqUrl = new URL(req.getRequestURL().toString());
return new URL("http", "localhost", reqUrl.getPort(), req.getContextPath());
}
private static String prop(Dictionary props, String key) {
Object value = props.get(key);
if (value == null) {
throw new AssertionError((Object)("undefined key: " + key));
}
if (value instanceof String[]) {
return CollectionUtil.mkString(Arrays.asList((String[])value), (String)";");
}
return value.toString();
}
protected void bindAccessLogger(AccessLog accessLog) {
this.accessLogger = accessLog;
}
protected void unbindAccessLogger(AccessLog accessLog) {
if (this.accessLogger == accessLog) {
this.accessLogger = null;
}
}
protected void bindRepo(SlingRepository slingRepository) {
this.repo = slingRepository;
}
protected void unbindRepo(SlingRepository slingRepository) {
if (this.repo == slingRepository) {
this.repo = null;
}
}
protected void bindImageServer(ImageServerComponent imageServerComponent) {
this.imageServer = imageServerComponent;
}
protected void unbindImageServer(ImageServerComponent imageServerComponent) {
if (this.imageServer == imageServerComponent) {
this.imageServer = null;
}
}
protected void bindTokenService(MemoryTokenService memoryTokenService) {
this.tokenService = memoryTokenService;
}
protected void unbindTokenService(MemoryTokenService memoryTokenService) {
if (this.tokenService == memoryTokenService) {
this.tokenService = null;
}
}
protected void bindSlingSettings(SlingSettingsService slingSettingsService) {
this.slingSettings = slingSettingsService;
}
protected void unbindSlingSettings(SlingSettingsService slingSettingsService) {
if (this.slingSettings == slingSettingsService) {
this.slingSettings = null;
}
}
protected void bindExternalizer(Externalizer externalizer) {
this.externalizer = externalizer;
}
protected void unbindExternalizer(Externalizer externalizer) {
if (this.externalizer == externalizer) {
this.externalizer = null;
}
}
}