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.portal.upgrade.v6_1_0;
016    
017    import com.liferay.portal.image.DLHook;
018    import com.liferay.portal.image.DatabaseHook;
019    import com.liferay.portal.image.FileSystemHook;
020    import com.liferay.portal.kernel.dao.jdbc.DataAccess;
021    import com.liferay.portal.kernel.dao.shard.ShardUtil;
022    import com.liferay.portal.kernel.image.Hook;
023    import com.liferay.portal.kernel.log.Log;
024    import com.liferay.portal.kernel.log.LogFactoryUtil;
025    import com.liferay.portal.kernel.upgrade.UpgradeProcess;
026    import com.liferay.portal.kernel.util.FileUtil;
027    import com.liferay.portal.kernel.util.MimeTypesUtil;
028    import com.liferay.portal.kernel.util.StringBundler;
029    import com.liferay.portal.kernel.util.StringPool;
030    import com.liferay.portal.kernel.util.Validator;
031    import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
032    import com.liferay.portal.model.Company;
033    import com.liferay.portal.model.Image;
034    import com.liferay.portal.service.ImageLocalServiceUtil;
035    import com.liferay.portal.util.ClassLoaderUtil;
036    import com.liferay.portal.util.PortalUtil;
037    import com.liferay.portal.util.PropsValues;
038    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
039    import com.liferay.portlet.documentlibrary.model.DLFileEntryTypeConstants;
040    import com.liferay.portlet.documentlibrary.model.DLFolder;
041    import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
042    import com.liferay.portlet.documentlibrary.store.DLStoreUtil;
043    import com.liferay.portlet.documentlibrary.util.ImageProcessorUtil;
044    
045    import java.io.InputStream;
046    
047    import java.sql.Connection;
048    import java.sql.DatabaseMetaData;
049    import java.sql.PreparedStatement;
050    import java.sql.ResultSet;
051    import java.sql.Timestamp;
052    
053    import java.util.ArrayList;
054    import java.util.Collections;
055    import java.util.HashMap;
056    import java.util.List;
057    import java.util.Map;
058    
059    /**
060     * @author Sergio Gonz??lez
061     * @author Miguel Pastor
062     */
063    public class UpgradeImageGallery extends UpgradeProcess {
064    
065            public UpgradeImageGallery() throws Exception {
066                    ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader();
067    
068                    _sourceHookClassName = FileSystemHook.class.getName();
069    
070                    if (Validator.isNotNull(PropsValues.IMAGE_HOOK_IMPL)) {
071                            _sourceHookClassName = PropsValues.IMAGE_HOOK_IMPL;
072                    }
073    
074                    _sourceHook = (Hook)classLoader.loadClass(
075                            _sourceHookClassName).newInstance();
076            }
077    
078            protected void addDLFileEntry(
079                            String uuid, long fileEntryId, long groupId, long companyId,
080                            long userId, String userName, long versionUserId,
081                            String versionUserName, Timestamp createDate,
082                            Timestamp modifiedDate, long repositoryId, long folderId,
083                            String name, String extension, String mimeType, String title,
084                            String description, String extraSettings, long fileEntryTypeId,
085                            String version, long size, int readCount, long smallImageId,
086                            long largeImageId, long custom1ImageId, long custom2ImageId)
087                    throws Exception {
088    
089                    Connection con = null;
090                    PreparedStatement ps = null;
091    
092                    try {
093                            con = DataAccess.getUpgradeOptimizedConnection();
094    
095                            StringBundler sb = new StringBundler(9);
096    
097                            sb.append("insert into DLFileEntry (uuid_, fileEntryId, groupId, ");
098                            sb.append("companyId, userId, userName, versionUserId, ");
099                            sb.append("versionUserName, createDate, modifiedDate, ");
100                            sb.append("repositoryId, folderId, name, extension, mimeType, ");
101                            sb.append("title, description, extraSettings, fileEntryTypeId, ");
102                            sb.append("version, size_, readCount, smallImageId, ");
103                            sb.append("largeImageId, custom1ImageId, custom2ImageId) values (");
104                            sb.append("?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ");
105                            sb.append("?, ?, ?, ?, ?, ?, ?, ?, ?)");
106    
107                            String sql = sb.toString();
108    
109                            ps = con.prepareStatement(sql);
110    
111                            ps.setString(1, uuid);
112                            ps.setLong(2, fileEntryId);
113                            ps.setLong(3, groupId);
114                            ps.setLong(4, companyId);
115                            ps.setLong(5, userId);
116                            ps.setString(6, userName);
117                            ps.setLong(7, versionUserId);
118                            ps.setString(8, versionUserName);
119                            ps.setTimestamp(9, createDate);
120                            ps.setTimestamp(10, modifiedDate);
121                            ps.setLong(11, repositoryId);
122                            ps.setLong(12, folderId);
123                            ps.setString(13, name);
124                            ps.setString(14, extension);
125                            ps.setString(15, mimeType);
126                            ps.setString(16, title);
127                            ps.setString(17, description);
128                            ps.setString(18, extraSettings);
129                            ps.setLong(19, fileEntryTypeId);
130                            ps.setString(20, version);
131                            ps.setLong(21, size);
132                            ps.setInt(22, readCount);
133                            ps.setLong(23, smallImageId);
134                            ps.setLong(24, largeImageId);
135                            ps.setLong(25, custom1ImageId);
136                            ps.setLong(26, custom2ImageId);
137    
138                            ps.executeUpdate();
139                    }
140                    finally {
141                            DataAccess.cleanUp(con, ps);
142                    }
143            }
144    
145            protected void addDLFileVersion(
146                            long fileVersionId, long groupId, long companyId, long userId,
147                            String userName, Timestamp createDate, long repositoryId,
148                            long folderId, long fileEntryId, String extension, String mimeType,
149                            String title, String description, String changeLog,
150                            String extraSettings, long fileEntryTypeId, String version,
151                            long size, int status, long statusByUserId, String statusByUserName,
152                            Timestamp statusDate)
153                    throws Exception {
154    
155                    Connection con = null;
156                    PreparedStatement ps = null;
157    
158                    try {
159                            con = DataAccess.getUpgradeOptimizedConnection();
160    
161                            StringBundler sb = new StringBundler(9);
162    
163                            sb.append("insert into DLFileVersion (fileVersionId, groupId, ");
164                            sb.append("companyId, userId, userName, createDate, ");
165                            sb.append("modifiedDate, repositoryId, folderId, fileEntryId, ");
166                            sb.append("extension, mimeType, title, description, changeLog, ");
167                            sb.append("extraSettings, fileEntryTypeId, version, size_, ");
168                            sb.append("status, statusByUserId, statusByUserName, statusDate) ");
169                            sb.append("values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ");
170                            sb.append("?, ?, ?, ?, ?, ?, ?, ?)");
171    
172                            String sql = sb.toString();
173    
174                            ps = con.prepareStatement(sql);
175    
176                            ps.setLong(1, fileVersionId);
177                            ps.setLong(2, groupId);
178                            ps.setLong(3, companyId);
179                            ps.setLong(4, userId);
180                            ps.setString(5, userName);
181                            ps.setTimestamp(6, createDate);
182                            ps.setTimestamp(7, statusDate);
183                            ps.setLong(8, repositoryId);
184                            ps.setLong(9, folderId);
185                            ps.setLong(10, fileEntryId);
186                            ps.setString(11, extension);
187                            ps.setString(12, mimeType);
188                            ps.setString(13, title);
189                            ps.setString(14, description);
190                            ps.setString(15, changeLog);
191                            ps.setString(16, extraSettings);
192                            ps.setLong(17, fileEntryTypeId);
193                            ps.setString(18, version);
194                            ps.setLong(19, size);
195                            ps.setInt(20, status);
196                            ps.setLong(21, statusByUserId);
197                            ps.setString(22, statusByUserName);
198                            ps.setTimestamp(23, statusDate);
199    
200                            ps.executeUpdate();
201                    }
202                    finally {
203                            DataAccess.cleanUp(con, ps);
204                    }
205            }
206    
207            protected void addDLFolderEntry(
208                            String uuid, long folderId, long groupId, long companyId,
209                            long userId, String userName, Timestamp createDate,
210                            Timestamp modifiedDate, long repositoryId, long parentFolderId,
211                            String name, String description, Timestamp lastPostDate)
212                    throws Exception {
213    
214                    Connection con = null;
215                    PreparedStatement ps = null;
216    
217                    try {
218                            con = DataAccess.getUpgradeOptimizedConnection();
219    
220                            StringBundler sb = new StringBundler(5);
221    
222                            sb.append("insert into DLFolder (uuid_, folderId, groupId, ");
223                            sb.append("companyId, userId, userName, createDate, ");
224                            sb.append("modifiedDate, repositoryId, mountPoint, ");
225                            sb.append("parentFolderId, name, description, lastPostDate) ");
226                            sb.append("values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
227    
228                            String sql = sb.toString();
229    
230                            ps = con.prepareStatement(sql);
231    
232                            ps.setString(1, uuid);
233                            ps.setLong(2, folderId);
234                            ps.setLong(3, groupId);
235                            ps.setLong(4, companyId);
236                            ps.setLong(5, userId);
237                            ps.setString(6, userName);
238                            ps.setTimestamp(7, createDate);
239                            ps.setTimestamp(8, modifiedDate);
240                            ps.setLong(9, repositoryId);
241                            ps.setBoolean(10, false);
242                            ps.setLong(11, parentFolderId);
243                            ps.setString(12, name);
244                            ps.setString(13, description);
245                            ps.setTimestamp(14, lastPostDate);
246    
247                            ps.executeUpdate();
248                    }
249                    finally {
250                            DataAccess.cleanUp(con, ps);
251                    }
252            }
253    
254            protected void addIGImageDLFileEntryType() throws Exception {
255                    if (!PropsValues.DL_FILE_ENTRY_TYPE_IG_IMAGE_AUTO_CREATE_ON_UPGRADE) {
256                            return;
257                    }
258    
259                    Connection con = null;
260                    PreparedStatement ps = null;
261                    ResultSet rs = null;
262    
263                    try {
264                            con = DataAccess.getUpgradeOptimizedConnection();
265    
266                            ps = con.prepareStatement("select distinct companyId from IGImage");
267    
268                            rs = ps.executeQuery();
269    
270                            while (rs.next()) {
271                                    long companyId = rs.getLong("companyId");
272    
273                                    long groupId = getCompanyGroupId(companyId);
274                                    long userId = getDefaultUserId(companyId);
275                                    Timestamp now = new Timestamp(System.currentTimeMillis());
276    
277                                    addIGImageDLFileEntryType(
278                                            groupId, companyId, userId, StringPool.BLANK, now, now);
279                            }
280                    }
281                    finally {
282                            DataAccess.cleanUp(con, ps, rs);
283                    }
284            }
285    
286            protected void addIGImageDLFileEntryType(
287                            long groupId, long companyId, long userId, String userName,
288                            Timestamp createDate, Timestamp modifiedDate)
289                    throws Exception {
290    
291                    Connection con = null;
292                    PreparedStatement ps = null;
293                    ResultSet rs = null;
294    
295                    try {
296                            con = DataAccess.getUpgradeOptimizedConnection();
297    
298                            StringBundler sb = new StringBundler(4);
299    
300                            sb.append("insert into DLFileEntryType (uuid_, groupId, ");
301                            sb.append("companyId, userId, userName, createDate, ");
302                            sb.append("modifiedDate, name, description, fileEntryTypeId) ");
303                            sb.append("values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
304    
305                            ps = con.prepareStatement(sb.toString());
306    
307                            ps.setString(1, PortalUUIDUtil.generate());
308                            ps.setLong(2, groupId);
309                            ps.setLong(3, companyId);
310                            ps.setLong(4, userId);
311                            ps.setString(5, userName);
312                            ps.setTimestamp(6, createDate);
313                            ps.setTimestamp(7, modifiedDate);
314                            ps.setString(8, DLFileEntryTypeConstants.NAME_IG_IMAGE);
315                            ps.setString(9, DLFileEntryTypeConstants.NAME_IG_IMAGE);
316                            ps.setLong(10, increment());
317    
318                            ps.executeUpdate();
319                    }
320                    finally {
321                            DataAccess.cleanUp(con, ps, rs);
322                    }
323            }
324    
325            protected void deleteConflictingIGPermissions_1to5(
326                            long igCodeId, long dlCodeId)
327                    throws Exception {
328    
329                    Connection con = null;
330                    PreparedStatement ps = null;
331                    ResultSet rs = null;
332    
333                    try {
334                            con = DataAccess.getUpgradeOptimizedConnection();
335    
336                            DatabaseMetaData databaseMetaData = con.getMetaData();
337    
338                            boolean supportsBatchUpdates =
339                                    databaseMetaData.supportsBatchUpdates();
340    
341                            ps = con.prepareStatement(
342                                    "select primKey from Resource_ where codeId = " + igCodeId);
343    
344                            rs = ps.executeQuery();
345    
346                            PreparedStatement batchPS = con.prepareStatement(
347                                    "delete from Resource_ where codeId = ? and primKey = ?");
348    
349                            int count = 0;
350    
351                            while (rs.next()) {
352                                    batchPS.setLong(1, dlCodeId);
353                                    batchPS.setString(2, rs.getString("primKey"));
354    
355                                    if (supportsBatchUpdates) {
356                                            batchPS.addBatch();
357    
358                                            if (count == PropsValues.HIBERNATE_JDBC_BATCH_SIZE) {
359                                                    batchPS.executeBatch();
360    
361                                                    count = 0;
362                                            }
363                                            else {
364                                                    count++;
365                                            }
366                                    }
367                                    else {
368                                            batchPS.executeUpdate();
369                                    }
370                            }
371    
372                            if (supportsBatchUpdates && (count > 0)) {
373                                    batchPS.executeBatch();
374                            }
375    
376                            batchPS.close();
377                    }
378                    finally {
379                            DataAccess.cleanUp(con, ps, rs);
380                    }
381            }
382    
383            protected void deleteConflictingIGPermissions_6(
384                            String igResourceName, String dlResourceName)
385                    throws Exception {
386    
387                    Connection con = null;
388                    PreparedStatement ps = null;
389                    ResultSet rs = null;
390    
391                    try {
392                            con = DataAccess.getUpgradeOptimizedConnection();
393    
394                            DatabaseMetaData databaseMetaData = con.getMetaData();
395    
396                            boolean supportsBatchUpdates =
397                                    databaseMetaData.supportsBatchUpdates();
398    
399                            ps = con.prepareStatement(
400                                    "select companyId, scope, primKey, roleId from " +
401                                            "ResourcePermission where name = ?");
402    
403                            ps.setString(1, igResourceName);
404    
405                            rs = ps.executeQuery();
406    
407                            PreparedStatement batchPS = con.prepareStatement(
408                                    "delete from ResourcePermission where name = ? and " +
409                                            "companyId = ? and scope = ? and primKey = ? and " +
410                                                    "roleId = ?");
411    
412                            int count = 0;
413    
414                            while (rs.next()) {
415                                    batchPS.setString(1, dlResourceName);
416                                    batchPS.setLong(2, rs.getLong("companyId"));
417                                    batchPS.setInt(3, rs.getInt("scope"));
418                                    batchPS.setString(4, rs.getString("primKey"));
419                                    batchPS.setLong(5, rs.getLong("roleId"));
420    
421                                    if (supportsBatchUpdates) {
422                                            batchPS.addBatch();
423    
424                                            if (count == PropsValues.HIBERNATE_JDBC_BATCH_SIZE) {
425                                                    batchPS.executeBatch();
426    
427                                                    count = 0;
428                                            }
429                                            else {
430                                                    count++;
431                                            }
432                                    }
433                                    else {
434                                            batchPS.executeUpdate();
435                                    }
436                            }
437    
438                            if (supportsBatchUpdates && (count > 0)) {
439                                    batchPS.executeBatch();
440                            }
441    
442                            batchPS.close();
443                    }
444                    finally {
445                            DataAccess.cleanUp(con, ps, rs);
446                    }
447            }
448    
449            @Override
450            protected void doUpgrade() throws Exception {
451                    addIGImageDLFileEntryType();
452                    updateIGFolderEntries();
453                    updateIGImageEntries();
454                    updateIGPermissions(_IG_IMAGE_CLASS_NAME, _DL_FILE_CLASS_NAME);
455                    updateIGPermissions(_IG_FOLDER_CLASS_NAME, _DL_FOLDER_CLASS_NAME);
456    
457                    migrateImageFiles();
458    
459                    UpgradeDocumentLibrary upgradeDocumentLibrary =
460                            new UpgradeDocumentLibrary();
461    
462                    upgradeDocumentLibrary.updateSyncs();
463            }
464    
465            protected long getBitwiseValue(
466                    Map<String, Long> bitwiseValues, List<String> actionIds) {
467    
468                    long bitwiseValue = 0;
469    
470                    for (String actionId : actionIds) {
471                            Long actionIdBitwiseValue = bitwiseValues.get(actionId);
472    
473                            if (actionIdBitwiseValue == null) {
474                                    continue;
475                            }
476    
477                            bitwiseValue |= actionIdBitwiseValue;
478                    }
479    
480                    return bitwiseValue;
481            }
482    
483            protected Map<String, Long> getBitwiseValues(String name) throws Exception {
484                    Connection con = null;
485                    PreparedStatement ps = null;
486                    ResultSet rs = null;
487    
488                    String currentShardName = null;
489    
490                    try {
491                            currentShardName = ShardUtil.setTargetSource(
492                                    PropsValues.SHARD_DEFAULT_NAME);
493    
494                            con = DataAccess.getUpgradeOptimizedConnection();
495    
496                            ps = con.prepareStatement(
497                                    "select actionId, bitwiseValue from ResourceAction " +
498                                            "where name = ?");
499    
500                            ps.setString(1, name);
501    
502                            rs = ps.executeQuery();
503    
504                            Map<String, Long> bitwiseValues = new HashMap<String, Long>();
505    
506                            while (rs.next()) {
507                                    String actionId = rs.getString("actionId");
508                                    long bitwiseValue = rs.getLong("bitwiseValue");
509    
510                                    bitwiseValues.put(actionId, bitwiseValue);
511                            }
512    
513                            return bitwiseValues;
514                    }
515                    finally {
516                            if (Validator.isNotNull(currentShardName)) {
517                                    ShardUtil.setTargetSource(currentShardName);
518                            }
519    
520                            DataAccess.cleanUp(con, ps, rs);
521                    }
522            }
523    
524            protected long getCompanyGroupId(long companyId) throws Exception {
525                    Connection con = null;
526                    PreparedStatement ps = null;
527                    ResultSet rs = null;
528    
529                    try {
530                            con = DataAccess.getUpgradeOptimizedConnection();
531    
532                            ps = con.prepareStatement(
533                                    "select groupId from Group_ where classNameId = ? and " +
534                                            "classPK = ?");
535    
536                            ps.setLong(1, PortalUtil.getClassNameId(Company.class.getName()));
537                            ps.setLong(2, companyId);
538    
539                            rs = ps.executeQuery();
540    
541                            if (rs.next()) {
542                                    return rs.getLong("groupId");
543                            }
544    
545                            return 0;
546                    }
547                    finally {
548                            DataAccess.cleanUp(con, ps, rs);
549                    }
550            }
551    
552            protected long getDefaultUserId(long companyId) throws Exception {
553                    Connection con = null;
554                    PreparedStatement ps = null;
555                    ResultSet rs = null;
556    
557                    try {
558                            con = DataAccess.getUpgradeOptimizedConnection();
559    
560                            ps = con.prepareStatement(
561                                    "select userId from User_ where companyId = ? and " +
562                                            "defaultUser = ?");
563    
564                            ps.setLong(1, companyId);
565                            ps.setBoolean(2, true);
566    
567                            rs = ps.executeQuery();
568    
569                            if (rs.next()) {
570                                    return rs.getLong("userId");
571                            }
572    
573                            return 0;
574                    }
575                    finally {
576                            DataAccess.cleanUp(con, ps, rs);
577                    }
578            }
579    
580            protected Object[] getImage(long imageId) throws Exception {
581                    Connection con = null;
582                    PreparedStatement ps = null;
583                    ResultSet rs = null;
584    
585                    try {
586                            con = DataAccess.getUpgradeOptimizedConnection();
587    
588                            ps = con.prepareStatement(
589                                    "select type_, size_ from Image where imageId = " + imageId);
590    
591                            rs = ps.executeQuery();
592    
593                            if (rs.next()) {
594                                    String type = rs.getString("type_");
595                                    long size = rs.getInt("size_");
596    
597                                    return new Object[] {type, size};
598                            }
599    
600                            return null;
601                    }
602                    finally {
603                            DataAccess.cleanUp(con, ps, rs);
604                    }
605            }
606    
607            protected List<String> getResourceActionIds(
608                    Map<String, Long> bitwiseValues, long actionIdsLong) {
609    
610                    List<String> actionIds = new ArrayList<String>();
611    
612                    for (String actionId : bitwiseValues.keySet()) {
613                            long bitwiseValue = bitwiseValues.get(actionId);
614    
615                            if ((actionIdsLong & bitwiseValue) == bitwiseValue) {
616                                    actionIds.add(actionId);
617                            }
618                    }
619    
620                    return actionIds;
621            }
622    
623            protected long getResourceCodeId(long companyId, String name, int scope)
624                    throws Exception {
625    
626                    Connection con = null;
627                    PreparedStatement ps = null;
628                    ResultSet rs = null;
629    
630                    try {
631                            con = DataAccess.getUpgradeOptimizedConnection();
632    
633                            ps = con.prepareStatement(
634                                    "select codeId from ResourceCode where companyId = ? and " +
635                                            "name = ? and scope = ?");
636    
637                            ps.setLong(1, companyId);
638                            ps.setString(2, name);
639                            ps.setInt(3, scope);
640    
641                            rs = ps.executeQuery();
642    
643                            if (rs.next()) {
644                                    return rs.getLong("codeId");
645                            }
646    
647                            return 0;
648                    }
649                    finally {
650                            DataAccess.cleanUp(con, ps, rs);
651                    }
652            }
653    
654            protected void migrateFile(
655                            long repositoryId, long companyId, String name, Image image)
656                    throws Exception {
657    
658                    InputStream is = _sourceHook.getImageAsStream(image);
659    
660                    byte[] bytes = FileUtil.getBytes(is);
661    
662                    if (name == null) {
663                            name = image.getImageId() + StringPool.PERIOD + image.getType();
664                    }
665    
666                    if (DLStoreUtil.hasFile(companyId, repositoryId, name)) {
667                            DLStoreUtil.deleteFile(companyId, repositoryId, name);
668                    }
669    
670                    DLStoreUtil.addFile(companyId, repositoryId, name, false, bytes);
671            }
672    
673            protected void migrateImage(long imageId) throws Exception {
674                    Image image = ImageLocalServiceUtil.getImage(imageId);
675    
676                    try {
677                            migrateFile(0, 0, null, image);
678                    }
679                    catch (Exception e) {
680                            if (_log.isWarnEnabled()) {
681                                    _log.warn("Ignoring exception for image " + imageId, e);
682                            }
683    
684                            return;
685                    }
686    
687                    _sourceHook.deleteImage(image);
688            }
689    
690            protected void migrateImage(
691                            long fileEntryId, long companyId, long groupId, long folderId,
692                            String name, long smallImageId, long largeImageId,
693                            long custom1ImageId, long custom2ImageId)
694                    throws Exception {
695    
696                    Image largeImage = null;
697    
698                    if (largeImageId != 0) {
699                            largeImage = ImageLocalServiceUtil.getImage(largeImageId);
700    
701                            long repositoryId = DLFolderConstants.getDataRepositoryId(
702                                    groupId, folderId);
703    
704                            try {
705                                    migrateFile(repositoryId, companyId, name, largeImage);
706                            }
707                            catch (Exception e) {
708                                    if (_log.isWarnEnabled()) {
709                                            _log.warn(
710                                                    "Ignoring exception for image " + largeImageId, e);
711                                    }
712                            }
713                    }
714    
715                    long thumbnailImageId = 0;
716    
717                    if (smallImageId != 0) {
718                            thumbnailImageId = smallImageId;
719                    }
720                    else if (custom1ImageId != 0) {
721                            thumbnailImageId = custom1ImageId;
722                    }
723                    else if (custom2ImageId != 0) {
724                            thumbnailImageId = custom2ImageId;
725                    }
726    
727                    Image thumbnailImage = null;
728    
729                    if (thumbnailImageId != 0) {
730                            thumbnailImage = ImageLocalServiceUtil.getImage(thumbnailImageId);
731    
732                            Connection con = null;
733                            PreparedStatement ps = null;
734                            ResultSet rs = null;
735    
736                            try {
737                                    InputStream is = _sourceHook.getImageAsStream(thumbnailImage);
738    
739                                    con = DataAccess.getUpgradeOptimizedConnection();
740    
741                                    ps = con.prepareStatement(
742                                            "select max(fileVersionId) from DLFileVersion where " +
743                                                    "fileEntryId = " + fileEntryId);
744    
745                                    rs = ps.executeQuery();
746    
747                                    if (rs.next()) {
748                                            long fileVersionId = rs.getLong(1);
749    
750                                            ImageProcessorUtil.storeThumbnail(
751                                                    companyId, groupId, fileEntryId, fileVersionId,
752                                                    custom1ImageId, custom2ImageId, is,
753                                                    thumbnailImage.getType());
754                                    }
755                            }
756                            catch (Exception e) {
757                                    if (_log.isWarnEnabled()) {
758                                            _log.warn(
759                                                    "Ignoring exception for image " + thumbnailImageId, e);
760                                    }
761                            }
762                            finally {
763                                    DataAccess.cleanUp(con, ps, rs);
764                            }
765                    }
766    
767                    if (largeImageId != 0) {
768                            _sourceHook.deleteImage(largeImage);
769    
770                            runSQL("delete from Image where imageId = " + largeImageId);
771                    }
772    
773                    if ((largeImageId != thumbnailImageId) && (thumbnailImageId != 0)) {
774                            _sourceHook.deleteImage(thumbnailImage);
775    
776                            runSQL("delete from Image where imageId = " + thumbnailImageId);
777                    }
778            }
779    
780            protected void migrateImageFiles() throws Exception {
781                    Connection con = null;
782                    PreparedStatement ps = null;
783                    ResultSet rs = null;
784    
785                    try {
786                            con = DataAccess.getUpgradeOptimizedConnection();
787    
788                            StringBundler sb = new StringBundler(8);
789    
790                            sb.append("select fileEntryId, companyId, groupId, folderId, ");
791                            sb.append("name, smallImageId, largeImageId, custom1ImageId, ");
792                            sb.append("custom2ImageId from DLFileEntry where ((smallImageId ");
793                            sb.append("is not null) and (smallImageId != 0)) or ");
794                            sb.append("((largeImageId is not null) and (largeImageId != 0)) ");
795                            sb.append("or ((custom1ImageId is not null) and (custom1ImageId ");
796                            sb.append("!= 0)) or ((custom2ImageId is not null) and ");
797                            sb.append("(custom2ImageId != 0))");
798    
799                            ps = con.prepareStatement(sb.toString());
800    
801                            rs = ps.executeQuery();
802    
803                            while (rs.next()) {
804                                    long fileEntryId = rs.getLong("fileEntryId");
805                                    long companyId = rs.getLong("companyId");
806                                    long groupId = rs.getLong("groupId");
807                                    long folderId = rs.getLong("folderId");
808                                    String name = rs.getString("name");
809                                    long smallImageId = rs.getLong("smallImageId");
810                                    long largeImageId = rs.getLong("largeImageId");
811                                    long custom1ImageId = rs.getLong("custom1ImageId");
812                                    long custom2ImageId = rs.getLong("custom2ImageId");
813    
814                                    migrateImage(
815                                            fileEntryId, companyId, groupId, folderId, name,
816                                            smallImageId, largeImageId, custom1ImageId, custom2ImageId);
817                            }
818                    }
819                    finally {
820                            DataAccess.cleanUp(con, ps, rs);
821                    }
822    
823                    if (_sourceHookClassName.equals(DLHook.class.getName())) {
824                            return;
825                    }
826    
827                    try {
828                            con = DataAccess.getUpgradeOptimizedConnection();
829    
830                            ps = con.prepareStatement("select imageId from Image");
831    
832                            rs = ps.executeQuery();
833    
834                            while (rs.next()) {
835                                    long imageId = rs.getLong("imageId");
836    
837                                    migrateImage(imageId);
838                            }
839                    }
840                    finally {
841                            DataAccess.cleanUp(con, ps, rs);
842                    }
843    
844                    if (_sourceHookClassName.equals(DatabaseHook.class.getName())) {
845                            runSQL("update Image set text_ = ''");
846                    }
847            }
848    
849            protected void updateIGFolderEntries() throws Exception {
850                    Connection con = null;
851                    PreparedStatement ps = null;
852                    ResultSet rs = null;
853    
854                    try {
855                            con = DataAccess.getUpgradeOptimizedConnection();
856    
857                            ps = con.prepareStatement(
858                                    "select * from IGFolder order by folderId asc");
859    
860                            rs = ps.executeQuery();
861    
862                            Map<Long, Long> folderIds = new HashMap<Long, Long>();
863    
864                            while (rs.next()) {
865                                    String uuid = rs.getString("uuid_");
866                                    long folderId = rs.getLong("folderId");
867                                    long groupId = rs.getLong("groupId");
868                                    long companyId = rs.getLong("companyId");
869                                    long userId = rs.getLong("userId");
870                                    String userName = rs.getString("userName");
871                                    Timestamp createDate = rs.getTimestamp("createDate");
872                                    Timestamp modifiedDate = rs.getTimestamp("modifiedDate");
873                                    long parentFolderId = rs.getLong("parentFolderId");
874                                    String name = rs.getString("name");
875                                    String description = rs.getString("description");
876    
877                                    if (folderIds.containsKey(parentFolderId)) {
878                                            parentFolderId = folderIds.get(parentFolderId);
879                                    }
880    
881                                    boolean update = updateIGImageFolderId(
882                                            groupId, name, parentFolderId, folderId, folderIds);
883    
884                                    if (!update) {
885                                            addDLFolderEntry(
886                                                    uuid, folderId, groupId, companyId, userId, userName,
887                                                    createDate, modifiedDate, groupId, parentFolderId, name,
888                                                    description, modifiedDate);
889                                    }
890                            }
891    
892                            runSQL("drop table IGFolder");
893                    }
894                    finally {
895                            DataAccess.cleanUp(con, ps, rs);
896                    }
897            }
898    
899            protected void updateIGImageEntries() throws Exception {
900                    Connection con = null;
901                    PreparedStatement ps = null;
902                    ResultSet rs = null;
903    
904                    try {
905                            con = DataAccess.getUpgradeOptimizedConnection();
906    
907                            ps = con.prepareStatement(
908                                    "select fileEntryTypeId, companyId from DLFileEntryType " +
909                                            "where name = ?");
910    
911                            ps.setString(1, DLFileEntryTypeConstants.NAME_IG_IMAGE);
912    
913                            rs = ps.executeQuery();
914    
915                            boolean hasIGImageFileEntryType = false;
916    
917                            while (rs.next()) {
918                                    long fileEntryTypeId = rs.getLong("fileEntryTypeId");
919                                    long companyId = rs.getLong("companyId");
920    
921                                    updateIGImageEntries(companyId, fileEntryTypeId);
922    
923                                    hasIGImageFileEntryType = true;
924                            }
925    
926                            if (!hasIGImageFileEntryType) {
927                                    updateIGImageEntries(0, 0);
928                            }
929    
930                            runSQL("drop table IGImage");
931                    }
932                    finally {
933                            DataAccess.cleanUp(con, ps, rs);
934                    }
935            }
936    
937            protected void updateIGImageEntries(long companyId, long fileEntryTypeId)
938                    throws Exception {
939    
940                    Connection con = null;
941                    PreparedStatement ps = null;
942                    ResultSet rs = null;
943    
944                    try {
945                            con = DataAccess.getUpgradeOptimizedConnection();
946    
947                            String sql = "select * from IGImage";
948    
949                            if (companyId != 0) {
950                                    sql = "select * from IGImage where companyId = ?";
951                            }
952    
953                            ps = con.prepareStatement(sql);
954    
955                            if (companyId != 0) {
956                                    ps.setLong(1, companyId);
957                            }
958    
959                            rs = ps.executeQuery();
960    
961                            while (rs.next()) {
962                                    String uuid = rs.getString("uuid_");
963                                    long imageId = rs.getLong("imageId");
964                                    long groupId = rs.getLong("groupId");
965                                    companyId = rs.getLong("companyId");
966                                    long userId = rs.getLong("userId");
967                                    String userName = rs.getString("userName");
968                                    Timestamp createDate = rs.getTimestamp("createDate");
969                                    Timestamp modifiedDate = rs.getTimestamp("modifiedDate");
970                                    long folderId = rs.getLong("folderId");
971                                    String title = rs.getString("name");
972                                    String description = rs.getString("description");
973                                    long smallImageId = rs.getLong("smallImageId");
974                                    long largeImageId = rs.getLong("largeImageId");
975                                    long custom1ImageId = rs.getLong("custom1ImageId");
976                                    long custom2ImageId = rs.getLong("custom2ImageId");
977    
978                                    Object[] image = getImage(largeImageId);
979    
980                                    if (image == null) {
981                                            continue;
982                                    }
983    
984                                    String extension = (String)image[0];
985    
986                                    String mimeType = MimeTypesUtil.getContentType(
987                                            "A." + extension);
988    
989                                    String name = String.valueOf(
990                                            increment(DLFileEntry.class.getName()));
991    
992                                    long size = (Long)image[1];
993    
994                                    try {
995                                            addDLFileEntry(
996                                                    uuid, imageId, groupId, companyId, userId, userName,
997                                                    userId, userName, createDate, modifiedDate, groupId,
998                                                    folderId, name, extension, mimeType, title, description,
999                                                    StringPool.BLANK, fileEntryTypeId, "1.0", size, 0,
1000                                                    smallImageId, largeImageId, custom1ImageId,
1001                                                    custom2ImageId);
1002                                    }
1003                                    catch (Exception e) {
1004                                            title = title.concat(StringPool.SPACE).concat(
1005                                                    String.valueOf(imageId));
1006    
1007                                            addDLFileEntry(
1008                                                    uuid, imageId, groupId, companyId, userId, userName,
1009                                                    userId, userName, createDate, modifiedDate, groupId,
1010                                                    folderId, name, extension, mimeType, title, description,
1011                                                    StringPool.BLANK, fileEntryTypeId, "1.0", size, 0,
1012                                                    smallImageId, largeImageId, custom1ImageId,
1013                                                    custom2ImageId);
1014                                    }
1015    
1016                                    addDLFileVersion(
1017                                            increment(), groupId, companyId, userId, userName,
1018                                            createDate, groupId, folderId, imageId, extension, mimeType,
1019                                            title, description, StringPool.BLANK, StringPool.BLANK,
1020                                            fileEntryTypeId, "1.0", size, 0, userId, userName,
1021                                            modifiedDate);
1022                            }
1023                    }
1024                    finally {
1025                            DataAccess.cleanUp(con, ps, rs);
1026                    }
1027            }
1028    
1029            protected boolean updateIGImageFolderId(
1030                            long groupId, String name, long parentFolderId, long folderId,
1031                            Map<Long, Long> folderIds)
1032                    throws Exception {
1033    
1034                    Connection con = null;
1035                    PreparedStatement ps = null;
1036                    ResultSet rs = null;
1037    
1038                    try {
1039                            con = DataAccess.getUpgradeOptimizedConnection();
1040    
1041                            ps = con.prepareStatement(
1042                                    "select folderId from DLFolder where groupId = " + groupId +
1043                                            " and parentFolderId = " + parentFolderId +
1044                                                    " and name = ?");
1045    
1046                            ps.setString(1, name);
1047    
1048                            rs = ps.executeQuery();
1049    
1050                            if (rs.next()) {
1051                                    long newFolderId = rs.getLong("folderId");
1052    
1053                                    runSQL(
1054                                            "update IGImage set folderId = " + newFolderId +
1055                                                    " where folderId = " + folderId);
1056    
1057                                    folderIds.put(folderId, newFolderId);
1058    
1059                                    return true;
1060                            }
1061                    }
1062                    finally {
1063                            DataAccess.cleanUp(con, ps, rs);
1064                    }
1065    
1066                    return false;
1067            }
1068    
1069            protected void updateIGPermissions(String igClassName, String dlClassName)
1070                    throws Exception {
1071    
1072                    if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) {
1073                            upgradeIGPermissions_6(igClassName, dlClassName);
1074                    }
1075                    else {
1076                            upgradeIGPermissions_1to5(igClassName, dlClassName);
1077                    }
1078            }
1079    
1080            protected void updateIGtoDLPermissions(
1081                            String igResourceName, String dlResourceName)
1082                    throws Exception {
1083    
1084                    Map<String, Long> igBitwiseValues = getBitwiseValues(igResourceName);
1085    
1086                    if (igBitwiseValues.isEmpty()) {
1087                            if (_log.isWarnEnabled()) {
1088                                    _log.warn(
1089                                            "Resource actions do not exist for " + igResourceName);
1090                            }
1091    
1092                            return;
1093                    }
1094    
1095                    Map<String, Long> dlBitwiseValues = getBitwiseValues(dlResourceName);
1096    
1097                    if (dlBitwiseValues.isEmpty()) {
1098                            if (_log.isWarnEnabled()) {
1099                                    _log.warn(
1100                                            "Resource actions do not exist for " + dlResourceName);
1101                            }
1102    
1103                            return;
1104                    }
1105    
1106                    // The size of igBitwiseValues is based on the number of actions defined
1107                    // in resource actions which was 7 and 4 for IGFolder and IGImage
1108                    // respectively. This means the loop will execute at most 2^7 (128)
1109                    // times. If we were to check before update, we would still have to
1110                    // perform 128 queries, so we may as well just update 128 times even if
1111                    // no candidates exist for a given value.
1112    
1113                    for (int i = 0; i < Math.pow(2, igBitwiseValues.size()); i++) {
1114                            List<String> igActionIds = getResourceActionIds(igBitwiseValues, i);
1115    
1116                            if (igResourceName.equals(_IG_FOLDER_CLASS_NAME)) {
1117                                    Collections.replaceAll(
1118                                            igActionIds, "ADD_IMAGE", "ADD_DOCUMENT");
1119                            }
1120    
1121                            long dlActionIdsLong = getBitwiseValue(
1122                                    dlBitwiseValues, igActionIds);
1123    
1124                            runSQL(
1125                                    "update ResourcePermission set name = '" + dlResourceName +
1126                                            "', actionIds = " + dlActionIdsLong + " where name = '" +
1127                                                    igResourceName + "'" + " and actionIds = " + i);
1128                    }
1129            }
1130    
1131            protected void upgradeIGPermissions_1to5(
1132                            String igClassName, String dlClassName)
1133                    throws Exception {
1134    
1135                    Connection con = null;
1136                    PreparedStatement ps = null;
1137                    ResultSet rs = null;
1138    
1139                    try {
1140                            con = DataAccess.getUpgradeOptimizedConnection();
1141    
1142                            ps = con.prepareStatement(
1143                                    "select codeId, companyId, scope from ResourceCode where name" +
1144                                            " = ?");
1145    
1146                            ps.setString(1, igClassName);
1147    
1148                            rs = ps.executeQuery();
1149    
1150                            while (rs.next()) {
1151                                    long igCodeId = rs.getLong("codeId");
1152                                    long companyId = rs.getLong("companyId");
1153                                    int scope = rs.getInt("scope");
1154    
1155                                    long dlCodeId = getResourceCodeId(
1156                                            companyId, dlClassName, scope);
1157    
1158                                    if (dlCodeId == 0) {
1159                                            continue;
1160                                    }
1161    
1162                                    deleteConflictingIGPermissions_1to5(igCodeId, dlCodeId);
1163    
1164                                    runSQL(
1165                                            "update Resource_ set codeId = " + dlCodeId +
1166                                                    " where codeId = " + igCodeId);
1167                            }
1168                    }
1169                    finally {
1170                            DataAccess.cleanUp(con, ps, rs);
1171                    }
1172            }
1173    
1174            protected void upgradeIGPermissions_6(
1175                            String igClassName, String dlClassName)
1176                    throws Exception {
1177    
1178                    deleteConflictingIGPermissions_6(igClassName, dlClassName);
1179    
1180                    updateIGtoDLPermissions(igClassName, dlClassName);
1181            }
1182    
1183            private static final String _DL_FILE_CLASS_NAME =
1184                    DLFileEntry.class.getName();
1185    
1186            private static final String _DL_FOLDER_CLASS_NAME =
1187                    DLFolder.class.getName();
1188    
1189            private static final String _IG_FOLDER_CLASS_NAME =
1190                    "com.liferay.portlet.imagegallery.model.IGFolder";
1191    
1192            private static final String _IG_IMAGE_CLASS_NAME =
1193                    "com.liferay.portlet.imagegallery.model.IGImage";
1194    
1195            private static Log _log = LogFactoryUtil.getLog(UpgradeImageGallery.class);
1196    
1197            private Hook _sourceHook;
1198            private String _sourceHookClassName;
1199    
1200    }