Rearranges pz2/sp client logic to isolate error messaging
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / sp / ServiceProxyClient.java
index 92e46a7..12cc734 100644 (file)
@@ -3,7 +3,6 @@ package com.indexdata.mkjsf.pazpar2.sp;
 import static com.indexdata.mkjsf.utils.Utils.nl;\r
 \r
 import java.io.BufferedReader;\r
-import java.io.ByteArrayOutputStream;\r
 import java.io.File;\r
 import java.io.FileReader;\r
 import java.io.IOException;\r
@@ -13,6 +12,7 @@ import java.util.List;
 import java.util.Map;\r
 import java.util.StringTokenizer;\r
 \r
+import org.apache.http.Header;\r
 import org.apache.http.HttpEntity;\r
 import org.apache.http.HttpResponse;\r
 import org.apache.http.StatusLine;\r
@@ -32,7 +32,6 @@ import org.apache.http.impl.conn.PoolingClientConnectionManager;
 import org.apache.http.util.EntityUtils;\r
 import org.apache.log4j.Logger;\r
 \r
-import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException;\r
 import com.indexdata.mkjsf.config.Configuration;\r
 import com.indexdata.mkjsf.config.ConfigurationReader;\r
 import com.indexdata.mkjsf.errors.ConfigurationException;\r
@@ -41,6 +40,7 @@ import com.indexdata.mkjsf.pazpar2.SearchClient;
 import com.indexdata.mkjsf.pazpar2.commands.CommandParameter;\r
 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;\r
 import com.indexdata.mkjsf.pazpar2.commands.sp.AuthCommand;\r
+import com.indexdata.mkjsf.pazpar2.data.CommandError;\r
 import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser;\r
 import com.indexdata.mkjsf.utils.Utils;\r
 \r
@@ -83,6 +83,7 @@ public class ServiceProxyClient implements SearchClient {
       ipAuth = new AuthCommand(null);\r
       ipAuth.setParameterInState(new CommandParameter("action","=","ipauth"));\r
     } catch (ConfigurationException c) {\r
+      // TODO: \r
       c.printStackTrace();\r
     }    \r
   }\r
