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(
326                            String igResourceName, String dlResourceName)
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 companyId, scope, primKey, roleId from " +
343                                            "ResourcePermission where name = ?");
344    
345                            ps.setString(1, igResourceName);
346    
347                            rs = ps.executeQuery();
348    
349                            ps = con.prepareStatement(
350                                    "delete from ResourcePermission where name = ? and " +
351                                            "companyId = ? and scope = ? and primKey = ? and " +
352                                                    "roleId = ?");
353    
354                            int count = 0;
355    
356                            while (rs.next()) {
357                                    ps.setString(1, dlResourceName);
358                                    ps.setLong(2, rs.getLong("companyId"));
359                                    ps.setInt(3, rs.getInt("scope"));
360                                    ps.setString(4, rs.getString("primKey"));
361                                    ps.setLong(5, rs.getLong("roleId"));
362    
363                                    if (supportsBatchUpdates) {
364                                            ps.addBatch();
365    
366                                            if (count == PropsValues.HIBERNATE_JDBC_BATCH_SIZE) {
367                                                    ps.executeBatch();
368    
369                                                    count = 0;
370                                            }
371                                            else {
372                                                    count++;
373                                            }
374                                    }
375                                    else {
376                                            ps.executeUpdate();
377                                    }
378                            }
379    
380                            if (supportsBatchUpdates && (count > 0)) {
381                                    ps.executeBatch();
382                            }
383                    }
384                    finally {
385                            DataAccess.cleanUp(con, ps, rs);
386                    }
387            }
388    
389            @Override
390            protected void doUpgrade() throws Exception {
391                    addIGImageDLFileEntryType();
392                    updateIGFolderEntries();
393                    updateIGImageEntries();
394                    updateIGFolderPermissions();
395                    updateIGImagePermissions();
396    
397                    migrateImageFiles();
398    
399                    UpgradeDocumentLibrary upgradeDocumentLibrary =
400                            new UpgradeDocumentLibrary();
401    
402                    upgradeDocumentLibrary.updateSyncs();
403            }
404    
405            protected long getBitwiseValue(
406                    Map<String, Long> bitwiseValues, List<String> actionIds) {
407    
408                    long bitwiseValue = 0;
409    
410                    for (String actionId : actionIds) {
411                            Long actionIdBitwiseValue = bitwiseValues.get(actionId);
412    
413                            if (actionIdBitwiseValue == null) {
414                                    continue;
415                            }
416    
417                            bitwiseValue |= actionIdBitwiseValue;
418                    }
419    
420                    return bitwiseValue;
421            }
422    
423            protected Map<String, Long> getBitwiseValues(String name) throws Exception {
424                    Connection con = null;
425                    PreparedStatement ps = null;
426                    ResultSet rs = null;
427    
428                    String currentShardName = null;
429    
430                    try {
431                            currentShardName = ShardUtil.setTargetSource(
432                                    PropsValues.SHARD_DEFAULT_NAME);
433    
434                            con = DataAccess.getUpgradeOptimizedConnection();
435    
436                            ps = con.prepareStatement(
437                                    "select actionId, bitwiseValue from ResourceAction " +
438                                            "where name = ?");
439    
440                            ps.setString(1, name);
441    
442                            rs = ps.executeQuery();
443    
444                            Map<String, Long> bitwiseValues = new HashMap<String, Long>();
445    
446                            while (rs.next()) {
447                                    String actionId = rs.getString("actionId");
448                                    long bitwiseValue = rs.getLong("bitwiseValue");
449    
450                                    bitwiseValues.put(actionId, bitwiseValue);
451                            }
452    
453                            return bitwiseValues;
454                    }
455                    finally {
456                            if (Validator.isNotNull(currentShardName)) {
457                                    ShardUtil.setTargetSource(currentShardName);
458                            }
459    
460                            DataAccess.cleanUp(con, ps, rs);
461                    }
462            }
463    
464            protected long getCompanyGroupId(long companyId) throws Exception {
465                    Connection con = null;
466                    PreparedStatement ps = null;
467                    ResultSet rs = null;
468    
469                    try {
470                            con = DataAccess.getUpgradeOptimizedConnection();
471    
472                            ps = con.prepareStatement(
473                                    "select groupId from Group_ where classNameId = ? and " +
474                                            "classPK = ?");
475    
476                            ps.setLong(1, PortalUtil.getClassNameId(Company.class.getName()));
477                            ps.setLong(2, companyId);
478    
479                            rs = ps.executeQuery();
480    
481                            if (rs.next()) {
482                                    return rs.getLong("groupId");
483                            }
484    
485                            return 0;
486                    }
487                    finally {
488                            DataAccess.cleanUp(con, ps, rs);
489                    }
490            }
491    
492            protected long getDefaultUserId(long companyId) throws Exception {
493                    Connection con = null;
494                    PreparedStatement ps = null;
495                    ResultSet rs = null;
496    
497                    try {
498                            con = DataAccess.getUpgradeOptimizedConnection();
499    
500                            ps = con.prepareStatement(
501                                    "select userId from User_ where companyId = ? and " +
502                                            "defaultUser = ?");
503    
504                            ps.setLong(1, companyId);
505                            ps.setBoolean(2, true);
506    
507                            rs = ps.executeQuery();
508    
509                            if (rs.next()) {
510                                    return rs.getLong("userId");
511                            }
512    
513                            return 0;
514                    }
515                    finally {
516                            DataAccess.cleanUp(con, ps, rs);
517                    }
518            }
519    
520            protected Object[] getImage(long imageId) throws Exception {
521                    Connection con = null;
522                    PreparedStatement ps = null;
523                    ResultSet rs = null;
524    
525                    try {
526                            con = DataAccess.getUpgradeOptimizedConnection();
527    
528                            ps = con.prepareStatement(
529                                    "select type_, size_ from Image where imageId = " + imageId);
530    
531                            rs = ps.executeQuery();
532    
533                            if (rs.next()) {
534                                    String type = rs.getString("type_");
535                                    long size = rs.getInt("size_");
536    
537                                    return new Object[] {type, size};
538                            }
539    
540                            return null;
541                    }
542                    finally {
543                            DataAccess.cleanUp(con, ps, rs);
544                    }
545            }
546    
547            protected List<String> getResourceActionIds(
548                    Map<String, Long> bitwiseValues, long actionIdsLong) {
549    
550                    List<String> actionIds = new ArrayList<String>();
551    
552                    for (String actionId : bitwiseValues.keySet()) {
553                            long bitwiseValue = bitwiseValues.get(actionId);
554    
555                            if ((actionIdsLong & bitwiseValue) == bitwiseValue) {
556                                    actionIds.add(actionId);
557                            }
558                    }
559    
560                    return actionIds;
561            }
562    
563            protected void migrateFile(
564                            long repositoryId, long companyId, String name, Image image)
565                    throws Exception {
566    
567                    InputStream is = _sourceHook.getImageAsStream(image);
568    
569                    byte[] bytes = FileUtil.getBytes(is);
570    
571                    if (name == null) {
572                            name = image.getImageId() + StringPool.PERIOD + image.getType();
573                    }
574    
575                    if (DLStoreUtil.hasFile(companyId, repositoryId, name)) {
576                            DLStoreUtil.deleteFile(companyId, repositoryId, name);
577                    }
578    
579                    DLStoreUtil.addFile(companyId, repositoryId, name, false, bytes);
580            }
581    
582            protected void migrateImage(long imageId) throws Exception {
583                    Image image = ImageLocalServiceUtil.getImage(imageId);
584    
585                    try {
586                            migrateFile(0, 0, null, image);
587                    }
588                    catch (Exception e) {
589                            if (_log.isWarnEnabled()) {
590                                    _log.warn("Ignoring exception for image " + imageId, e);
591                            }
592    
593                            return;
594                    }
595    
596                    _sourceHook.deleteImage(image);
597            }
598    
599            protected void migrateImage(
600                            long fileEntryId, long companyId, long groupId, long folderId,
601                            String name, long smallImageId, long largeImageId,
602                            long custom1ImageId, long custom2ImageId)
603                    throws Exception {
604    
605                    Image largeImage = null;
606    
607                    if (largeImageId != 0) {
608                            largeImage = ImageLocalServiceUtil.getImage(largeImageId);
609    
610                            long repositoryId = DLFolderConstants.getDataRepositoryId(
611                                    groupId, folderId);
612    
613                            try {
614                                    migrateFile(repositoryId, companyId, name, largeImage);
615                            }
616                            catch (Exception e) {
617                                    if (_log.isWarnEnabled()) {
618                                            _log.warn(
619                                                    "Ignoring exception for image " + largeImageId, e);
620                                    }
621                            }
622                    }
623    
624                    long thumbnailImageId = 0;
625    
626                    if (smallImageId != 0) {
627                            thumbnailImageId = smallImageId;
628                    }
629                    else if (custom1ImageId != 0) {
630                            thumbnailImageId = custom1ImageId;
631                    }
632                    else if (custom2ImageId != 0) {
633                            thumbnailImageId = custom2ImageId;
634                    }
635    
636                    Image thumbnailImage = null;
637    
638                    if (thumbnailImageId != 0) {
639                            thumbnailImage = ImageLocalServiceUtil.getImage(thumbnailImageId);
640    
641                            Connection con = null;
642                            PreparedStatement ps = null;
643                            ResultSet rs = null;
644    
645                            try {
646                                    InputStream is = _sourceHook.getImageAsStream(thumbnailImage);
647    
648                                    con = DataAccess.getUpgradeOptimizedConnection();
649    
650                                    ps = con.prepareStatement(
651                                            "select max(fileVersionId) from DLFileVersion where " +
652                                                    "fileEntryId = " + fileEntryId);
653    
654                                    rs = ps.executeQuery();
655    
656                                    if (rs.next()) {
657                                            long fileVersionId = rs.getLong(1);
658    
659                                            ImageProcessorUtil.storeThumbnail(
660                                                    companyId, groupId, fileEntryId, fileVersionId,
661                                                    custom1ImageId, custom2ImageId, is,
662                                                    thumbnailImage.getType());
663                                    }
664                            }
665                            catch (Exception e) {
666                                    if (_log.isWarnEnabled()) {
667                                            _log.warn(
668                                                    "Ignoring exception for image " + thumbnailImageId, e);
669                                    }
670                            }
671                            finally {
672                                    DataAccess.cleanUp(con, ps, rs);
673                            }
674                    }
675    
676                    if (largeImageId != 0) {
677                            _sourceHook.deleteImage(largeImage);
678    
679                            runSQL("delete from Image where imageId = " + largeImageId);
680                    }
681    
682                    if ((largeImageId != thumbnailImageId) && (thumbnailImageId != 0)) {
683                            _sourceHook.deleteImage(thumbnailImage);
684    
685                            runSQL("delete from Image where imageId = " + thumbnailImageId);
686                    }
687            }
688    
689            protected void migrateImageFiles() throws Exception {
690                    Connection con = null;
691                    PreparedStatement ps = null;
692                    ResultSet rs = null;
693    
694                    try {
695                            con = DataAccess.getUpgradeOptimizedConnection();
696    
697                            StringBundler sb = new StringBundler(8);
698    
699                            sb.append("select fileEntryId, companyId, groupId, folderId, ");
700                            sb.append("name, smallImageId, largeImageId, custom1ImageId, ");
701                            sb.append("custom2ImageId from DLFileEntry where ((smallImageId ");
702                            sb.append("is not null) and (smallImageId != 0)) or ");
703                            sb.append("((largeImageId is not null) and (largeImageId != 0)) ");
704                            sb.append("or ((custom1ImageId is not null) and (custom1ImageId ");
705                            sb.append("!= 0)) or ((custom2ImageId is not null) and ");
706                            sb.append("(custom2ImageId != 0))");
707    
708                            ps = con.prepareStatement(sb.toString());
709    
710                            rs = ps.executeQuery();
711    
712                            while (rs.next()) {
713                                    long fileEntryId = rs.getLong("fileEntryId");
714                                    long companyId = rs.getLong("companyId");
715                                    long groupId = rs.getLong("groupId");
716                                    long folderId = rs.getLong("folderId");
717                                    String name = rs.getString("name");
718                                    long smallImageId = rs.getLong("smallImageId");
719                                    long largeImageId = rs.getLong("largeImageId");
720                                    long custom1ImageId = rs.getLong("custom1ImageId");
721                                    long custom2ImageId = rs.getLong("custom2ImageId");
722    
723                                    migrateImage(
724                                            fileEntryId, companyId, groupId, folderId, name,
725                                            smallImageId, largeImageId, custom1ImageId, custom2ImageId);
726                            }
727                    }
728                    finally {
729                            DataAccess.cleanUp(con, ps, rs);
730                    }
731    
732                    if (_sourceHookClassName.equals(DLHook.class.getName())) {
733                            return;
734                    }
735    
736                    try {
737                            con = DataAccess.getUpgradeOptimizedConnection();
738    
739                            ps = con.prepareStatement("select imageId from Image");
740    
741                            rs = ps.executeQuery();
742    
743                            while (rs.next()) {
744                                    long imageId = rs.getLong("imageId");
745    
746                                    migrateImage(imageId);
747                            }
748                    }
749                    finally {
750                            DataAccess.cleanUp(con, ps, rs);
751                    }
752    
753                    if (_sourceHookClassName.equals(DatabaseHook.class.getName())) {
754                            runSQL("update Image set text_ = ''");
755                    }
756            }
757    
758            protected void updateIGFolderEntries() throws Exception {
759                    Connection con = null;
760                    PreparedStatement ps = null;
761                    ResultSet rs = null;
762    
763                    try {
764                            con = DataAccess.getUpgradeOptimizedConnection();
765    
766                            ps = con.prepareStatement(
767                                    "select * from IGFolder order by folderId asc");
768    
769                            rs = ps.executeQuery();
770    
771                            Map<Long, Long> folderIds = new HashMap<Long, Long>();
772    
773                            while (rs.next()) {
774                                    String uuid = rs.getString("uuid_");
775                                    long folderId = rs.getLong("folderId");
776                                    long groupId = rs.getLong("groupId");
777                                    long companyId = rs.getLong("companyId");
778                                    long userId = rs.getLong("userId");
779                                    String userName = rs.getString("userName");
780                                    Timestamp createDate = rs.getTimestamp("createDate");
781                                    Timestamp modifiedDate = rs.getTimestamp("modifiedDate");
782                                    long parentFolderId = rs.getLong("parentFolderId");
783                                    String name = rs.getString("name");
784                                    String description = rs.getString("description");
785    
786                                    if (folderIds.containsKey(parentFolderId)) {
787                                            parentFolderId = folderIds.get(parentFolderId);
788                                    }
789    
790                                    boolean update = updateIGImageFolderId(
791                                            groupId, name, parentFolderId, folderId, folderIds);
792    
793                                    if (!update) {
794                                            addDLFolderEntry(
795                                                    uuid, folderId, groupId, companyId, userId, userName,
796                                                    createDate, modifiedDate, groupId, parentFolderId, name,
797                                                    description, modifiedDate);
798                                    }
799                            }
800    
801                            runSQL("drop table IGFolder");
802                    }
803                    finally {
804                            DataAccess.cleanUp(con, ps, rs);
805                    }
806            }
807    
808            protected void updateIGFolderPermissions() throws Exception {
809                    deleteConflictingIGPermissions(
810                            _IG_FOLDER_CLASS_NAME, DLFolder.class.getName());
811    
812                    updateIGtoDLPermissions(
813                            _IG_FOLDER_CLASS_NAME, DLFolder.class.getName());
814            }
815    
816            protected void updateIGImageEntries() throws Exception {
817                    Connection con = null;
818                    PreparedStatement ps = null;
819                    ResultSet rs = null;
820    
821                    try {
822                            con = DataAccess.getUpgradeOptimizedConnection();
823    
824                            ps = con.prepareStatement(
825                                    "select fileEntryTypeId, companyId from DLFileEntryType " +
826                                            "where name = ?");
827    
828                            ps.setString(1, DLFileEntryTypeConstants.NAME_IG_IMAGE);
829    
830                            rs = ps.executeQuery();
831    
832                            boolean hasIGImageFileEntryType = false;
833    
834                            while (rs.next()) {
835                                    long fileEntryTypeId = rs.getLong("fileEntryTypeId");
836                                    long companyId = rs.getLong("companyId");
837    
838                                    updateIGImageEntries(companyId, fileEntryTypeId);
839    
840                                    hasIGImageFileEntryType = true;
841                            }
842    
843                            if (!hasIGImageFileEntryType) {
844                                    updateIGImageEntries(0, 0);
845                            }
846    
847                            runSQL("drop table IGImage");
848                    }
849                    finally {
850                            DataAccess.cleanUp(con, ps, rs);
851                    }
852            }
853    
854            protected void updateIGImageEntries(long companyId, long fileEntryTypeId)
855                    throws Exception {
856    
857                    Connection con = null;
858                    PreparedStatement ps = null;
859                    ResultSet rs = null;
860    
861                    try {
862                            con = DataAccess.getUpgradeOptimizedConnection();
863    
864                            String sql = "select * from IGImage";
865    
866                            if (companyId != 0) {
867                                    sql = "select * from IGImage where companyId = ?";
868                            }
869    
870                            ps = con.prepareStatement(sql);
871    
872                            if (companyId != 0) {
873                                    ps.setLong(1, companyId);
874                            }
875    
876                            rs = ps.executeQuery();
877    
878                            while (rs.next()) {
879                                    String uuid = rs.getString("uuid_");
880                                    long imageId = rs.getLong("imageId");
881                                    long groupId = rs.getLong("groupId");
882                                    companyId = rs.getLong("companyId");
883                                    long userId = rs.getLong("userId");
884                                    String userName = rs.getString("userName");
885                                    Timestamp createDate = rs.getTimestamp("createDate");
886                                    Timestamp modifiedDate = rs.getTimestamp("modifiedDate");
887                                    long folderId = rs.getLong("folderId");
888                                    String title = rs.getString("name");
889                                    String description = rs.getString("description");
890                                    long smallImageId = rs.getLong("smallImageId");
891                                    long largeImageId = rs.getLong("largeImageId");
892                                    long custom1ImageId = rs.getLong("custom1ImageId");
893                                    long custom2ImageId = rs.getLong("custom2ImageId");
894    
895                                    Object[] image = getImage(largeImageId);
896    
897                                    if (image == null) {
898                                            continue;
899                                    }
900    
901                                    String extension = (String)image[0];
902    
903                                    String mimeType = MimeTypesUtil.getExtensionContentType(
904                                            extension);
905    
906                                    String name = String.valueOf(
907                                            increment(DLFileEntry.class.getName()));
908    
909                                    long size = (Long)image[1];
910    
911                                    try {
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                                    catch (Exception e) {
921                                            title = title.concat(StringPool.SPACE).concat(
922                                                    String.valueOf(imageId));
923    
924                                            addDLFileEntry(
925                                                    uuid, imageId, groupId, companyId, userId, userName,
926                                                    userId, userName, createDate, modifiedDate, groupId,
927                                                    folderId, name, extension, mimeType, title, description,
928                                                    StringPool.BLANK, fileEntryTypeId, "1.0", size, 0,
929                                                    smallImageId, largeImageId, custom1ImageId,
930                                                    custom2ImageId);
931                                    }
932    
933                                    addDLFileVersion(
934                                            increment(), groupId, companyId, userId, userName,
935                                            createDate, groupId, folderId, imageId, extension, mimeType,
936                                            title, description, StringPool.BLANK, StringPool.BLANK,
937                                            fileEntryTypeId, "1.0", size, 0, userId, userName,
938                                            modifiedDate);
939                            }
940                    }
941                    finally {
942                            DataAccess.cleanUp(con, ps, rs);
943                    }
944            }
945    
946            protected boolean updateIGImageFolderId(
947                            long groupId, String name, long parentFolderId, long folderId,
948                            Map<Long, Long> folderIds)
949                    throws Exception {
950    
951                    Connection con = null;
952                    PreparedStatement ps = null;
953                    ResultSet rs = null;
954    
955                    try {
956                            con = DataAccess.getUpgradeOptimizedConnection();
957    
958                            ps = con.prepareStatement(
959                                    "select folderId from DLFolder where groupId = " + groupId +
960                                            " and parentFolderId = " + parentFolderId +
961                                                    " and name = ?");
962    
963                            ps.setString(1, name);
964    
965                            rs = ps.executeQuery();
966    
967                            if (rs.next()) {
968                                    long newFolderId = rs.getLong("folderId");
969    
970                                    runSQL(
971                                            "update IGImage set folderId = " + newFolderId +
972                                                    " where folderId = " + folderId);
973    
974                                    folderIds.put(folderId, newFolderId);
975    
976                                    return true;
977                            }
978                    }
979                    finally {
980                            DataAccess.cleanUp(con, ps, rs);
981                    }
982    
983                    return false;
984            }
985    
986            protected void updateIGImagePermissions() throws Exception {
987                    deleteConflictingIGPermissions(
988                            _IG_IMAGE_CLASS_NAME, DLFileEntry.class.getName());
989    
990                    updateIGtoDLPermissions(
991                            _IG_IMAGE_CLASS_NAME, DLFileEntry.class.getName());
992            }
993    
994            protected void updateIGtoDLPermissions(
995                            String igResourceName, String dlResourceName)
996                    throws Exception {
997    
998                    Map<String, Long> igBitwiseValues = getBitwiseValues(igResourceName);
999    
1000                    if (igBitwiseValues.isEmpty()) {
1001                            if (_log.isWarnEnabled()) {
1002                                    _log.warn(
1003                                            "Resource actions do not exist for " + igResourceName);
1004                            }
1005    
1006                            return;
1007                    }
1008    
1009                    Map<String, Long> dlBitwiseValues = getBitwiseValues(dlResourceName);
1010    
1011                    if (dlBitwiseValues.isEmpty()) {
1012                            if (_log.isWarnEnabled()) {
1013                                    _log.warn(
1014                                            "Resource actions do not exist for " + dlResourceName);
1015                            }
1016    
1017                            return;
1018                    }
1019    
1020                    // The size of igBitwiseValues is based on the number of actions defined
1021                    // in resource actions which was 7 and 4 for IGFolder and IGImage
1022                    // respectively. This means the loop will execute at most 2^7 (128)
1023                    // times. If we were to check before update, we would still have to
1024                    // perform 128 queries, so we may as well just update 128 times even if
1025                    // no candidates exist for a given value.
1026    
1027                    for (int i = 0; i < Math.pow(2, igBitwiseValues.size()); i++) {
1028                            List<String> igActionIds = getResourceActionIds(igBitwiseValues, i);
1029    
1030                            if (igResourceName.equals(_IG_FOLDER_CLASS_NAME)) {
1031                                    Collections.replaceAll(
1032                                            igActionIds, "ADD_IMAGE", "ADD_DOCUMENT");
1033                            }
1034    
1035                            long dlActionIdsLong = getBitwiseValue(
1036                                    dlBitwiseValues, igActionIds);
1037    
1038                            runSQL(
1039                                    "update ResourcePermission set name = '" + dlResourceName +
1040                                            "', actionIds = " + dlActionIdsLong + " where name = '" +
1041                                                    igResourceName + "'" + " and actionIds = " + i);
1042                    }
1043            }
1044    
1045            private static final String _IG_FOLDER_CLASS_NAME =
1046                    "com.liferay.portlet.imagegallery.model.IGFolder";
1047    
1048            private static final String _IG_IMAGE_CLASS_NAME =
1049                    "com.liferay.portlet.imagegallery.model.IGImage";
1050    
1051            private static Log _log = LogFactoryUtil.getLog(UpgradeImageGallery.class);
1052    
1053            private Hook _sourceHook;
1054            private String _sourceHookClassName;
1055    
1056    }