001    /**
002     * Copyright (c) 2000-2011 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.convert;
016    
017    import com.liferay.counter.service.CounterLocalServiceUtil;
018    import com.liferay.portal.NoSuchResourceActionException;
019    import com.liferay.portal.convert.util.PermissionView;
020    import com.liferay.portal.convert.util.ResourcePermissionView;
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.dao.orm.QueryUtil;
025    import com.liferay.portal.kernel.exception.PortalException;
026    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
027    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedWriter;
028    import com.liferay.portal.kernel.log.Log;
029    import com.liferay.portal.kernel.log.LogFactoryUtil;
030    import com.liferay.portal.kernel.util.FileUtil;
031    import com.liferay.portal.kernel.util.GetterUtil;
032    import com.liferay.portal.kernel.util.MultiValueMap;
033    import com.liferay.portal.kernel.util.MultiValueMapFactoryUtil;
034    import com.liferay.portal.kernel.util.PropsKeys;
035    import com.liferay.portal.kernel.util.ReleaseInfo;
036    import com.liferay.portal.kernel.util.StringPool;
037    import com.liferay.portal.kernel.util.StringUtil;
038    import com.liferay.portal.kernel.util.Tuple;
039    import com.liferay.portal.kernel.util.UnmodifiableList;
040    import com.liferay.portal.kernel.util.Validator;
041    import com.liferay.portal.model.Company;
042    import com.liferay.portal.model.Group;
043    import com.liferay.portal.model.Release;
044    import com.liferay.portal.model.ReleaseConstants;
045    import com.liferay.portal.model.ResourceAction;
046    import com.liferay.portal.model.ResourceCode;
047    import com.liferay.portal.model.ResourceConstants;
048    import com.liferay.portal.model.ResourcePermission;
049    import com.liferay.portal.model.Role;
050    import com.liferay.portal.model.RoleConstants;
051    import com.liferay.portal.model.impl.PermissionModelImpl;
052    import com.liferay.portal.model.impl.ResourceCodeModelImpl;
053    import com.liferay.portal.model.impl.ResourceModelImpl;
054    import com.liferay.portal.model.impl.ResourcePermissionModelImpl;
055    import com.liferay.portal.model.impl.RoleModelImpl;
056    import com.liferay.portal.security.permission.PermissionCacheUtil;
057    import com.liferay.portal.security.permission.ResourceActionsUtil;
058    import com.liferay.portal.service.ClassNameLocalServiceUtil;
059    import com.liferay.portal.service.CompanyLocalServiceUtil;
060    import com.liferay.portal.service.GroupLocalServiceUtil;
061    import com.liferay.portal.service.ReleaseLocalServiceUtil;
062    import com.liferay.portal.service.ResourceActionLocalServiceUtil;
063    import com.liferay.portal.service.ResourceCodeLocalServiceUtil;
064    import com.liferay.portal.service.RoleLocalServiceUtil;
065    import com.liferay.portal.service.UserLocalServiceUtil;
066    import com.liferay.portal.service.persistence.BatchSessionUtil;
067    import com.liferay.portal.upgrade.util.Table;
068    import com.liferay.portal.util.MaintenanceUtil;
069    import com.liferay.portal.util.PropsValues;
070    import com.liferay.portal.util.ShutdownUtil;
071    
072    import java.io.FileReader;
073    import java.io.FileWriter;
074    import java.io.Writer;
075    
076    import java.sql.Connection;
077    import java.sql.PreparedStatement;
078    import java.sql.ResultSet;
079    import java.sql.Types;
080    
081    import java.util.ArrayList;
082    import java.util.Collections;
083    import java.util.HashMap;
084    import java.util.HashSet;
085    import java.util.List;
086    import java.util.Map;
087    import java.util.Set;
088    
089    /**
090     * <p>
091     * This class converts all existing permissions from the legacy permissions
092     * algorithm to the latest algorithm.
093     * </p>
094     *
095     * @author Alexander Chow
096     */
097    public class ConvertPermissionAlgorithm extends ConvertProcess {
098    
099            @Override
100            public String getDescription() {
101                    return "convert-legacy-permission-algorithm";
102            }
103    
104            @Override
105            public String[] getParameterNames() {
106                    return new String[] {"generate-custom-roles=checkbox"};
107            }
108    
109            @Override
110            public boolean isEnabled() {
111                    boolean enabled = false;
112    
113                    if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 6) {
114                            enabled = true;
115                    }
116    
117                    return enabled;
118            }
119    
120            protected void convertToBitwise() throws Exception {
121    
122                    // ResourceAction and ResourcePermission
123    
124                    MaintenanceUtil.appendStatus(
125                            "Generating ResourceAction and ResourcePermission data");
126    
127                    Table table = new Table(
128                            ResourceCodeModelImpl.TABLE_NAME,
129                            new Object[][] {
130                                    {"name", new Integer(Types.VARCHAR)}
131                            });
132    
133                    table.setSelectSQL(
134                            "SELECT name FROM " + ResourceCodeModelImpl.TABLE_NAME +
135                                    " GROUP BY name");
136    
137                    String tempFile = table.generateTempFile();
138    
139                    UnsyncBufferedReader resourceNameReader = new UnsyncBufferedReader(
140                            new FileReader(tempFile));
141    
142                    Writer resourcePermissionWriter = new UnsyncBufferedWriter(
143                            new FileWriter(tempFile + _EXT_RESOURCE_PERMISSION));
144    
145                    PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM = 6;
146    
147                    try {
148                            String line = null;
149    
150                            while (Validator.isNotNull(line = resourceNameReader.readLine())) {
151                                    String[] values = StringUtil.split(line);
152    
153                                    if (values.length == 0) {
154                                            continue;
155                                    }
156    
157                                    String name = values[0];
158    
159                                    List<String> defaultActionIds =
160                                            ResourceActionsUtil.getResourceActions(name);
161    
162                                    ResourceActionLocalServiceUtil.checkResourceActions(
163                                            name, defaultActionIds);
164    
165                                    convertResourcePermission(resourcePermissionWriter, name);
166                            }
167    
168                            resourcePermissionWriter.close();
169    
170                            MaintenanceUtil.appendStatus("Updating ResourcePermission table");
171    
172                            Table resourcePermissionTable = new Table(
173                                    ResourcePermissionModelImpl.TABLE_NAME,
174                                    ResourcePermissionModelImpl.TABLE_COLUMNS);
175    
176                            resourcePermissionTable.populateTable(
177                                    tempFile + _EXT_RESOURCE_PERMISSION);
178                    }
179                    catch (Exception e) {
180                            PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM = 5;
181    
182                            throw e;
183                    }
184                    finally {
185                            resourceNameReader.close();
186    
187                            resourcePermissionWriter.close();
188    
189                            FileUtil.delete(tempFile);
190                            FileUtil.delete(tempFile + _EXT_RESOURCE_PERMISSION);
191                    }
192    
193                    // Clean up
194    
195                    MaintenanceUtil.appendStatus("Cleaning up legacy tables");
196    
197                    DB db = DBFactoryUtil.getDB();
198    
199                    db.runSQL("DELETE FROM " + ResourceCodeModelImpl.TABLE_NAME);
200                    db.runSQL("DELETE FROM " + PermissionModelImpl.TABLE_NAME);
201                    db.runSQL("DELETE FROM " + ResourceModelImpl.TABLE_NAME);
202                    db.runSQL("DELETE FROM Roles_Permissions");
203    
204                    Release release = null;
205    
206                    try {
207                            release = ReleaseLocalServiceUtil.getRelease(
208                                    ReleaseConstants.DEFAULT_SERVLET_CONTEXT_NAME,
209                                    ReleaseInfo.getBuildNumber());
210                    }
211                    catch (PortalException pe) {
212                            release = ReleaseLocalServiceUtil.addRelease(
213                                    ReleaseConstants.DEFAULT_SERVLET_CONTEXT_NAME,
214                                    ReleaseInfo.getBuildNumber());
215                    }
216    
217                    ReleaseLocalServiceUtil.updateRelease(
218                            release.getReleaseId(), ReleaseInfo.getBuildNumber(),
219                            ReleaseInfo.getBuildDate(), false);
220    
221                    MaintenanceUtil.appendStatus("Converted to bitwise permission");
222            }
223    
224            protected void convertToRBAC() throws Exception {
225                    initializeRBAC();
226    
227                    // Groups_Permissions
228    
229                    convertPermissions(
230                            RoleConstants.TYPE_SITE, "Groups_Permissions",
231                            new String[] {"groupId"}, "Groups_Roles",
232                            new Object[][] {
233                                    {"groupId", Types.BIGINT}, {"roleId", Types.BIGINT}
234                            });
235    
236                    // OrgGroupPermission
237    
238                    convertPermissions(
239                            RoleConstants.TYPE_ORGANIZATION, "OrgGroupPermission",
240                            new String[] {"organizationId", "groupId"}, "OrgGroupRole",
241                            new Object[][] {
242                                    {"organizationId", Types.BIGINT}, {"groupId", Types.BIGINT},
243                                    {"roleId", Types.BIGINT}
244                            });
245    
246                    // Users_Permissions
247    
248                    convertPermissions(
249                            RoleConstants.TYPE_REGULAR, "Users_Permissions",
250                            new String[] {"userId"}, "Users_Roles",
251                            new Object[][] {
252                                    {"userId", Types.BIGINT}, {"roleId", Types.BIGINT}
253                            });
254    
255                    // Clean up
256    
257                    PermissionCacheUtil.clearCache();
258    
259                    PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM = 5;
260    
261                    MaintenanceUtil.appendStatus("Converted to RBAC permission");
262            }
263    
264            protected String convertGuestUsers(String legacyFile) throws Exception {
265                    UnsyncBufferedReader legacyFileReader = new UnsyncBufferedReader(
266                            new FileReader(legacyFile));
267    
268                    Writer legacyFileUpdatedWriter = new UnsyncBufferedWriter(
269                            new FileWriter(legacyFile + _UPDATED));
270                    Writer legacyFileExtRolesPermissionsWriter = new UnsyncBufferedWriter(
271                            new FileWriter(legacyFile + _EXT_ROLES_PERMIMISSIONS));
272    
273                    try {
274                            String line = null;
275    
276                            while (Validator.isNotNull(line = legacyFileReader.readLine())) {
277                                    String[] values = StringUtil.split(line);
278    
279                                    long companyId = PermissionView.getCompanyId(values);
280                                    long permissionId = PermissionView.getPermissionId(values);
281                                    int scope = PermissionView.getScopeId(values);
282                                    long userId = PermissionView.getPrimaryKey(values);
283    
284                                    if ((scope == ResourceConstants.SCOPE_INDIVIDUAL) &&
285                                            (_guestUsersSet.contains(userId))) {
286    
287                                            long roleId = _guestRolesMap.get(companyId).getRoleId();
288    
289                                            String key = roleId + "_" + permissionId;
290    
291                                            if (_rolesPermissions.contains(key)) {
292                                                    continue;
293                                            }
294                                            else {
295                                                    _rolesPermissions.add(key);
296                                            }
297    
298                                            legacyFileExtRolesPermissionsWriter.write(
299                                                    roleId + "," + permissionId + "\n");
300                                    }
301                                    else {
302                                            legacyFileUpdatedWriter.write(line + "\n");
303                                    }
304                            }
305                    }
306                    finally {
307                            legacyFileReader.close();
308    
309                            legacyFileUpdatedWriter.close();
310                            legacyFileExtRolesPermissionsWriter.close();
311                    }
312    
313                    Table table = new Table(
314                            "Roles_Permissions",
315                            new Object[][] {
316                                    {"roleId", Types.BIGINT}, {"permissionId", Types.BIGINT}
317                            });
318    
319                    table.populateTable(legacyFile + _EXT_ROLES_PERMIMISSIONS);
320    
321                    FileUtil.delete(legacyFile);
322                    FileUtil.delete(legacyFile + _EXT_ROLES_PERMIMISSIONS);
323    
324                    return legacyFile + _UPDATED;
325            }
326    
327            protected void convertPermissions(
328                            int type, String legacyName, String[] primKeys, String newName,
329                            Object[][] newColumns)
330                    throws Exception {
331    
332                    MaintenanceUtil.appendStatus("Processing " + legacyName);
333    
334                    Table legacyTable = new PermissionView(legacyName, primKeys);
335    
336                    String legacyFile = legacyTable.generateTempFile();
337    
338                    if (legacyFile == null) {
339                            return;
340                    }
341    
342                    if (type == RoleConstants.TYPE_REGULAR) {
343                            legacyFile = convertGuestUsers(legacyFile);
344    
345                            MaintenanceUtil.appendStatus(
346                                    "Converted guest users to guest roles");
347                    }
348    
349                    convertRoles(legacyFile, type, newName, newColumns);
350    
351                    MaintenanceUtil.appendStatus("Converted roles for " + legacyName);
352    
353                    DB db = DBFactoryUtil.getDB();
354    
355                    db.runSQL(legacyTable.getDeleteSQL());
356    
357                    FileUtil.delete(legacyFile);
358            }
359    
360            protected void convertResourcePermission(Writer writer, String name)
361                    throws Exception {
362    
363                    ResourcePermissionView resourcePermissionView =
364                            new ResourcePermissionView(name);
365    
366                    UnsyncBufferedReader resourcePermissionReader = null;
367    
368                    String resourcePermissionFile =
369                            resourcePermissionView.generateTempFile();
370    
371                    if (resourcePermissionFile == null) {
372                            return;
373                    }
374    
375                    MultiValueMap<Tuple, String> mvp =
376                            (MultiValueMap<Tuple, String>)
377                                    MultiValueMapFactoryUtil.getMultiValueMap(
378                                            _CONVERT_RESOURCE_PERMISSION);
379    
380                    try {
381                            resourcePermissionReader = new UnsyncBufferedReader(
382                                    new FileReader(resourcePermissionFile));
383    
384                            String line = null;
385    
386                            while (Validator.isNotNull(
387                                            line = resourcePermissionReader.readLine())) {
388    
389                                    String[] values = StringUtil.split(line);
390    
391                                    String actionId = ResourcePermissionView.getActionId(values);
392                                    long companyId = ResourcePermissionView.getCompanyId(values);
393                                    int scope = ResourcePermissionView.getScope(values);
394                                    String primKey = ResourcePermissionView.getPrimaryKey(values);
395                                    long roleId = ResourcePermissionView.getRoleId(values);
396    
397                                    mvp.put(new Tuple(companyId, scope, primKey, roleId), actionId);
398                            }
399                    }
400                    finally {
401                            if (resourcePermissionReader != null) {
402                                    resourcePermissionReader.close();
403                            }
404    
405                            FileUtil.delete(resourcePermissionFile);
406                    }
407    
408                    for (Tuple key : mvp.keySet()) {
409                            long resourcePermissionId = CounterLocalServiceUtil.increment(
410                                    ResourcePermission.class.getName());
411    
412                            long companyId = (Long)key.getObject(0);
413                            int scope = (Integer)key.getObject(1);
414                            String primKey = (String)key.getObject(2);
415                            long roleId = (Long)key.getObject(3);
416    
417                            long actionIds = 0;
418    
419                            for (String actionId : mvp.getAll(key)) {
420                                    try {
421                                            ResourceAction resourceAction =
422                                                    ResourceActionLocalServiceUtil.getResourceAction(
423                                                            name, actionId);
424    
425                                            actionIds |= resourceAction.getBitwiseValue();
426                                    }
427                                    catch (NoSuchResourceActionException nsrae) {
428                                            if (_log.isWarnEnabled()) {
429                                                    String msg = nsrae.getMessage();
430    
431                                                    _log.warn("Could not find resource action " + msg);
432                                            }
433                                    }
434                            }
435    
436                            writer.append(resourcePermissionId + StringPool.COMMA);
437                            writer.append(companyId + StringPool.COMMA);
438                            writer.append(name + StringPool.COMMA);
439                            writer.append(scope + StringPool.COMMA);
440                            writer.append(primKey + StringPool.COMMA);
441                            writer.append(roleId + StringPool.COMMA);
442                            writer.append(0 + StringPool.COMMA);
443                            writer.append(actionIds + StringPool.COMMA + StringPool.NEW_LINE);
444                    }
445            }
446    
447            protected void convertRoles(
448                            String legacyFile, int type, String newName, Object[][] newColumns)
449                    throws Exception {
450    
451                    UnsyncBufferedReader legacyFileReader = new UnsyncBufferedReader(
452                            new FileReader(legacyFile));
453    
454                    Writer legacyFileExtRoleWriter = new UnsyncBufferedWriter(
455                            new FileWriter(legacyFile + _EXT_ROLE));
456                    Writer legacyFileExtRolesPermissionsWriter = new UnsyncBufferedWriter(
457                            new FileWriter(legacyFile + _EXT_ROLES_PERMIMISSIONS));
458                    Writer legacyFileExtOtherRolesWriter = new UnsyncBufferedWriter(
459                            new FileWriter(legacyFile + _EXT_OTHER_ROLES));
460    
461                    try {
462    
463                            // Group by resource id
464    
465                            MultiValueMap<Long, String[]> mvp =
466                                    (MultiValueMap<Long, String[]>)
467                                            MultiValueMapFactoryUtil.getMultiValueMap(_CONVERT_ROLES);
468    
469                            String line = null;
470    
471                            while (Validator.isNotNull(line = legacyFileReader.readLine())) {
472                                    String[] values = StringUtil.split(line);
473    
474                                    long resourceId = PermissionView.getResourceId(values);
475    
476                                    mvp.put(resourceId, values);
477                            }
478    
479                            // Assign role for each grouping
480    
481                            for (Long key : mvp.keySet()) {
482                                    List<String[]> valuesList = new ArrayList<String[]>(
483                                            mvp.getAll(key));
484    
485                                    String[] values = valuesList.get(0);
486    
487                                    long companyId = PermissionView.getCompanyId(values);
488                                    long groupId = PermissionView.getPrimaryKey(values);
489                                    String name = PermissionView.getNameId(values);
490                                    int scope = PermissionView.getScopeId(values);
491    
492                                    // Group action ids and permission ids
493    
494                                    List<String> actionsIds = new ArrayList<String>();
495                                    List<Long> permissionIds = new ArrayList<Long>();
496    
497                                    for (String[] curValues : valuesList) {
498                                            String actionId = PermissionView.getActionId(curValues);
499                                            long permissionId = PermissionView.getPermissionId(
500                                                    curValues);
501    
502                                            actionsIds.add(actionId);
503                                            permissionIds.add(permissionId);
504                                    }
505    
506                                    // Look for owner and system roles
507    
508                                    if ((type != RoleConstants.TYPE_ORGANIZATION) &&
509                                            (scope == ResourceConstants.SCOPE_INDIVIDUAL)) {
510    
511                                            // Find default actions
512    
513                                            List<String> defaultActions = null;
514    
515                                            if (type == RoleConstants.TYPE_REGULAR) {
516                                                    defaultActions =
517                                                            ResourceActionsUtil.getResourceActions(name);
518                                            }
519                                            else {
520                                                    defaultActions =
521                                                            ResourceActionsUtil.getResourceGroupDefaultActions(
522                                                                    name);
523                                            }
524    
525                                            // Resolve owner and system roles
526    
527                                            Role defaultRole = null;
528    
529                                            if (type == RoleConstants.TYPE_REGULAR) {
530                                                    if (defaultActions instanceof UnmodifiableList) {
531                                                            defaultActions = new ArrayList<String>(
532                                                                    defaultActions);
533                                                    }
534    
535                                                    Collections.sort(actionsIds);
536                                                    Collections.sort(defaultActions);
537    
538                                                    if (defaultActions.equals(actionsIds)) {
539                                                            defaultRole = _ownerRolesMap.get(companyId);
540                                                    }
541                                            }
542                                            else {
543                                                    if (defaultActions.containsAll(actionsIds)) {
544                                                            Role[] defaultRoles = _defaultRolesMap.get(
545                                                                    companyId);
546    
547                                                            Group group = _groupsMap.get(groupId);
548    
549                                                            if (group == null) {
550                                                                    continue;
551                                                            }
552    
553                                                            if (group.isOrganization()) {
554                                                                    defaultRole = defaultRoles[0];
555                                                            }
556                                                            else if (group.isRegularSite()) {
557                                                                    defaultRole = defaultRoles[2];
558                                                            }
559                                                            else if (group.isUser() || group.isUserGroup()) {
560                                                                    defaultRole = defaultRoles[1];
561                                                            }
562                                                    }
563                                            }
564    
565                                            if (defaultRole != null) {
566                                                    long roleId = defaultRole.getRoleId();
567    
568                                                    for (Long permissionId : permissionIds) {
569                                                            String curKey = roleId + "_" + permissionId;
570    
571                                                            if (_rolesPermissions.contains(curKey)) {
572                                                                    continue;
573                                                            }
574                                                            else {
575                                                                    _rolesPermissions.add(curKey);
576                                                            }
577    
578                                                            legacyFileExtRolesPermissionsWriter.write(
579                                                                    roleId + "," + permissionId + ",\n");
580                                                    }
581    
582                                                    continue;
583                                            }
584                                    }
585    
586                                    if (isGenerateCustomRoles()) {
587    
588                                            // Role_
589    
590                                            long roleId = CounterLocalServiceUtil.increment();
591    
592                                            String roleName = StringUtil.upperCaseFirstLetter(
593                                                    RoleConstants.getTypeLabel(type));
594    
595                                            roleName += " " + StringUtil.toHexString(roleId);
596    
597                                            String[] roleColumns = new String[] {
598                                                    String.valueOf(roleId), String.valueOf(companyId),
599                                                    String.valueOf(
600                                                            ClassNameLocalServiceUtil.getClassNameId(
601                                                                    Role.class)),
602                                                    String.valueOf(roleId), roleName, StringPool.BLANK,
603                                                    "Autogenerated role from portal upgrade",
604                                                    String.valueOf(type), "lfr-permission-algorithm-5"
605                                            };
606    
607                                            for (int i = 0; i < roleColumns.length; i++) {
608                                                    legacyFileExtRoleWriter.write(
609                                                            roleColumns[i] + StringPool.COMMA);
610    
611                                                    if (i == (roleColumns.length - 1)) {
612                                                            legacyFileExtRoleWriter.write(StringPool.NEW_LINE);
613                                                    }
614                                            }
615    
616                                            // Roles_Permissions
617    
618                                            for (Long permissionId : permissionIds) {
619                                                    String curKey = roleId + "_" + permissionId;
620    
621                                                    if (_rolesPermissions.contains(curKey)) {
622                                                            continue;
623                                                    }
624                                                    else {
625                                                            _rolesPermissions.add(curKey);
626                                                    }
627    
628                                                    legacyFileExtRolesPermissionsWriter.write(
629                                                            roleId + "," + permissionId + ",\n");
630                                            }
631    
632                                            // Others_Roles
633    
634                                            for (int i = 0; i < newColumns.length - 1; i++) {
635                                                    legacyFileExtOtherRolesWriter.write(
636                                                            values[i] + StringPool.COMMA);
637                                            }
638    
639                                            legacyFileExtOtherRolesWriter.write(roleId + ",\n");
640                                    }
641                            }
642                    }
643                    finally {
644                            legacyFileReader.close();
645    
646                            legacyFileExtRoleWriter.close();
647                            legacyFileExtRolesPermissionsWriter.close();
648                            legacyFileExtOtherRolesWriter.close();
649                    }
650    
651                    // Role_
652    
653                    Table roleTable = new Table(
654                            RoleModelImpl.TABLE_NAME, RoleModelImpl.TABLE_COLUMNS);
655    
656                    roleTable.populateTable(legacyFile + _EXT_ROLE);
657    
658                    // Roles_Permissions
659    
660                    Table rolesPermissionsTable = new Table(
661                            "Roles_Permissions",
662                            new Object[][] {
663                                    {"roleId", Types.BIGINT}, {"permissionId", Types.BIGINT}
664                            });
665    
666                    rolesPermissionsTable.populateTable(
667                            legacyFile + _EXT_ROLES_PERMIMISSIONS);
668    
669                    // Others_Roles
670    
671                    Table othersRolesTable = new Table(newName, newColumns);
672    
673                    othersRolesTable.populateTable(legacyFile + _EXT_OTHER_ROLES);
674    
675                    // Clean up
676    
677                    FileUtil.delete(legacyFile + _EXT_ROLE);
678                    FileUtil.delete(legacyFile + _EXT_ROLES_PERMIMISSIONS);
679                    FileUtil.delete(legacyFile + _EXT_OTHER_ROLES);
680            }
681    
682            @Override
683            protected void doConvert() throws Exception {
684                    try {
685                            BatchSessionUtil.setEnabled(true);
686    
687                            initialize();
688    
689                            if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 5) {
690                                    convertToRBAC();
691                            }
692    
693                            convertToBitwise();
694    
695                            MaintenanceUtil.appendStatus(
696                                    "Please set " + PropsKeys.PERMISSIONS_USER_CHECK_ALGORITHM +
697                                            " in your portal-ext.properties to 6 and restart server");
698                    }
699                    finally {
700                            ShutdownUtil.shutdown(0);
701                    }
702            }
703    
704            protected void initialize() throws Exception {
705    
706                    // Resource actions for unknown portlets
707    
708                    List<ResourceCode> resourceCodes =
709                            ResourceCodeLocalServiceUtil.getResourceCodes(
710                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS);
711    
712                    for (ResourceCode resourceCode : resourceCodes) {
713                            String name = resourceCode.getName();
714    
715                            if (!name.contains(StringPool.PERIOD)) {
716                                    ResourceActionsUtil.getPortletResourceActions(name);
717                            }
718                    }
719            }
720    
721            protected void initializeRBAC() throws Exception {
722    
723                    // System roles and default users
724    
725                    List<Company> companies = CompanyLocalServiceUtil.getCompanies();
726    
727                    for (Company company : companies) {
728                            long companyId = company.getCompanyId();
729    
730                            _defaultRolesMap.put(
731                                    companyId,
732                                    new Role[] {
733                                            RoleLocalServiceUtil.getRole(
734                                                    companyId, RoleConstants.ORGANIZATION_USER),
735                                            RoleLocalServiceUtil.getRole(
736                                                    companyId, RoleConstants.POWER_USER),
737                                            RoleLocalServiceUtil.getRole(
738                                                    companyId, RoleConstants.SITE_MEMBER)
739                                            }
740                                    );
741    
742                            Role guestRole = RoleLocalServiceUtil.getRole(
743                                    companyId, RoleConstants.GUEST);
744    
745                            _guestRolesMap.put(companyId, guestRole);
746    
747                            Role ownerRole = RoleLocalServiceUtil.getRole(
748                                    companyId, RoleConstants.OWNER);
749    
750                            _ownerRolesMap.put(companyId, ownerRole);
751    
752                            long defaultUserId = UserLocalServiceUtil.getDefaultUserId(
753                                    companyId);
754    
755                            _guestUsersSet.add(defaultUserId);
756                    }
757    
758                    // Roles_Permissions
759    
760                    Connection con = null;
761                    PreparedStatement ps = null;
762                    ResultSet rs = null;
763    
764                    try {
765                            con = DataAccess.getConnection();
766    
767                            ps = con.prepareStatement("SELECT * FROM Roles_Permissions");
768    
769                            rs = ps.executeQuery();
770    
771                            while (rs.next()) {
772                                    long roleId = rs.getLong("roleId");
773                                    long permissionId = rs.getLong("permissionId");
774    
775                                    _rolesPermissions.add(roleId + "_" + permissionId);
776                            }
777                    }
778                    finally {
779                            DataAccess.cleanUp(con, ps, rs);
780                    }
781    
782                    // Groups
783    
784                    List<Group> groups = GroupLocalServiceUtil.getGroups(
785                            QueryUtil.ALL_POS, QueryUtil.ALL_POS);
786    
787                    for (Group group : groups) {
788                            _groupsMap.put(group.getGroupId(), group);
789                    }
790            }
791    
792            protected boolean isGenerateCustomRoles() {
793                    String[] parameterValues = getParameterValues();
794    
795                    return GetterUtil.getBoolean(parameterValues[0]);
796            }
797    
798            private static final String _CONVERT_RESOURCE_PERMISSION =
799                    PropsKeys.MULTI_VALUE_MAP + ConvertPermissionAlgorithm.class.getName() +
800                            ".convertResourcePermission";
801    
802            private static final String _CONVERT_ROLES =
803                    PropsKeys.MULTI_VALUE_MAP + ConvertPermissionAlgorithm.class.getName() +
804                            ".convertRoles";
805    
806            private static final String _EXT_OTHER_ROLES = ".others_roles";
807    
808            private static final String _EXT_RESOURCE_PERMISSION =
809                    ".resource_permission";
810    
811            private static final String _EXT_ROLE = ".role";
812    
813            private static final String _EXT_ROLES_PERMIMISSIONS = ".roles_permissions";
814    
815            private static final String _UPDATED = ".updated";
816    
817            private static Log _log = LogFactoryUtil.getLog(
818                    ConvertPermissionAlgorithm.class);
819    
820            private Map<Long, Role[]> _defaultRolesMap = new HashMap<Long, Role[]>();
821            private Map<Long, Group> _groupsMap = new HashMap<Long, Group>();
822            private Map<Long, Role> _guestRolesMap = new HashMap<Long, Role>();
823            private Set<Long> _guestUsersSet = new HashSet<Long>();
824            private Map<Long, Role> _ownerRolesMap = new HashMap<Long, Role>();
825            private Set<String> _rolesPermissions = new HashSet<String>();
826    
827    }