001    /**
002     * Copyright (c) 2000-present 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.portal.upgrade.v6_2_0;
016    
017    import com.liferay.portal.kernel.dao.jdbc.AutoBatchPreparedStatementUtil;
018    import com.liferay.portal.kernel.log.Log;
019    import com.liferay.portal.kernel.log.LogFactoryUtil;
020    import com.liferay.portal.kernel.portlet.PortletPreferencesFactoryUtil;
021    import com.liferay.portal.kernel.upgrade.BaseUpgradePortletPreferences;
022    import com.liferay.portal.kernel.util.GetterUtil;
023    import com.liferay.portal.kernel.util.HtmlUtil;
024    import com.liferay.portal.kernel.util.HttpUtil;
025    import com.liferay.portal.kernel.util.LocaleUtil;
026    import com.liferay.portal.kernel.util.LoggingTimer;
027    import com.liferay.portal.kernel.util.PortalUtil;
028    import com.liferay.portal.kernel.util.StringBundler;
029    import com.liferay.portal.kernel.util.StringPool;
030    import com.liferay.portal.kernel.util.StringUtil;
031    import com.liferay.portal.kernel.util.Validator;
032    import com.liferay.portal.kernel.xml.Attribute;
033    import com.liferay.portal.kernel.xml.Document;
034    import com.liferay.portal.kernel.xml.Element;
035    import com.liferay.portal.kernel.xml.SAXReaderUtil;
036    import com.liferay.portal.kernel.xml.XPath;
037    import com.liferay.portal.upgrade.v6_2_0.util.JournalFeedTable;
038    import com.liferay.util.xml.XMLUtil;
039    
040    import java.sql.PreparedStatement;
041    import java.sql.ResultSet;
042    import java.sql.Timestamp;
043    
044    import java.util.HashMap;
045    import java.util.List;
046    import java.util.Locale;
047    import java.util.Map;
048    
049    import javax.portlet.PortletPreferences;
050    
051    /**
052     * @author Brian Wing Shun Chan
053     * @author Marcellus Tavares
054     * @author Juan Fern??ndez
055     * @author Bruno Basto
056     */
057    public class UpgradeJournal extends BaseUpgradePortletPreferences {
058    
059            protected void addDDMStructure(
060                            String uuid_, long ddmStructureId, long groupId, long companyId,
061                            long userId, String userName, Timestamp createDate,
062                            Timestamp modifiedDate, long parentDDMStructureId, long classNameId,
063                            String ddmStructureKey, String name, String description, String xsd,
064                            String storageType, int type)
065                    throws Exception {
066    
067                    StringBundler sb = new StringBundler(5);
068    
069                    sb.append("insert into DDMStructure (uuid_, structureId, groupId, ");
070                    sb.append("companyId, userId, userName, createDate, modifiedDate, ");
071                    sb.append("parentStructureId, classNameId, structureKey, name, ");
072                    sb.append("description, xsd, storageType, type_) values (?, ?, ?, ?, ");
073                    sb.append("?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
074    
075                    String sql = sb.toString();
076    
077                    try (PreparedStatement ps = connection.prepareStatement(sql)) {
078                            ps.setString(1, uuid_);
079                            ps.setLong(2, ddmStructureId);
080                            ps.setLong(3, groupId);
081                            ps.setLong(4, companyId);
082                            ps.setLong(5, userId);
083                            ps.setString(6, userName);
084                            ps.setTimestamp(7, createDate);
085                            ps.setTimestamp(8, modifiedDate);
086                            ps.setLong(9, parentDDMStructureId);
087                            ps.setLong(10, classNameId);
088                            ps.setString(11, ddmStructureKey);
089                            ps.setString(12, name);
090                            ps.setString(13, description);
091                            ps.setString(14, getDDMXSD(xsd, getDefaultLocale(companyId)));
092                            ps.setString(15, storageType);
093                            ps.setInt(16, type);
094    
095                            ps.executeUpdate();
096                    }
097                    catch (Exception e) {
098                            _log.error(
099                                    "Unable to upgrade dynamic data mapping structure with UUID " +
100                                            uuid_);
101    
102                            throw e;
103                    }
104            }
105    
106            protected void addDDMStructure(
107                            String uuid_, long ddmStructureId, long groupId, long companyId,
108                            long userId, String userName, Timestamp createDate,
109                            Timestamp modifiedDate, String parentStructureId,
110                            String ddmStructureKey, String name, String description, String xsd)
111                    throws Exception {
112    
113                    long parentDDMStructureId = 0;
114    
115                    if (Validator.isNotNull(parentStructureId)) {
116                            parentDDMStructureId = updateStructure(parentStructureId);
117                    }
118    
119                    long insertedDDMStructureId = getDDMStructureId(
120                            groupId, ddmStructureKey, false);
121    
122                    if (insertedDDMStructureId == 0) {
123                            addDDMStructure(
124                                    uuid_, ddmStructureId, groupId, companyId, userId, userName,
125                                    createDate, modifiedDate, parentDDMStructureId,
126                                    PortalUtil.getClassNameId(
127                                            "com.liferay.portlet.journal.model.JournalArticle"),
128                                    ddmStructureKey, name, description, xsd, "xml",
129                                    _DDM_STRUCTURE_TYPE_DEFAULT);
130                    }
131            }
132    
133            protected void addDDMTemplate(
134                            String uuid_, long ddmTemplateId, long groupId, long companyId,
135                            long userId, String userName, Timestamp createDate,
136                            Timestamp modifiedDate, long classNameId, long classPK,
137                            String templateKey, String name, String description, String type,
138                            String mode, String language, String script, boolean cacheable,
139                            boolean smallImage, long smallImageId, String smallImageURL)
140                    throws Exception {
141    
142                    StringBundler sb = new StringBundler(6);
143    
144                    sb.append("insert into DDMTemplate (uuid_, templateId, groupId, ");
145                    sb.append("companyId, userId, userName, createDate, modifiedDate,");
146                    sb.append("classNameId, classPK , templateKey, name, description,");
147                    sb.append("type_, mode_, language, script, cacheable, smallImage,");
148                    sb.append("smallImageId, smallImageURL) values (?, ?, ?, ?, ?, ?,?, ");
149                    sb.append("?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
150    
151                    String sql = sb.toString();
152    
153                    try (PreparedStatement ps = connection.prepareStatement(sql)) {
154                            ps.setString(1, uuid_);
155                            ps.setLong(2, ddmTemplateId);
156                            ps.setLong(3, groupId);
157                            ps.setLong(4, companyId);
158                            ps.setLong(5, userId);
159                            ps.setString(6, userName);
160                            ps.setTimestamp(7, createDate);
161                            ps.setTimestamp(8, modifiedDate);
162                            ps.setLong(9, classNameId);
163                            ps.setLong(10, classPK);
164                            ps.setString(11, templateKey);
165                            ps.setString(12, name);
166                            ps.setString(13, description);
167                            ps.setString(14, type);
168                            ps.setString(15, mode);
169                            ps.setString(16, language);
170                            ps.setString(17, script);
171                            ps.setBoolean(18, cacheable);
172                            ps.setBoolean(19, smallImage);
173                            ps.setLong(20, smallImageId);
174                            ps.setString(21, smallImageURL);
175    
176                            ps.executeUpdate();
177                    }
178                    catch (Exception e) {
179                            _log.error(
180                                    "Unable to upgrade dynamic data mapping template with UUID " +
181                                            uuid_);
182    
183                            throw e;
184                    }
185            }
186    
187            protected void addMetadataEntry(
188                    Element metadataElement, String name, String value) {
189    
190                    Element entryElement = metadataElement.addElement("entry");
191    
192                    entryElement.addAttribute("name", name);
193                    entryElement.addCDATA(value);
194            }
195    
196            protected String decodeURL(String url) {
197                    try {
198                            return HttpUtil.decodeURL(url);
199                    }
200                    catch (IllegalArgumentException iae) {
201                            return url;
202                    }
203            }
204    
205            @Override
206            protected void doUpgrade() throws Exception {
207                    alter(
208                            JournalFeedTable.class,
209                            new AlterColumnName("feedType", "feedFormat VARCHAR(75) null"));
210    
211                    setUpStrutureAttributesMappings();
212    
213                    updateStructures();
214                    updateTemplates();
215    
216                    updateAssetEntryClassTypeId();
217    
218                    super.doUpgrade();
219            }
220    
221            protected Element fetchMetadataEntry(
222                    Element parentElement, String attributeName, String attributeValue) {
223    
224                    StringBundler sb = new StringBundler(5);
225    
226                    sb.append("entry[@");
227                    sb.append(attributeName);
228                    sb.append(StringPool.EQUAL);
229                    sb.append(HtmlUtil.escapeXPathAttribute(attributeValue));
230                    sb.append(StringPool.CLOSE_BRACKET);
231    
232                    XPath xPath = SAXReaderUtil.createXPath(sb.toString());
233    
234                    return (Element)xPath.selectSingleNode(parentElement);
235            }
236    
237            protected long getCompanyGroupId(long companyId) throws Exception {
238                    try (PreparedStatement ps = connection.prepareStatement(
239                                    "select groupId from Group_ where classNameId = ? and " +
240                                            "classPK = ?")) {
241    
242                            ps.setLong(
243                                    1,
244                                    PortalUtil.getClassNameId("com.liferay.portal.model.Company"));
245                            ps.setLong(2, companyId);
246    
247                            try (ResultSet rs = ps.executeQuery()) {
248                                    if (rs.next()) {
249                                            return rs.getLong("groupId");
250                                    }
251    
252                                    return 0;
253                            }
254                    }
255            }
256    
257            protected long getDDMStructureClassNameId() {
258                    return PortalUtil.getClassNameId(
259                            "com.liferay.portlet.dynamicdatamapping.model.DDMStructure");
260            }
261    
262            protected long getDDMStructureId(
263                    long groupId, long companyGroupId, String structureId) {
264    
265                    return getDDMStructureId(groupId, companyGroupId, structureId, true);
266            }
267    
268            protected long getDDMStructureId(
269                    long groupId, long companyGroupId, String structureId, boolean warn) {
270    
271                    if (Validator.isNull(structureId)) {
272                            return 0;
273                    }
274    
275                    Long ddmStructureId = _ddmStructureIds.get(groupId + "#" + structureId);
276    
277                    if ((ddmStructureId == null) && (companyGroupId != 0)) {
278                            ddmStructureId = _ddmStructureIds.get(
279                                    companyGroupId + "#" + structureId);
280                    }
281    
282                    if (ddmStructureId != null) {
283                            return ddmStructureId;
284                    }
285    
286                    if (warn && _log.isWarnEnabled()) {
287                            StringBundler sb = new StringBundler();
288    
289                            sb.append("Unable to get the DDM structure ID for group ");
290                            sb.append(groupId);
291    
292                            if (companyGroupId != 0) {
293                                    sb.append(" or global group");
294                            }
295    
296                            sb.append(" and journal structure ID ");
297                            sb.append(structureId);
298    
299                            _log.warn(sb.toString());
300                    }
301    
302                    return 0;
303            }
304    
305            protected long getDDMStructureId(
306                    long groupId, String structureId, boolean warn) {
307    
308                    return getDDMStructureId(groupId, 0, structureId, warn);
309            }
310    
311            protected String getDDMXSD(String journalXSD, Locale defaultLocale)
312                    throws Exception {
313    
314                    Document document = SAXReaderUtil.read(journalXSD);
315    
316                    Element rootElement = document.getRootElement();
317    
318                    rootElement.addAttribute("available-locales", defaultLocale.toString());
319                    rootElement.addAttribute("default-locale", defaultLocale.toString());
320    
321                    List<Element> dynamicElementElements = rootElement.elements(
322                            "dynamic-element");
323    
324                    for (Element dynamicElementElement : dynamicElementElements) {
325                            updateJournalXSDDynamicElement(
326                                    dynamicElementElement, defaultLocale.toString());
327                    }
328    
329                    return XMLUtil.formatXML(document);
330            }
331    
332            protected Locale getDefaultLocale(long companyId) throws Exception {
333                    try (PreparedStatement ps = connection.prepareStatement(
334                                    "select languageId from User_ where companyId = ? and " +
335                                            "defaultUser = ?")) {
336    
337                            ps.setLong(1, companyId);
338                            ps.setBoolean(2, true);
339    
340                            try (ResultSet rs = ps.executeQuery()) {
341                                    if (rs.next()) {
342                                            String languageId = rs.getString("languageId");
343    
344                                            return LocaleUtil.fromLanguageId(languageId);
345                                    }
346                            }
347                    }
348    
349                    return LocaleUtil.getSiteDefault();
350            }
351    
352            @Override
353            protected String[] getPortletIds() {
354                    return new String[] {
355                            "56_INSTANCE_%", "62_INSTANCE_%", "101_INSTANCE_%"
356                    };
357            }
358    
359            protected void removeAttribute(Element element, String attributeName) {
360                    Attribute attribute = element.attribute(attributeName);
361    
362                    if (attribute == null) {
363                            return;
364                    }
365    
366                    element.remove(attribute);
367            }
368    
369            protected void setUpStrutureAttributesMappings() {
370                    _ddmDataTypes.put("boolean", "boolean");
371                    _ddmDataTypes.put("document_library", "document-library");
372                    _ddmDataTypes.put("image", "image");
373                    _ddmDataTypes.put("link_to_layout", "link-to-page");
374                    _ddmDataTypes.put("list", "string");
375                    _ddmDataTypes.put("multi-list", "string");
376                    _ddmDataTypes.put("text", "string");
377                    _ddmDataTypes.put("text_area", "html");
378                    _ddmDataTypes.put("text_box", "string");
379    
380                    _ddmMetadataAttributes.put("instructions", "tip");
381                    _ddmMetadataAttributes.put("label", "label");
382                    _ddmMetadataAttributes.put("predefinedValue", "predefinedValue");
383    
384                    _journalTypesToDDMTypes.put("boolean", "checkbox");
385                    _journalTypesToDDMTypes.put("document_library", "ddm-documentlibrary");
386                    _journalTypesToDDMTypes.put("image", "ddm-image");
387                    _journalTypesToDDMTypes.put("image_gallery", "ddm-documentlibrary");
388                    _journalTypesToDDMTypes.put("link_to_layout", "ddm-link-to-page");
389                    _journalTypesToDDMTypes.put("list", "select");
390                    _journalTypesToDDMTypes.put("multi-list", "select");
391                    _journalTypesToDDMTypes.put("selection_break", "ddm-separator");
392                    _journalTypesToDDMTypes.put("text", "text");
393                    _journalTypesToDDMTypes.put("text_area", "ddm-text-html");
394                    _journalTypesToDDMTypes.put("text_box", "textarea");
395            }
396    
397            protected void updateAssetEntryClassTypeId() throws Exception {
398                    try (LoggingTimer loggingTimer = new LoggingTimer();
399                            PreparedStatement ps1 = connection.prepareStatement(
400                                    "select companyId, groupId, resourcePrimKey, structureId " +
401                                            "from JournalArticle where structureId != ''");
402                            ResultSet rs = ps1.executeQuery()) {
403    
404                            long classNameId = PortalUtil.getClassNameId(
405                                    "com.liferay.portlet.journal.model.JournalArticle");
406    
407                            try (PreparedStatement ps2 =
408                                            AutoBatchPreparedStatementUtil.concurrentAutoBatch(
409                                                    connection,
410                                                    "update AssetEntry set classTypeId = ? where " +
411                                                            "classNameId = ? AND classPK = ?")) {
412    
413                                    while (rs.next()) {
414                                            long groupId = rs.getLong("groupId");
415                                            long companyId = rs.getLong("companyId");
416                                            long resourcePrimKey = rs.getLong("resourcePrimKey");
417                                            String structureId = rs.getString("structureId");
418    
419                                            long ddmStructureId = getDDMStructureId(
420                                                    groupId, getCompanyGroupId(companyId), structureId);
421    
422                                            ps2.setLong(1, ddmStructureId);
423                                            ps2.setLong(2, classNameId);
424                                            ps2.setLong(3, resourcePrimKey);
425    
426                                            ps2.addBatch();
427                                    }
428    
429                                    ps2.executeBatch();
430                            }
431                    }
432            }
433    
434            protected void updateJournalXSDDynamicElement(
435                    Element element, String defaultLanguageId) {
436    
437                    String name = element.attributeValue("name");
438                    String type = element.attributeValue("type");
439    
440                    Element metadataElement = element.element("meta-data");
441    
442                    if (metadataElement == null) {
443                            metadataElement = element.addElement("meta-data");
444                    }
445    
446                    if (type.equals("multi-list")) {
447                            element.addAttribute("multiple", "true");
448                    }
449                    else {
450                            Element parentElement = element.getParent();
451    
452                            String parentType = parentElement.attributeValue("type");
453    
454                            if ((parentType != null) && parentType.equals("select")) {
455                                    metadataElement.addAttribute("locale", defaultLanguageId);
456    
457                                    addMetadataEntry(metadataElement, "label", decodeURL(name));
458    
459                                    removeAttribute(element, "index-type");
460    
461                                    element.addAttribute("name", "option" + StringUtil.randomId());
462                                    element.addAttribute("type", "option");
463                                    element.addAttribute("value", decodeURL(type));
464    
465                                    return;
466                            }
467                    }
468    
469                    String indexType = StringPool.BLANK;
470    
471                    Attribute indexTypeAttribute = element.attribute("index-type");
472    
473                    if (indexTypeAttribute != null) {
474                            indexType = indexTypeAttribute.getValue();
475    
476                            element.remove(indexTypeAttribute);
477                    }
478    
479                    element.remove(element.attribute("type"));
480    
481                    if (!type.equals("selection_break")) {
482                            String dataType = _ddmDataTypes.get(type);
483    
484                            if (dataType == null) {
485                                    dataType = "string";
486                            }
487    
488                            element.addAttribute("dataType", dataType);
489                    }
490    
491                    element.addAttribute("indexType", indexType);
492    
493                    String required = "false";
494    
495                    Element requiredElement = fetchMetadataEntry(
496                            metadataElement, "name", "required");
497    
498                    if (requiredElement != null) {
499                            required = requiredElement.getText();
500                    }
501    
502                    element.addAttribute("required", required);
503    
504                    element.addAttribute("showLabel", "true");
505    
506                    String newType = _journalTypesToDDMTypes.get(type);
507    
508                    if (newType == null) {
509                            newType = type;
510                    }
511    
512                    element.addAttribute("type", newType);
513    
514                    if (newType.startsWith("ddm")) {
515                            element.addAttribute("fieldNamespace", "ddm");
516                    }
517    
518                    metadataElement.addAttribute("locale", defaultLanguageId);
519    
520                    List<Element> entryElements = metadataElement.elements();
521    
522                    if (entryElements.isEmpty()) {
523                            addMetadataEntry(metadataElement, "label", name);
524                    }
525                    else {
526                            for (Element entryElement : entryElements) {
527                                    String oldEntryName = entryElement.attributeValue("name");
528    
529                                    String newEntryName = _ddmMetadataAttributes.get(oldEntryName);
530    
531                                    if (newEntryName == null) {
532                                            metadataElement.remove(entryElement);
533                                    }
534                                    else {
535                                            entryElement.addAttribute("name", newEntryName);
536                                    }
537                            }
538                    }
539    
540                    if (newType.equals("ddm-date") || newType.equals("ddm-decimal") ||
541                            newType.equals("ddm-integer") ||
542                            newType.equals("ddm-link-to-page") ||
543                            newType.equals("ddm-number") || newType.equals("ddm-text-html") ||
544                            newType.equals("text") || newType.equals("textarea")) {
545    
546                            element.addAttribute("width", "25");
547                    }
548                    else if (newType.equals("ddm-image")) {
549                            element.addAttribute("fieldNamespace", "ddm");
550                            element.addAttribute("readOnly", "false");
551                    }
552    
553                    element.add(metadataElement.detach());
554    
555                    List<Element> dynamicElementElements = element.elements(
556                            "dynamic-element");
557    
558                    for (Element dynamicElementElement : dynamicElementElements) {
559                            updateJournalXSDDynamicElement(
560                                    dynamicElementElement, defaultLanguageId);
561                    }
562            }
563    
564            protected void updatePreferencesClassPKs(
565                            PortletPreferences preferences, String key)
566                    throws Exception {
567    
568                    String[] oldValues = preferences.getValues(key, null);
569    
570                    if (oldValues == null) {
571                            return;
572                    }
573    
574                    String[] newValues = new String[oldValues.length];
575    
576                    for (int i = 0; i < oldValues.length; i++) {
577                            String oldValue = oldValues[i];
578    
579                            String newValue = oldValue;
580    
581                            String[] oldPrimaryKeys = StringUtil.split(oldValue);
582    
583                            for (String oldPrimaryKey : oldPrimaryKeys) {
584                                    if (!Validator.isNumber(oldPrimaryKey)) {
585                                            break;
586                                    }
587    
588                                    Long newPrimaryKey = _ddmStructurePKs.get(
589                                            GetterUtil.getLong(oldPrimaryKey));
590    
591                                    if (Validator.isNotNull(newPrimaryKey)) {
592                                            newValue = StringUtil.replace(
593                                                    newValue, oldPrimaryKey, String.valueOf(newPrimaryKey));
594                                    }
595                            }
596    
597                            newValues[i] = newValue;
598                    }
599    
600                    preferences.setValues(key, newValues);
601            }
602    
603            protected void updateResourcePermission(
604                            long companyId, String oldClassName, String newClassName,
605                            long oldPrimKey, long newPrimKey)
606                    throws Exception {
607    
608                    StringBundler sb = new StringBundler(11);
609    
610                    sb.append("update ResourcePermission set name = '");
611                    sb.append(newClassName);
612                    sb.append("', primKey = '");
613                    sb.append(newPrimKey);
614                    sb.append("' where companyId = ");
615                    sb.append(companyId);
616                    sb.append(" and name = '");
617                    sb.append(oldClassName);
618                    sb.append("' and primKey = '");
619                    sb.append(oldPrimKey);
620                    sb.append("'");
621    
622                    runSQL(sb.toString());
623            }
624    
625            protected long updateStructure(ResultSet rs) throws Exception {
626                    String uuid_ = rs.getString("uuid_");
627                    long id_ = rs.getLong("id_");
628                    long groupId = rs.getLong("groupId");
629                    long companyId = rs.getLong("companyId");
630                    long userId = rs.getLong("userId");
631                    String userName = rs.getString("userName");
632                    Timestamp createDate = rs.getTimestamp("createDate");
633                    Timestamp modifiedDate = rs.getTimestamp("modifiedDate");
634                    String structureId = rs.getString("structureId");
635                    String parentStructureId = rs.getString("parentStructureId");
636                    String name = rs.getString("name");
637                    String description = rs.getString("description");
638                    String xsd = rs.getString("xsd");
639    
640                    Long ddmStructureId = _ddmStructureIds.get(groupId + "#" + structureId);
641    
642                    if (ddmStructureId != null) {
643                            return ddmStructureId;
644                    }
645    
646                    ddmStructureId = increment();
647    
648                    addDDMStructure(
649                            uuid_, ddmStructureId, groupId, companyId, userId, userName,
650                            createDate, modifiedDate, parentStructureId, structureId, name,
651                            description, xsd);
652    
653                    updateResourcePermission(
654                            companyId, "com.liferay.portlet.journal.model.JournalStructure",
655                            "com.liferay.portlet.dynamicdatamapping.model.DDMStructure", id_,
656                            ddmStructureId);
657    
658                    _ddmStructureIds.put(groupId + "#" + structureId, ddmStructureId);
659                    _ddmStructurePKs.put(id_, ddmStructureId);
660    
661                    return ddmStructureId;
662            }
663    
664            protected long updateStructure(String structureId) throws Exception {
665                    try (PreparedStatement ps = connection.prepareStatement(
666                                    "select * from JournalStructure where structureId = ?")) {
667    
668                            ps.setString(1, structureId);
669    
670                            try (ResultSet rs = ps.executeQuery()) {
671                                    if (rs.next()) {
672                                            return updateStructure(rs);
673                                    }
674    
675                                    return 0;
676                            }
677                    }
678                    catch (Exception e) {
679                            _log.error(
680                                    "Unable to update journal structure with structure ID " +
681                                            structureId);
682    
683                            throw e;
684                    }
685            }
686    
687            protected void updateStructures() throws Exception {
688                    try (LoggingTimer loggingTimer = new LoggingTimer();
689                            PreparedStatement ps = connection.prepareStatement(
690                                    "select * from JournalStructure");
691                            ResultSet rs = ps.executeQuery()) {
692    
693                            while (rs.next()) {
694                                    updateStructure(rs);
695                            }
696    
697                            runSQL("drop table JournalStructure");
698                    }
699            }
700    
701            protected void updateTemplates() throws Exception {
702                    try (LoggingTimer loggingTimer = new LoggingTimer();
703                            PreparedStatement ps = connection.prepareStatement(
704                                    "select * from JournalTemplate");
705                            ResultSet rs = ps.executeQuery()) {
706    
707                            while (rs.next()) {
708                                    String uuid_ = rs.getString("uuid_");
709                                    long id_ = rs.getLong("id_");
710                                    long groupId = rs.getLong("groupId");
711                                    long companyId = rs.getLong("companyId");
712                                    long userId = rs.getLong("userId");
713                                    String userName = rs.getString("userName");
714                                    Timestamp createDate = rs.getTimestamp("createDate");
715                                    Timestamp modifiedDate = rs.getTimestamp("modifiedDate");
716                                    String templateId = rs.getString("templateId");
717                                    String structureId = rs.getString("structureId");
718                                    String name = rs.getString("name");
719                                    String description = rs.getString("description");
720                                    String language = rs.getString("langType");
721                                    String script = rs.getString("xsl");
722                                    boolean cacheable = rs.getBoolean("cacheable");
723                                    boolean smallImage = rs.getBoolean("smallImage");
724                                    long smallImageId = rs.getLong("smallImageId");
725                                    String smallImageURL = rs.getString("smallImageURL");
726    
727                                    long ddmTemplateId = increment();
728    
729                                    long classNameId = getDDMStructureClassNameId();
730    
731                                    long classPK = getDDMStructureId(
732                                            groupId, getCompanyGroupId(companyId), structureId);
733    
734                                    addDDMTemplate(
735                                            uuid_, ddmTemplateId, groupId, companyId, userId, userName,
736                                            createDate, modifiedDate, classNameId, classPK, templateId,
737                                            name, description, _DDM_TEMPLATE_TYPE_DISPLAY,
738                                            _DDM_TEMPLATE_MODE_CREATE, language, script, cacheable,
739                                            smallImage, smallImageId, smallImageURL);
740    
741                                    updateResourcePermission(
742                                            companyId,
743                                            "com.liferay.portlet.journal.model.JournalTemplate",
744                                            "com.liferay.portlet.dynamicdatamapping.model.DDMTemplate",
745                                            id_, ddmTemplateId);
746                            }
747    
748                            runSQL("drop table JournalTemplate");
749                    }
750            }
751    
752            @Override
753            protected String upgradePreferences(
754                            long companyId, long ownerId, int ownerType, long plid,
755                            String portletId, String xml)
756                    throws Exception {
757    
758                    PortletPreferences preferences = PortletPreferencesFactoryUtil.fromXML(
759                            companyId, ownerId, ownerType, plid, portletId, xml);
760    
761                    if (portletId.startsWith(_PORTLET_ID_ASSET_PUBLISHER)) {
762                            updatePreferencesClassPKs(
763                                    preferences, "anyClassTypeJournalArticleAssetRendererFactory");
764                            updatePreferencesClassPKs(preferences, "classTypeIds");
765                            updatePreferencesClassPKs(
766                                    preferences, "classTypeIdsJournalArticleAssetRendererFactory");
767                    }
768                    else if (portletId.startsWith(_PORTLET_ID_JOURNAL_CONTENT)) {
769                            String templateId = preferences.getValue(
770                                    "templateId", StringPool.BLANK);
771    
772                            if (Validator.isNotNull(templateId)) {
773                                    preferences.reset("templateId");
774    
775                                    preferences.setValue("ddmTemplateKey", templateId);
776                            }
777                    }
778                    else if (portletId.startsWith(_PORTLET_ID_JOURNAL_CONTENT_LIST)) {
779                            String structureId = preferences.getValue(
780                                    "structureId", StringPool.BLANK);
781    
782                            if (Validator.isNotNull(structureId)) {
783                                    preferences.reset("structureId");
784    
785                                    preferences.setValue("ddmStructureKey", structureId);
786                            }
787                    }
788    
789                    return PortletPreferencesFactoryUtil.toXML(preferences);
790            }
791    
792            private static final int _DDM_STRUCTURE_TYPE_DEFAULT = 0;
793    
794            private static final String _DDM_TEMPLATE_MODE_CREATE = "create";
795    
796            private static final String _DDM_TEMPLATE_TYPE_DISPLAY = "display";
797    
798            private static final String _PORTLET_ID_ASSET_PUBLISHER = "101";
799    
800            private static final String _PORTLET_ID_JOURNAL_CONTENT = "56";
801    
802            private static final String _PORTLET_ID_JOURNAL_CONTENT_LIST = "62";
803    
804            private static final Log _log = LogFactoryUtil.getLog(UpgradeJournal.class);
805    
806            private final Map<String, String> _ddmDataTypes = new HashMap<>();
807            private final Map<String, String> _ddmMetadataAttributes = new HashMap<>();
808            private final Map<String, Long> _ddmStructureIds = new HashMap<>();
809            private final Map<Long, Long> _ddmStructurePKs = new HashMap<>();
810            private final Map<String, String> _journalTypesToDDMTypes = new HashMap<>();
811    
812    }