details:   https://code.openbravo.com/erp/devel/pi/rev/a18a9f23fc35
changeset: 13755:a18a9f23fc35
user:      Antonio Moreno <antonio.moreno <at> openbravo.com>
date:      Mon Sep 12 12:09:03 2011 +0200
summary:   Fixed issue 17641. Reimplemented backend side of the Delete Client 
process.

diffstat:

 src-db/database/lib/dbsourcemanager.jar                     |    0 
 src-test/org/openbravo/test/xml/ClientExportImportTest.java |   30 +
 src/org/openbravo/erpCommon/ad_process/DeleteClient.java    |   15 +-
 src/org/openbravo/service/system/SystemService.java         |  203 ++++++++++++
 4 files changed, 238 insertions(+), 10 deletions(-)

diffs (truncated from 350 to 300 lines):

diff -r 956e2fb068d8 -r a18a9f23fc35 src-db/database/lib/dbsourcemanager.jar
Binary file src-db/database/lib/dbsourcemanager.jar has changed
diff -r 956e2fb068d8 -r a18a9f23fc35 
src-test/org/openbravo/test/xml/ClientExportImportTest.java
--- a/src-test/org/openbravo/test/xml/ClientExportImportTest.java       Mon Sep 
12 08:52:38 2011 +0200
+++ b/src-test/org/openbravo/test/xml/ClientExportImportTest.java       Mon Sep 
12 12:09:03 2011 +0200
@@ -28,6 +28,10 @@
 import java.util.Map;
 import java.util.Set;
 
+import org.apache.ddlutils.Platform;
+import org.apache.ddlutils.model.Database;
+import org.apache.ddlutils.model.Table;
+import org.apache.ddlutils.platform.ExcludeFilter;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
@@ -39,6 +43,7 @@
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.dal.service.OBQuery;
+import org.openbravo.ddlutils.util.DBSMOBUtil;
 import org.openbravo.model.ad.system.Client;
 import org.openbravo.model.ad.utility.TreeNode;
 import org.openbravo.model.common.enterprise.Organization;
@@ -49,6 +54,7 @@
 import org.openbravo.service.db.DataExportService;
 import org.openbravo.service.db.DataImportService;
 import org.openbravo.service.db.ImportResult;
+import org.openbravo.service.system.SystemService;
 
 /**
  * Tests export and import of client dataset.
@@ -206,6 +212,30 @@
     // SystemService.getInstance().removeAllClientData(newClientId);
   }
 
+  /**
+   * Test which copies a client, then deletes it, and then tests that the 
foreign keys are still
+   * activated
+   */
+  public void testDeleteClient() {
+    Platform platform = SystemService.getInstance().getPlatform();
+    ExcludeFilter excludeFilter = DBSMOBUtil.getInstance().getExcludeFilter(
+        new File(OBPropertiesProvider.getInstance().getOpenbravoProperties()
+            .getProperty("source.path")));
+    Database dbBefore = platform.loadModelFromDatabase(excludeFilter);
+    String newClientId = exportImport(QA_TEST_CLIENT_ID);
+    Client client = OBDal.getInstance().get(Client.class, newClientId);
+
+    SystemService.getInstance().deleteClient(client);
+    Database dbAfter = platform.loadModelFromDatabase(excludeFilter);
+    for (int i = 0; i < dbBefore.getTableCount(); i++) {
+      Table table1 = dbBefore.getTable(i);
+      Table table2 = dbAfter.getTable(i);
+      for (int j = 0; j < table1.getForeignKeyCount(); j++) {
+        assertTrue(table1.getForeignKey(j).equals(table2.getForeignKey(j)));
+      }
+    }
+  }
+
   // tests mantis issue 8509 related to import of ad tree node as
   // part of client import:
   // 8509: References in the database without using foreign keys can go wrong 
in import
diff -r 956e2fb068d8 -r a18a9f23fc35 
src/org/openbravo/erpCommon/ad_process/DeleteClient.java
--- a/src/org/openbravo/erpCommon/ad_process/DeleteClient.java  Mon Sep 12 
08:52:38 2011 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/DeleteClient.java  Mon Sep 12 
12:09:03 2011 +0200
@@ -28,15 +28,17 @@
 
 import org.openbravo.base.secureApp.HttpSecureAppServlet;
 import org.openbravo.base.secureApp.VariablesSecureApp;
+import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.ad_actionButton.ActionButtonDefaultData;
 import org.openbravo.erpCommon.businessUtility.WindowTabs;
-import org.openbravo.erpCommon.reference.PInstanceProcessData;
 import org.openbravo.erpCommon.utility.LeftTabsBar;
 import org.openbravo.erpCommon.utility.NavigationBar;
 import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.erpCommon.utility.SequenceIdData;
 import org.openbravo.erpCommon.utility.ToolBar;
 import org.openbravo.erpCommon.utility.Utility;
