001    /**
002     * Copyright (c) 2000-2011 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.templateparser.Transformer;
022    import com.liferay.portal.kernel.upload.UploadPortletRequest;
023    import com.liferay.portal.kernel.util.GetterUtil;
024    import com.liferay.portal.kernel.util.ParamUtil;
025    import com.liferay.portal.kernel.util.StreamUtil;
026    import com.liferay.portal.kernel.util.StringPool;
027    import com.liferay.portal.kernel.util.Validator;
028    import com.liferay.portal.kernel.xml.Document;
029    import com.liferay.portal.kernel.xml.Element;
030    import com.liferay.portal.kernel.xml.SAXReaderUtil;
031    import com.liferay.portal.model.CompanyConstants;
032    import com.liferay.portal.service.ServiceContext;
033    import com.liferay.portal.theme.ThemeDisplay;
034    import com.liferay.portlet.documentlibrary.DuplicateDirectoryException;
035    import com.liferay.portlet.documentlibrary.DuplicateFileException;
036    import com.liferay.portlet.documentlibrary.store.DLStoreUtil;
037    import com.liferay.portlet.dynamicdatalists.model.DDLRecord;
038    import com.liferay.portlet.dynamicdatalists.model.DDLRecordSet;
039    import com.liferay.portlet.dynamicdatalists.model.DDLRecordVersion;
040    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
041    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
042    import com.liferay.portlet.dynamicdatamapping.service.DDMTemplateLocalServiceUtil;
043    import com.liferay.portlet.dynamicdatamapping.storage.Field;
044    import com.liferay.portlet.dynamicdatamapping.storage.FieldConstants;
045    import com.liferay.portlet.dynamicdatamapping.storage.Fields;
046    import com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil;
047    import com.liferay.portlet.dynamicdatamapping.util.DDMXMLUtil;
048    import com.liferay.portlet.journal.util.JournalUtil;
049    import com.liferay.util.portlet.PortletRequestUtil;
050    
051    import java.io.InputStream;
052    
053    import java.util.Date;
054    import java.util.Iterator;
055    import java.util.List;
056    import java.util.Map;
057    
058    import javax.portlet.RenderRequest;
059    import javax.portlet.RenderResponse;
060    
061    /**
062     * @author Marcelllus Tavares
063     * @author Eduardo Lundgren
064     */
065    public class DDLUtil {
066    
067            public static void addAllReservedEls(
068                    Element rootElement, Map<String, String> tokens,
069                    DDLRecordSet recordSet) {
070    
071                    JournalUtil.addReservedEl(
072                            rootElement, tokens, DDLConstants.RESERVED_RECORD_SET_ID,
073                            String.valueOf(recordSet.getRecordSetId()));
074    
075                    JournalUtil.addReservedEl(
076                            rootElement, tokens, DDLConstants.RESERVED_RECORD_SET_NAME,
077                            recordSet.getName());
078    
079                    JournalUtil.addReservedEl(
080                            rootElement, tokens, DDLConstants.RESERVED_RECORD_SET_DESCRIPTION,
081                            recordSet.getDescription());
082    
083                    JournalUtil.addReservedEl(
084                            rootElement, tokens, DDLConstants.RESERVED_DDM_STRUCTURE_ID,
085                            String.valueOf(recordSet.getDDMStructureId()));
086            }
087    
088            public static String getRecordFileUploadPath(DDLRecord record) {
089                    return "ddl_records/" + record.getRecordId();
090            }
091    
092            public static JSONObject getRecordJSONObject(DDLRecord record)
093                    throws Exception {
094    
095                    DDLRecordSet recordSet = record.getRecordSet();
096    
097                    DDMStructure ddmStructure = recordSet.getDDMStructure();
098    
099                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
100    
101                    for (String fieldName : ddmStructure.getFieldNames()) {
102                            jsonObject.put(fieldName, StringPool.BLANK);
103                    }
104    
105                    jsonObject.put("displayIndex", record.getDisplayIndex());
106                    jsonObject.put("recordId", record.getRecordId());
107    
108                    Fields fields = record.getFields();
109    
110                    Iterator<Field> itr = fields.iterator();
111    
112                    while (itr.hasNext()) {
113                            Field field = itr.next();
114    
115                            String fieldName = field.getName();
116                            Object fieldValue = field.getValue();
117    
118                            if (fieldValue instanceof Date) {
119                                    jsonObject.put(fieldName, ((Date)fieldValue).getTime());
120                            }
121                            else {
122                                    fieldValue = String.valueOf(fieldValue);
123    
124                                    if (ddmStructure.getFieldDisplayChildLabelAsValue(fieldName)) {
125                                            Map<String, String> childFields = ddmStructure.getFields(
126                                                    fieldName, FieldConstants.VALUE, (String)fieldValue);
127    
128                                            if (childFields != null) {
129                                                    fieldValue = childFields.get(FieldConstants.LABEL);
130                                            }
131                                    }
132    
133                                    jsonObject.put(fieldName, (String)fieldValue);
134                            }
135                    }
136    
137                    return jsonObject;
138            }
139    
140            public static JSONArray getRecordSetJSONArray(DDLRecordSet recordSet)
141                    throws Exception {
142    
143                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
144    
145                    DDMStructure ddmStructure = recordSet.getDDMStructure();
146    
147                    Map<String, Map<String, String>> fieldsMap =
148                            ddmStructure.getFieldsMap();
149    
150                    for (Map<String, String> fields : fieldsMap.values()) {
151                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
152    
153                            String dataType = fields.get(FieldConstants.DATA_TYPE);
154    
155                            jsonObject.put("dataType", dataType);
156    
157                            boolean editable = GetterUtil.getBoolean(
158                                    fields.get(FieldConstants.EDITABLE), true);
159    
160                            jsonObject.put("editable", editable);
161    
162                            String label = fields.get(FieldConstants.LABEL);
163    
164                            jsonObject.put("label", label);
165    
166                            String name = fields.get(FieldConstants.NAME);
167    
168                            jsonObject.put("name", name);
169    
170                            boolean required = GetterUtil.getBoolean(
171                                    fields.get(FieldConstants.REQUIRED));
172    
173                            jsonObject.put("required", required);
174    
175                            boolean sortable = GetterUtil.getBoolean(
176                                    fields.get(FieldConstants.SORTABLE), true);
177    
178                            jsonObject.put("sortable", sortable);
179    
180                            String type = fields.get(FieldConstants.TYPE);
181    
182                            jsonObject.put("type", type);
183    
184                            jsonArray.put(jsonObject);
185                    }
186    
187                    return jsonArray;
188            }
189    
190            public static JSONArray getRecordsJSONArray(DDLRecordSet recordSet)
191                    throws Exception {
192    
193                    return getRecordsJSONArray(recordSet.getRecords());
194            }
195    
196            public static JSONArray getRecordsJSONArray(List<DDLRecord> records)
197                    throws Exception {
198    
199                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
200    
201                    for (DDLRecord record : records) {
202                            JSONObject jsonObject = getRecordJSONObject(record);
203    
204                            jsonArray.put(jsonObject);
205                    }
206    
207                    return jsonArray;
208            }
209    
210            public static String getTemplateContent(
211                            long ddmTemplateId, DDLRecordSet recordSet,
212                            ThemeDisplay themeDisplay, RenderRequest renderRequest,
213                            RenderResponse renderResponse)
214                    throws Exception {
215    
216                    String viewMode = ParamUtil.getString(renderRequest, "viewMode");
217    
218                    String languageId = LanguageUtil.getLanguageId(renderRequest);
219    
220                    String xmlRequest = PortletRequestUtil.toXML(
221                            renderRequest, renderResponse);
222    
223                    if (Validator.isNull(xmlRequest)) {
224                            xmlRequest = "<request />";
225                    }
226    
227                    Map<String, String> tokens = JournalUtil.getTokens(
228                            recordSet.getGroupId(), themeDisplay, xmlRequest);
229    
230                    String xml = StringPool.BLANK;
231    
232                    Document document = SAXReaderUtil.createDocument();
233    
234                    Element rootElement = document.addElement("root");
235    
236                    Document requestDocument = SAXReaderUtil.read(xmlRequest);
237    
238                    rootElement.add(requestDocument.getRootElement().createCopy());
239    
240                    addAllReservedEls(rootElement, tokens, recordSet);
241    
242                    xml = DDMXMLUtil.formatXML(document);
243    
244                    DDMTemplate template = DDMTemplateLocalServiceUtil.getTemplate(
245                            ddmTemplateId);
246    
247                    return _transformer.transform(
248                            themeDisplay, tokens, viewMode, languageId, xml,
249                            template.getScript(), template.getLanguage());
250            }
251    
252            public static String uploadFieldFile(
253                            DDLRecord record, String fieldName, InputStream inputStream)
254                    throws Exception {
255    
256                    DDLRecordVersion recordVersion = record.getLatestRecordVersion();
257    
258                    String dirName =
259                            getRecordFileUploadPath(record) + StringPool.SLASH +
260                                    recordVersion.getVersion();
261    
262                    try {
263                            DLStoreUtil.addDirectory(
264                                    record.getCompanyId(), CompanyConstants.SYSTEM, dirName);
265                    }
266                    catch (DuplicateDirectoryException dde) {
267                    }
268    
269                    String fileName = dirName + StringPool.SLASH + fieldName;
270    
271                    try {
272                            DLStoreUtil.addFile(
273                                    record.getCompanyId(), CompanyConstants.SYSTEM, fileName,
274                                    inputStream);
275                    }
276                    catch (DuplicateFileException dfe) {
277                    }
278    
279                    return fileName;
280            }
281    
282            public static void uploadRecordFiles(
283                            DDLRecord record, UploadPortletRequest uploadPortletRequest,
284                            ServiceContext serviceContext)
285                    throws Exception {
286    
287                    DDLRecordSet recordSet = record.getRecordSet();
288                    DDMStructure ddmStructure = recordSet.getDDMStructure();
289    
290                    Fields fields = new Fields();
291    
292                    InputStream inputStream = null;
293    
294                    for (String fieldName : ddmStructure.getFieldNames()) {
295                            String fieldDataType = ddmStructure.getFieldDataType(fieldName);
296    
297                            if (!fieldDataType.equals(FieldConstants.FILE_UPLOAD)) {
298                                    continue;
299                            }
300    
301                            String fileName = uploadPortletRequest.getFileName(fieldName);
302    
303                            try {
304                                    Field field = record.getField(fieldName);
305    
306                                    String fieldValue = StringPool.BLANK;
307    
308                                    if (field != null) {
309                                            fieldValue = String.valueOf(field.getValue());
310                                    }
311    
312                                    inputStream = uploadPortletRequest.getFileAsStream(
313                                            fieldName, true);
314    
315                                    if (inputStream != null) {
316                                            String filePath = uploadFieldFile(
317                                                    record, fieldName, inputStream);
318    
319                                            JSONObject recordFileJSONObject =
320                                                    JSONFactoryUtil.createJSONObject();
321    
322                                            recordFileJSONObject.put("name", fileName);
323                                            recordFileJSONObject.put("path", filePath);
324                                            recordFileJSONObject.put("recordId", record.getRecordId());
325    
326                                            fieldValue = recordFileJSONObject.toString();
327                                    }
328    
329                                    field = new Field(
330                                            ddmStructure.getStructureId(), fieldName, fieldValue);
331    
332                                    fields.put(field);
333                            }
334                            finally {
335                                    StreamUtil.cleanUp(inputStream);
336                            }
337                    }
338    
339                    DDLRecordVersion recordVersion = record.getLatestRecordVersion();
340    
341                    StorageEngineUtil.update(
342                            recordVersion.getDDMStorageId(), fields, true, serviceContext);
343            }
344    
345            private static Transformer _transformer = new DDLTransformer();
346    
347    }