details:   https://code.openbravo.com/erp/devel/pi/rev/f7c49ae6cfd1
changeset: 32553:f7c49ae6cfd1
user:      Asier Lostalé <asier.lostale <at> openbravo.com>
date:      Thu Aug 10 08:47:31 2017 +0200
summary:   related to issue 36359: fixed related test case

  Test for preference to allow/disable unpaged datasource request was 
incorrectly
  affected by WS user cache beacuse it was mixing WS and datasource request 
sessions.

  Being PreferenceCache session scoped, it is not necessary to create Preference
  through WS, it can be directly created in test as far as it is ensured DS 
request
  is performed in a new session.

details:   https://code.openbravo.com/erp/devel/pi/rev/ce623b3c1938
changeset: 32554:ce623b3c1938
user:      Asier Lostalé <asier.lostale <at> openbravo.com>
date:      Thu Aug 10 08:49:37 2017 +0200
summary:   fixed bug 36359: can get stale cached WS user context

  Don't invalidate cache on Preference modifications as they occur very often 
and,
  in general, they shouldn't affect WS sessions.

diffstat:

 src-test/src/org/openbravo/test/datasource/BaseDataSourceTestDal.java          
      |   16 +-
 
src-test/src/org/openbravo/test/datasource/TestAllowUnpagedDatasourcePreference.java
 |  198 ++-------
 src/org/openbravo/service/UserCtxCacheObserver.java                            
      |    5 +-
 3 files changed, 64 insertions(+), 155 deletions(-)

diffs (truncated from 325 to 300 lines):

diff -r 79642582d449 -r ce623b3c1938 
src-test/src/org/openbravo/test/datasource/BaseDataSourceTestDal.java
--- a/src-test/src/org/openbravo/test/datasource/BaseDataSourceTestDal.java     
Wed Aug 09 15:27:55 2017 +0200
+++ b/src-test/src/org/openbravo/test/datasource/BaseDataSourceTestDal.java     
Thu Aug 10 08:49:37 2017 +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) 2014 Openbravo SLU 
+ * All portions are Copyright (C) 2014-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -19,8 +19,11 @@
 
 package org.openbravo.test.datasource;
 
+import java.util.HashMap;
 import java.util.Map;
 
+import javax.servlet.http.HttpServletResponse;
+
 import org.openbravo.test.base.OBBaseTest;
 
 /**
@@ -40,6 +43,8 @@
   private static boolean authenticated = false;
   private static String cookie;
 
+  protected static final String POST_METHOD = "POST";
+
   /**
    * Performs a request to Openbravo returning its response and asserting the 
response code matches
    * expectedResponse.
@@ -116,4 +121,13 @@
 
     DatasourceTestUtil.changeProfile(getOpenbravoURL(), cookie, roleId, 
langId, orgId, warehouseId);
   }
+
+  /** Logs out current session */
+  protected void logout() throws Exception {
+    Map<String, String> params = new HashMap<>();
+    params.put("_action", 
"org.openbravo.client.application.LogOutActionHandler");
+    doRequest("/org.openbravo.client.kernel", params, 
HttpServletResponse.SC_OK, POST_METHOD);
+    authenticated = false;
+    cookie = null;
+  }
 }
diff -r 79642582d449 -r ce623b3c1938 
src-test/src/org/openbravo/test/datasource/TestAllowUnpagedDatasourcePreference.java
--- 
a/src-test/src/org/openbravo/test/datasource/TestAllowUnpagedDatasourcePreference.java
      Wed Aug 09 15:27:55 2017 +0200
+++ 
b/src-test/src/org/openbravo/test/datasource/TestAllowUnpagedDatasourcePreference.java
      Thu Aug 10 08:49:37 2017 +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) 2015-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2015-2017 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -22,35 +22,29 @@
 import static org.hamcrest.Matchers.equalTo;
 import static org.junit.Assert.assertThat;
 
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.net.Authenticator;
-import java.net.HttpURLConnection;
-import java.net.PasswordAuthentication;
-import java.net.URL;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.Map;
 
-import org.apache.commons.lang.StringUtils;
+import javax.servlet.http.HttpServletResponse;
+
 import org.apache.log4j.Logger;
+import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
 import org.junit.runners.Parameterized.Parameters;
-import org.openbravo.base.exception.OBException;
+import org.openbravo.base.provider.OBProvider;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.businessUtility.Preferences;
 import org.openbravo.erpCommon.utility.OBMessageUtils;