+import org.openbravo.model.ad.system.Client;
+import org.openbravo.service.system.SystemService;
 import org.openbravo.xmlEngine.XmlDocument;
 
 public class DeleteClient extends HttpSecureAppServlet {
@@ -75,15 +77,8 @@
         myMessage.setMessage(Utility.parseTranslation(this, vars, 
vars.getLanguage(),
             "@DeleteClient_SelectClient@"));
       } else {
-        PInstanceProcessData.insertPInstance(this, pinstance, "800147", 
strClient, "N",
-            vars.getUser(), vars.getClient(), vars.getOrg());
-        PInstanceProcessData.insertPInstanceParam(this, pinstance, "10", 
"AD_Client_ID", strClient,
-            vars.getClient(), vars.getOrg(), vars.getUser());
-
-        DeleteClientData.adDeleteClient(this, pinstance);
-
-        PInstanceProcessData[] pinstanceData = 
PInstanceProcessData.select(this, pinstance);
-        myMessage = Utility.getProcessInstanceMessage(this, vars, 
pinstanceData);
+        Client client = OBDal.getInstance().get(Client.class, strClient);
+        SystemService.getInstance().deleteClient(client);
       }
     } catch (Exception e) {
       myMessage = Utility.translateError(this, vars, vars.getLanguage(), 
e.getMessage());
diff -r 956e2fb068d8 -r a18a9f23fc35 
src/org/openbravo/service/system/SystemService.java
--- a/src/org/openbravo/service/system/SystemService.java       Mon Sep 12 
08:52:38 2011 +0200
+++ b/src/org/openbravo/service/system/SystemService.java       Mon Sep 12 
12:09:03 2011 +0200
@@ -19,10 +19,22 @@
 
 package org.openbravo.service.system;
 
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
+import java.util.Properties;
+import java.util.Vector;
 
+import org.apache.commons.dbcp.BasicDataSource;
+import org.apache.ddlutils.Platform;
+import org.apache.ddlutils.PlatformFactory;
 import org.apache.ddlutils.model.Database;
+import org.apache.ddlutils.platform.ExcludeFilter;
 import org.apache.log4j.Logger;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.base.model.Entity;
@@ -30,17 +42,23 @@
 import org.openbravo.base.model.Property;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.provider.OBSingleton;
+import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.base.structure.BaseOBObject;
+import org.openbravo.dal.core.DalUtil;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.core.SessionHandler;
 import org.openbravo.dal.core.TriggerHandler;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
+import org.openbravo.ddlutils.task.DatabaseUtils;
+import org.openbravo.ddlutils.util.DBSMOBUtil;
 import org.openbravo.model.ad.module.Module;
 import org.openbravo.model.ad.system.Client;
 import org.openbravo.model.ad.system.ClientInformation;
 import org.openbravo.model.common.enterprise.Organization;
+import org.openbravo.scheduling.OBScheduler;
 import 
org.openbravo.service.system.SystemValidationResult.SystemValidationType;
+import org.quartz.SchedulerException;
 
 /**
  * Provides utility like services.
@@ -49,6 +67,7 @@
  */
 public class SystemService implements OBSingleton {
   private static SystemService instance;
+  protected Logger log4j = Logger.getLogger(this.getClass());
 
   public static synchronized SystemService getInstance() {
     if (instance == null) {
@@ -270,4 +289,188 @@
       }
     }
   }
+
+  /**
+   * This process deletes a client from the database. During its execution, 
the Scheduler is
+   * stopped, and all sessions active for other users are cancelled
+   * 
+   * @param client
+   */
+  public void deleteClient(Client client) {
+    try {
+      long t1 = System.currentTimeMillis();
+      Platform platform = getPlatform();
+      Connection con = OBDal.getInstance().getConnection();
+      killConnectionsAndSafeMode(con);
+      try {
+        if (OBScheduler.getInstance() != null && 
OBScheduler.getInstance().getScheduler() != null
+            && OBScheduler.getInstance().getScheduler().isStarted())
+          OBScheduler.getInstance().getScheduler().standby();
+      } catch (Exception e) {
+        log4j.warn("Could not shutdown scheduler", e);
+        // We will not log an exception if the scheduler complains. The user 
shouldn't notice this
+      }
+      OBDal.getInstance().getConnection().commit();
+      disableConstraints(platform);
+      OBContext.setAdminMode(false);
+      OBDal.getInstance().flush();
+      OBDal.getInstance().getConnection().commit();
+      String clientId = (String) DalUtil.getId(client);
+
+      List<String> sqlCommands = new ArrayList<String>();
+
+      List<Entity> entities = ModelProvider.getInstance().getModel();
+      for (Entity entity : entities) {
+        if ((entity.isClientEnabled() || entity.getName().equals("ADClient")) 
&& !entity.isView()) {
+          try {
+            final String sql;
+            sql = "delete from " + entity.getTableName() + " where 
ad_client_id=?";
+            sqlCommands.add(sql);
+          } catch (Exception e) {
+            e.printStackTrace();
+          }
+        }
+      }
+      for (String command : sqlCommands) {
+        PreparedStatement ps = con.prepareStatement(command);
+        ps.setString(1, clientId);
+        ps.executeUpdate();
+      }
+      PreparedStatement stpref = con
+          .prepareStatement("DELETE FROM ad_preference p where 
visibleat_client_id=?");
+      stpref.setString(1, clientId);
+      stpref.executeUpdate();
+      PreparedStatement stpers = con
+          .prepareStatement("DELETE FROM obuiapp_uipersonalization p where 
visibleat_client_id=?");
+      stpers.setString(1, clientId);
+      stpers.executeUpdate();
+      con.commit();
+      OBDal.getInstance().commitAndClose();
+      enableConstraints(platform);
+      Connection con2 = platform.borrowConnection();
+      try {
+        resetSafeMode(con2);
+      } finally {
+        platform.returnConnection(con2);
+      }
+      log4j.info("Delete client took " + (System.currentTimeMillis() - t1) + " 
miliseconds");
+    } catch (Exception e) {
+      log4j.error("exception when deleting the client: ", e);
+    } finally {
+      OBContext.restorePreviousMode();
+      // We restart the scheduler
+      try {
+        if (OBScheduler.getInstance() != null && 
OBScheduler.getInstance().getScheduler() != null) {
+          OBScheduler.getInstance().getScheduler().start();
+        }
+      } catch (SchedulerException e) {
+        log4j.error("There was an error while restarting the scheduler", e);
+      }
+    }
+  }
+
+  private void resetSafeMode(Connection con) {
+
+    try {
+      PreparedStatement ps2 = con
+          .prepareStatement("UPDATE AD_SYSTEM_INFO SET SYSTEM_STATUS='RB70'");
+      ps2.executeUpdate();
+    } catch (Exception e) {
+      log4j.error("Couldn't reset the safe mode", e);
+    }
+  }
+
+  private void killConnectionsAndSafeMode(Connection con) {
+    try {
+      PreparedStatement updateSession = con
+          .prepareStatement("UPDATE AD_SESSION SET SESSION_ACTIVE='N' WHERE 
CREATEDBY<>?");
+      updateSession.setString(1, OBContext.getOBContext().getUser().getId());
+      updateSession.executeUpdate();
+      PreparedStatement ps2 = con
+          .prepareStatement("UPDATE AD_SYSTEM_INFO SET SYSTEM_STATUS='RB80'");
+      ps2.executeUpdate();
+    } catch (Exception e) {
+      log4j.error("Couldn't destroy concurrent sessions", e);
+    }
+  }
+
+  /**
+   * Returns a dbsourcemanager Platform object
+   * 
+   * @return
+   */
+  public Platform getPlatform() {
+    Properties obProp = 
OBPropertiesProvider.getInstance().getOpenbravoProperties();
+    // We disable check constraints before inserting reference data
+    String driver = obProp.getProperty("bbdd.driver");
+    String url = obProp.getProperty("bbdd.rdbms").equals("POSTGRE") ? obProp
+        .getProperty("bbdd.url") + "/" + obProp.getProperty("bbdd.sid") : 
obProp
+        .getProperty("bbdd.url");
+    String user = obProp.getProperty("bbdd.user");
+    String password = obProp.getProperty("bbdd.password");
+    BasicDataSource datasource = DBSMOBUtil.getDataSource(driver, url, user, 
password);
+    Platform platform = PlatformFactory.createNewPlatformInstance(datasource);
+    return platform;
+  }
+
+  private void disableConstraints(Platform platform) throws 
FileNotFoundException, IOException {
+    log4j.info("Disabling constraints...");
+    ExcludeFilter excludeFilter = DBSMOBUtil.getInstance().getExcludeFilter(
+        new File(OBPropertiesProvider.getInstance().getOpenbravoProperties()
+            .getProperty("source.path")));
+    Database xmlModel = platform.loadModelFromDatabase(excludeFilter);
+    Connection con = null;
+    try {
+      con = platform.borrowConnection();
+      log4j.info("   Disabling foreign keys");
+      platform.disableAllFK(con, xmlModel, false);

------------------------------------------------------------------------------
Doing More with Less: The Next Generation Virtual Desktop 
What are the key obstacles that have prevented many mid-market businesses
from deploying virtual desktops?   How do next-generation virtual desktops
provide companies an easier-to-deploy, easier-to-manage and more affordable
virtual desktop model.http://www.accelacomm.com/jaw/sfnl/114/51426474/
_______________________________________________
Openbravo-commits mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openbravo-commits

Reply via email to