Scene7SearchHtmlServlet.java
21.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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.granite.xss.XSSAPI
* com.day.cq.commons.date.RelativeTimeFormat
* com.day.cq.i18n.I18n
* com.day.cq.search.PredicateGroup
* com.day.cq.search.Query
* com.day.cq.search.QueryBuilder
* com.day.cq.search.result.SearchResult
* javax.jcr.Session
* javax.servlet.ServletException
* javax.servlet.http.HttpServletRequest
* org.apache.commons.lang.ArrayUtils
* 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.SlingHttpServletRequest
* org.apache.sling.api.SlingHttpServletResponse
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ResourceResolverFactory
* org.apache.sling.api.servlets.SlingAllMethodsServlet
* org.apache.sling.commons.json.JSONObject
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.dam.scene7.impl.servlets;
import com.adobe.granite.xss.XSSAPI;
import com.day.cq.commons.date.RelativeTimeFormat;
import com.day.cq.dam.scene7.api.S7Config;
import com.day.cq.dam.scene7.api.S7ConfigResolver;
import com.day.cq.dam.scene7.api.Scene7AssetMimetypeService;
import com.day.cq.dam.scene7.api.Scene7Service;
import com.day.cq.dam.scene7.api.constants.Scene7AssetType;
import com.day.cq.dam.scene7.api.model.Scene7Asset;
import com.day.cq.dam.scene7.impl.MetadataCondition;
import com.day.cq.dam.scene7.impl.utils.RequestUtils;
import com.day.cq.dam.scene7.impl.utils.Scene7AssetUtils;
import com.day.cq.i18n.I18n;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.SearchResult;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.jcr.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.ArrayUtils;
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.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
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.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(label="%cq.scene7.servlet.name", description="%cq.scene7.servlet.description")
@Service
@Properties(value={@Property(name="sling.servlet.resourceTypes", value={"dam/components/scene7/scene7page"}), @Property(name="sling.servlet.selectors", value={"search"}), @Property(name="sling.servlet.extensions", value={"html"}), @Property(name="sling.servlet.methods", value={"GET"})})
public class Scene7SearchHtmlServlet
extends SlingAllMethodsServlet {
private static final Logger LOG = LoggerFactory.getLogger(Scene7SearchHtmlServlet.class);
private static final String PATH = "path";
private static final String SEARCH_TERM = "searchTerm";
private static final String ASSET_TYPE = "assetType";
private static final String PUBLISH_STATUS = "publishStatus";
private static final String LIMIT = "limit";
private static final String FLASH_THUMB_URL = "https://s7sps1.scene7.com/IpsWeb/assets/skins/standard/icons/AssetIcons/Flash_2.png";
@Reference
protected Scene7Service scene7Service;
@Reference
private S7ConfigResolver s7configResolver;
@Reference
private QueryBuilder queryBuilder;
@Reference
private Scene7AssetMimetypeService scene7AssetMimeTypeService;
@Reference
private ResourceResolverFactory resolverFactory;
@Reference
private XSSAPI xssapi;
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
I18n i18n = new I18n((HttpServletRequest)request);
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
Resource resource = request.getResource();
S7Config s7Config = null;
if (resource == null) {
LOG.warn("Could not load a valid Scene7 configuration!");
response.getWriter().write("");
return;
}
String configPath = resource.getPath();
configPath = configPath.replaceAll("/jcr:content$", "");
s7Config = this.s7configResolver.getS7Config(resource.getResourceResolver(), configPath);
List<Scene7Asset> assets = this.searchAssets(s7Config, request);
if (assets == null) {
response.getWriter().write("");
return;
}
int originlAssetNo = assets.size();
if (assets != null) {
ArrayList<String> filterOutAssets = new ArrayList<String>();
filterOutAssets.add(Scene7AssetType.CATALOG.getValue());
assets = this.filterByProducts(assets, filterOutAssets, s7Config);
}
int afterAssetNo = assets.size();
int filterAssetNo = originlAssetNo - afterAssetNo;
StringBuffer sbAssetCard = new StringBuffer();
Iterator<Scene7Asset> i$ = assets.iterator();
while (i$.hasNext()) {
Scene7Asset asset = i$.next();
try {
String ref;
String lastModified;
String thumbUrl;
String flashUrl;
String rootPath = s7Config.getBasePath();
String publishServer = s7Config.getPublishServer();
if ("on".equalsIgnoreCase(s7Config.isPublishEnabled())) {
publishServer = s7Config.getPreviewServer();
}
if (!publishServer.substring(publishServer.length() - 1).equals("/")) {
publishServer = publishServer + "/";
}
String imageUrl = publishServer + "is/image/" + rootPath;
String videoUrl = publishServer + "e2/";
boolean isCQ = false;
Session session = (Session)request.getResourceResolver().adaptTo(Session.class);
DateFormat outdf = DateFormat.getDateTimeInstance(0, 0);
String type = asset.getAssetTypeStr();
String name = asset.getName();
String thumb = RequestUtils.buildURL(imageUrl, name, null);
String nanos = lastModified = asset.getModifiedDate().toString();
try {
lastModified = outdf.format(asset.getModifiedDate());
}
catch (Exception e) {
LOG.error(e.getMessage(), (Throwable)e);
}
String originalPath = asset.getOriginalPath();
String originalFile = asset.getOriginalFile();
String rootFolder = asset.getRootFolder();
String fileName = asset.getFileName();
Long width = asset.getWidth();
Long height = asset.getHeight();
Integer fileSize = asset.getFileSize();
String modifiedBy = asset.getModifiedBy();
if (Scene7AssetType.VIDEO.getValue().equals(type) || Scene7AssetType.MASTER_VIDEO.getValue().equals(type)) {
if (originalFile.endsWith(".swf") || type.equals("MasterVideo") && !originalFile.endsWith(".mp4")) {
++filterAssetNo;
continue;
}
ref = RequestUtils.buildURL(videoUrl, rootFolder + fileName, null);
} else {
ref = RequestUtils.buildURL(imageUrl, name, null);
}
String mimeType = this.scene7AssetMimeTypeService.getMimeTypeForAssetType(asset.getAssetType(), Scene7AssetUtils.getExtensionForFileReference(ref));
String templateParams = null;
JSONObject parameters = new JSONObject();
if (Scene7AssetType.TEMPLATE.getValue().equals(type)) {
asset = Scene7AssetUtils.extractTemplateSizeInformation(asset, this.scene7Service, s7Config);
templateParams = Scene7AssetUtils.extractTemplateParams(asset.getUrlModifier());
width = asset.getWidth();
height = asset.getHeight();
parameters.put("imageWidth", (Object)width);
parameters.put("imageHeight", (Object)height);
parameters.put("templateParams", (Object)templateParams);
parameters.put("type", (Object)type);
}
if (Scene7AssetType.FLASH.getValue().equals(type) && (flashUrl = s7Config.getFlashTemplatesServer()) != null) {
if (!flashUrl.endsWith("/")) {
flashUrl = flashUrl + "/";
}
ref = RequestUtils.buildURL(flashUrl, originalPath + originalFile, null);
thumb = "https://s7sps1.scene7.com/IpsWeb/assets/skins/standard/icons/AssetIcons/Flash_2.png";
}
if (Scene7AssetType.FXG.getValue().equals(type)) {
String fxgServer = s7Config.getFXGServer();
ref = RequestUtils.buildURL(fxgServer, rootPath + name, null);
thumb = RequestUtils.buildURL(fxgServer, rootPath + name, "fmt=jpeg");
}
isCQ = false;
if (!type.equals("Template")) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("path", "/content/dam");
map.put("property", "dam:scene7Name");
map.put("property.value", name);
Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), session);
SearchResult result = query.getResult();
isCQ = result.getHits().size() > 0;
}
thumbUrl = (thumbUrl = thumb).indexOf("?") != -1 ? thumbUrl + "&wid=319" + "&nanos=" + nanos : thumbUrl + "?wid=319" + "&nanos=" + nanos;
ResourceBundle resourceBundle = request.getResourceBundle(request.getLocale());
long lastModifiedMillis = asset.getModifiedDate().getTime();
Calendar modifiedDateRaw = Calendar.getInstance();
modifiedDateRaw.setTimeInMillis(lastModifiedMillis);
String modifiedDateStr = new RelativeTimeFormat("r", resourceBundle).format(lastModifiedMillis);
sbAssetCard.append("<article class=\"card-asset cq-draggable\" draggable=\"true\"\n");
sbAssetCard.append(" data-path='" + this.xssapi.encodeForHTMLAttr(ref) + "'\n");
sbAssetCard.append(" data-asset-group='s7media'\n");
sbAssetCard.append(" data-type='" + this.xssapi.encodeForHTMLAttr(type) + "'\n");
sbAssetCard.append(" data-param='" + this.xssapi.encodeForHTMLAttr(parameters.toString()) + "'\n");
if (mimeType != null && !mimeType.equals("")) {
sbAssetCard.append(" data-asset-mimetype='" + this.xssapi.encodeForHTMLAttr(mimeType) + "'\n");
}
sbAssetCard.append(">\n");
sbAssetCard.append(" <i class=\"select\"></i>\n");
sbAssetCard.append(" <i class=\"move\"></i>\n");
sbAssetCard.append(" <div class=\"card\">\n");
sbAssetCard.append(" <span class=\"image\">\n");
sbAssetCard.append(" <img class=\"show-grid cq-dd-image\" src=\"" + this.xssapi.encodeForHTMLAttr(thumbUrl) + "\" alt=\"" + this.xssapi.encodeForHTMLAttr(name) + "\">\n");
sbAssetCard.append(" </span>\n");
sbAssetCard.append(" <a href=\"#\" class=\"label\">\n");
sbAssetCard.append(" <h4>" + this.xssapi.encodeForHTML(name) + "</h4>\n");
if (mimeType != null && !mimeType.equals("")) {
sbAssetCard.append(" <p class=\"type\">" + this.xssapi.encodeForHTML(mimeType) + "</p>\n");
}
if (width != null && height != null) {
sbAssetCard.append(" <p class=\"resolution\">" + width + " x " + height + "</p>\n");
} else {
sbAssetCard.append(" <p class=\"resolution\"></p>\n");
}
if (fileSize != null) {
sbAssetCard.append(" <p class=\"size\">" + this.xssapi.encodeForHTML(this.readableFileSize(fileSize)) + "</p>\n");
}
sbAssetCard.append(" <div class=\"info\">\n");
sbAssetCard.append(" <p class=\"modified\">\n");
sbAssetCard.append(" <i class=\"coral-Icon coral-Icon--edit coral-Icon--sizeS\" title=\"" + i18n.get("Modified") + "\"></i>\n");
sbAssetCard.append(" <span class=\"date\">" + this.xssapi.encodeForHTML(i18n.getVar(modifiedDateStr)) + "</span>\n");
sbAssetCard.append(" </p>\n");
sbAssetCard.append(" <p class=\"links\"></p>\n");
sbAssetCard.append(" <p class=\"comments\"></p>\n");
sbAssetCard.append(" </div>\n");
sbAssetCard.append(" </a>\n");
sbAssetCard.append(" </div>\n");
sbAssetCard.append("</article>\n");
}
catch (Exception e) {
LOG.warn("Failed for generate asset card for scene7 asset: " + e.getMessage());
}
}
for (int i = 0; i < filterAssetNo; ++i) {
sbAssetCard.append("<article style=\"visibility:hidden; display:none\"></article>\n");
}
response.getWriter().write(sbAssetCard.toString());
}
private String readableFileSize(int size) {
if (size <= 0) {
return "0";
}
String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int)(Math.log10(size) / Math.log10(1024.0));
return new DecimalFormat("#,##0.#").format((double)size / Math.pow(1024.0, digitGroups)) + " " + units[digitGroups];
}
private List<Scene7Asset> searchAssets(S7Config s7Config, SlingHttpServletRequest request) throws UnsupportedEncodingException {
String assetType;
List<Scene7Asset> assets = null;
String path = request.getParameter("path");
if (path == null || path.equals("")) {
path = s7Config.getBasePath();
}
path = URLDecoder.decode(path, "utf-8");
String term = request.getParameter("searchTerm").trim();
MetadataCondition[] conditions = null;
if (term != null && !term.equals("")) {
conditions = new MetadataCondition[]{new MetadataCondition("name", 4, term)};
}
Object[] assetTypes = (assetType = request.getParameter("assetType")) != null ? assetType.split(",") : null;
String[] assetSubTypes = this.getSubTypes((String[])assetTypes);
this.convertSubTypes((String[])assetTypes);
assetTypes = (String[])ArrayUtils.add((Object[])assetTypes, (Object)Scene7AssetType.CATALOG.getValue());
Boolean searchMarkForPublish = true;
if (request.getParameter("publishStatus") == null || request.getParameter("publishStatus").equals("")) {
searchMarkForPublish = null;
} else if (request.getParameter("publishStatus").equals("Activate")) {
searchMarkForPublish = true;
} else if (request.getParameter("publishStatus").equals("Deactivate")) {
searchMarkForPublish = false;
}
String limit = request.getParameter("limit");
String startLimit = limit.substring(0, limit.indexOf(".."));
String endLimit = limit.substring(limit.indexOf("..") + 2);
int start = Integer.parseInt(startLimit);
int end = Integer.parseInt(endLimit);
int perPage = end - start;
int page = end / perPage;
assets = conditions != null ? this.scene7Service.searchAssetsByMetadata(path, Boolean.TRUE, (String[])assetTypes, assetSubTypes, searchMarkForPublish, conditions, perPage, page, s7Config) : this.scene7Service.searchAssets(path, Boolean.FALSE, searchMarkForPublish, (String[])assetTypes, assetSubTypes, new String[]{"assetArray/items/assetHandle", "assetArray/items/type", "assetArray/items/subType", "assetArray/items/name", "totalRows"}, null, perPage, page, s7Config);
if (assets != null) {
int len = assets.size();
String[] assetHandles = new String[len];
for (int i = 0; i < len; ++i) {
assetHandles[i] = assets.get(i).getAssetHandle();
}
assets = this.scene7Service.getAssets(assetHandles, null, null, s7Config);
}
return assets;
}
private List<Scene7Asset> filterByProducts(List<Scene7Asset> assetList, List<String> assetTypes, S7Config s7Config) {
HashSet<String> filteredAssetHandles = new HashSet<String>();
Iterator<Scene7Asset> i$ = assetList.iterator();
while (i$.hasNext()) {
Scene7Asset asset = i$.next();
if (!assetTypes.contains(asset.getAssetTypeStr())) continue;
filteredAssetHandles.add(asset.getAssetHandle());
asset = this.scene7Service.getAssociatedAssets(asset, s7Config);
for (Scene7Asset associatedAsset : asset.getSubAssets()) {
filteredAssetHandles.add(associatedAsset.getAssetHandle());
}
}
Iterator<Scene7Asset> assetIterator = assetList.iterator();
while (assetIterator.hasNext()) {
Scene7Asset currentAsset = assetIterator.next();
if (!filteredAssetHandles.contains(currentAsset.getAssetHandle())) continue;
assetIterator.remove();
}
return assetList;
}
private String[] getSubTypes(String[] assetTypes) {
if (assetTypes == null) {
return null;
}
ArrayList<String> typeArr = new ArrayList<String>();
for (int i = 0; i < assetTypes.length; ++i) {
if (!this.isAssetSet(assetTypes[i])) continue;
typeArr.add(assetTypes[i]);
}
if (typeArr.size() == 0) {
return null;
}
String[] ret = new String[typeArr.size()];
typeArr.toArray(ret);
return ret;
}
private void convertSubTypes(String[] assetTypes) {
if (assetTypes == null) {
return;
}
for (int i = 0; i < assetTypes.length; ++i) {
if (!this.isAssetSet(assetTypes[i])) continue;
assetTypes[i] = "AssetSet";
}
}
private boolean isAssetSet(String subtype) {
return subtype.equals("MediaSet") || subtype.equals("MbrSet") || subtype.equals("VideoSet") || subtype.equals("OfferSet") || subtype.equals("TemplateSet") || subtype.equals("SpinSet2d");
}
protected void bindScene7Service(Scene7Service scene7Service) {
this.scene7Service = scene7Service;
}
protected void unbindScene7Service(Scene7Service scene7Service) {
if (this.scene7Service == scene7Service) {
this.scene7Service = null;
}
}
protected void bindS7configResolver(S7ConfigResolver s7ConfigResolver) {
this.s7configResolver = s7ConfigResolver;
}
protected void unbindS7configResolver(S7ConfigResolver s7ConfigResolver) {
if (this.s7configResolver == s7ConfigResolver) {
this.s7configResolver = null;
}
}
protected void bindQueryBuilder(QueryBuilder queryBuilder) {
this.queryBuilder = queryBuilder;
}
protected void unbindQueryBuilder(QueryBuilder queryBuilder) {
if (this.queryBuilder == queryBuilder) {
this.queryBuilder = null;
}
}
protected void bindScene7AssetMimeTypeService(Scene7AssetMimetypeService scene7AssetMimetypeService) {
this.scene7AssetMimeTypeService = scene7AssetMimetypeService;
}
protected void unbindScene7AssetMimeTypeService(Scene7AssetMimetypeService scene7AssetMimetypeService) {
if (this.scene7AssetMimeTypeService == scene7AssetMimetypeService) {
this.scene7AssetMimeTypeService = null;
}
}
protected void bindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
this.resolverFactory = resourceResolverFactory;
}
protected void unbindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
if (this.resolverFactory == resourceResolverFactory) {
this.resolverFactory = null;
}
}
protected void bindXssapi(XSSAPI xSSAPI) {
this.xssapi = xSSAPI;
}
protected void unbindXssapi(XSSAPI xSSAPI) {
if (this.xssapi == xSSAPI) {
this.xssapi = null;
}
}
}