Adds support for chosing pz2 or sp service run-time
authorNiels Erik G. Nielsen <nielserik@indexdata.com>
Wed, 8 May 2013 19:45:34 +0000 (15:45 -0400)
committerNiels Erik G. Nielsen <nielserik@indexdata.com>
Wed, 8 May 2013 19:45:34 +0000 (15:45 -0400)
The client type as well as the service url can thus be
changed dynamically.

Defining service type deploy time is now done by a config parameter -
rather than -- as it used to be -- by setting an injection instruction
in beans.xml.

src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java
src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Client.java
src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Interface.java
src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java [deleted file]
src/main/java/com/indexdata/mkjsf/pazpar2/SearchClient.java
src/main/java/com/indexdata/mkjsf/pazpar2/ServiceProxyExtensions.java [new file with mode: 0644]
src/main/java/com/indexdata/mkjsf/pazpar2/commands/sp/InitDocUpload.java
src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java [deleted file]
src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java [deleted file]

index f0cfa7d..490cee6 100644 (file)
@@ -2,17 +2,21 @@ package com.indexdata.mkjsf.pazpar2;
 \r
 import java.io.Serializable;\r
 import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.HashMap;\r
 import java.util.List;\r
+import java.util.Map;\r
 import java.util.StringTokenizer;\r
 \r
 import javax.annotation.PostConstruct;\r
 import javax.enterprise.context.SessionScoped;\r
-import javax.enterprise.inject.Alternative;\r
 import javax.inject.Inject;\r
 import javax.inject.Named;\r
 \r
 import org.apache.log4j.Logger;\r
 \r
+import com.indexdata.mkjsf.config.Configurable;\r
+import com.indexdata.mkjsf.config.Configuration;\r
 import com.indexdata.mkjsf.config.ConfigurationReader;\r
 import com.indexdata.mkjsf.controls.ResultsPager;\r
 import com.indexdata.mkjsf.errors.ConfigurationError;\r
@@ -25,27 +29,40 @@ import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData;
 import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseParser;\r
 import com.indexdata.mkjsf.pazpar2.data.Pazpar2Responses;\r
 import com.indexdata.mkjsf.pazpar2.data.RecordResponse;\r
+import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser;\r
 import com.indexdata.mkjsf.pazpar2.state.StateListener;\r
 import com.indexdata.mkjsf.pazpar2.state.StateManager;\r
 import com.indexdata.mkjsf.utils.Utils;\r
 \r
