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