001    /**
002     * Copyright (c) 2000-2013 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.portal.verify;
016    
017    import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery;
018    import com.liferay.portal.kernel.dao.orm.Disjunction;
019    import com.liferay.portal.kernel.dao.orm.DynamicQuery;
020    import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
021    import com.liferay.portal.kernel.dao.orm.Projection;
022    import com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil;
023    import com.liferay.portal.kernel.dao.orm.Property;
024    import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
025    import com.liferay.portal.kernel.dao.orm.QueryUtil;
026    import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
027    import com.liferay.portal.kernel.exception.PortalException;
028    import com.liferay.portal.kernel.exception.SystemException;
029    import com.liferay.portal.kernel.json.JSONFactoryUtil;
030    import com.liferay.portal.kernel.json.JSONObject;
031    import com.liferay.portal.kernel.log.Log;
032    import com.liferay.portal.kernel.log.LogFactoryUtil;
033    import com.liferay.portal.kernel.repository.model.FileEntry;
034    import com.liferay.portal.kernel.repository.model.FileVersion;
035    import com.liferay.portal.kernel.repository.model.Folder;
036    import com.liferay.portal.kernel.util.GetterUtil;
037    import com.liferay.portal.kernel.util.MimeTypesUtil;
038    import com.liferay.portal.kernel.util.StringBundler;
039    import com.liferay.portal.kernel.util.StringPool;
040    import com.liferay.portal.kernel.util.StringUtil;
041    import com.liferay.portal.kernel.util.Validator;
042    import com.liferay.portal.kernel.xml.Attribute;
043    import com.liferay.portal.kernel.xml.Document;
044    import com.liferay.portal.kernel.xml.DocumentException;
045    import com.liferay.portal.kernel.xml.Element;
046    import com.liferay.portal.kernel.xml.Node;
047    import com.liferay.portal.kernel.xml.SAXReaderUtil;
048    import com.liferay.portal.kernel.xml.XPath;
049    import com.liferay.portal.model.AuditedModel;
050    import com.liferay.portal.model.BaseModel;
051    import com.liferay.portal.model.CompanyConstants;
052    import com.liferay.portal.model.User;
053    import com.liferay.portal.service.ServiceContext;
054    import com.liferay.portal.service.UserLocalServiceUtil;
055    import com.liferay.portal.util.PortalUtil;
056    import com.liferay.portlet.documentlibrary.NoSuchFileEntryException;
057    import com.liferay.portlet.documentlibrary.NoSuchFolderException;
058    import com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata;
059    import com.liferay.portlet.documentlibrary.model.DLFileVersion;
060    import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
061    import com.liferay.portlet.documentlibrary.model.DLSyncConstants;
062    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
063    import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
064    import com.liferay.portlet.documentlibrary.service.DLFileEntryMetadataLocalServiceUtil;
065    import com.liferay.portlet.documentlibrary.store.DLStoreUtil;
066    import com.liferay.portlet.dynamicdatalists.model.DDLRecord;
067    import com.liferay.portlet.dynamicdatalists.model.DDLRecordModel;
068    import com.liferay.portlet.dynamicdatalists.model.DDLRecordSet;
069    import com.liferay.portlet.dynamicdatalists.model.DDLRecordVersion;
070    import com.liferay.portlet.dynamicdatalists.service.DDLRecordLocalServiceUtil;
071    import com.liferay.portlet.dynamicdatamapping.model.DDMContent;
072    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
073    import com.liferay.portlet.dynamicdatamapping.model.DDMStructureLink;
074    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
075    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplateConstants;
076    import com.liferay.portlet.dynamicdatamapping.service.DDMStructureLinkLocalServiceUtil;
077    import com.liferay.portlet.dynamicdatamapping.service.DDMStructureLocalServiceUtil;
078    import com.liferay.portlet.dynamicdatamapping.service.DDMTemplateLocalServiceUtil;
079    import com.liferay.portlet.dynamicdatamapping.service.persistence.DDMContentActionableDynamicQuery;
080    import com.liferay.portlet.dynamicdatamapping.service.persistence.DDMContentUtil;
081    import com.liferay.portlet.dynamicdatamapping.service.persistence.DDMTemplateActionableDynamicQuery;
082    import com.liferay.portlet.dynamicdatamapping.storage.Field;
083    import com.liferay.portlet.dynamicdatamapping.storage.FieldConstants;
084    import com.liferay.portlet.dynamicdatamapping.storage.Fields;
085    import com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil;
086    import com.liferay.portlet.dynamicdatamapping.util.DDMImpl;
087    import com.liferay.portlet.dynamicdatamapping.util.DDMXMLUtil;
088    
089    import java.io.File;
090    import java.io.Serializable;
091    
092    import java.util.HashMap;
093    import java.util.HashSet;
094    import java.util.List;
095    import java.util.Map;
096    import java.util.Set;
097    
098    /**
099     * @author Marcellus Tavares
100     */
101    public class VerifyDynamicDataMapping extends VerifyProcess {
102    
103            protected void addFieldsDisplay(Element rootElement) {
104                    List<Element> dynamicElementElements = rootElement.elements(
105                            "dynamic-element");
106    
107                    StringBundler sb = new StringBundler(4 * dynamicElementElements.size());
108    
109                    for (Element dynamicElementElement : dynamicElementElements) {
110                            String fieldName = dynamicElementElement.attributeValue("name");
111    
112                            sb.append(fieldName);
113                            sb.append(DDMImpl.INSTANCE_SEPARATOR);
114                            sb.append(StringUtil.randomId());
115    
116                            if (dynamicElementElements.indexOf(dynamicElementElement) !=
117                                            (dynamicElementElements.size() - 1)) {
118    
119                                    sb.append(StringPool.COMMA);
120                            }
121                    }
122    
123                    Element element = rootElement.addElement("dynamic-element");
124    
125                    element.addAttribute("name", DDMImpl.FIELDS_DISPLAY_NAME);
126    
127                    Element dynamicContentElement = element.addElement("dynamic-content");
128    
129                    dynamicContentElement.addCDATA(sb.toString());
130            }
131    
132            protected FileEntry addFileEntry(
133                            long companyId, long userId, long groupId, long folderId,
134                            String fileName, String filePath, int status)
135                    throws Exception {
136    
137                    String contentType = MimeTypesUtil.getContentType(fileName);
138    
139                    String title = fileName;
140    
141                    try {
142                            return DLAppLocalServiceUtil.getFileEntry(groupId, folderId, title);
143                    }
144                    catch (NoSuchFileEntryException nsfe) {
145                            if (_log.isDebugEnabled()) {
146                                    _log.debug(nsfe, nsfe);
147                            }
148                    }
149    
150                    try {
151                            File file = DLStoreUtil.getFile(
152                                    companyId, CompanyConstants.SYSTEM, filePath);
153    
154                            ServiceContext serviceContext = createServiceContext();
155    
156                            FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(
157                                    userId, groupId, folderId, fileName, contentType, title,
158                                    StringPool.BLANK, StringPool.BLANK, file, serviceContext);
159    
160                            updateFileEntryStatus(fileEntry, status, serviceContext);
161    
162                            return fileEntry;
163                    }
164                    catch (Exception e) {
165                            if (_log.isWarnEnabled()) {
166                                    _log.warn("Unable to add file entry " + fileName, e);
167                            }
168    
169                            return null;
170                    }
171            }
172    
173            protected Folder addFolder(
174                            long userId, long groupId, long primaryKey, String fieldName)
175                    throws Exception {
176    
177                    Folder ddmFolder = addFolder(
178                            userId, groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, "DDM",
179                            StringPool.BLANK);
180    
181                    Folder primaryKeyFolder = addFolder(
182                            userId, groupId, ddmFolder.getFolderId(),
183                            String.valueOf(primaryKey), StringPool.BLANK);
184    
185                    return addFolder(
186                            userId, groupId, primaryKeyFolder.getFolderId(), fieldName,
187                            StringPool.BLANK);
188            }
189    
190            protected Folder addFolder(
191                            long userId, long groupId, long parentFolderId, String name,
192                            String description)
193                    throws Exception {
194    
195                    try {
196                            return DLAppLocalServiceUtil.getFolder(
197                                    groupId, parentFolderId, name);
198                    }
199                    catch (NoSuchFolderException nsfe) {
200                            return DLAppLocalServiceUtil.addFolder(
201                                    userId, groupId, parentFolderId, name, description,
202                                    createServiceContext());
203                    }
204            }
205    
206            protected boolean checkDuplicateNames(DDMStructure structure)
207                    throws Exception {
208    
209                    String xml =
210                            "<root>" + getFullStructureXML(structure, StringPool.BLANK) +
211                                    "</root>";
212    
213                    Document document = SAXReaderUtil.read(xml);
214    
215                    Set<String> duplicateElementNames =
216                            getDuplicateElementNames(
217                                    document.getRootElement(), new HashSet<String>(),
218                                    new HashSet<String>());
219    
220                    if (duplicateElementNames.isEmpty()) {
221                            return false;
222                    }
223    
224                    if (!_log.isWarnEnabled()) {
225                            return true;
226                    }
227    
228                    StringBundler sb = new StringBundler(
229                            duplicateElementNames.size() * 2 + 7);
230    
231                    sb.append("Structure with class name ID ");
232                    sb.append(structure.getClassNameId());
233                    sb.append(" and structure key = ");
234                    sb.append(structure.getStructureKey());
235                    sb.append(" contains more than one element that is identified by the ");
236                    sb.append("same name either within itself or within any of its ");
237                    sb.append("parent structures. The duplicate element names are: ");
238    
239                    for (String duplicateElementName : duplicateElementNames) {
240                            sb.append(duplicateElementName);
241                            sb.append(StringPool.COMMA_AND_SPACE);
242                    }
243    
244                    sb.setIndex(sb.index() - 1);
245    
246                    _log.warn(sb.toString());
247    
248                    return true;
249            }
250    
251            protected boolean createDefaultMetadataElement(
252                    Element dynamicElementElement, String defaultLanguageId) {
253    
254                    boolean hasDefaultMetadataElement = hasDefaultMetadataElement(
255                            dynamicElementElement, defaultLanguageId);
256    
257                    if (hasDefaultMetadataElement) {
258                            return false;
259                    }
260    
261                    Element metadataElement = dynamicElementElement.addElement("meta-data");
262    
263                    metadataElement.addAttribute("locale", defaultLanguageId);
264    
265                    Element entryElement = metadataElement.addElement("entry");
266    
267                    entryElement.addAttribute("name", "label");
268                    entryElement.addCDATA(StringPool.BLANK);
269    
270                    return true;
271            }
272    
273            protected ServiceContext createServiceContext() {
274                    ServiceContext serviceContext = new ServiceContext();
275    
276                    serviceContext.setAddGroupPermissions(true);
277                    serviceContext.setAddGuestPermissions(true);
278    
279                    return serviceContext;
280            }
281    
282            @Override
283            protected void doVerify() throws Exception {
284                    setUpClassNameIds();
285    
286                    List<DDMStructure> structures =
287                            DDMStructureLocalServiceUtil.getStructures();
288    
289                    boolean duplicateExists = false;
290    
291                    for (DDMStructure structure : structures) {
292                            if (checkDuplicateNames(structure)) {
293                                    duplicateExists = true;
294                            }
295                    }
296    
297                    if (duplicateExists) {
298                            throw new VerifyException(
299                                    "Duplicate element name found in structures");
300                    }
301    
302                    for (DDMStructure structure : structures) {
303                            verifyStructure(structure);
304                    }
305    
306                    verifyDDMContent();
307    
308                    verifyDDMTemplateWithDate();
309            }
310    
311            protected Set<String> getDuplicateElementNames(
312                    Element element, Set<String> elementNames,
313                    Set<String> duplicateElementNames) {
314    
315                    String elementName = element.attributeValue("name");
316    
317                    if (!elementNames.add(elementName)) {
318                            duplicateElementNames.add(elementName);
319                    }
320    
321                    List<Element> dynamicElements = element.elements("dynamic-element");
322    
323                    for (Element dynamicElement : dynamicElements) {
324                            duplicateElementNames = getDuplicateElementNames(
325                                    dynamicElement, elementNames, duplicateElementNames);
326                    }
327    
328                    return duplicateElementNames;
329            }
330    
331            protected String getFileUploadPath(BaseModel<?> baseModel)
332                    throws Exception {
333    
334                    StringBundler sb = new StringBundler(7);
335    
336                    long primaryKey = 0;
337    
338                    String version = StringPool.BLANK;
339    
340                    if (baseModel instanceof DDLRecordModel) {
341                            DDLRecord ddlRecord = (DDLRecord)baseModel;
342    
343                            primaryKey = ddlRecord.getPrimaryKey();
344    
345                            DDLRecordVersion ddlRecordVersion = ddlRecord.getRecordVersion();
346    
347                            version = ddlRecordVersion.getVersion();
348                    }
349                    else {
350                            DLFileEntryMetadata dlFileEntryMetadata =
351                                    (DLFileEntryMetadata)baseModel;
352    
353                            primaryKey = dlFileEntryMetadata.getPrimaryKey();
354    
355                            DLFileVersion dlFileVersion = dlFileEntryMetadata.getFileVersion();
356    
357                            version = dlFileVersion.getVersion();
358                    }
359    
360                    sb.append("ddm");
361                    sb.append(StringPool.SLASH);
362                    sb.append(baseModel.getModelClassName());
363                    sb.append(StringPool.SLASH);
364                    sb.append(primaryKey);
365                    sb.append(StringPool.SLASH);
366                    sb.append(version);
367    
368                    return sb.toString();
369            }
370    
371            protected String getFullStructureXML(DDMStructure structure, String xml)
372                    throws Exception {
373    
374                    if (structure.getParentStructureId() != 0) {
375                            DDMStructure parentStructure =
376                                    DDMStructureLocalServiceUtil.getStructure(
377                                            structure.getParentStructureId());
378    
379                            xml = getFullStructureXML(parentStructure, xml);
380                    }
381    
382                    Document document = SAXReaderUtil.read(structure.getXsd());
383    
384                    Element rootElement = document.getRootElement();
385    
386                    List<Element> dynamicElements = rootElement.elements("dynamic-element");
387    
388                    for (Element dynamicElement : dynamicElements) {
389                            xml += dynamicElement.asXML();
390                    }
391    
392                    return xml;
393            }
394    
395            protected String getJSON(FileEntry fileEntry) {
396                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
397    
398                    jsonObject.put("groupId", fileEntry.getGroupId());
399                    jsonObject.put("uuid", fileEntry.getUuid());
400    
401                    return jsonObject.toString();
402            }
403    
404            protected long getUserId(AuditedModel auditedModel) throws Exception {
405                    User user = UserLocalServiceUtil.fetchUser(auditedModel.getUserId());
406    
407                    if (user != null) {
408                            return user.getUserId();
409                    }
410    
411                    User defaultUser = UserLocalServiceUtil.getDefaultUser(
412                            auditedModel.getCompanyId());
413    
414                    if (_log.isWarnEnabled()) {
415                            _log.warn(
416                                    "Using default user " + defaultUser.getUserId() +
417                                            " for audited model " + auditedModel.getModelClassName() +
418                                                    " with primary key " + auditedModel.getPrimaryKeyObj());
419                    }
420    
421                    return defaultUser.getUserId();
422            }
423    
424            protected boolean hasDefaultMetadataElement(
425                    Element dynamicElementElement, String defaultLanguageId) {
426    
427                    List<Element> metadataElements = dynamicElementElement.elements(
428                            "meta-data");
429    
430                    for (Element metadataElement : metadataElements) {
431                            String languageId = metadataElement.attributeValue("locale");
432    
433                            if (languageId.equals(defaultLanguageId)) {
434                                    return true;
435                            }
436                    }
437    
438                    return false;
439            }
440    
441            protected boolean hasFieldsDisplayElement(Element rootElement) {
442                    List<Element> dynamicElementElements = rootElement.elements(
443                            "dynamic-element");
444    
445                    for (Element dynamicElementElement : dynamicElementElements) {
446                            String fieldName = dynamicElementElement.attributeValue("name");
447    
448                            if (fieldName.equals(DDMImpl.FIELDS_DISPLAY_NAME)) {
449                                    if (dynamicElementElement.hasContent()) {
450                                            return true;
451                                    }
452                                    else {
453                                            rootElement.remove(dynamicElementElement);
454    
455                                            return false;
456                                    }
457                            }
458                    }
459    
460                    return false;
461            }
462    
463            protected boolean hasFileUploadFields(DDMStructure structure)
464                    throws Exception {
465    
466                    Map<String, Map<String, String>> fieldsMap = structure.getFieldsMap();
467    
468                    for (Map<String, String> field : fieldsMap.values()) {
469                            String dataType = field.get(FieldConstants.DATA_TYPE);
470    
471                            if (dataType.equals("document-library") ||
472                                    dataType.equals("file-upload")) {
473    
474                                    return true;
475                            }
476                    }
477    
478                    return false;
479            }
480    
481            protected void setUpClassNameIds() {
482                    _ddlRecordSetClassNameId = PortalUtil.getClassNameId(
483                            DDLRecordSet.class);
484                    _ddmStructureClassNameId = PortalUtil.getClassNameId(
485                            DDMStructure.class);
486                    _dlFileEntryMetadataClassNameId = PortalUtil.getClassNameId(
487                            DLFileEntryMetadata.class);
488            }
489    
490            protected void updateDDLFileUploadReferences(long ddlRecordSetId)
491                    throws Exception {
492    
493                    List<DDLRecord> ddlRecords = DDLRecordLocalServiceUtil.getRecords(
494                            ddlRecordSetId);
495    
496                    for (DDLRecord ddlRecord : ddlRecords) {
497                            updateFileUploadReferences(
498                                    ddlRecord.getCompanyId(), ddlRecord.getDDMStorageId(),
499                                    getUserId(ddlRecord), ddlRecord.getGroupId(), ddlRecord,
500                                    ddlRecord.getStatus());
501                    }
502            }
503    
504            protected void updateDLFileUploadReferences(long dlFileEntryMetadataId)
505                    throws Exception {
506    
507                    DLFileEntryMetadata dlFileEntryMetadata =
508                            DLFileEntryMetadataLocalServiceUtil.getFileEntryMetadata(
509                                    dlFileEntryMetadataId);
510    
511                    FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(
512                            dlFileEntryMetadata.getFileEntryId());
513    
514                    FileVersion fileVersion = fileEntry.getFileVersion();
515    
516                    updateFileUploadReferences(
517                            fileEntry.getCompanyId(), dlFileEntryMetadata.getDDMStorageId(),
518                            getUserId(fileEntry), fileEntry.getGroupId(), dlFileEntryMetadata,
519                            fileVersion.getStatus());
520            }
521    
522            protected void updateFileEntryStatus(
523                            FileEntry fileEntry, int status, ServiceContext serviceContext)
524                    throws Exception {
525    
526                    FileVersion fileVersion = fileEntry.getFileVersion();
527    
528                    Map<String, Serializable> workflowContext =
529                            new HashMap<String, Serializable>();
530    
531                    workflowContext.put("event", DLSyncConstants.EVENT_ADD);
532    
533                    DLFileEntryLocalServiceUtil.updateStatus(
534                            fileVersion.getUserId(), fileVersion.getFileVersionId(), status,
535                            workflowContext, serviceContext);
536            }
537    
538            protected void updateFileUploadReferences(DDMStructure structure)
539                    throws Exception {
540    
541                    if (!hasFileUploadFields(structure)) {
542                            return;
543                    }
544    
545                    List<DDMStructureLink> structureLinks =
546                            DDMStructureLinkLocalServiceUtil.getStructureLinks(
547                                    structure.getStructureId(), QueryUtil.ALL_POS,
548                                    QueryUtil.ALL_POS);
549    
550                    for (DDMStructureLink structureLink : structureLinks) {
551                            updateFileUploadReferences(structureLink);
552                    }
553    
554                    List<DDMTemplate> templates = DDMTemplateLocalServiceUtil.getTemplates(
555                            structure.getGroupId(), _ddmStructureClassNameId,
556                            structure.getStructureId(),
557                            DDMTemplateConstants.TEMPLATE_TYPE_FORM);
558    
559                    for (DDMTemplate template : templates) {
560                            updateTemplate(template, updateXSD(template.getScript()));
561                    }
562            }
563    
564            protected void updateFileUploadReferences(DDMStructureLink structureLink)
565                    throws Exception {
566    
567                    long classNameId = structureLink.getClassNameId();
568    
569                    if (classNameId == _ddlRecordSetClassNameId) {
570                            updateDDLFileUploadReferences(structureLink.getClassPK());
571                    }
572                    else if (classNameId == _dlFileEntryMetadataClassNameId) {
573                            updateDLFileUploadReferences(structureLink.getClassPK());
574                    }
575            }
576    
577            protected void updateFileUploadReferences(
578                            long companyId, long storageId, long userId, long groupId,
579                            BaseModel<?> baseModel, int status)
580                    throws Exception {
581    
582                    Fields fields = StorageEngineUtil.getFields(storageId);
583    
584                    for (Field field : fields) {
585                            String dataType = field.getDataType();
586    
587                            if (!(dataType.equals("file-upload") ||
588                                      dataType.equals("document-library")) ||
589                                    Validator.isNull(field.getValue())) {
590    
591                                    continue;
592                            }
593    
594                            long primaryKey = GetterUtil.getLong(baseModel.getPrimaryKeyObj());
595    
596                            Folder folder = addFolder(
597                                    userId, groupId, primaryKey, field.getName());
598    
599                            String valueString = String.valueOf(field.getValue());
600    
601                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject(
602                                    valueString);
603    
604                            String filePath =
605                                    getFileUploadPath(baseModel) + StringPool.SLASH +
606                                            field.getName();
607    
608                            FileEntry fileEntry = addFileEntry(
609                                    companyId, userId, groupId, folder.getFolderId(),
610                                    jsonObject.getString("name"), filePath, status);
611    
612                            if (fileEntry != null) {
613                                    field.setValue(getJSON(fileEntry));
614                            }
615                    }
616    
617                    ServiceContext serviceContext = new ServiceContext();
618    
619                    StorageEngineUtil.update(storageId, fields, false, serviceContext);
620            }
621    
622            protected void updateStructure(DDMStructure structure, String xsd)
623                    throws Exception {
624    
625                    xsd = DDMXMLUtil.formatXML(xsd);
626    
627                    structure.setXsd(xsd);
628    
629                    DDMStructureLocalServiceUtil.updateDDMStructure(structure);
630            }
631    
632            protected void updateTemplate(DDMTemplate template, String script)
633                    throws Exception {
634    
635                    script = DDMXMLUtil.formatXML(script);
636    
637                    template.setScript(script);
638    
639                    DDMTemplateLocalServiceUtil.updateDDMTemplate(template);
640            }
641    
642            protected String updateTemplateScriptDateGetDateStatement(
643                            String language, String script) {
644    
645                    StringBundler oldTemplateScriptSB = new StringBundler(3);
646                    StringBundler newTemplateScriptSB = new StringBundler(4);
647    
648                    if (language.equals("ftl")) {
649                            oldTemplateScriptSB.append("dateUtil.getDate\\(");
650                            oldTemplateScriptSB.append("(.*)");
651                            oldTemplateScriptSB.append("locale\\s*\\)");
652    
653                            newTemplateScriptSB.append("dateUtil.getDate(");
654                            newTemplateScriptSB.append("$1");
655                            newTemplateScriptSB.append("locale, timeZoneUtil.");
656                            newTemplateScriptSB.append("getTimeZone(\"UTC\"))");
657                    }
658                    else if (language.equals("vm")) {
659                            oldTemplateScriptSB.append("dateUtil.getDate\\(");
660                            oldTemplateScriptSB.append("(.*)");
661                            oldTemplateScriptSB.append("\\$locale\\s*\\)");
662    
663                            newTemplateScriptSB.append("dateUtil.getDate(");
664                            newTemplateScriptSB.append("$1");
665                            newTemplateScriptSB.append("\\$locale, \\$timeZoneUtil.");
666                            newTemplateScriptSB.append("getTimeZone(\"UTC\"))");
667                    }
668    
669                    return script.replaceAll(
670                            oldTemplateScriptSB.toString(), newTemplateScriptSB.toString());
671            }
672    
673            protected String updateXSD(String xsd) throws Exception {
674                    Document document = SAXReaderUtil.read(xsd);
675    
676                    Element rootElement = document.getRootElement();
677    
678                    List<Element> dynamicElementElements = rootElement.elements(
679                            "dynamic-element");
680    
681                    for (Element dynamicElementElement : dynamicElementElements) {
682                            updateXSDDynamicElement(dynamicElementElement);
683                    }
684    
685                    return document.asXML();
686            }
687    
688            protected void updateXSDDynamicElement(Element element) {
689                    String dataType = element.attributeValue("dataType");
690    
691                    if (Validator.equals(dataType, "file-upload")) {
692                            element.addAttribute("dataType", "document-library");
693                            element.addAttribute("type", "ddm-documentlibrary");
694                    }
695    
696                    List<Element> dynamicElementElements = element.elements(
697                            "dynamic-element");
698    
699                    for (Element dynamicElementElement : dynamicElementElements) {
700                            updateXSDDynamicElement(dynamicElementElement);
701                    }
702    
703                    Attribute attribute = element.attribute("autoGeneratedName");
704    
705                    if (attribute != null) {
706                            element.remove(attribute);
707                    }
708            }
709    
710            protected void verifyDDMContent() throws Exception {
711                    ActionableDynamicQuery actionableDynamicQuery =
712                            new DDMContentActionableDynamicQuery() {
713    
714                                    @Override
715                                    protected void addCriteria(DynamicQuery dynamicQuery) {
716                                            Disjunction disjunction =
717                                                    RestrictionsFactoryUtil.disjunction();
718    
719                                            DynamicQuery ddlRecordDynamicQuery =
720                                                    DDLRecordLocalServiceUtil.dynamicQuery();
721    
722                                            Projection projection = ProjectionFactoryUtil.property(
723                                                    "DDMStorageId");
724    
725                                            ddlRecordDynamicQuery.setProjection(projection);
726    
727                                            Property contentIdProperty = PropertyFactoryUtil.forName(
728                                                    "contentId");
729    
730                                            disjunction.add(
731                                                    contentIdProperty.in(ddlRecordDynamicQuery));
732    
733                                            DynamicQuery dlFileEntryMetadataDynamicQuery =
734                                                    DLFileEntryMetadataLocalServiceUtil.dynamicQuery();
735    
736                                            Property fileEntryTypeIdProperty =
737                                                    PropertyFactoryUtil.forName("fileEntryTypeId");
738    
739                                            dlFileEntryMetadataDynamicQuery.add(
740                                                    fileEntryTypeIdProperty.ne(0L));
741    
742                                            dlFileEntryMetadataDynamicQuery.setProjection(projection);
743    
744                                            disjunction.add(
745                                                    contentIdProperty.in(dlFileEntryMetadataDynamicQuery));
746    
747                                            dynamicQuery.add(disjunction);
748                                    }
749    
750                                    @Override
751                                    protected void performAction(Object object)
752                                            throws PortalException, SystemException {
753    
754                                            DDMContent ddmContent = (DDMContent)object;
755    
756                                            try {
757                                                    Document document = SAXReaderUtil.read(
758                                                            ddmContent.getXml());
759    
760                                                    Element rootElement = document.getRootElement();
761    
762                                                    if (!hasFieldsDisplayElement(
763                                                                    document.getRootElement())) {
764    
765                                                            addFieldsDisplay(rootElement);
766    
767                                                            String xml = document.asXML();
768    
769                                                            ddmContent.setXml(DDMXMLUtil.formatXML(xml));
770    
771                                                            DDMContentUtil.update(ddmContent);
772                                                    }
773                                            }
774                                            catch (DocumentException de) {
775                                                    throw new PortalException(de);
776                                            }
777                                    }
778                    };
779    
780                    actionableDynamicQuery.performActions();
781            }
782    
783            protected void verifyDDMTemplateWithDate() throws Exception {
784                    ActionableDynamicQuery actionableDynamicQuery =
785                            new DDMTemplateActionableDynamicQuery() {
786    
787                                    @Override
788                                    protected void addCriteria(DynamicQuery dynamicQuery) {
789    
790                                            DynamicQuery ddmStructureDynamicQuery =
791                                                    DynamicQueryFactoryUtil.forClass(DDMStructure.class);
792    
793                                                    Property storageTypeProperty =
794                                                            PropertyFactoryUtil.forName("storageType");
795    
796                                                    ddmStructureDynamicQuery.add(
797                                                            storageTypeProperty.eq("xml"));
798    
799                                                    Property xsdProperty = PropertyFactoryUtil.forName(
800                                                            "xsd");
801    
802                                                    ddmStructureDynamicQuery.add(
803                                                            xsdProperty.like("%dataType=\"date\"%"));
804    
805                                                    Projection projection = ProjectionFactoryUtil.property(
806                                                            "structureId");
807    
808                                                    ddmStructureDynamicQuery.setProjection(projection);
809    
810                                                    Property typeProperty = PropertyFactoryUtil.forName(
811                                                            "type");
812    
813                                                    dynamicQuery.add(
814                                                            typeProperty.eq(
815                                                                    DDMTemplateConstants.TEMPLATE_TYPE_DISPLAY));
816    
817                                                    Property classPKProperty = PropertyFactoryUtil.forName(
818                                                                    "classPK");
819    
820                                                    dynamicQuery.add(
821                                                            classPKProperty.in(ddmStructureDynamicQuery));
822                                    }
823    
824                                    @Override
825                                    protected void performAction(Object object)
826                                            throws PortalException, SystemException {
827    
828                                            DDMTemplate ddmTemplate = (DDMTemplate)object;
829    
830                                            String script = updateTemplateScriptDateGetDateStatement(
831                                                    ddmTemplate.getLanguage(), ddmTemplate.getScript());
832    
833                                            ddmTemplate.setScript(script);
834    
835                                            DDMTemplateLocalServiceUtil.updateDDMTemplate(ddmTemplate);
836                                    }
837                    };
838    
839                    actionableDynamicQuery.performActions();
840            }
841    
842            protected void verifyStructure(DDMStructure structure) throws Exception {
843                    updateFileUploadReferences(structure);
844    
845                    updateStructure(structure, updateXSD(structure.getXsd()));
846    
847                    boolean modified = false;
848    
849                    String defaultLanguageId = structure.getDefaultLanguageId();
850    
851                    XPath xPathSelector = SAXReaderUtil.createXPath("//dynamic-element");
852    
853                    Document document = structure.getDocument();
854    
855                    List<Node> nodes = xPathSelector.selectNodes(document);
856    
857                    for (Node node : nodes) {
858                            Element dynamicElementElement = (Element)node;
859    
860                            if (createDefaultMetadataElement(
861                                            dynamicElementElement, defaultLanguageId)) {
862    
863                                    modified = true;
864                            }
865                    }
866    
867                    if (modified) {
868                            updateStructure(structure, document.asXML());
869                    }
870            }
871    
872            private static Log _log = LogFactoryUtil.getLog(
873                    VerifyDynamicDataMapping.class);
874    
875            private long _ddlRecordSetClassNameId;
876            private long _ddmStructureClassNameId;
877            private long _dlFileEntryMetadataClassNameId;
878    
879    }