-import org.openbravo.model.ad.access.Role;
-import org.openbravo.model.ad.access.User;
+import org.openbravo.model.ad.domain.Preference;
 import org.openbravo.model.ad.system.Client;
 import org.openbravo.model.common.enterprise.Organization;
+import org.openbravo.service.json.JsonConstants;
 
 /**
  * Test case for 'Allow Unpaged Datasource In Manual Request' preference
@@ -86,164 +80,62 @@
 
   @Test
   public void testDatasourceRequest() throws Exception {
-    OBContext.setAdminMode();
-    User user = null;
-    String defaultClient = null;
-    String defaultOrg = null;
-    String defaultRole = null;
+    OBContext.setAdminMode(false);
     String preferenceId = "";
     try {
-      user = OBDal.getInstance().get(User.class, "100"); // Openbravo user;
-      defaultClient = user.getDefaultClient() != null ? 
user.getDefaultClient().getId() : null;
-      defaultOrg = user.getDefaultOrganization() != null ? 
user.getDefaultOrganization().getId()
-          : null;
-      defaultRole = user.getDefaultRole().getId();
+      preferenceId = createPreference(preferenceValue);
 
-      // Execute ws with system administrator credentials
-      user.setDefaultClient(OBDal.getInstance().get(Client.class, "0"));
-      user.setDefaultOrganization(OBDal.getInstance().get(Organization.class, 
"0"));
-      user.setDefaultRole(OBDal.getInstance().get(Role.class, "0"));
-      OBDal.getInstance().commitAndClose();
+      // Preference is cached at session scope, ensure a new session is created
+      logout();
 
       // ensures a role with an access to a UOM entity
       changeProfile(ROLE_SYSTEM, LANGUAGE_ID, ORGANIZATION, WAREHOUSE_ID);
 
-      // Create the 'Allow Unpaged Datasource In Manual Request' preference
-      preferenceId = createPreference(preferenceValue);
-      // Create a manual request to the datasource
-      String response = "";
-      Map<String, String> params = new HashMap<String, String>();
-      params = new HashMap<String, String>();
+      Map<String, String> params = new HashMap<>();
       params.put("_operationType", "fetch");
-      try {
-        response = doRequest("/org.openbravo.service.datasource/UOM", params, 
200, "POST");
-      } catch (Exception ignore) {
-        // Expected exception when preference value is "N"
-        logger.debug("Exception in datasource request:" + ignore.getMessage(), 
ignore);
+      String response = doRequest("/org.openbravo.service.datasource/UOM", 
params,
+          HttpServletResponse.SC_OK, POST_METHOD);
+
+      switch (preferenceValue) {
+      case Preferences.NO:
+        String errorMsg = 
OBMessageUtils.messageBD("OBJSON_NoPagedFetchManual");
+        assertThat("Datasource returned error message " + response,
+            getResponseErrorMessage(response), equalTo(errorMsg));
+        break;
+      case Preferences.YES:
+        int responseStatus = new 
JSONObject(response).getJSONObject("response").getInt("status");
+        assertThat("Response status " + response, responseStatus,
+            equalTo(JsonConstants.RPCREQUEST_STATUS_SUCCESS));
       }
-      // Compare the error message in response, if any
-      String errorMsg = "";
-      if (Preferences.NO.equals(preferenceValue)) {
-        errorMsg = OBMessageUtils.messageBD("OBJSON_NoPagedFetchManual");
-      }
-      assertThat("Datasource returned error message", 
getResponseErrorMessage(response),
-          equalTo(errorMsg));
+
     } finally {
-      if (!StringUtils.isEmpty(preferenceId)) {
-        deletePreference(preferenceId);
-      }
-      // restore user defaults
-      Client client = defaultClient != null ? 
OBDal.getInstance().get(Client.class, defaultClient)
-          : null;
-      Organization org = defaultOrg != null ? 
OBDal.getInstance().get(Organization.class,
-          defaultOrg) : null;
-      user = OBDal.getInstance().get(User.class, "100");
-      user.setDefaultClient(client);
-      user.setDefaultOrganization(org);
-      user.setDefaultRole(OBDal.getInstance().get(Role.class, defaultRole));
-      OBDal.getInstance().commitAndClose();
+      OBDal.getInstance().remove(OBDal.getInstance().get(Preference.class, 
preferenceId));
       OBContext.restorePreviousMode();
     }
   }
 
   private String createPreference(String value) {
-    try {
-      String content = "{" //
-          + "  \"data\": {" //
-          + "    \"entityName\": \"ADPreference\"," //
-          + "    \"property\": 
\"OBJSON_AllowUnpagedDatasourceManualRequest\"," //
-          + "    \"propertyList\": true," //
-          + "    \"visibleAtClient\": \"0\"," //
-          + "    \"visibleAtOrganization\": \"0\"," //
-          + "    \"searchKey\": \"" + value + "\"" //
-          + "  }" //
-          + "}";
-      final HttpURLConnection hc = createConnection(
-          "/org.openbravo.service.json.jsonrest/ADPreference", "POST");
-      final OutputStream os = hc.getOutputStream();
-      os.write(content.getBytes("UTF-8"));
-      os.flush();
-      os.close();
-      hc.connect();
-      // Get ws response
-      StringBuilder sb = new StringBuilder();
-      final InputStream is = hc.getInputStream();
-      BufferedReader reader = new BufferedReader(new InputStreamReader(is, 
"UTF-8"));
-      String line;
-      while ((line = reader.readLine()) != null) {
-        sb.append(line).append("\n");
-      }
-      return getIdFromResponse(sb.toString());
+    Preference pref = OBProvider.getInstance().get(Preference.class);
+    pref.setProperty("OBJSON_AllowUnpagedDatasourceManualRequest");
+    pref.setPropertyList(true);
+    pref.setSearchKey(value);
+    pref.setVisibleAtClient(OBDal.getInstance().getProxy(Client.class, "0"));
+    
pref.setVisibleAtOrganization(OBDal.getInstance().getProxy(Organization.class, 
"0"));
+    pref.setClient(OBDal.getInstance().getProxy(Client.class, "0"));
+    pref.setOrganization(OBDal.getInstance().getProxy(Organization.class, 
"0"));
+    OBDal.getInstance().save(pref);
 
-    } catch (Exception e) {
-      throw new OBException("Exception on create preference: ", e);
-    }
+    // commit to make the new preference available from datasource request in 
a different trx
+    OBDal.getInstance().commitAndClose();
+    return pref.getId();
   }
 
-  private String deletePreference(String preferenceId) {
-    try {
-      // String content = "";
-      final HttpURLConnection hc = createConnection(
-          "/org.openbravo.service.json.jsonrest/ADPreference/" + preferenceId, 
"DELETE");
-      hc.connect();
-      // Get ws response
-      StringBuilder sb = new StringBuilder();
-      final InputStream is = hc.getInputStream();
-      BufferedReader reader = new BufferedReader(new InputStreamReader(is, 
"UTF-8"));
-      String line;
-      while ((line = reader.readLine()) != null) {
-        sb.append(line).append("\n");
-      }
-      return sb.toString();
-
-    } catch (Exception e) {
-      throw new OBException("Exception on delete preference: ", e);
+  private String getResponseErrorMessage(String response) throws JSONException 
{
+    JSONObject jsonResponse = new 
JSONObject(response).getJSONObject("response");
+    if (jsonResponse.has("error")) {
+      JSONObject error = jsonResponse.getJSONObject("error");
+      return error.getString("message");
     }
-  }
-
-  private HttpURLConnection createConnection(String wsPart, String method) 
throws Exception {
-    Authenticator.setDefault(new Authenticator() {
-      @Override
-      protected PasswordAuthentication getPasswordAuthentication() {
-        return new PasswordAuthentication(LOGIN, PWD.toCharArray());
-      }
-    });
-    final URL url = new URL(getOpenbravoURL() + wsPart);
-    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();
-    hc.setRequestMethod(method);
-    hc.setAllowUserInteraction(false);
-    hc.setDefaultUseCaches(false);
-    hc.setDoOutput(true);
-    hc.setDoInput(true);
-    hc.setInstanceFollowRedirects(true);
-    hc.setUseCaches(false);
-    hc.setRequestProperty("Content-Type", "text/xml");
-    return hc;
-  }
-
-  private String getResponseErrorMessage(String response) {
-    try {
-      JSONObject jsonResponse = new 
JSONObject(response).getJSONObject("response");
-      if (jsonResponse.has("error")) {
-        JSONObject error = jsonResponse.getJSONObject("error");
-        return error.getString("message");
-      }
-      return "";
-    } catch (Exception ex) {
-      return "";
-    }
-  }
-
-  private String getIdFromResponse(String response) {
-    try {
-      JSONObject jsonResponse = new 
JSONObject(response).getJSONObject("response");
-      if (jsonResponse.has("data")) {
-        JSONObject data = jsonResponse.getJSONArray("data").getJSONObject(0);
-        return data.getString("id");
-      }
-      return "";
-    } catch (Exception ex) {
-      return "";

------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot
_______________________________________________
Openbravo-commits mailing list
Openbravo-commits@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/openbravo-commits

Reply via email to