-@Named("pz2") @SessionScoped @Alternative\r
-public class Pz2Bean implements Pz2Interface, StateListener, Serializable {\r
+@Named("pz2") @SessionScoped\r
+public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Serializable {\r
+\r
+  private static final String MODULE_NAME = "service";\r
+  private static String SERVICE_TYPE_TBD = "TBD", SERVICE_TYPE_PZ2 = "PZ2", SERVICE_TYPE_SP = "SP";\r
+  private static final List<String> serviceTypes = \r
+                Arrays.asList(SERVICE_TYPE_PZ2,SERVICE_TYPE_SP,SERVICE_TYPE_TBD);\r
+  private String serviceType = SERVICE_TYPE_TBD;\r
+  private List<String> serviceProxyUrls = new ArrayList<String>();\r
+  public static final String SERVICE_PROXY_URL_LIST = "SERVICE_PROXY_URL_LIST";\r
+  private List<String> pazpar2Urls = new ArrayList<String>();\r
+  public static final String PAZPAR2_URL_LIST = "PAZPAR2_URL_LIST";\r
+\r
 \r
   private static final long serialVersionUID = 3440277287081557861L;\r
   private static Logger logger = Logger.getLogger(Pz2Bean.class);\r
-  private static Logger responseLogger = Logger.getLogger("com.indexdata.mkjsf.pazpar2.responses");\r
-  \r
-  protected SearchClient searchClient = null;\r
-  \r
+  private static Logger responseLogger = Logger.getLogger("com.indexdata.mkjsf.pazpar2.responses");   \r
+  protected Pz2Client pz2Client = null;\r
+  protected ServiceProxyClient spClient = null;\r
+  protected SearchClient searchClient = null;  \r
+    \r
   @Inject ConfigurationReader configurator;\r
   @Inject StateManager stateMgr;\r
   @Inject Pazpar2Commands pzreq;\r
   @Inject Pazpar2Responses pzresp;\r
   @Inject ErrorCentral errors;\r
+  @Inject ServiceProxyUser user;\r
   \r
   protected ResultsPager pager = null; \r
-\r
   \r
   protected ErrorHelper errorHelper = null;\r
               \r
@@ -55,19 +72,25 @@ public class Pz2Bean implements Pz2Interface, StateListener, Serializable {
   \r
   @PostConstruct\r
   public void postConstruct() {    \r
-    logger.debug("in start of Pz2Bean post-construct configurator is " + configurator);\r
+    logger.debug("Pz2Bean post-construct: Configurator is " + configurator);\r
     logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next.");\r
-    searchClient = new Pz2Client();\r
-    logger.info("Using [" + Utils.objectId(searchClient) + "] configured by [" \r
-                          + Utils.objectId(configurator) + "]" );    \r
-    configureClient(searchClient,configurator);    \r
+    pz2Client = new Pz2Client();\r
+    configureClient(pz2Client,configurator);\r
+    spClient = new ServiceProxyClient();\r
+    configureClient(spClient,configurator);\r
+    try {\r
+      this.configure(configurator);\r
+    } catch (ConfigurationException e) {\r
+      logger.error("There was a problem configuring the Pz2Bean (\"pz2\")");\r
+      e.printStackTrace();\r
+    }    \r
     stateMgr.addStateListener(this);    \r
   }  \r
   \r
-  public void configureClient(SearchClient searchClient, ConfigurationReader configReader) {\r
+  public void configureClient(SearchClient client, ConfigurationReader configReader) {\r
     logger.debug(Utils.objectId(this) + " will configure search client for the session");\r
     try {\r
-      searchClient.configure(configReader);            \r
+      client.configure(configReader);            \r
     } catch (ConfigurationException e) {\r
       logger.debug("Pz2Bean adding configuration error");\r
       errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage()));                \r
@@ -75,6 +98,12 @@ public class Pz2Bean implements Pz2Interface, StateListener, Serializable {
     logger.info(configReader.document());\r
     pzresp.reset();    \r
   }\r
+  \r
+  public void resetSearchAndResults () {\r
+    pzreq.getRecord().removeParametersInState();\r
+    pzreq.getSearch().removeParametersInState();\r
+    pzresp.reset();    \r
+  }\r
 \r
     \r
   public void doSearch(String query) {\r
@@ -264,9 +293,81 @@ public class Pz2Bean implements Pz2Interface, StateListener, Serializable {
     } \r
   }\r
   \r
+  public void setServiceProxyUrl(String url) {\r
+    searchClient = spClient;\r
+    setServiceUrl(url);\r
+  }\r
+  \r
+  public String getServiceProxyUrl () {\r
+    return spClient.getServiceUrl();\r
+  }\r
+  \r
+  public void setPazpar2Url(String url) {\r
+    searchClient = pz2Client;\r
+    setServiceUrl(url);\r
+  }\r
+  \r
+  public String getPazpar2Url() {\r
+    return pz2Client.getServiceUrl();\r
+  }\r
+\r
+  \r
+  @Override\r
+  public void setServiceUrl(String url) {\r
+    if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {\r
+      pzreq.getRecord().removeParametersInState();\r
+      pzreq.getSearch().removeParametersInState();\r
+      pzresp.reset();\r
+      user.clear();\r
+      searchClient.setServiceUrl(url);\r
+    }    \r
+  }\r
+  \r
+  public String getServiceUrl() {\r
+    return (searchClient!=null ? searchClient.getServiceUrl() : "");\r
+  }\r
+  \r
+  public boolean getServiceUrlIsDefined() {\r
+    return (searchClient != null && searchClient.hasServiceUrl());\r
+  }\r
+  \r
+  public List<String> getServiceProxyUrls() {\r
+    List<String> urls = new ArrayList<String>();\r
+    urls.add("");\r
+    urls.addAll(serviceProxyUrls);\r
+    return urls;\r
+  }\r
+  \r
+  public List<String> getPazpar2Urls () {\r
+    List<String> urls = new ArrayList<String>();\r
+    urls.add("");\r
+    urls.addAll(pazpar2Urls);\r
+    return urls;\r
+  }\r
+  \r
+  public String getServiceType () {\r
+    return serviceType;\r
+  }\r
+  \r
+  public boolean isPazpar2Service () {\r
+    return serviceType.equals(SERVICE_TYPE_PZ2);\r
+  }\r
+  \r
+  public boolean isServiceProxyService() {\r
+    return serviceType.equals(SERVICE_TYPE_SP);\r
+  }\r
+  \r
+  public boolean serviceIsToBeDecided () {\r
+    return serviceType.equals(SERVICE_TYPE_TBD);\r
+  }\r
+  \r
+  public ServiceProxyClient getSpClient () {\r
+    return spClient;\r
+  }  \r
+  \r
   @Override\r
   public boolean getAuthenticationRequired () {\r
-    return searchClient.isAuthenticatingClient();\r
+    return spClient.isAuthenticatingClient();\r
   }\r
 \r
   @Override\r
@@ -283,5 +384,76 @@ public class Pz2Bean implements Pz2Interface, StateListener, Serializable {
   public String getWatchActiveclientsRecord () {\r
     return ":pz2watch:activeclientsForm:activeclientsFieldRecord";\r
   }\r
+\r
+  @Override\r
+  public void configure(ConfigurationReader reader)\r
+      throws ConfigurationException {\r
+    Configuration config = reader.getConfiguration(this);\r
+    if (config == null) {\r
+      serviceType = SERVICE_TYPE_TBD;\r
+    } else {\r
+      String service = config.get("TYPE");\r
+      if (service == null || service.length()==0) {\r
+        serviceType = SERVICE_TYPE_TBD;\r
+      } else if (serviceTypes.contains(service.toUpperCase())) {        \r
+        setServiceType(service.toUpperCase());\r
+      } else {\r
+        logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);\r
+        serviceType = SERVICE_TYPE_TBD;\r
+      }\r
+      serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");\r
+      pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");\r
+    }\r
+    logger.info("Service Type is configured to " + serviceType);\r
+    \r
+  }\r
+\r
+  @Override\r
+  public Map<String, String> getDefaults() {\r
+    return new HashMap<String,String>();\r
+  }\r
+\r
+  @Override\r
+  public String getModuleName() {\r
+    return MODULE_NAME;\r
+  }\r
+\r
+  @Override\r
+  public List<String> documentConfiguration() {\r
+    return new ArrayList<String>();\r
+  }\r
+\r
+  @Override\r
+  public void setServiceTypePZ2() {\r
+    setServiceType(SERVICE_TYPE_PZ2);    \r
+  }\r
+\r
+  @Override\r
+  public void setServiceTypeSP() {\r
+    setServiceType(SERVICE_TYPE_SP);        \r
+  }\r
+\r
+  @Override\r
+  public void setServiceTypeTBD() {\r
+    setServiceType(SERVICE_TYPE_TBD);    \r
+  }\r
+  \r
+  private void setServiceType(String type) {\r
+    if (!serviceType.equals(type)  &&\r
+        !serviceType.equals(SERVICE_TYPE_TBD)) {\r
+      resetSearchAndResults();\r
+    }\r
+    serviceType = type;\r
+    if (serviceType.equals(SERVICE_TYPE_PZ2)) {\r
+      searchClient = pz2Client;\r
+      logger.info("Setting a Pazpar2 client to serve requests.");\r
+    } else if (serviceType.equals(SERVICE_TYPE_SP)) {\r
+      searchClient = spClient;\r
+      logger.info("Setting a Service Proxy client to serve requests.");\r
+    } else {\r
+      logger.info("Clearing search client. No client defined to serve requests at this point.");\r
+      searchClient = null;\r
+    }\r
+  }\r
   \r
 }\r
index a68e67f..2bfb52b 100644 (file)
@@ -35,9 +35,10 @@ public class Pz2Client implements SearchClient {
   private Pazpar2ClientConfiguration cfg = null;\r
   public static final String MODULENAME = "pz2client";\r
   public static Map<String,String> DEFAULTS = new HashMap<String,String>();\r
-  Configuration config = null;\r
+  Configuration config = null;  \r
   \r
   static {    \r
+    DEFAULTS.put("PAZPAR2_URL", "");\r
     DEFAULTS.put("PROXY_MODE","1");\r
     DEFAULTS.put("SERIALIZE_REQUESTS", "false");\r
     DEFAULTS.put("STREAMBUFF_SIZE", "4096");\r
@@ -50,7 +51,7 @@ public class Pz2Client implements SearchClient {
   public void configure(ConfigurationReader configReader) throws ConfigurationException {    \r
     logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
     try {\r
-      config = configReader.getConfiguration(this);\r
+      config = configReader.getConfiguration(this);      \r
       cfg = new Pazpar2ClientConfiguration(new ConfigurationGetter(config));\r
     } catch (ProxyErrorException pe) {\r
       logger.error("Could not configure Pazpar2 client: " + pe.getMessage());\r
@@ -89,7 +90,7 @@ public class Pz2Client implements SearchClient {
 \r
   @Override\r
   public CommandResponse executeCommand(Pazpar2Command command) {\r
-    Pz2CommandResponse commandResponse = null;\r
+    ClientCommandResponse commandResponse = null;\r
     ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
     ClientCommand clientCommand = new ClientCommand(command.getCommandName(), command.getEncodedQueryString());\r
     Pazpar2HttpResponse pz2HttpResponse = null;\r
@@ -97,25 +98,25 @@ public class Pz2Client implements SearchClient {
     try {\r
       pz2HttpResponse = client.executeCommand(clientCommand, baos);\r
       if (pz2HttpResponse.getStatusCode()==200) {\r
-        commandResponse = new Pz2CommandResponse(pz2HttpResponse,baos);\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse,baos);\r
       } else if (pz2HttpResponse.getStatusCode()==417) {\r
         logger.error("Pazpar2 status code 417: " + baos.toString("UTF-8"));\r
-        commandResponse = new Pz2CommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2: Expectation failed (417)", baos.toString("UTF-8")),"text/xml");                       \r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2: Expectation failed (417)", baos.toString("UTF-8")),"text/xml");                       \r
       } else {\r
         String resp = baos.toString("UTF-8");\r
         logger.error("Pazpar2 status code was " + pz2HttpResponse.getStatusCode() + ": " + resp);\r
-        commandResponse = new Pz2CommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2 error occurred", baos.toString("UTF-8")),"text/xml");\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2 error occurred", baos.toString("UTF-8")),"text/xml");\r
         throw new Pazpar2ErrorException(resp,pz2HttpResponse.getStatusCode(),resp,null);\r
       }       \r
     } catch (IOException e) {\r
       logger.error(e.getMessage());\r
       e.printStackTrace();\r
-      commandResponse = new Pz2CommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml");      \r
+      commandResponse = new ClientCommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml");      \r
     } catch (Pazpar2ErrorException e) {\r
       logger.error(e.getMessage());\r
       e.printStackTrace();\r
       logger.error("Creating error XML");\r
-      commandResponse = new Pz2CommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml");\r
+      commandResponse = new ClientCommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml");\r
     }\r
     long end = System.currentTimeMillis();      \r
     logger.debug("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );\r
@@ -175,4 +176,20 @@ public class Pz2Client implements SearchClient {
     return config;\r
   }\r
 \r
+  @Override\r
+  public String getServiceUrl() {\r
+    return cfg.PAZPAR2_URL;    \r
+  }\r
+\r
+  @Override\r
+  public boolean hasServiceUrl() {\r
+    return cfg.PAZPAR2_URL != null && cfg.PAZPAR2_URL.length()>0;\r
+  }\r
+  \r
+  @Override \r
+  public void setServiceUrl (String serviceUrl) {    \r
+    cfg.PAZPAR2_URL = serviceUrl;\r
+    \r
+  }\r
+\r
 }\r
index bf8aa40..7b0b863 100644 (file)
@@ -101,5 +101,14 @@ public interface Pz2Interface extends Serializable {
   public String getCheckHistory ();\r
   public String getWatchActiveclients ();\r
   public String getWatchActiveclientsRecord ();\r
-     \r
+\r
+  public void setServiceTypePZ2 ();\r
+  public void setServiceTypeSP ();\r
+  public void setServiceTypeTBD ();\r
+  public void setServiceUrl(String url);\r
+  public String getServiceUrl();\r
+  public String getServiceType();\r
+  public boolean isPazpar2Service ();  \r
+  public boolean isServiceProxyService();  \r
+  public boolean serviceIsToBeDecided ();\r
 }\r
diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java
deleted file mode 100644 (file)
index 7bc0145..0000000
+++ /dev/null
@@ -1,149 +0,0 @@
-package com.indexdata.mkjsf.pazpar2;\r
-\r
-import java.io.IOException;\r
-import java.io.UnsupportedEncodingException;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import javax.annotation.PostConstruct;\r
-import javax.enterprise.context.SessionScoped;\r
-import javax.enterprise.inject.Alternative;\r
-import javax.inject.Inject;\r
-import javax.inject.Named;\r
-\r
-import org.apache.log4j.Logger;\r
-\r
-import com.indexdata.mkjsf.config.ConfigurationReader;\r
-import com.indexdata.mkjsf.pazpar2.sp.ServiceProxyClient;\r
-import com.indexdata.mkjsf.pazpar2.sp.ServiceProxyCommandResponse;\r
-import com.indexdata.mkjsf.pazpar2.sp.ServiceProxyInterface;\r
-import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser;\r
-import com.indexdata.mkjsf.utils.Utils;\r
-\r
-@Named("pz2") @SessionScoped @Alternative\r
-public class Pz2ProxyBean extends Pz2Bean implements ServiceProxyInterface {\r
-    \r
-  private static final long serialVersionUID = 4221824985678758225L;\r
-  private static Logger logger = Logger.getLogger(Pz2ProxyBean.class);  \r
-  private String initDocFileName = "";\r
-  private String initDocResponse = "";\r
-    \r
-  @Inject ConfigurationReader configurator;\r
-  @Inject ServiceProxyUser user;    \r
-  \r
-  public Pz2ProxyBean() {\r
-  }\r
-  \r
-  @PostConstruct\r
-  public void postConstruct() {\r
-    if (searchClient == null) {\r
-      logger.debug(Utils.objectId(this) + " will instantiate a ServiceProxyClient next.");    \r
-      searchClient = new ServiceProxyClient();\r
-      logger.info("Using [" + Utils.objectId(searchClient) + "] configured by [" \r
-                            + Utils.objectId(configurator) + "]" );    \r
-      configureClient(searchClient,configurator);\r
-      stateMgr.addStateListener(this);      \r
-    } else {\r
-      logger.debug("Pz2ProxyBean:postConstruct: searchClient already instantiated " +\r
-                       "during construction of parent object Pz2Bean.");\r
-    }\r
-  }\r
-  \r
-  public void login(String un, String pw) {\r
-    if (user.isAuthenticated() && user.getName().equals(un) && ((ServiceProxyClient) searchClient).checkAuthentication(user)) {\r
-      logger.info("Repeat request from UI to authenticate user. Auth verified for given user name so skipping log-in.");\r
-    } else {\r
-      logger.info("doing un/pw login");\r
-      user.setName(un);\r
-      user.setPassword(pw);\r
-      login("dummy");\r
-    }\r
-  }\r
-\r
-  @Override\r
-  public String login(String navigateTo) {\r
-    logger.info("doing login");\r
-    ((ServiceProxyClient)searchClient).authenticate(user);    \r
-    pzreq.getRecord().removeParametersInState();\r
-    pzreq.getSearch().removeParametersInState();\r
-    pzresp.reset();\r
-    return navigateTo;\r
-  }\r
-  \r
-  public void ipAuthenticate (ServiceProxyUser user) {\r
-    if (!user.isIpAuthenticated()) {\r
-      if (user.isAuthenticated()) {\r
-        user.clear();\r
-      }\r
-      pzreq.getRecord().removeParametersInState();\r
-      pzreq.getSearch().removeParametersInState();\r
-      pzresp.reset();\r
-      ((ServiceProxyClient)searchClient).ipAuthenticate(user);\r
-    }\r
-  }\r
-\r
-  @Override\r
-  public void setServiceProxyUrl(String url) {\r
-    logger.info("Setting Service Proxy url: " + url);    \r
-    if (url!=null & !url.equals(((ServiceProxyClient)searchClient).getServiceProxyUrl())) {\r
-      pzreq.getRecord().removeParametersInState();\r
-      pzreq.getSearch().removeParametersInState();\r
-      pzresp.reset();\r
-      user.clear();\r
-      ((ServiceProxyClient)searchClient).setServiceProxyUrl(url);\r
-    }    \r
-  }\r
-  \r
-  public String getServiceProxyUrl() {\r
-    return ((ServiceProxyClient)searchClient).getServiceProxyUrl();\r
-  }\r
-  \r
-  public boolean getServiceProxyUrlIsDefined() {\r
-    return ((ServiceProxyClient)searchClient).getServiceProxyUrl().length()>0;\r
-  }\r
-  \r
-  public List<String> getServiceProxyUrls() {\r
-    List<String> urls = new ArrayList<String>();\r
-    urls.add("");\r
-    urls.addAll(((ServiceProxyClient)searchClient).getServiceProxyUrls());\r
-    return urls;\r
-  }\r
-    \r
-  public String getInitDocPath () {\r
-    return searchClient.getConfiguration().get("INIT_DOC_PATH");\r
-  }\r
-  \r
-  @Override\r
-  public void setInitFileName(String fileName) {\r
-    this.initDocFileName = fileName;\r
-    \r
-  }\r
-\r
-  @Override\r
-  public String getInitFileName() {\r
-    return initDocFileName;\r
-  }\r
-\r
-  @Override\r
-  public ServiceProxyCommandResponse postInit() throws UnsupportedEncodingException, IOException {    \r
-    String initDocPath = ((ServiceProxyClient)searchClient).getInitDocPaths().get(0);\r
-    logger.info("Paths: " + ((ServiceProxyClient)searchClient).getInitDocPaths());\r
-    logger.info("Path: " + initDocPath);\r
-    pzresp.reset();\r
-    ServiceProxyCommandResponse response = ((ServiceProxyClient)searchClient).postInitDoc(initDocPath + getInitFileName());    \r
-    return response;\r
-  }\r
-  \r
-  @Override\r
-  public ServiceProxyCommandResponse postInit(byte[] initDoc, boolean includeDebug) throws UnsupportedEncodingException, IOException {    \r
-    pzresp.reset();\r
-    ServiceProxyCommandResponse response = ((ServiceProxyClient)searchClient).postInitDoc(initDoc,includeDebug);    \r
-    return response;\r
-  }\r
-\r
-  @Override\r
-  public String getInitResponse() {\r
-    return initDocResponse;\r
-  }\r
-  \r
-}\r
index c7ec2c5..745a6b6 100644 (file)
@@ -20,4 +20,7 @@ public interface SearchClient extends Configurable, Serializable {
   \r
   public boolean isAuthenticatingClient();  \r
   public Configuration getConfiguration();\r
+  public String getServiceUrl();\r
+  public void setServiceUrl(String url);\r
+  public boolean hasServiceUrl();  \r
 }\r
diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/ServiceProxyExtensions.java b/src/main/java/com/indexdata/mkjsf/pazpar2/ServiceProxyExtensions.java
new file mode 100644 (file)
index 0000000..04343c3
--- /dev/null
@@ -0,0 +1,111 @@
+package com.indexdata.mkjsf.pazpar2;\r
+\r
+import java.io.IOException;\r
+import java.io.Serializable;\r
+import java.io.UnsupportedEncodingException;\r
+\r
+import javax.enterprise.context.SessionScoped;\r
+import javax.inject.Inject;\r
+import javax.inject.Named;\r
+\r
+import org.apache.log4j.Logger;\r
+\r
+import com.indexdata.mkjsf.config.ConfigurationReader;\r
+import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands;\r
+import com.indexdata.mkjsf.pazpar2.commands.sp.InitDocUpload;\r
+import com.indexdata.mkjsf.pazpar2.data.Pazpar2Responses;\r
+import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser;\r
+\r
+@Named("pz2x") @SessionScoped\r
+public class ServiceProxyExtensions  implements ServiceProxyInterface, Serializable {\r
+    \r
+  private static final long serialVersionUID = 4221824985678758225L;\r
+  private static Logger logger = Logger.getLogger(ServiceProxyExtensions.class);  \r
+  private String initDocFileName = "";\r
+  private String initDocResponse = "";  \r
+  private InitDocUpload initDocUpload; \r
+    \r
+  @Inject ConfigurationReader configurator;  \r
+  @Inject ServiceProxyUser user;    \r
+  @Inject Pz2Bean pz2;\r
+  @Inject Pazpar2Commands pzreq;\r
+  @Inject Pazpar2Responses pzresp;\r
+\r
+  \r
+  public ServiceProxyExtensions() {\r
+    this.initDocUpload = new InitDocUpload(this);\r
+    // TODO: \r
+    //stateMgr.addStateListener(this);\r
+  }\r
+    \r
+  public void login(String un, String pw) {\r
+    if (user.isAuthenticated() && user.getName().equals(un) && pz2.spClient.checkAuthentication(user)) {\r
+      logger.info("Repeat request from UI to authenticate user. Auth verified for given user name so skipping log-in.");\r
+    } else {\r
+      logger.info("doing un/pw login");\r
+      user.setName(un);\r
+      user.setPassword(pw);\r
+      login("dummy");\r
+    }\r
+  }\r
+\r
+  @Override\r
+  public String login(String navigateTo) {\r
+    logger.info("doing login by " + user + " using " + pz2 + " and client " + pz2.getSpClient());\r
+    pz2.getSpClient().authenticate(user);\r
+    pz2.resetSearchAndResults();\r
+    return navigateTo;\r
+  }\r
+  \r
+  public void ipAuthenticate (ServiceProxyUser user) {\r
+    if (!user.isIpAuthenticated()) {\r
+      if (user.isAuthenticated()) {\r
+        user.clear();\r
+      }\r
+      pz2.resetSearchAndResults();\r
+      pz2.getSpClient().ipAuthenticate(user);\r
+    }\r
+  }\r
+    \r
+  public String getInitDocPath () {\r
+    return pz2.getSpClient().getConfiguration().get("INIT_DOC_PATH");\r
+  }\r
+  \r
+  @Override\r
+  public void setInitFileName(String fileName) {\r
+    this.initDocFileName = fileName;\r
+    \r
+  }\r
+\r
+  @Override\r
+  public String getInitFileName() {\r
+    return initDocFileName;\r
+  }\r
+\r
+  @Override\r
+  public ClientCommandResponse postInit() throws UnsupportedEncodingException, IOException {    \r
+    String initDocPath = pz2.getSpClient().getInitDocPaths().get(0);\r
+    logger.info("Paths: " + pz2.getSpClient().getInitDocPaths());\r
+    logger.info("Path: " + initDocPath);\r
+    pz2.resetSearchAndResults();\r
+    ClientCommandResponse response = pz2.getSpClient().postInitDoc(initDocPath + getInitFileName());    \r
+    return response;\r
+  }\r
+  \r
+  @Override\r
+  public ClientCommandResponse postInit(byte[] initDoc, boolean includeDebug) throws UnsupportedEncodingException, IOException {    \r
+    pz2.resetSearchAndResults();\r
+    ClientCommandResponse response = pz2.getSpClient().postInitDoc(initDoc,includeDebug);    \r
+    return response;\r
+  }\r
+\r
+  @Override\r
+  public String getInitResponse() {\r
+    return initDocResponse;\r
+  }\r
+  \r
+  public InitDocUpload getInitDocUpload () {\r
+    return initDocUpload;\r
+  }\r
+  \r
+}\r
index 02b4c37..7a2fb46 100644 (file)
@@ -3,12 +3,11 @@ package com.indexdata.mkjsf.pazpar2.commands.sp;
 import java.io.IOException;\r
 \r
 import javax.enterprise.context.SessionScoped;\r
-import javax.inject.Inject;\r
 import javax.inject.Named;\r
 \r
 import org.apache.log4j.Logger;\r
 \r
-import com.indexdata.mkjsf.pazpar2.Pz2ProxyBean;\r
+import com.indexdata.mkjsf.pazpar2.ServiceProxyExtensions;\r
 import com.indexdata.mkjsf.utils.FileUpload;\r
 import com.indexdata.mkjsf.utils.Utils;\r
 \r
@@ -17,10 +16,14 @@ import com.indexdata.mkjsf.utils.Utils;
 public class InitDocUpload extends FileUpload {\r
 \r
   private static Logger logger = Logger.getLogger(InitDocUpload.class);\r
-  private static final long serialVersionUID = 1846749236304941323L;\r
-  @Inject Pz2ProxyBean spBean;\r
+  private static final long serialVersionUID = 1846749236304941323L;  \r
   private boolean includeDebug = false;\r
-\r
+  private ServiceProxyExtensions spBean;\r
+  \r
+  public InitDocUpload(ServiceProxyExtensions spBean) {\r
+    this.spBean = spBean;\r
+  }\r
+  \r
   public String submit() throws IOException {\r
     logger.info(Utils.objectId(this) + " submitting");\r
     //String fileName = FilenameUtils.getName(uploadedFile.getName());\r
diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java
deleted file mode 100644 (file)
index e52e797..0000000
+++ /dev/null
@@ -1,304 +0,0 @@
-package com.indexdata.mkjsf.pazpar2.sp;\r
-\r
-import static com.indexdata.mkjsf.utils.Utils.nl;\r
-\r
-import java.io.BufferedReader;\r
-import java.io.File;\r
-import java.io.FileReader;\r
-import java.io.IOException;\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-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
-import org.apache.http.client.ClientProtocolException;\r
-import org.apache.http.client.HttpClient;\r
-import org.apache.http.client.ResponseHandler;\r
-import org.apache.http.client.methods.HttpGet;\r
-import org.apache.http.client.methods.HttpPost;\r
-import org.apache.http.conn.ClientConnectionManager;\r
-import org.apache.http.conn.scheme.PlainSocketFactory;\r
-import org.apache.http.conn.scheme.Scheme;\r
-import org.apache.http.conn.scheme.SchemeRegistry;\r
-import org.apache.http.entity.ByteArrayEntity;\r
-import org.apache.http.entity.FileEntity;\r
-import org.apache.http.impl.client.DefaultHttpClient;\r
-import org.apache.http.impl.conn.PoolingClientConnectionManager;\r
-import org.apache.http.util.EntityUtils;\r
-import org.apache.log4j.Logger;\r
-\r
-import com.indexdata.mkjsf.config.Configuration;\r
-import com.indexdata.mkjsf.config.ConfigurationReader;\r
-import com.indexdata.mkjsf.errors.ConfigurationException;\r
-import com.indexdata.mkjsf.pazpar2.CommandResponse;\r
-import com.indexdata.mkjsf.pazpar2.SearchClient;\r
-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
-public class ServiceProxyClient implements SearchClient {\r
-    \r
-  private static final long serialVersionUID = -4031644009579840277L;\r
-  private static Logger logger = Logger.getLogger(ServiceProxyClient.class);\r
-  public static final String MODULENAME = "proxyclient";\r
-  public static final String SERVICE_PROXY_URL = "SERVICE_PROXY_URL";\r
-  public static final String SP_INIT_DOC_PATHS = "SP_INIT_DOC_PATHS";\r
-  private String selectedServiceUrl = "";\r
-  private List<String> serviceUrls = new ArrayList<String>();\r
-  private List<String> initDocPaths = null;\r
-  private Configuration config = null;\r
-  \r
-  ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler();\r
-  private transient HttpClient client;  \r
-  private Pazpar2Command checkAuth = null;\r
-  private Pazpar2Command ipAuth = null;\r
-\r
-  public ServiceProxyClient () {\r
-    SchemeRegistry schemeRegistry = new SchemeRegistry();\r
-    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));\r
-    ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);\r
-    client = new DefaultHttpClient(cm);\r
-  }\r
-    \r
-  @Override\r
-  public void configure (ConfigurationReader configReader) {\r
-    logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
-    try {\r
-      config = configReader.getConfiguration(this);      \r
-      serviceUrls = getMultiProperty(config.get(SERVICE_PROXY_URL),",");\r
-      if (serviceUrls.size()==1) {\r
-        selectedServiceUrl = serviceUrls.get(0);\r
-      }\r
-      this.initDocPaths = getMultiProperty(config.get(SP_INIT_DOC_PATHS),",");\r
-      checkAuth = new AuthCommand(null);\r
-      checkAuth.setParameterInState(new CommandParameter("action","=","check"));\r
-      ipAuth = new AuthCommand(null);\r
-      ipAuth.setParameterInState(new CommandParameter("action","=","ipauth"));\r
-    } catch (ConfigurationException c) {\r
-      // TODO: \r
-      c.printStackTrace();\r
-    }    \r
-  }\r
-  \r
-  private List<String> getMultiProperty(String prop, String separator) {\r
-    List<String> props = new ArrayList<String>();\r
-    if (prop != null) {      \r
-      StringTokenizer tokenizer = new StringTokenizer(prop,separator);\r
-      while (tokenizer.hasMoreElements()) {\r
-        props.add(tokenizer.nextToken());\r
-      }     \r
-    }\r
-    return props;\r
-  }\r
-  \r
-  public boolean authenticate (ServiceProxyUser user) {\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
-    } else {\r
-      user.credentialsAuthenticationSucceeded(true);\r
-      return true;\r
-    }      \r
-  }\r
-  \r
-  public boolean checkAuthentication (ServiceProxyUser user) {    \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
-    } else {                \r
-      return true;\r
-    }      \r
-  }\r
-  \r
-  public boolean ipAuthenticate (ServiceProxyUser user) {\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
-    } else {\r
-      user.ipAuthenticationSucceeded(true);\r
-      return true;\r
-    }          \r
-  }\r
-  \r
-  public boolean isAuthenticatingClient () {\r
-    return true;\r
-  }\r
-  \r
-  public boolean isAuthenticated (ServiceProxyUser user) {\r
-    if (user.getProperty("name") != null && user.getProperty("password") != null) {\r
-      return checkAuthentication(user);\r
-    } else {\r
-      return false;\r
-    }\r
-  }\r
-  \r
-  /**\r
-   * Makes the request\r
-   * @param request\r
-   * @return HTTP response as a String\r
-   * @throws ClientProtocolException\r
-   * @throws IOException\r
-   */\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 = 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
-        contentType = response.getEntity().getContentType();        \r
-      }       \r
-      EntityUtils.consume(entity);      \r
-      return resp;\r
-    }\r
-    public int getStatusCode() {\r
-      return statusLine.getStatusCode();\r
-    }    \r
-    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
-    return handler.getStatusCode();\r
-  }\r
-  \r
-  public String getReasonPhrase() {\r
-    return handler.getReasonPhrase();\r
-  }\r
-\r
-  @Override\r
-  public void setSearchCommand(Pazpar2Command command) {\r
-    // Do nothing, Service Proxy is handling this    \r
-  }\r
-\r
-  @Override\r
-  public CommandResponse executeCommand(Pazpar2Command command) {\r
-    return send(command);\r
-  }\r
-\r
-  public ServiceProxyClient cloneMe() {\r
-    logger.debug("Cloning Pz2Client");\r
-    ServiceProxyClient clone = new ServiceProxyClient();\r
-    clone.client = this.client;\r
-    clone.serviceUrls = this.serviceUrls;\r
-    clone.selectedServiceUrl = this.selectedServiceUrl;\r
-    clone.initDocPaths = this.initDocPaths;\r
-    return clone;\r
-  }\r
-\r
-  @Override\r
-  public Map<String, String> getDefaults() {    \r
-    return new HashMap<String,String>();\r
-  }\r
-\r
-  @Override\r
-  public String getModuleName() {\r
-    return MODULENAME;\r
-  }\r
-  \r
-  @Override\r
-  public List<String> documentConfiguration () {\r
-    List<String> doc = new ArrayList<String>();\r
-    doc.add(nl+ MODULENAME + " was configured to access the Pazpar2 service proxy at: " + (selectedServiceUrl.length()>0 ? selectedServiceUrl : "[not defined yet]"));\r
-    return null;\r
-  }\r
-  \r
-  public ServiceProxyCommandResponse postInitDoc (String filePath) throws IOException {\r
-    logger.info("Looking to post the file in : [" + filePath +"]");\r
-    HttpPost post = new HttpPost(selectedServiceUrl+"?command=init&includeDebug=yes");\r
-    File initDoc = new File(filePath);\r
-    logger.info("Posting to SP: ");\r
-    if (logger.isDebugEnabled()) {\r
-      BufferedReader reader = new BufferedReader(new FileReader(initDoc));\r
-      String line;\r
-      while ( (line = reader.readLine()) != null) {\r
-        System.out.println(line);\r
-      }\r
-      reader.close();\r
-    }\r
-    post.setEntity(new FileEntity(initDoc));\r
-    byte[] response = client.execute(post, handler);\r
-    logger.debug("Response on POST was: " + new String(response,"UTF-8"));    \r
-    return new ServiceProxyCommandResponse(handler.getStatusCode(),response,handler.getContentType());    \r
-  }\r
-  \r
-  public List<String> getInitDocPaths () {\r
-    logger.debug("Get init doc paths ");\r
-    logger.debug("length: " + initDocPaths.size());\r
-    return initDocPaths;\r
-  }\r
-  \r
-  public ServiceProxyCommandResponse postInitDoc(byte[] initDoc, boolean includeDebug) throws IOException {\r
-    HttpPost post = new HttpPost(selectedServiceUrl+"?command=init" + (includeDebug? "&includeDebug=yes" : ""));\r
-    post.setEntity(new ByteArrayEntity(initDoc));\r
-    byte[] response = client.execute(post, handler);\r
-    logger.debug("Response on POST was: " + new String(response,"UTF-8"));    \r
-    return new ServiceProxyCommandResponse(handler.getStatusCode(),response,handler.getContentType());    \r
-  }\r
-  \r
-  public void setServiceProxyUrl (String url) {\r
-    selectedServiceUrl = url;\r
-  }\r
-  \r
-  public String getServiceProxyUrl () {\r
-    return selectedServiceUrl;\r
-  }\r
-  \r
-  public List<String> getServiceProxyUrls () {\r
-    return serviceUrls;\r
-  }\r
-    \r
-  public Configuration getConfiguration () {\r
-    return config;\r
-  }\r
-  \r
-}\r
diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java
deleted file mode 100644 (file)
index 74d5f75..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.indexdata.mkjsf.pazpar2.sp;\r
-\r
-import java.io.IOException;\r
-import java.io.UnsupportedEncodingException;\r
-\r
-import com.indexdata.mkjsf.pazpar2.Pz2Interface;\r
-\r
-public interface ServiceProxyInterface extends Pz2Interface {  \r
-  public String login(String navigateTo);  \r
-  public void setInitFileName (String fileName);  \r
-  public String getInitFileName();\r
-  public ServiceProxyCommandResponse postInit() throws UnsupportedEncodingException, IOException;\r
-  public ServiceProxyCommandResponse postInit(byte[] initDoc, boolean includeDebug) throws UnsupportedEncodingException, IOException;\r
-  public String getInitResponse();\r
-  public void setServiceProxyUrl(String url);\r
-  public String getServiceProxyUrl();\r
-}\r