Related to issue 30057: code review preview
authorVíctor Martínez Romanos <victor.martinez@openbravo.com>
Thu, 25 Jun 2015 18:56:49 +0200
changeset 27157 d7e8168bd47b
parent 27156 1c428b6ceb65
child 27158 b9068c9d09d1
child 27164 60ba8db95a9d
Related to issue 30057: code review preview

Removed flushes from RoleEventHandler because they create conflicts. As a consequence we lose the ability to clear the session, but this shouldn't be a problem because it's very unlikely to have environments with great amount of organizations.
In RoleEventHandler we only create access to * organization when access level is Client (before this changeset it created also records for other organizations and it is useless).
Reverted changes for Initial Client/Organization Setup. RoleEventHandler won't do anything if executed from an Initial Client/Organization Setup (this change is a way to isolate the problems reported at #30253)
Added log4j to RoleEventHandler.
Removed admin mode from RoleEventHandler because it's not needed (the user always has access t the entities involved in the process).
src/org/openbravo/erpCommon/businessUtility/InitialClientSetup.java
src/org/openbravo/erpCommon/businessUtility/InitialOrgSetup.java
src/org/openbravo/event/RoleEventHandler.java
--- a/src/org/openbravo/erpCommon/businessUtility/InitialClientSetup.java	Fri Jun 05 15:21:15 2015 +0200
+++ b/src/org/openbravo/erpCommon/businessUtility/InitialClientSetup.java	Thu Jun 25 18:56:49 2015 +0200
@@ -37,6 +37,7 @@
 import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.erpCommon.utility.Utility;
 import org.openbravo.model.ad.access.Role;
+import org.openbravo.model.ad.access.RoleOrganization;
 import org.openbravo.model.ad.access.User;
 import org.openbravo.model.ad.module.ADClientModule;
 import org.openbravo.model.ad.module.Module;
@@ -472,6 +473,20 @@
     log4j.debug("insertRoles() - Role inserted correctly");
     logEvent("@AD_Role_ID@=" + strRoleName);
 
+    log4j.debug("insertRoles() - Inserting role org access");
+    try {
+      RoleOrganization roleOrg = InitialSetupUtility.insertRoleOrganization(role, null);
+      if (roleOrg == null)
+        return logErrorAndRollback("@CreateClientFailed@",
+            "insertRoles() - Not able to insert the role organizations access" + strRoleName);
+    } catch (Exception e) {
+      return logErrorAndRollback("@CreateClientFailed@",
+          "insertRoles() - Not able to insert the role organizations access" + strRoleName, e);
+    }
+    log4j.debug("insertRoles() - Role organizations access inserted correctly");
+
+    logEvent("@AD_Role_ID@=" + strRoleName);
+
     return obeResult;
   }
 
--- a/src/org/openbravo/erpCommon/businessUtility/InitialOrgSetup.java	Fri Jun 05 15:21:15 2015 +0200
+++ b/src/org/openbravo/erpCommon/businessUtility/InitialOrgSetup.java	Thu Jun 25 18:56:49 2015 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2010-2015 Openbravo SLU
+ * All portions are Copyright (C) 2010-2014 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -34,6 +34,7 @@
 import org.openbravo.erpCommon.modules.ModuleUtiltiy;
 import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.model.ad.access.Role;
+import org.openbravo.model.ad.access.RoleOrganization;
 import org.openbravo.model.ad.access.User;
 import org.openbravo.model.ad.access.UserRoles;
 import org.openbravo.model.ad.datamodel.Table;
@@ -624,6 +625,18 @@
     }
     log4j.debug("insertRoles() - Role inserted correctly");
 
