001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.dynamicdatamapping.util;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.exception.SystemException;
019    import com.liferay.portal.kernel.json.JSONFactoryUtil;
020    import com.liferay.portal.kernel.json.JSONObject;
021    import com.liferay.portal.kernel.security.pacl.DoPrivileged;
022    import com.liferay.portal.kernel.servlet.ServletResponseUtil;
023    import com.liferay.portal.kernel.upload.UploadRequest;
024    import com.liferay.portal.kernel.util.GetterUtil;
025    import com.liferay.portal.kernel.util.MimeTypesUtil;
026    import com.liferay.portal.kernel.util.StreamUtil;
027    import com.liferay.portal.kernel.util.StringBundler;
028    import com.liferay.portal.kernel.util.StringPool;
029    import com.liferay.portal.kernel.util.Validator;
030    import com.liferay.portal.model.BaseModel;
031    import com.liferay.portal.model.CompanyConstants;
032    import com.liferay.portal.service.ServiceContext;
033    import com.liferay.portal.util.PortalUtil;
034    import com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata;
035    import com.liferay.portlet.documentlibrary.model.DLFileEntryMetadataModel;
036    import com.liferay.portlet.documentlibrary.model.DLFileVersion;
037    import com.liferay.portlet.documentlibrary.store.DLStoreUtil;
038    import com.liferay.portlet.documentlibrary.store.Store;
039    import com.liferay.portlet.dynamicdatalists.model.DDLRecord;
040    import com.liferay.portlet.dynamicdatalists.model.DDLRecordModel;
041    import com.liferay.portlet.dynamicdatalists.model.DDLRecordVersion;
042    import com.liferay.portlet.dynamicdatamapping.NoSuchTemplateException;
043    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
044    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
045    import com.liferay.portlet.dynamicdatamapping.service.DDMStructureLocalServiceUtil;
046    import com.liferay.portlet.dynamicdatamapping.service.DDMTemplateLocalServiceUtil;
047    import com.liferay.portlet.dynamicdatamapping.storage.Field;
048    import com.liferay.portlet.dynamicdatamapping.storage.FieldConstants;
049    import com.liferay.portlet.dynamicdatamapping.storage.Fields;
050    import com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil;
051    
052    import java.io.InputStream;
053    import java.io.Serializable;
054    
055    import java.util.Date;
056    import java.util.Set;
057    
058    import javax.servlet.http.HttpServletRequest;
059    import javax.servlet.http.HttpServletResponse;
060    
061    /**
062     * @author Eduardo Lundgren
063     */
064    @DoPrivileged
065    public class DDMImpl implements DDM {
066    
067            public static final String TYPE_CHECKBOX = "checkbox";
068    
069            public static final String TYPE_DDM_DOCUMENTLIBRARY = "ddm-documentlibrary";
070    
071            public static final String TYPE_DDM_FILEUPLOAD = "ddm-fileupload";
072    
073            public static final String TYPE_RADIO = "radio";
074    
075            public static final String TYPE_SELECT = "select";
076    
077            @Override
078            public Fields getFields(
079                            long ddmStructureId, long ddmTemplateId,
080                            ServiceContext serviceContext)
081                    throws PortalException, SystemException {
082    
083                    return getFields(
084                            ddmStructureId, ddmTemplateId, StringPool.BLANK, serviceContext);
085            }
086    
087            @Override
088            public Fields getFields(
089                            long ddmStructureId, long ddmTemplateId, String fieldNamespace,
090                            ServiceContext serviceContext)
091                    throws PortalException, SystemException {
092    
093                    DDMStructure ddmStructure = DDMStructureLocalServiceUtil.getStructure(
094                            ddmStructureId);
095    
096                    try {
097                            DDMTemplate ddmTemplate = DDMTemplateLocalServiceUtil.getTemplate(
098                                    ddmTemplateId);
099    
100                            ddmStructure.setXsd(ddmTemplate.getScript());
101                    }
102                    catch (NoSuchTemplateException nste) {
103                    }
104    
105                    Set<String> fieldNames = ddmStructure.getFieldNames();
106    
107                    Fields fields = new Fields();
108    
109                    for (String fieldName : fieldNames) {
110                            Field field = new Field();
111    
112                            field.setName(fieldName);
113    
114                            String fieldDataType = ddmStructure.getFieldDataType(fieldName);
115                            String fieldType = ddmStructure.getFieldType(fieldName);
116                            Serializable fieldValue = serviceContext.getAttribute(
117                                    fieldNamespace + fieldName);
118    
119                            if (fieldDataType.equals(FieldConstants.DATE)) {
120                                    int fieldValueMonth = GetterUtil.getInteger(
121                                            serviceContext.getAttribute(
122                                                    fieldNamespace + fieldName + "Month"));
123                                    int fieldValueYear = GetterUtil.getInteger(
124                                            serviceContext.getAttribute(
125                                                    fieldNamespace + fieldName + "Year"));
126                                    int fieldValueDay = GetterUtil.getInteger(
127                                            serviceContext.getAttribute(
128                                                    fieldNamespace + fieldName + "Day"));
129    
130                                    Date fieldValueDate = PortalUtil.getDate(
131                                            fieldValueMonth, fieldValueDay, fieldValueYear);
132    
133                                    if (fieldValueDate != null) {
134                                            fieldValue = String.valueOf(fieldValueDate.getTime());
135                                    }
136                            }
137    
138                            if (Validator.isNull(fieldValue) ||
139                                    fieldDataType.equals(FieldConstants.FILE_UPLOAD)) {
140    
141                                    continue;
142                            }
143    
144                            if (fieldType.equals(DDMImpl.TYPE_RADIO) ||
145                                    fieldType.equals(DDMImpl.TYPE_SELECT)) {
146    
147                                    if (fieldValue instanceof String) {
148                                            fieldValue = new String[] {String.valueOf(fieldValue)};
149                                    }
150    
151                                    fieldValue = JSONFactoryUtil.serialize(fieldValue);
152                            }
153    
154                            Serializable fieldValueSerializable =
155                                    FieldConstants.getSerializable(
156                                            fieldDataType, GetterUtil.getString(fieldValue));
157    
158                            field.setValue(fieldValueSerializable);
159    
160                            fields.put(field);
161                    }
162    
163                    return fields;
164            }
165    
166            @Override
167            public Fields getFields(long ddmStructureId, ServiceContext serviceContext)
168                    throws PortalException, SystemException {
169    
170                    return getFields(ddmStructureId, 0, serviceContext);
171            }
172    
173            @Override
174            public Fields getFields(
175                            long ddmStructureId, String fieldNamespace,
176                            ServiceContext serviceContext)
177                    throws PortalException, SystemException {
178    
179                    return getFields(ddmStructureId, 0, fieldNamespace, serviceContext);
180            }
181    
182            @Override
183            public String getFileUploadPath(BaseModel<?> baseModel) {
184                    StringBundler sb = new StringBundler(7);
185    
186                    try {
187                            long primaryKey = 0;
188    
189                            String version = StringPool.BLANK;
190    
191                            if (baseModel instanceof DDLRecordModel) {
192                                    DDLRecord record = (DDLRecord)baseModel;
193    
194                                    primaryKey = record.getPrimaryKey();
195    
196                                    DDLRecordVersion recordVersion =
197                                            record.getLatestRecordVersion();
198    
199                                    version = recordVersion.getVersion();
200                            }
201                            else if (baseModel instanceof DLFileEntryMetadataModel) {
202                                    DLFileEntryMetadata fileEntryMetadata =
203                                            (DLFileEntryMetadata)baseModel;
204    
205                                    primaryKey = fileEntryMetadata.getPrimaryKey();
206    
207                                    DLFileVersion fileVersion = fileEntryMetadata.getFileVersion();
208    
209                                    version = fileVersion.getVersion();
210                            }
211    
212                            sb.append("ddm");
213                            sb.append(StringPool.SLASH);
214                            sb.append(baseModel.getModelClassName());
215                            sb.append(StringPool.SLASH);
216                            sb.append(primaryKey);
217                            sb.append(StringPool.SLASH);
218                            sb.append(version);
219                    }
220                    catch (Exception e) {
221                    }
222    
223                    return sb.toString();
224            }
225    
226            @Override
227            public void sendFieldFile(
228                            HttpServletRequest request, HttpServletResponse response,
229                            Field field)
230                    throws Exception {
231    
232                    if (field == null) {
233                            return;
234                    }
235    
236                    DDMStructure structure = field.getDDMStructure();
237    
238                    Serializable fieldValue = field.getValue();
239    
240                    JSONObject fileJSONObject = JSONFactoryUtil.createJSONObject(
241                            String.valueOf(fieldValue));
242    
243                    String fileName = fileJSONObject.getString("name");
244                    String filePath = fileJSONObject.getString("path");
245    
246                    InputStream is = DLStoreUtil.getFileAsStream(
247                            structure.getCompanyId(), CompanyConstants.SYSTEM, filePath);
248                    long contentLength = DLStoreUtil.getFileSize(
249                            structure.getCompanyId(), CompanyConstants.SYSTEM, filePath);
250                    String contentType = MimeTypesUtil.getContentType(fileName);
251    
252                    ServletResponseUtil.sendFile(
253                            request, response, fileName, is, contentLength, contentType);
254            }
255    
256            @Override
257            public String uploadFieldFile(
258                            long structureId, long storageId, BaseModel<?> baseModel,
259                            String fieldName, ServiceContext serviceContext)
260                    throws Exception {
261    
262                    return uploadFieldFile(
263                            structureId, storageId, baseModel, fieldName, StringPool.BLANK,
264                            serviceContext);
265            }
266    
267            @Override
268            public String uploadFieldFile(
269                            long structureId, long storageId, BaseModel<?> baseModel,
270                            String fieldName, String fieldNamespace,
271                            ServiceContext serviceContext)
272                    throws Exception {
273    
274                    HttpServletRequest request = serviceContext.getRequest();
275    
276                    if (!(request instanceof UploadRequest)) {
277                            return StringPool.BLANK;
278                    }
279    
280                    UploadRequest uploadRequest = (UploadRequest)request;
281    
282                    String fileName = uploadRequest.getFileName(fieldNamespace + fieldName);
283    
284                    String fieldValue = StringPool.BLANK;
285    
286                    InputStream inputStream = null;
287    
288                    Fields fields = StorageEngineUtil.getFields(storageId);
289    
290                    try {
291                            inputStream = uploadRequest.getFileAsStream(
292                                    fieldNamespace + fieldName, true);
293    
294                            if (inputStream != null) {
295                                    String filePath = storeFieldFile(
296                                            baseModel, fieldName, inputStream, serviceContext);
297    
298                                    JSONObject recordFileJSONObject =
299                                            JSONFactoryUtil.createJSONObject();
300    
301                                    recordFileJSONObject.put("name", fileName);
302                                    recordFileJSONObject.put("path", filePath);
303                                    recordFileJSONObject.put(
304                                            "className", baseModel.getModelClassName());
305                                    recordFileJSONObject.put(
306                                            "classPK", String.valueOf(baseModel.getPrimaryKeyObj()));
307    
308                                    fieldValue = recordFileJSONObject.toString();
309                            }
310                            else if (fields.contains(fieldName)) {
311                                    return StringPool.BLANK;
312                            }
313    
314                            Field field = new Field(structureId, fieldName, fieldValue);
315    
316                            fields.put(field);
317    
318                            StorageEngineUtil.update(storageId, fields, true, serviceContext);
319                    }
320                    finally {
321                            StreamUtil.cleanUp(inputStream);
322                    }
323    
324                    return fieldValue;
325            }
326    
327            protected String storeFieldFile(
328                            BaseModel<?> baseModel, String fieldName, InputStream inputStream,
329                            ServiceContext serviceContext)
330                    throws PortalException, SystemException {
331    
332                    long companyId = serviceContext.getCompanyId();
333    
334                    String dirName = getFileUploadPath(baseModel);
335    
336                    if (!DLStoreUtil.hasDirectory(
337                                    companyId, CompanyConstants.SYSTEM, dirName)) {
338    
339                            DLStoreUtil.addDirectory(
340                                    companyId, CompanyConstants.SYSTEM, dirName);
341                    }
342    
343                    String fileName = dirName + StringPool.SLASH + fieldName;
344    
345                    if (DLStoreUtil.hasFile(
346                                    companyId, CompanyConstants.SYSTEM, fileName,
347                                    Store.VERSION_DEFAULT)) {
348    
349                            DLStoreUtil.deleteFile(
350                                    companyId, CompanyConstants.SYSTEM, fileName,
351                                    Store.VERSION_DEFAULT);
352                    }
353    
354                    DLStoreUtil.addFile(
355                            companyId, CompanyConstants.SYSTEM, fileName, false, inputStream);
356    
357                    return fileName;
358            }
359    
360    }