001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portlet.dynamicdatalists.util;
016    
017    import com.liferay.portal.kernel.json.JSONArray;
018    import com.liferay.portal.kernel.json.JSONFactoryUtil;
019    import com.liferay.portal.kernel.json.JSONObject;
020    import com.liferay.portal.kernel.language.LanguageUtil;
021    import com.liferay.portal.kernel.repository.model.FileEntry;
022    import com.liferay.portal.kernel.templateparser.Transformer;
023    import com.liferay.portal.kernel.util.GetterUtil;
024    import com.liferay.portal.kernel.util.LocaleUtil;
025    import com.liferay.portal.kernel.util.ParamUtil;
026    import com.liferay.portal.kernel.util.StringPool;
027    import com.liferay.portal.kernel.util.StringUtil;
028    import com.liferay.portal.kernel.util.Validator;
029    import com.liferay.portal.kernel.xml.Document;
030    import com.liferay.portal.kernel.xml.Element;
031    import com.liferay.portal.kernel.xml.SAXReaderUtil;
032    import com.liferay.portal.service.ServiceContext;
033    import com.liferay.portal.theme.ThemeDisplay;
034    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
035    import com.liferay.portlet.dynamicdatalists.model.DDLRecord;
036    import com.liferay.portlet.dynamicdatalists.model.DDLRecordConstants;
037    import com.liferay.portlet.dynamicdatalists.model.DDLRecordSet;
038    import com.liferay.portlet.dynamicdatalists.model.DDLRecordVersion;
039    import com.liferay.portlet.dynamicdatalists.service.DDLRecordLocalServiceUtil;
040    import com.liferay.portlet.dynamicdatalists.service.DDLRecordServiceUtil;
041    import com.liferay.portlet.dynamicdatalists.service.DDLRecordSetLocalServiceUtil;
042    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
043    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
044    import com.liferay.portlet.dynamicdatamapping.service.DDMTemplateLocalServiceUtil;
045    import com.liferay.portlet.dynamicdatamapping.storage.Field;
046    import com.liferay.portlet.dynamicdatamapping.storage.FieldConstants;
047    import com.liferay.portlet.dynamicdatamapping.storage.Fields;
048    import com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil;
049    import com.liferay.portlet.dynamicdatamapping.util.DDMImpl;
050    import com.liferay.portlet.dynamicdatamapping.util.DDMUtil;
051    import com.liferay.portlet.dynamicdatamapping.util.DDMXMLUtil;
052    import com.liferay.portlet.journal.util.JournalUtil;
053    import com.liferay.util.portlet.PortletRequestUtil;
054    
055    import java.util.Date;
056    import java.util.Iterator;
057    import java.util.List;
058    import java.util.Map;
059    
060    import javax.portlet.RenderRequest;
061    import javax.portlet.RenderResponse;
062    
063    import javax.servlet.http.HttpServletRequest;
064    import javax.servlet.http.HttpServletResponse;
065    
066    /**
067     * @author Marcelllus Tavares
068     * @author Eduardo Lundgren
069     */
070    public class DDLImpl implements DDL {
071    
072            public void addAllReservedEls(
073                    Element rootElement, Map<String, String> tokens,
074                    DDLRecordSet recordSet) {
075    
076                    JournalUtil.addReservedEl(
077                            rootElement, tokens, DDLConstants.RESERVED_RECORD_SET_ID,
078                            String.valueOf(recordSet.getRecordSetId()));
079    
080                    JournalUtil.addReservedEl(
081                            rootElement, tokens, DDLConstants.RESERVED_RECORD_SET_NAME,
082                            recordSet.getName());
083    
084                    JournalUtil.addReservedEl(
085                            rootElement, tokens, DDLConstants.RESERVED_RECORD_SET_DESCRIPTION,
086                            recordSet.getDescription());
087    
088                    JournalUtil.addReservedEl(
089                            rootElement, tokens, DDLConstants.RESERVED_DDM_STRUCTURE_ID,
090                            String.valueOf(recordSet.getDDMStructureId()));
091            }
092    
093            public JSONObject getRecordJSONObject(DDLRecord record) throws Exception {
094                    return getRecordJSONObject(record, false);
095            }
096    
097            public JSONObject getRecordJSONObject(
098                            DDLRecord record, boolean latestRecordVersion)
099                    throws Exception {
100    
101                    DDLRecordSet recordSet = record.getRecordSet();
102    
103                    DDMStructure ddmStructure = recordSet.getDDMStructure();
104    
105                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
106    
107                    for (String fieldName : ddmStructure.getFieldNames()) {
108                            jsonObject.put(fieldName, StringPool.BLANK);
109                    }
110    
111                    jsonObject.put("displayIndex", record.getDisplayIndex());
112                    jsonObject.put("recordId", record.getRecordId());
113    
114                    DDLRecordVersion recordVersion = record.getRecordVersion();
115    
116                    if (latestRecordVersion) {
117                            recordVersion = record.getLatestRecordVersion();
118                    }
119    
120                    Fields fields = StorageEngineUtil.getFields(
121                            recordVersion.getDDMStorageId());
122    
123                    Iterator<Field> itr = fields.iterator();
124    
125                    while (itr.hasNext()) {
126                            Field field = itr.next();
127    
128                            String fieldName = field.getName();
129                            String fieldType = field.getType();
130                            Object fieldValue = field.getValue();
131    
132                            if (fieldValue instanceof Date) {
133                                    jsonObject.put(fieldName, ((Date)fieldValue).getTime());
134                            }
135                            else if (fieldType.equals(DDMImpl.TYPE_DDM_DOCUMENTLIBRARY) &&
136                                             Validator.isNotNull(fieldValue)) {
137    
138                                    JSONObject fieldValueJSONObject =
139                                            JSONFactoryUtil.createJSONObject(
140                                                    String.valueOf(fieldValue));
141    
142                                    String uuid = fieldValueJSONObject.getString("uuid");
143                                    long groupId = fieldValueJSONObject.getLong("groupId");
144    
145                                    fieldValueJSONObject.put(
146                                            "title", getFileEntryTitle(uuid, groupId));
147    
148                                    jsonObject.put(fieldName, fieldValueJSONObject.toString());
149                            }
150                            else if ((fieldType.equals(DDMImpl.TYPE_RADIO) ||
151                                              fieldType.equals(DDMImpl.TYPE_SELECT)) &&
152                                             Validator.isNotNull(fieldValue)) {
153    
154                                    fieldValue = JSONFactoryUtil.createJSONArray(
155                                            String.valueOf(fieldValue));
156    
157                                    jsonObject.put(fieldName, (JSONArray)fieldValue);
158                            }
159                            else {
160                                    jsonObject.put(fieldName, String.valueOf(fieldValue));
161                            }
162                    }
163    
164                    return jsonObject;
165            }
166    
167            public JSONArray getRecordSetJSONArray(DDLRecordSet recordSet)
168                    throws Exception {
169    
170                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
171    
172                    DDMStructure ddmStructure = recordSet.getDDMStructure();
173    
174                    Map<String, Map<String, String>> fieldsMap =
175                            ddmStructure.getFieldsMap();
176    
177                    for (Map<String, String> fields : fieldsMap.values()) {
178                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
179    
180                            String dataType = fields.get(FieldConstants.DATA_TYPE);
181    
182                            jsonObject.put("dataType", dataType);
183    
184                            boolean editable = GetterUtil.getBoolean(
185                                    fields.get(FieldConstants.EDITABLE), true);
186    
187                            jsonObject.put("editable", editable);
188    
189                            String label = fields.get(FieldConstants.LABEL);
190    
191                            jsonObject.put("label", label);
192    
193                            String name = fields.get(FieldConstants.NAME);
194    
195                            jsonObject.put("name", name);
196    
197                            boolean required = GetterUtil.getBoolean(
198                                    fields.get(FieldConstants.REQUIRED));
199    
200                            jsonObject.put("required", required);
201    
202                            boolean sortable = GetterUtil.getBoolean(
203                                    fields.get(FieldConstants.SORTABLE), true);
204    
205                            jsonObject.put("sortable", sortable);
206    
207                            String type = fields.get(FieldConstants.TYPE);
208    
209                            jsonObject.put("type", type);
210    
211                            jsonArray.put(jsonObject);
212                    }
213    
214                    return jsonArray;
215            }
216    
217            public JSONArray getRecordsJSONArray(DDLRecordSet recordSet)
218                    throws Exception {
219    
220                    return getRecordsJSONArray(recordSet.getRecords(), false);
221            }
222    
223            public JSONArray getRecordsJSONArray(List<DDLRecord> records)
224                    throws Exception {
225    
226                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
227    
228                    for (DDLRecord record : records) {
229                            JSONObject jsonObject = getRecordJSONObject(record);
230    
231                            jsonArray.put(jsonObject);
232                    }
233    
234                    return jsonArray;
235            }
236    
237            public JSONArray getRecordsJSONArray(
238                            List<DDLRecord> records, boolean latestRecordVersion)
239                    throws Exception {
240    
241                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
242    
243                    for (DDLRecord record : records) {
244                            JSONObject jsonObject = getRecordJSONObject(
245                                    record, latestRecordVersion);
246    
247                            jsonArray.put(jsonObject);
248                    }
249    
250                    return jsonArray;
251            }
252    
253            public String getTemplateContent(
254                            long ddmTemplateId, DDLRecordSet recordSet,
255                            ThemeDisplay themeDisplay, RenderRequest renderRequest,
256                            RenderResponse renderResponse)
257                    throws Exception {
258    
259                    String viewMode = ParamUtil.getString(renderRequest, "viewMode");
260    
261                    String languageId = LanguageUtil.getLanguageId(renderRequest);
262    
263                    String xmlRequest = PortletRequestUtil.toXML(
264                            renderRequest, renderResponse);
265    
266                    if (Validator.isNull(xmlRequest)) {
267                            xmlRequest = "<request />";
268                    }
269    
270                    Map<String, String> tokens = JournalUtil.getTokens(
271                            recordSet.getGroupId(), themeDisplay, xmlRequest);
272    
273                    tokens.put("template_id", StringUtil.valueOf(ddmTemplateId));
274    
275                    String xml = StringPool.BLANK;
276    
277                    Document document = SAXReaderUtil.createDocument();
278    
279                    Element rootElement = document.addElement("root");
280    
281                    Document requestDocument = SAXReaderUtil.read(xmlRequest);
282    
283                    rootElement.add(requestDocument.getRootElement().createCopy());
284    
285                    addAllReservedEls(rootElement, tokens, recordSet);
286    
287                    xml = DDMXMLUtil.formatXML(document);
288    
289                    DDMTemplate template = DDMTemplateLocalServiceUtil.getTemplate(
290                            ddmTemplateId);
291    
292                    return _transformer.transform(
293                            themeDisplay, tokens, viewMode, languageId, xml,
294                            template.getScript(), template.getLanguage());
295            }
296    
297            public void sendRecordFileUpload(
298                            HttpServletRequest request, HttpServletResponse response,
299                            DDLRecord record, String fieldName)
300                    throws Exception {
301    
302                    Field field = record.getField(fieldName);
303    
304                    DDMUtil.sendFieldFile(request, response, field);
305            }
306    
307            public void sendRecordFileUpload(
308                            HttpServletRequest request, HttpServletResponse response,
309                            long recordId, String fieldName)
310                    throws Exception {
311    
312                    DDLRecord record = DDLRecordServiceUtil.getRecord(recordId);
313    
314                    sendRecordFileUpload(request, response, record, fieldName);
315            }
316    
317            public DDLRecord updateRecord(
318                            long recordId, long recordSetId, boolean mergeFields,
319                            boolean checkPermission, ServiceContext serviceContext)
320                    throws Exception {
321    
322                    boolean majorVersion = ParamUtil.getBoolean(
323                            serviceContext, "majorVersion");
324    
325                    DDLRecord record = DDLRecordLocalServiceUtil.fetchRecord(recordId);
326    
327                    DDLRecordSet recordSet = DDLRecordSetLocalServiceUtil.getDDLRecordSet(
328                            recordSetId);
329    
330                    DDMStructure ddmStructure = recordSet.getDDMStructure();
331    
332                    Fields fields = DDMUtil.getFields(
333                            ddmStructure.getStructureId(), serviceContext);
334    
335                    if (record != null) {
336                            if (checkPermission) {
337                                    record = DDLRecordServiceUtil.updateRecord(
338                                            recordId, majorVersion,
339                                            DDLRecordConstants.DISPLAY_INDEX_DEFAULT, fields,
340                                            mergeFields, serviceContext);
341                            }
342                            else {
343                                    record = DDLRecordLocalServiceUtil.updateRecord(
344                                            serviceContext.getUserId(), recordId, majorVersion,
345                                            DDLRecordConstants.DISPLAY_INDEX_DEFAULT, fields,
346                                            mergeFields, serviceContext);
347                            }
348                    }
349                    else {
350                            if (checkPermission) {
351                                    record = DDLRecordServiceUtil.addRecord(
352                                            serviceContext.getScopeGroupId(), recordSetId,
353                                            DDLRecordConstants.DISPLAY_INDEX_DEFAULT, fields,
354                                            serviceContext);
355                            }
356                            else {
357                                    record = DDLRecordLocalServiceUtil.addRecord(
358                                            serviceContext.getUserId(),
359                                            serviceContext.getScopeGroupId(), recordSetId,
360                                            DDLRecordConstants.DISPLAY_INDEX_DEFAULT, fields,
361                                            serviceContext);
362                            }
363    
364                    }
365    
366                    uploadRecordFieldFiles(record, serviceContext);
367    
368                    return record;
369            }
370    
371            public DDLRecord updateRecord(
372                            long recordId, long recordSetId, boolean mergeFields,
373                            ServiceContext serviceContext)
374                    throws Exception {
375    
376                    return updateRecord(
377                            recordId, recordSetId, mergeFields, true, serviceContext);
378            }
379    
380            public String uploadRecordFieldFile(
381                            DDLRecord record, String fieldName, ServiceContext serviceContext)
382                    throws Exception {
383    
384                    DDLRecordSet recordSet = record.getRecordSet();
385    
386                    DDMStructure ddmStructure = recordSet.getDDMStructure();
387    
388                    DDLRecordVersion recordVersion = record.getLatestRecordVersion();
389    
390                    return DDMUtil.uploadFieldFile(
391                            ddmStructure.getStructureId(), recordVersion.getDDMStorageId(),
392                            record, fieldName, serviceContext);
393            }
394    
395            protected String getFileEntryTitle(String uuid, long groupId) {
396                    try {
397                            FileEntry fileEntry =
398                                    DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(
399                                            uuid, groupId);
400    
401                            return fileEntry.getTitle();
402                    }
403                    catch (Exception e) {
404                            return LanguageUtil.format(
405                                    LocaleUtil.getDefault(), "is-temporarily-unavailable",
406                                    "content");
407                    }
408            }
409    
410            protected void uploadRecordFieldFiles(
411                            DDLRecord record, ServiceContext serviceContext)
412                    throws Exception {
413    
414                    DDLRecordSet recordSet = record.getRecordSet();
415    
416                    DDMStructure ddmStructure = recordSet.getDDMStructure();
417    
418                    for (String fieldName : ddmStructure.getFieldNames()) {
419                            String fieldDataType = ddmStructure.getFieldDataType(fieldName);
420    
421                            if (fieldDataType.equals(FieldConstants.FILE_UPLOAD)) {
422                                    uploadRecordFieldFile(record, fieldName, serviceContext);
423                            }
424                    }
425            }
426    
427            private Transformer _transformer = new DDLTransformer();
428    
429    }