EntityCreationUtil.java
18.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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.cq.mobile.platform.MobileResource
* com.adobe.cq.mobile.platform.MobileResourceLocator
* com.adobe.cq.mobile.platform.MobileResourceType
* com.day.cq.commons.jcr.JcrUtil
* com.day.cq.i18n.I18n
* com.day.cq.wcm.api.Page
* com.day.cq.wcm.api.PageManager
* com.day.cq.wcm.webservicesupport.Configuration
* javax.jcr.Node
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.servlet.http.HttpServletRequest
* org.apache.commons.lang3.StringUtils
* org.apache.sling.api.SlingHttpServletRequest
* org.apache.sling.api.request.RequestParameter
* org.apache.sling.api.request.RequestParameterMap
* org.apache.sling.api.request.RequestPathInfo
* org.apache.sling.api.resource.ModifiableValueMap
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ResourceUtil
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.cq.mobile.dps.impl.utils;
import com.adobe.cq.mobile.dps.DPSCollection;
import com.adobe.cq.mobile.dps.DPSEntity;
import com.adobe.cq.mobile.dps.DPSException;
import com.adobe.cq.mobile.dps.DPSProject;
import com.adobe.cq.mobile.dps.impl.DPSClient;
import com.adobe.cq.mobile.dps.impl.DPSEntityImporter;
import com.adobe.cq.mobile.dps.impl.ImportStatus;
import com.adobe.cq.mobile.dps.impl.utils.DPSUtil;
import com.adobe.cq.mobile.platform.MobileResource;
import com.adobe.cq.mobile.platform.MobileResourceLocator;
import com.adobe.cq.mobile.platform.MobileResourceType;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.i18n.I18n;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.webservicesupport.Configuration;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.request.RequestParameterMap;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EntityCreationUtil {
public static final String PARAM_TEMPLATE = "template";
public static final String PARAM_UPLOAD = "upload";
private static final Logger LOGGER = LoggerFactory.getLogger(EntityCreationUtil.class);
private static void validateParameters(SlingHttpServletRequest request, String[] mandatoryParameters) throws DPSException {
I18n i18n = new I18n((HttpServletRequest)request);
ResourceResolver resolver = request.getResourceResolver();
Session session = (Session)resolver.adaptTo(Session.class);
String mandatoryMissing = "";
for (String nextMandatory : mandatoryParameters) {
RequestParameter mandatoryCheck = request.getRequestParameter(nextMandatory);
if (mandatoryCheck != null) continue;
if (mandatoryMissing.length() > 0) {
mandatoryMissing = mandatoryMissing + ", ";
}
mandatoryMissing = mandatoryMissing + nextMandatory;
}
if (StringUtils.isNotEmpty((CharSequence)mandatoryMissing)) {
throw new DPSException(i18n.get("Missing mandatory parameter(s): {0}", "missing parameters", new Object[]{mandatoryMissing}));
}
String appInstanceSuffix = request.getRequestPathInfo().getSuffix();
if (StringUtils.isEmpty((CharSequence)appInstanceSuffix)) {
throw new DPSException(i18n.get("Missing mandatory suffix."));
}
Resource appPublishInstance = resolver.getResource(appInstanceSuffix);
if (appPublishInstance == null) {
throw new DPSException(i18n.get("Invalid suffix: {0}", null, new Object[]{appInstanceSuffix}));
}
MobileResource suffixMobileResource = (MobileResource)appPublishInstance.adaptTo(MobileResource.class);
if (suffixMobileResource == null) {
throw new DPSException(i18n.get("Invalid suffix: {0}", null, new Object[]{appInstanceSuffix}));
}
MobileResourceLocator locator = (MobileResourceLocator)resolver.adaptTo(MobileResourceLocator.class);
MobileResource group = locator.findClosestResourceByType(appPublishInstance, MobileResourceType.GROUP.getType(), new String[0]);
if (group == null) {
throw new DPSException(i18n.get("Error finding the app-group of {0}", "Path", new Object[]{appInstanceSuffix}));
}
try {
String template = request.getRequestParameter("template").getString("utf-8");
if (!session.nodeExists(template)) {
throw new DPSException(i18n.get("Invalid template: {0}", "Template path", new Object[]{template}));
}
}
catch (Exception ex) {
if (ex instanceof DPSException) {
throw (DPSException)ex;
}
throw new DPSException(ex.getMessage(), ex);
}
}
public static Page createEntity(SlingHttpServletRequest request, String[] allowedProperties, String[] mandatoryParameters, DPSClient dpsClient, boolean creatingArticle, String dpsCapitalType, String entityHomeName, String nameParameter, MobileResource group, String entityTitle, ArrayList<String> warnings) throws DPSException {
EntityCreationUtil.validateParameters(request, mandatoryParameters);
Page newEntity = null;
I18n i18n = new I18n((HttpServletRequest)request);
ResourceResolver resolver = request.getResourceResolver();
Session session = (Session)resolver.adaptTo(Session.class);
PageManager pageManager = (PageManager)resolver.adaptTo(PageManager.class);
MobileResourceLocator locator = (MobileResourceLocator)resolver.adaptTo(MobileResourceLocator.class);
String appInstanceSuffix = request.getRequestPathInfo().getSuffix();
Resource appPublishInstance = resolver.getResource(appInstanceSuffix);
MobileResource suffixMobileResource = (MobileResource)appPublishInstance.adaptTo(MobileResource.class);
String dpsType = i18n.getVar(dpsCapitalType).toLowerCase();
String dpsTypeUpper = i18n.getVar(dpsCapitalType);
try {
String nodeName;
String template = request.getRequestParameter("template").getString("utf-8");
String entityHome = group.getPath() + "/" + entityHomeName;
Resource articleHomeRes = resolver.resolve(entityHome);
Resource imported = resolver.resolve(entityHome + "/" + "imported");
if (ResourceUtil.isNonExistingResource((Resource)articleHomeRes) || ResourceUtil.isNonExistingResource((Resource)imported)) {
HashMap<String, String> properties = new HashMap<String, String>();
properties.put("jcr:primaryType", "sling:Folder");
Resource home = articleHomeRes;
if (ResourceUtil.isNonExistingResource((Resource)articleHomeRes)) {
home = resolver.create((Resource)group.adaptTo(Resource.class), entityHomeName, properties);
}
resolver.create(home, "imported", properties);
if (resolver.isLive()) {
resolver.commit();
}
}
if ("imported".equals(nodeName = request.getRequestParameter(nameParameter).getString())) {
throw new DPSException(i18n.get("'{0}' is a reserved Name.", "The string 'imported'.", new Object[]{"imported"}));
}
if (!JcrUtil.isValidName((String)nodeName)) {
throw new DPSException(i18n.get("Invalid {0} name: {1}", "Entity type and entity Node Name", new Object[]{dpsType, nodeName}));
}
if (session.nodeExists(entityHome + "/" + nodeName)) {
throw new DPSException(i18n.get("{0} name, {1}, already exists in AEM.", "Entity type and entity Node Name", new Object[]{dpsTypeUpper, nodeName}));
}
DPSProject project = (DPSProject)DPSUtil.getDPSObject((Page)group.adaptTo(Page.class));
if (project.getProjectId() == null || project.getDPSConfiguration() == null) {
warnings.add(i18n.get("WARNING: The operation could not connect to Experience Manager Mobile to ensure {0} name was unique.", "Entity type", new Object[]{dpsCapitalType}));
} else {
boolean entityExists;
try {
entityExists = creatingArticle ? dpsClient.articleExistsInDPS(project, nodeName) : dpsClient.bannerExistsInDPS(project, nodeName);
}
catch (DPSException dpsEx) {
warnings.add(i18n.get("WARNING: The operation failed to connect to Experience Manager Mobile to ensure {0} name was unique.", "Entity type", new Object[]{dpsCapitalType}));
entityExists = false;
}
if (entityExists) {
throw new DPSException(i18n.get("{0} name, {1}, already exists in Experience Manager Mobile.", "Entity type and entity Node Name", new Object[]{dpsCapitalType, nodeName}));
}
}
newEntity = pageManager.create(entityHome, nodeName, template, entityTitle);
session.save();
}
catch (DPSException dpsEx) {
throw dpsEx;
}
catch (Exception ex) {
throw new DPSException(i18n.get("Error extracting properties and creating {0}: {1}", "Entity type and Path to Page", new Object[]{dpsCapitalType, appPublishInstance.getPath()}), ex);
}
return newEntity;
}
public static void saveProperties(SlingHttpServletRequest request, Page newEntity, String[] allowedProperties, String dpsResourceType, DPSClient dpsClient, DPSEntityImporter dpsEntityImporter, MobileResource group) throws DPSException {
I18n i18n = new I18n((HttpServletRequest)request);
ResourceResolver resolver = request.getResourceResolver();
Session session = (Session)resolver.adaptTo(Session.class);
PageManager pageManager = (PageManager)resolver.adaptTo(PageManager.class);
String dpsCapitalType = dpsResourceType.substring(4);
String dpsType = i18n.get(dpsCapitalType.toLowerCase());
try {
ModifiableValueMap addPropertiesVM = (ModifiableValueMap)newEntity.getContentResource().adaptTo(ModifiableValueMap.class);
for (String nextProperty : allowedProperties) {
RequestParameter[] requestParameters = request.getRequestParameters(nextProperty);
if (requestParameters == null || requestParameters.length == 0) continue;
String requestType = EntityCreationUtil.getPropertyType(requestParameters, request, nextProperty);
if (!requestType.endsWith("[]")) {
Object obj = EntityCreationUtil.getSingleObject(requestParameters, requestType);
if (obj == null) continue;
addPropertiesVM.put((Object)nextProperty, obj);
continue;
}
Object[] values = EntityCreationUtil.getArrayObject(requestParameters, requestType);
if (values == null || values.length <= 0) continue;
addPropertiesVM.put((Object)nextProperty, (Object)values);
}
addPropertiesVM.put((Object)"dps-resourceType", (Object)dpsResourceType);
if (session.hasPendingChanges()) {
session.save();
}
}
catch (Exception ex) {
throw new DPSException(i18n.get("Error saving properties on {0}", "Path to Page", new Object[]{newEntity.getPath()}));
}
boolean uploadNewEntity = request.getRequestParameterMap().containsKey((Object)"upload") && "false".equalsIgnoreCase(request.getRequestParameter("upload").getString());
RequestParameter[] collections = request.getRequestParameters("dps-collections");
if (uploadNewEntity || collections != null) {
DPSEntity dpsEntity = (DPSEntity)DPSUtil.getDPSObject(newEntity);
try {
if (!uploadNewEntity) {
LOGGER.warn("New {} {} uploaded in order to add to a collection's content. Ignoring request parameter 'upload'.", (Object)dpsType, (Object)newEntity.getName());
}
dpsClient.uploadEntity(dpsEntity, true, false);
}
catch (DPSException dpsEx) {
throw new DPSException(i18n.get("Error uploading the new {0} to Experience Manager Mobile", "Entity Type", new Object[]{dpsType}));
}
if (collections != null) {
String collectionLinkErrorMessage = "";
for (RequestParameter collection : collections) {
try {
Page nextCollection = pageManager.getPage(collection.getString("UTF-8"));
DPSCollection dpsCollection = (DPSCollection)DPSUtil.getDPSObject(nextCollection);
dpsClient.addContentToCollection(dpsCollection, dpsEntity);
dpsEntityImporter.importDPSEntity(dpsCollection);
continue;
}
catch (Exception ex) {
collectionLinkErrorMessage = collectionLinkErrorMessage + i18n.get("Error associating to collection {0} ", "collection name", new Object[]{collection.getString()});
}
}
if (StringUtils.isNotEmpty((CharSequence)collectionLinkErrorMessage)) {
throw new DPSException(i18n.get("{0} created successfully but had the following errors: {1}", "Entity Type and a list of errors", new Object[]{dpsCapitalType, collectionLinkErrorMessage}));
}
}
}
}
public static void setImage(SlingHttpServletRequest request, Page newEntity, String dpsCapitalType, String imageParameterName, String imageNodeName) throws DPSException {
I18n i18n = new I18n((HttpServletRequest)request);
ResourceResolver resolver = request.getResourceResolver();
Session session = (Session)resolver.adaptTo(Session.class);
String dpsType = i18n.get(dpsCapitalType.toLowerCase());
RequestParameter imageParameter = request.getRequestParameter(imageParameterName);
if (imageParameter != null) {
try {
String imagePath = imageParameter.getString();
if (StringUtils.isNotEmpty((CharSequence)imagePath)) {
Node imageNode = JcrUtil.createPath((String)(newEntity.getPath() + "/" + "jcr:content" + "/" + imageNodeName), (String)"nt:unstructured", (Session)session);
if (session.hasPendingChanges()) {
session.save();
}
imageNode.setProperty("sling:resourceType", "foundation/components/image");
imageNode.setProperty("fileReference", imagePath);
imageNode.setProperty("imageRotate", 0);
imageNode.setProperty("imageCrop", "");
if (session.hasPendingChanges()) {
session.save();
}
}
}
catch (RepositoryException repEx) {
throw new DPSException(i18n.get("{0} created successfully but the image could not be save.", "Entity Type", new Object[]{dpsCapitalType}));
}
}
}
private static String getPropertyType(RequestParameter[] requestParameters, SlingHttpServletRequest request, String property) {
String type = "String";
String typeHint = request.getParameter(property + "@TypeHint");
if (StringUtils.isNotEmpty((CharSequence)typeHint)) {
type = typeHint;
} else if (requestParameters.length > 1) {
type = "String[]";
}
return type;
}
private static Object getSingleObject(RequestParameter[] requestParameters, String type) {
if (type.equals("String")) {
String value = null;
for (int i = 0; i < requestParameters.length; ++i) {
try {
if (!StringUtils.isNotEmpty((CharSequence)requestParameters[i].getString("utf-8"))) continue;
value = requestParameters[i].getString("utf-8");
break;
}
catch (UnsupportedEncodingException encodingEx) {
// empty catch block
}
}
return value;
}
if (type.equals("Boolean")) {
return requestParameters[0].getString().equalsIgnoreCase("true") || requestParameters[0].getString().equalsIgnoreCase("on");
}
return requestParameters[0];
}
private static Object[] getArrayObject(RequestParameter[] requestParameters, String type) {
if (type.equals("String[]")) {
int i;
int size = 0;
for (i = 0; i < requestParameters.length; ++i) {
try {
if (!StringUtils.isNotEmpty((CharSequence)requestParameters[i].getString("utf-8"))) continue;
++size;
continue;
}
catch (UnsupportedEncodingException encodingEx) {
// empty catch block
}
}
Object[] values = new String[size];
for (i = 0; i < requestParameters.length; ++i) {
try {
if (!StringUtils.isNotEmpty((CharSequence)requestParameters[i].getString("utf-8"))) continue;
values[i] = requestParameters[i].getString("utf-8");
continue;
}
catch (UnsupportedEncodingException encodingEx) {
// empty catch block
}
}
return values;
}
return null;
}
}