+    log4j.debug("insertRoles() - Inserting role org access");
+    try {
+      RoleOrganization roleOrg = InitialSetupUtility.insertRoleOrganization(role, org, true);
+      if (roleOrg == null)
+        return logErrorAndRollback("@CreateOrgFailed@",
+            "insertUser() - Not able to insert the role organizations access" + strOrgUser, null);
+    } catch (final Exception err) {
+      return logErrorAndRollback("@CreateOrgFailed@",
+          "insertUser() - Not able to insert the role organizations access" + strOrgUser, err);
+    }
+    log4j.debug("insertUser() - Role organizations access inserted correctly");
+
     log4j.debug("insertRoles() - Inserting user role");
     try {
       UserRoles userRoles = InitialSetupUtility.insertUserRole(client, user, null, role, true);
--- a/src/org/openbravo/event/RoleEventHandler.java	Fri Jun 05 15:21:15 2015 +0200
+++ b/src/org/openbravo/event/RoleEventHandler.java	Thu Jun 25 18:56:49 2015 +0200
@@ -33,7 +33,6 @@
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.client.kernel.event.EntityNewEvent;
 import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
-import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.ad.access.Role;
@@ -43,6 +42,9 @@
 import org.slf4j.LoggerFactory;
 
 public class RoleEventHandler extends EntityPersistenceEventObserver {
+  private static final String InitialOrgSetup_CLASSNAME = "org.openbravo.erpCommon.businessUtility.InitialOrgSetup";
+  private static final String InitialClientSetup_CLASSNAME = "org.openbravo.erpCommon.businessUtility.InitialClientSetup";
+
   private static Entity[] entities = { ModelProvider.getInstance().getEntity(Role.ENTITY_NAME) };
 
   protected Logger logger = LoggerFactory.getLogger(RoleEventHandler.class);
@@ -62,9 +64,17 @@
     final Property roleProperty = roleEntity.getProperty(Role.PROPERTY_ADROLEORGANIZATIONLIST);
     final Role role = (Role) event.getTargetInstance();
 
+    populateOrgAccess(event, role, roleProperty);
+  }
+
+  /**
+   * Creates the necessary Org Access records only when the role is set Manual=N and when we don't
+   * come from the Initial Client/Organization setup
+   */
+  private void populateOrgAccess(EntityNewEvent event, Role role, Property roleProperty) {
     // Create org access for new automatic role
     try {
-      if (role.isManual().booleanValue() == false) {
+      if (!role.isManual() && !isComingFromInitialClientOrganizationSetup()) {
         List<RoleOrganization> roleOrganizationList = getRoleOrganizationList(role);
         @SuppressWarnings("unchecked")
         final List<Object> roleOrganizations = (List<Object>) event.getCurrentState(roleProperty);
@@ -78,55 +88,49 @@
 
   // Get org access list
   private List<RoleOrganization> getRoleOrganizationList(Role role) throws Exception {
-
     List<RoleOrganization> roleOrganizationList = new ArrayList<RoleOrganization>();
 
-    // System level
-    if (StringUtils.equals(role.getUserLevel(), "S")) {
+    // Client or System level: Only * [isOrgAdmin=N]
+    if (StringUtils.equals(role.getUserLevel(), " C")
+        || StringUtils.equals(role.getUserLevel(), "S")) {
       roleOrganizationList.add(getRoleOrganization(role,
           OBDal.getInstance().get(Organization.class, "0"), false));
+      logger.debug("Added organization * to role " + role.getName());
     }
 
-    // Client or Client/Organization level
-    else if (StringUtils.equals(role.getUserLevel(), " C")
-        || StringUtils.equals(role.getUserLevel(), " CO")) {
+    // Client/Organization level: * [isOrgAdmin=N], other Orgs (but *) [isOrgAdmin=Y]
+    else if (StringUtils.equals(role.getUserLevel(), " CO")) {
       roleOrganizationList.add(getRoleOrganization(role,
           OBDal.getInstance().get(Organization.class, "0"), false));
+      logger.debug("Added organization * to role " + role.getName());
+
       OBCriteria<Organization> criteria = OBDal.getInstance().createCriteria(Organization.class);
       criteria.add(Restrictions.eq(Organization.PROPERTY_CLIENT, role.getClient()));
       criteria.add(Restrictions.ne(Organization.PROPERTY_ID, "0"));
       ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY);
       try {
-        int i = 0;
         while (scroll.next()) {
           final Organization organization = (Organization) scroll.get()[0];
           roleOrganizationList.add(getRoleOrganization(role, organization, true));
-          i++;
-          if (i % 100 == 0) {
-            OBDal.getInstance().flush();
-            OBDal.getInstance().getSession().clear();
-          }
+          logger.debug("Added organization " + organization.getName() + " to role "
+              + role.getName());
         }
       } finally {
         scroll.close();
       }
     }
 
-    // Organization level
+    // Organization level: Orgs (but *) [isOrgAdmin=Y]
     else if (StringUtils.equals(role.getUserLevel(), "  O")) {
       OBCriteria<Organization> criteria = OBDal.getInstance().createCriteria(Organization.class);
       criteria.add(Restrictions.eq(Organization.PROPERTY_CLIENT, role.getClient()));
       ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY);
       try {
-        int i = 0;
         while (scroll.next()) {
           final Organization organization = (Organization) scroll.get()[0];
           roleOrganizationList.add(getRoleOrganization(role, organization, true));
-          i++;
-          if (i % 100 == 0) {
-            OBDal.getInstance().flush();
-            OBDal.getInstance().getSession().clear();
-          }
+          logger.debug("Added organization " + organization.getName() + " to role "
+              + role.getName());
         }
       } finally {
         scroll.close();
@@ -139,18 +143,31 @@
   // Get org access
   private RoleOrganization getRoleOrganization(Role role, Organization orgProvided,
       boolean isOrgAdmin) throws Exception {
-    OBContext.setAdminMode();
-    try {
-      final RoleOrganization newRoleOrganization = OBProvider.getInstance().get(
-          RoleOrganization.class);
-      newRoleOrganization.setClient(role.getClient());
-      newRoleOrganization.setOrganization(orgProvided);
-      newRoleOrganization.setRole(role);
-      newRoleOrganization.setOrgAdmin(isOrgAdmin);
-      return newRoleOrganization;
-    } finally {
-      OBContext.restorePreviousMode();
+    final RoleOrganization newRoleOrganization = OBProvider.getInstance().get(
+        RoleOrganization.class);
+    newRoleOrganization.setClient(role.getClient());
+    newRoleOrganization.setOrganization(orgProvided);
+    newRoleOrganization.setRole(role);
+    newRoleOrganization.setOrgAdmin(isOrgAdmin);
+    return newRoleOrganization;
+  }
+
+  /**
+   * Returns true if the Initial Client/Organization Setup is in the stack trace
+   */
+  private boolean isComingFromInitialClientOrganizationSetup() {
+    boolean comeFrom_ICS_IOS = false;
+    for (final StackTraceElement ste : Thread.currentThread().getStackTrace()) {
+      final String clazz = ste.getClassName();
+      if (StringUtils.equals(clazz, InitialOrgSetup_CLASSNAME)
+          || StringUtils.equals(clazz, InitialClientSetup_CLASSNAME)) {
+        comeFrom_ICS_IOS = true;
+        logger
+            .debug("Coming from Initial Client/Organization Setup. RoleEventHandler will not insert Org Access records");
+        break;
+      }
     }
+    return comeFrom_ICS_IOS;
   }
 
 }
\ No newline at end of file