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.tools;
016    
017    import com.liferay.portal.dao.orm.common.SQLTransformer;
018    import com.liferay.portal.events.StartupHelperUtil;
019    import com.liferay.portal.kernel.cache.CacheRegistryUtil;
020    import com.liferay.portal.kernel.cache.MultiVMPoolUtil;
021    import com.liferay.portal.kernel.dao.db.DB;
022    import com.liferay.portal.kernel.dao.db.DBFactoryUtil;
023    import com.liferay.portal.kernel.dao.jdbc.DataAccess;
024    import com.liferay.portal.kernel.log.Log;
025    import com.liferay.portal.kernel.log.LogFactoryUtil;
026    import com.liferay.portal.kernel.spring.aop.Skip;
027    import com.liferay.portal.kernel.util.GetterUtil;
028    import com.liferay.portal.kernel.util.PropsKeys;
029    import com.liferay.portal.kernel.util.ReflectionUtil;
030    import com.liferay.portal.kernel.util.ReleaseInfo;
031    import com.liferay.portal.kernel.util.StringBundler;
032    import com.liferay.portal.kernel.util.Time;
033    import com.liferay.portal.model.Release;
034    import com.liferay.portal.model.ReleaseConstants;
035    import com.liferay.portal.service.ClassNameLocalServiceUtil;
036    import com.liferay.portal.service.ReleaseLocalServiceUtil;
037    import com.liferay.portal.service.ResourceActionLocalServiceUtil;
038    import com.liferay.portal.spring.aop.ServiceBeanAopCacheManager;
039    import com.liferay.portal.util.InitUtil;
040    import com.liferay.portal.util.PropsUtil;
041    import com.liferay.portal.util.PropsValues;
042    import com.liferay.util.dao.orm.CustomSQLUtil;
043    
044    import java.lang.annotation.Annotation;
045    import java.lang.reflect.Field;
046    
047    import java.sql.Connection;
048    import java.sql.Date;
049    import java.sql.PreparedStatement;
050    import java.sql.ResultSet;
051    
052    import java.util.HashMap;
053    import java.util.concurrent.ConcurrentHashMap;
054    
055    import org.aopalliance.intercept.MethodInvocation;
056    
057    import org.apache.commons.lang.time.StopWatch;
058    
059    /**
060     * @author Michael C. Han
061     * @author Brian Wing Shun Chan
062     */
063    public class DBUpgrader {
064    
065            public static void main(String[] args) {
066                    try {
067                            StopWatch stopWatch = new StopWatch();
068    
069                            stopWatch.start();
070    
071                            InitUtil.initWithSpring();
072    
073                            upgrade();
074                            verify();
075    
076                            System.out.println(
077                                    "\nSuccessfully completed upgrade process in " +
078                                            (stopWatch.getTime() / Time.SECOND) + " seconds.");
079    
080                            System.exit(0);
081                    }
082                    catch (Exception e) {
083                            e.printStackTrace();
084    
085                            System.exit(1);
086                    }
087            }
088    
089            public static void upgrade() throws Exception {
090    
091                    // Disable database caching before upgrade
092    
093                    if (_log.isDebugEnabled()) {
094                            _log.debug("Disable cache registry");
095                    }
096    
097                    CacheRegistryUtil.setActive(false);
098    
099                    // Check release
100    
101                    int buildNumber = ReleaseLocalServiceUtil.getBuildNumberOrCreate();
102    
103                    if (buildNumber > ReleaseInfo.getParentBuildNumber()) {
104                            StringBundler sb = new StringBundler(6);
105    
106                            sb.append("Attempting to deploy an older Liferay Portal version. ");
107                            sb.append("Current build version is ");
108                            sb.append(buildNumber);
109                            sb.append(" and attempting to deploy version ");
110                            sb.append(ReleaseInfo.getParentBuildNumber());
111                            sb.append(".");
112    
113                            throw new IllegalStateException(sb.toString());
114                    }
115                    else if (buildNumber < ReleaseInfo.RELEASE_5_2_3_BUILD_NUMBER) {
116                            String msg = "You must first upgrade to Liferay Portal 5.2.3";
117    
118                            System.out.println(msg);
119    
120                            throw new RuntimeException(msg);
121                    }
122    
123                    // Reload SQL
124    
125                    CustomSQLUtil.reloadCustomSQL();
126                    SQLTransformer.reloadSQLTransformer();
127    
128                    // Upgrade
129    
130                    if (_log.isDebugEnabled()) {
131                            _log.debug("Update build " + buildNumber);
132                    }
133    
134                    _checkPermissionAlgorithm();
135                    _checkReleaseState(_getReleaseState());
136    
137                    if (PropsValues.UPGRADE_DATABASE_TRANSACTIONS_DISABLED) {
138                            _disableTransactions();
139                    }
140    
141                    try {
142                            StartupHelperUtil.upgradeProcess(buildNumber);
143                    }
144                    catch (Exception e) {
145                            _updateReleaseState(ReleaseConstants.STATE_UPGRADE_FAILURE);
146    
147                            throw e;
148                    }
149                    finally {
150                            if (PropsValues.UPGRADE_DATABASE_TRANSACTIONS_DISABLED) {
151                                    _enableTransactions();
152                            }
153                    }
154    
155                    // Update company key
156    
157                    if (StartupHelperUtil.isUpgraded()) {
158                            if (_log.isDebugEnabled()) {
159                                    _log.debug("Update company key");
160                            }
161    
162                            _updateCompanyKey();
163                    }
164    
165                    // Check class names
166    
167                    if (_log.isDebugEnabled()) {
168                            _log.debug("Check class names");
169                    }
170    
171                    ClassNameLocalServiceUtil.checkClassNames();
172    
173                    // Check resource actions
174    
175                    if (_log.isDebugEnabled()) {
176                            _log.debug("Check resource actions");
177                    }
178    
179                    ResourceActionLocalServiceUtil.checkResourceActions();
180    
181                    // Delete temporary images
182    
183                    if (_log.isDebugEnabled()) {
184                            _log.debug("Delete temporary images");
185                    }
186    
187                    _deleteTempImages();
188    
189                    // Clear the caches only if the upgrade process was run
190    
191                    if (_log.isDebugEnabled()) {
192                            _log.debug("Clear cache if upgrade process was run");
193                    }
194    
195                    if (StartupHelperUtil.isUpgraded()) {
196                            MultiVMPoolUtil.clear();
197                    }
198            }
199    
200            public static void verify() throws Exception {
201    
202                    // Check release
203    
204                    Release release = ReleaseLocalServiceUtil.fetchRelease(
205                            ReleaseConstants.DEFAULT_SERVLET_CONTEXT_NAME);
206    
207                    if (release == null) {
208                            release = ReleaseLocalServiceUtil.addRelease(
209                                    ReleaseConstants.DEFAULT_SERVLET_CONTEXT_NAME,
210                                    ReleaseInfo.getParentBuildNumber());
211                    }
212    
213                    _checkReleaseState(release.getState());
214    
215                    // Update indexes
216    
217                    if (PropsValues.DATABASE_INDEXES_UPDATE_ON_STARTUP) {
218                            StartupHelperUtil.setDropIndexes(true);
219    
220                            StartupHelperUtil.updateIndexes();
221                    }
222                    else if (StartupHelperUtil.isUpgraded()) {
223                            StartupHelperUtil.updateIndexes();
224                    }
225    
226                    // Verify
227    
228                    if (PropsValues.VERIFY_DATABASE_TRANSACTIONS_DISABLED) {
229                            _disableTransactions();
230                    }
231    
232                    try {
233                            StartupHelperUtil.verifyProcess(release.isVerified());
234                    }
235                    catch (Exception e) {
236                            _updateReleaseState(ReleaseConstants.STATE_VERIFY_FAILURE);
237    
238                            throw e;
239                    }
240                    finally {
241                            if (PropsValues.VERIFY_DATABASE_TRANSACTIONS_DISABLED) {
242                                    _enableTransactions();
243                            }
244                    }
245    
246                    // Update indexes
247    
248                    if (PropsValues.DATABASE_INDEXES_UPDATE_ON_STARTUP ||
249                            StartupHelperUtil.isUpgraded()) {
250    
251                            StartupHelperUtil.updateIndexes(false);
252                    }
253    
254                    // Update release
255    
256                    boolean verified = StartupHelperUtil.isVerified();
257    
258                    if (release.isVerified()) {
259                            verified = true;
260                    }
261    
262                    ReleaseLocalServiceUtil.updateRelease(
263                            release.getReleaseId(), ReleaseInfo.getParentBuildNumber(),
264                            ReleaseInfo.getBuildDate(), verified);
265    
266                    // Enable database caching after verify
267    
268                    CacheRegistryUtil.setActive(true);
269            }
270    
271            private static void _checkPermissionAlgorithm() throws Exception {
272                    long count = _getResourceCodesCount();
273    
274                    if (count == 0) {
275                            return;
276                    }
277    
278                    StringBundler sb = new StringBundler(8);
279    
280                    sb.append("Permission conversion to algorithm 6 has not been ");
281                    sb.append("completed. Please complete the conversion prior to ");
282                    sb.append("starting the portal. The conversion process is ");
283                    sb.append("available in portal versions starting with ");
284                    sb.append(ReleaseInfo.RELEASE_5_2_3_BUILD_NUMBER);
285                    sb.append(" and prior to ");
286                    sb.append(ReleaseInfo.RELEASE_6_2_0_BUILD_NUMBER);
287                    sb.append(".");
288    
289                    throw new IllegalStateException(sb.toString());
290            }
291    
292            private static void _checkReleaseState(int state) throws Exception {
293                    if (state == ReleaseConstants.STATE_GOOD) {
294                            return;
295                    }
296    
297                    StringBundler sb = new StringBundler(6);
298    
299                    sb.append("The database contains changes from a previous ");
300                    sb.append("upgrade attempt that failed. Please restore the old ");
301                    sb.append("database and file system and retry the upgrade. A ");
302                    sb.append("patch may be required if the upgrade failed due to a");
303                    sb.append(" bug or an unforeseen data permutation that resulted ");
304                    sb.append("from a corrupt database.");
305    
306                    throw new IllegalStateException(sb.toString());
307            }
308    
309            private static void _deleteTempImages() throws Exception {
310                    DB db = DBFactoryUtil.getDB();
311    
312                    db.runSQL(_DELETE_TEMP_IMAGES_1);
313                    db.runSQL(_DELETE_TEMP_IMAGES_2);
314            }
315    
316            private static void _disableTransactions() throws Exception {
317                    if (_log.isDebugEnabled()) {
318                            _log.debug("Disable transactions");
319                    }
320    
321                    PropsValues.SPRING_HIBERNATE_SESSION_DELEGATED = false;
322    
323                    Field field = ReflectionUtil.getDeclaredField(
324                            ServiceBeanAopCacheManager.class, "_annotations");
325    
326                    field.set(
327                            null,
328                            new HashMap<MethodInvocation, Annotation[]>() {
329    
330                                    @Override
331                                    public Annotation[] get(Object key) {
332                                            return _annotations;
333                                    }
334    
335                                    private Annotation[] _annotations = new Annotation[] {
336                                            new Skip() {
337    
338                                                    @Override
339                                                    public Class<? extends Annotation> annotationType() {
340                                                            return Skip.class;
341                                                    }
342    
343                                            }
344                                    };
345    
346                            }
347                    );
348            }
349    
350            private static void _enableTransactions() throws Exception {
351                    if (_log.isDebugEnabled()) {
352                            _log.debug("Enable transactions");
353                    }
354    
355                    PropsValues.SPRING_HIBERNATE_SESSION_DELEGATED = GetterUtil.getBoolean(
356                            PropsUtil.get(PropsKeys.SPRING_HIBERNATE_SESSION_DELEGATED));
357    
358                    Field field = ReflectionUtil.getDeclaredField(
359                            ServiceBeanAopCacheManager.class, "_annotations");
360    
361                    field.set(
362                            null, new ConcurrentHashMap<MethodInvocation, Annotation[]>());
363            }
364    
365            private static int _getReleaseState() throws Exception {
366                    Connection con = null;
367                    PreparedStatement ps = null;
368                    ResultSet rs = null;
369    
370                    try {
371                            con = DataAccess.getConnection();
372    
373                            ps = con.prepareStatement(
374                                    "select state_ from Release_ where releaseId = ?");
375    
376                            ps.setLong(1, ReleaseConstants.DEFAULT_ID);
377    
378                            rs = ps.executeQuery();
379    
380                            if (rs.next()) {
381                                    return rs.getInt("state_");
382                            }
383    
384                            throw new IllegalArgumentException(
385                                    "No Release exists with the primary key " +
386                                            ReleaseConstants.DEFAULT_ID);
387                    }
388                    finally {
389                            DataAccess.cleanUp(con, ps, rs);
390                    }
391            }
392    
393            private static long _getResourceCodesCount() throws Exception {
394                    Connection con = null;
395                    PreparedStatement ps = null;
396                    ResultSet rs = null;
397    
398                    try {
399                            con = DataAccess.getConnection();
400    
401                            ps = con.prepareStatement("select count(*) from ResourceCode");
402    
403                            rs = ps.executeQuery();
404    
405                            if (rs.next()) {
406                                    int count = rs.getInt(1);
407    
408                                    return count;
409                            }
410    
411                            return 0;
412                    }
413                    catch (Exception e) {
414                            return 0;
415                    }
416                    finally {
417                            DataAccess.cleanUp(con, ps, rs);
418                    }
419            }
420    
421            private static void _updateCompanyKey() throws Exception {
422                    DB db = DBFactoryUtil.getDB();
423    
424                    db.runSQL("update Company set key_ = null");
425            }
426    
427            private static void _updateReleaseState(int state) throws Exception {
428                    Connection con = null;
429                    PreparedStatement ps = null;
430    
431                    try {
432                            con = DataAccess.getConnection();
433    
434                            ps = con.prepareStatement(
435                                    "update Release_ set modifiedDate = ?, state_ = ? where " +
436                                            "releaseId = ?");
437    
438                            ps.setDate(1, new Date(System.currentTimeMillis()));
439                            ps.setInt(2, state);
440                            ps.setLong(3, ReleaseConstants.DEFAULT_ID);
441    
442                            ps.executeUpdate();
443                    }
444                    finally {
445                            DataAccess.cleanUp(con, ps);
446                    }
447            }
448    
449            private static final String _DELETE_TEMP_IMAGES_1 =
450                    "delete from Image where imageId IN (SELECT articleImageId FROM " +
451                            "JournalArticleImage where tempImage = TRUE)";
452    
453            private static final String _DELETE_TEMP_IMAGES_2 =
454                    "delete from JournalArticleImage where tempImage = TRUE";
455    
456            private static Log _log = LogFactoryUtil.getLog(DBUpgrader.class);
457    
458    }