@@ -99,77 +100,46 @@ public class ServiceProxyClient implements SearchClient {
   }\r
   \r
   public boolean authenticate (ServiceProxyUser user) {\r
-    try {      \r
-      logger.info("Authenticating [" + user.getProperty("name") + "]");            \r
-      Pazpar2Command auth = new AuthCommand(null);\r
-      auth.setParametersInState(new CommandParameter("action","=","login"), \r
-                                new CommandParameter("username","=",user.getProperty("name")), \r
-                                new CommandParameter("password","=",user.getProperty("password")));                                \r
-      byte[] response = send(auth);\r
-      String responseStr = new String(response,"UTF-8");\r
-      logger.info(responseStr);      \r
-      if (responseStr.contains("FAIL")) {\r
-        user.credentialsAuthenticationSucceeded(false);\r
-        return false;\r
-      } else {\r
-        user.credentialsAuthenticationSucceeded(true);\r
-        return true;\r
-      }      \r
-    } catch (ClientProtocolException e) {\r
-      // TODO Auto-generated catch block\r
-      e.printStackTrace();\r
-      return false;\r
-    } catch (IOException e) {\r
-      // TODO Auto-generated catch block\r
-      e.printStackTrace();\r
+    logger.info("Authenticating [" + user.getProperty("name") + "]");            \r
+    Pazpar2Command auth = new AuthCommand(null);\r
+    auth.setParametersInState(new CommandParameter("action","=","login"), \r
+                              new CommandParameter("username","=",user.getProperty("name")), \r
+                              new CommandParameter("password","=",user.getProperty("password")));                                \r
+    ServiceProxyCommandResponse commandResponse = send(auth);\r
+    String responseStr = commandResponse.getResponseString();\r
+    logger.info(responseStr);      \r
+    if (responseStr.contains("FAIL")) {\r
+      user.credentialsAuthenticationSucceeded(false);\r
       return false;\r
-    }        \r
+    } else {\r
+      user.credentialsAuthenticationSucceeded(true);\r
+      return true;\r
+    }      \r
   }\r
   \r
   public boolean checkAuthentication (ServiceProxyUser user) {    \r
-    try {\r
-      byte[] response = send(checkAuth);\r
-      logger.info(new String(response,"UTF-8"));\r
-      String responseStr = new String(response,"UTF-8");    \r
-      if (responseStr.contains("FAIL")) {  \r
-        user.authenticationCheckFailed();\r
-        return false;\r
-      } else {                \r
-        return true;\r
-      }      \r
-    } catch (ClientProtocolException e) {\r
-      // TODO Auto-generated catch block\r
-      e.printStackTrace();\r
-      return false;\r
-    } catch (IOException e) {\r
-      // TODO Auto-generated catch block\r
-      e.printStackTrace();\r
+    ServiceProxyCommandResponse commandResponse = send(checkAuth);      \r
+    String responseStr = commandResponse.getResponseString();    \r
+    logger.info(responseStr);\r
+    if (responseStr.contains("FAIL")) {  \r
+      user.authenticationCheckFailed();\r
       return false;\r
-    }        \r
+    } else {                \r
+      return true;\r
+    }      \r
   }\r
   \r
   public boolean ipAuthenticate (ServiceProxyUser user) {\r
-    try {\r
-      byte[] response = send(ipAuth);\r
-      logger.info(new String(response,"UTF-8"));\r
-      String responseStr = new String(response,"UTF-8");    \r
-      if (responseStr.contains("FAIL")) {\r
-        user.ipAuthenticationSucceeded(false);        \r
-        return false;\r
-      } else {\r
-        user.ipAuthenticationSucceeded(true);\r
-        return true;\r
-      }      \r
-    } catch (ClientProtocolException e) {\r
-      // TODO Auto-generated catch block\r
-      e.printStackTrace();\r
-      return false;\r
-    } catch (IOException e) {\r
-      // TODO Auto-generated catch block\r
-      e.printStackTrace();\r
+    ServiceProxyCommandResponse commandResponse = send(ipAuth);      \r
+    String responseStr = commandResponse.getResponseString();\r
+    logger.info(responseStr);\r
+    if (responseStr.contains("FAIL")) {\r
+      user.ipAuthenticationSucceeded(false);        \r
       return false;\r
-    }        \r
-    \r
+    } else {\r
+      user.ipAuthenticationSucceeded(true);\r
+      return true;\r
+    }          \r
   }\r
   \r
   public boolean isAuthenticatingClient () {\r
@@ -191,24 +161,39 @@ public class ServiceProxyClient implements SearchClient {
    * @throws ClientProtocolException\r
    * @throws IOException\r
    */\r
-  private byte[] send(Pazpar2Command command) throws ClientProtocolException, IOException {\r
+  private ServiceProxyCommandResponse send(Pazpar2Command command) {\r
+    ServiceProxyCommandResponse commandResponse = null;\r
     String url = selectedServiceUrl + "?" + command.getEncodedQueryString(); \r
     logger.info("Sending request "+url);    \r
     HttpGet httpget = new HttpGet(url);     \r
-    byte[] response = client.execute(httpget, handler);    \r
-    return response;\r
+    byte[] response = null;\r
+    try {\r
+      response = client.execute(httpget, handler);\r
+      if (handler.getStatusCode()==200) {\r
+        commandResponse = new ServiceProxyCommandResponse(handler.getStatusCode(),response,handler.getContentType());\r
+      } else {\r
+        logger.error("Service Proxy status code: " + handler.getStatusCode());\r
+        commandResponse = new ServiceProxyCommandResponse(handler.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Service Proxy error occurred", new String(response,"UTF-8")),"text/xml");                       \r
+      }       \r
+    } catch (Exception e) {\r
+      e.printStackTrace();\r
+      commandResponse = new ServiceProxyCommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), e.getClass().getSimpleName(), (e.getMessage()!= null ? e.getMessage() : "") + (e.getCause()!=null ? e.getCause().getMessage() : "")),"text/xml");\r
+    }\r
+    return commandResponse; \r
   }\r
   \r
   public class ProxyPz2ResponseHandler implements ResponseHandler<byte[]> {\r
     private StatusLine statusLine = null;\r
+    private Header contentType = null;\r
     public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {\r
       byte[] resp = null;\r
       HttpEntity entity = response.getEntity();      \r
       statusLine = response.getStatusLine();\r
       if (entity != null) {        \r
         resp = EntityUtils.toByteArray(entity);        \r
-      } \r
-      EntityUtils.consume(entity);\r
+        contentType = response.getEntity().getContentType();        \r
+      }       \r
+      EntityUtils.consume(entity);      \r
       return resp;\r
     }\r
     public int getStatusCode() {\r
@@ -217,6 +202,9 @@ public class ServiceProxyClient implements SearchClient {
     public String getReasonPhrase() {\r
       return statusLine.getReasonPhrase();\r
     }\r
+    public String getContentType () {\r
+      return (contentType != null ? contentType.getValue() : "Content-Type not known"); \r
+    }\r
   }\r
 \r
   public int getStatusCode () {\r
@@ -233,11 +221,8 @@ public class ServiceProxyClient implements SearchClient {
   }\r
 \r
   @Override\r
-  public CommandResponse executeCommand(Pazpar2Command command,\r
-      ByteArrayOutputStream baos) throws Pazpar2ErrorException, IOException {\r
-    byte[] response = send(command);\r
-    baos.write(response);\r
-    return new ServiceProxyClientCommandResponse(getStatusCode(), new String(response,"UTF-8"));    \r
+  public CommandResponse executeCommand(Pazpar2Command command) {\r
+    return send(command);\r
   }\r
 \r
   public ServiceProxyClient cloneMe() {\r