Moves filter settings from pz2 bean to search command
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / pz2utils4jsf / pazpar2 / Pz2Session.java
index 3034a74..7c0cc86 100644 (file)
@@ -1,28 +1,28 @@
 package com.indexdata.pz2utils4jsf.pazpar2;\r
 \r
-import java.io.IOException;\r
 import java.util.ArrayList;\r
 import java.util.List;\r
 import java.util.Map;\r
 import java.util.StringTokenizer;\r
 import java.util.concurrent.ConcurrentHashMap;\r
 \r
-import javax.enterprise.context.SessionScoped;\r
-import javax.inject.Named;\r
+import javax.annotation.PostConstruct;\r
+import javax.inject.Inject;\r
 \r
 import org.apache.log4j.Logger;\r
 \r
-import com.indexdata.masterkey.pazpar2.client.Pazpar2Client;\r
-import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientConfiguration;\r
-import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientGeneric;\r
-import com.indexdata.masterkey.pazpar2.client.exceptions.ProxyErrorException;\r
-import com.indexdata.pz2utils4jsf.config.Pz2Configurator;\r
+import com.indexdata.pz2utils4jsf.config.ConfigurationReader;\r
 import com.indexdata.pz2utils4jsf.controls.ResultsPager;\r
-import com.indexdata.pz2utils4jsf.errors.ErrorInterface;\r
-import com.indexdata.pz2utils4jsf.errors.ErrorHelper;\r
 import com.indexdata.pz2utils4jsf.errors.ConfigurationError;\r
-import com.indexdata.pz2utils4jsf.pazpar2.data.CommandError;\r
+import com.indexdata.pz2utils4jsf.errors.ConfigurationException;\r
+import com.indexdata.pz2utils4jsf.errors.ErrorHelper;\r
+import com.indexdata.pz2utils4jsf.errors.ErrorInterface;\r
+import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter;\r
+import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandReadOnly;\r
+import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command;\r
+import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Commands;\r
 import com.indexdata.pz2utils4jsf.pazpar2.data.ByTarget;\r
+import com.indexdata.pz2utils4jsf.pazpar2.data.CommandError;\r
 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData;\r
 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseParser;\r
 import com.indexdata.pz2utils4jsf.pazpar2.data.RecordResponse;\r
@@ -31,68 +31,71 @@ import com.indexdata.pz2utils4jsf.pazpar2.data.ShowResponse;
 import com.indexdata.pz2utils4jsf.pazpar2.data.StatResponse;\r
 import com.indexdata.pz2utils4jsf.pazpar2.data.TermListsResponse;\r
 import com.indexdata.pz2utils4jsf.pazpar2.data.TermResponse;\r
-import com.indexdata.pz2utils4jsf.pazpar2.state.QueryStates;\r
+import com.indexdata.pz2utils4jsf.pazpar2.state.StateListener;\r
+import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager;\r
 import com.indexdata.pz2utils4jsf.utils.Utils;\r
 \r
-@Named @SessionScoped  \r
-public class Pz2Session implements Pz2Interface {\r
-  \r
+@ForStraightPz2\r
+public class Pz2Session implements Pz2Interface, StateListener {\r
+    \r
+  private static final long serialVersionUID = 3947514708343320514L;\r
   private static Logger logger = Logger.getLogger(Pz2Session.class);\r
   \r
-  private Map<String,Pazpar2ResponseData> dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
-  private QueryStates queryStates = new QueryStates();\r
+  protected Map<String,Pazpar2ResponseData> dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
+  \r
+  @Inject StateManager stateMgr;\r
+  @Inject Pazpar2Commands req;\r
   \r
-  private static final long serialVersionUID = 3947514708343320514L;  \r
-  private Pazpar2ClientConfiguration cfg = null;\r
-  private Pazpar2Client client = null;   \r
-  private TargetFilter targetFilter = null;  \r
-  private ResultsPager pager = null; \r
-  private ErrorHelper errorHelper = null;\r
-  private List<ErrorInterface> configurationErrors = null;\r
+  protected ErrorHelper errorHelper = null;\r
   \r
+  protected List<ErrorInterface> configurationErrors = null;\r
+  protected SearchClient searchClient = null;   \r
+  protected SingleTargetFilter singleTargetFilter = null;  \r
+  protected ResultsPager pager = null; \r
+    \r
   public Pz2Session () {\r
-    logger.info("Instantiating pz2 session object [" + Utils.objectId(this) + "]");      \r
+    logger.info("Instantiating pz2 session object [" + Utils.objectId(this) + "]");        \r
   }\r
-    \r
-  public void init(Pz2Configurator pz2conf) {\r
-    if (client==null) {\r
-      configurationErrors = new ArrayList<ErrorInterface>();\r
-      errorHelper = new ErrorHelper(pz2conf);\r
-      logger.info(Utils.objectId(this) + " is configuring itself using the provided " + Utils.objectId(pz2conf));\r
-      try {\r
-        cfg = new Pazpar2ClientConfiguration(pz2conf.getConfig());\r
-      } catch (ProxyErrorException pe) {\r
-        logger.error("Could not configure Pazpar2 client: " + pe.getMessage());\r
-        configurationErrors.add(new ConfigurationError("Pz2Client Config","ProxyError","Could not configure Pazpar2 client: " + pe.getMessage(),errorHelper));\r
-      } catch (IOException io) {\r
-        logger.error("Could not configure Pazpar2 client: " + io.getMessage());\r
-        configurationErrors.add(new ConfigurationError("Pz2Client Config","ProxyError","Could not configure Pazpar2 client: " + io.getMessage(),errorHelper));\r
-      }\r
-      if (cfg != null) {\r
-        try {\r
-          client = new Pazpar2ClientGeneric(cfg);     \r
-        } catch (ProxyErrorException pe) {\r
-          logger.error("Could not instantiate Pazpar2 client: " + pe.getMessage());\r
-          configurationErrors.add(new ConfigurationError("Pz2Client error","ProxyError","Could not create Pazpar2 client: " +pe.getMessage(),errorHelper));                \r
-        } \r
-        logger.info("Got " + configurationErrors.size() + " configuration errors");        \r
-      }\r
-      resetDataObjects();\r
-    } else {\r
-      logger.warn("Attempt to configure session but it already has a configured client");\r
-    }\r
+  \r
+  @PostConstruct\r
+  public void listenToStateManager() {\r
+    logger.debug("in post-construct of Pz2Session stateMgr is " + stateMgr);\r
+    logger.debug("in post-construct req is " + req);\r
+    stateMgr.addStateListener(this);\r
   }\r
     \r
+  public void configureClient(SearchClient searchClient, ConfigurationReader configReader) {\r
+    configurationErrors = new ArrayList<ErrorInterface>();\r
+    errorHelper = new ErrorHelper(configReader);    \r
+    logger.debug(Utils.objectId(this) + " will configure search client for the session");\r
+    try {\r
+      searchClient.configure(configReader);            \r
+      // At the time of writing this search client is injected using Weld. \r
+      // However, the client is used for asynchronously sending off requests\r
+      // to the server AND propagation of context to threads is currently \r
+      // not supported. Trying to do so throws a WELD-001303 error. \r
+      // To avoid that, a context free client is cloned from the context \r
+      // dependent one. \r
+      // If propagation to threads gets supported, the cloning can go. \r
+      this.searchClient = searchClient.cloneMe();         \r
+    } catch (ConfigurationException e) {\r
+      configurationErrors.add(new ConfigurationError("Search Client","Configuration",e.getMessage(),new ErrorHelper(configReader)));          \r
+    } \r
+    logger.info(configReader.document());\r
+    resetDataObjects();\r
+  }\r
+      \r
   public void doSearch(String query) {\r
     setCommandParameter("search",new CommandParameter("query","=",query));     \r
     doSearch();\r
   }\r
 \r
   public void doSearch() { \r
-    queryStates.hasPendingStateChange("search",false);\r
+    stateMgr.hasPendingStateChange("search",false);\r
     resetDataObjects();\r
+    removeCommand("record");\r
     setCommandParameter("show",new CommandParameter("start","=",0));    \r
-    logger.debug(Utils.objectId(this) + " is searching using "+getCommand("search").getParameter("query").getEncodedQueryString());\r
+    logger.debug(Utils.objectId(this) + " is searching using "+req.getCommandReadOnly("search").getUrlEncodedParameterValue("query"));\r
     doCommand("search");    \r
   }\r
       \r
@@ -119,8 +122,8 @@ public class Pz2Session implements Pz2Interface {
         logger.debug("Processing request for " + commands); \r
         List<CommandThread> threadList = new ArrayList<CommandThread>();\r
         StringTokenizer tokens = new StringTokenizer(commands,",");\r
-        while (tokens.hasMoreElements()) {\r
-          threadList.add(new CommandThread(getCommand(tokens.nextToken()),client));            \r
+        while (tokens.hasMoreElements()) {          \r
+          threadList.add(new CommandThread(req.getCommandReadOnly(tokens.nextToken()),searchClient));            \r
         }\r
         for (CommandThread thread : threadList) {\r
           thread.start();\r
@@ -134,10 +137,17 @@ public class Pz2Session implements Pz2Interface {
         }\r
         for (CommandThread thread : threadList) {\r
            String commandName = thread.getCommand().getName();\r
-           Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(thread.getResponse());\r
+           String response = thread.getResponse();\r
+           logger.debug("Response was: " + response);\r
+           Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(response);\r
            dataObjects.put(commandName, responseObject);        \r
         }\r
-        return getActiveClients();\r
+        if (commands.equals("record")) {\r
+          logger.debug("Record: Active clients: "+getRecord().getActiveClients());\r
+          return getRecord().getActiveClients();\r
+        } else {\r
+          return getActiveClients();\r
+        }  \r
       } else {\r
         logger.debug("Skipped requests for " + commands + " as there's not yet a query."); \r
         resetDataObjects();\r
@@ -149,113 +159,22 @@ public class Pz2Session implements Pz2Interface {
     }\r
     \r
   }\r
-        \r
-  public void setQuery (String query) {\r
-    logger.debug("Creating new command parameter for " + query);\r
-    setCommandParameter("search",new CommandParameter("query","=",query));\r
-  }\r
-  \r
-  public String getQuery () {\r
-    return getCommandParameterValueSimple("search","query",null);\r
-  }\r
-  \r
-  public void setFacet (String facetKey, String term) {           \r
-    if (term != null && term.length()>0) {\r
-      queryStates.getCurrentState().setCommandParameterExpression("search","query",new Expression(facetKey,"=",term),queryStates);\r
-      doSearch();\r
-    }            \r
-  }\r
-  \r
-  public void setFacetOnQuery (String facetKey, String term) {\r
-    String facetExpression = facetKey + "=" + term;    \r
-    if (term != null && term.length()>0) {\r
-      setCommandParameter("search",new CommandParameter("query","=", getQuery() + " and " + facetExpression));\r
-      doSearch();        \r
-    }            \r
-  }\r
-      \r
-  public void removeFacet(String facetKey, String term) {\r
-    queryStates.getCurrentState().removeCommandParameterExpression("search","query",new Expression(facetKey,"=",term),queryStates);\r
-    doSearch();\r
-  }\r
-  \r
-  public void setTargetFilter (String targetId, String targetName) {    \r
-    if (hasTargetFilter(new TargetFilter(targetId,targetName))) {\r
-      logger.debug("Already using target filter " + this.targetFilter.getFilterExpression());\r
-    } else {      \r
-      this.targetFilter = new TargetFilter(targetId,targetName);\r
-      setCommandParameter("search",new CommandParameter("filter","=",this.targetFilter.getFilterExpression()));      \r
-      doSearch();\r
-    }    \r
-  }\r
-\r
-  public TargetFilter getTargetFilter () {\r
-    return targetFilter;\r
-  }\r
-    \r
-  public void removeTargetFilter () {\r
-    logger.debug("Removing target filter " + targetFilter.getFilterExpression());\r
-    this.targetFilter = null;\r
-    removeCommandParameter("search","filter");         \r
-    doSearch();\r
-  }\r
-  \r
-  public boolean hasTargetFilter() {\r
-    return targetFilter != null;    \r
-  }\r
-        \r
-  public void setSort (String sortOption) {\r
-    logger.debug("Setting sort option: " + sortOption);\r
-    setCommandParameter("show",new CommandParameter("sort","=",sortOption));\r
-    update("show");\r
-  }\r
-  \r
-  public String getSort () {\r
-    return getCommandParameterValue("show","sort","relevance");\r
-  }\r
-    \r
-  public void setPageSize (int perPageOption) {\r
-    if (getPageSize()!=perPageOption) {\r
-     logger.debug("Setting perpage option to " + perPageOption + " and resetting start page.");\r
-     setCommandParameter("show",new CommandParameter("num","=",perPageOption));\r
-     setCommandParameter("show",new CommandParameter("start","=",0));\r
-     update("show");\r
-    } else {\r
-      logger.debug("Not updating page size, already is " + perPageOption);\r
-    }\r
-  }\r
-  \r
-  public int getPageSize () {\r
-    return getCommandParameterValue("show","num",20);\r
-  }\r
-  \r
-  public void setStart (int start) {\r
-    logger.debug("Setting start num to " + start);\r
-    setCommandParameter("show", new CommandParameter("start","=",start));  \r
-    update("show");\r
-  }\r
-  \r
-  public int getStart() {\r
-    return getCommandParameterValue("show","start",0);\r
-  }\r
-        \r
+            \r
+                    \r
   public String toggleRecord (String recId) {\r
     if (hasRecord(recId)) {\r
       removeCommand("record");  \r
       dataObjects.put("record", new RecordResponse());\r
       return "";\r
     } else {\r
-      return updateRecord(recId);\r
+      req.getRecord().setRecordId(recId);\r
+      return doCommand("record");\r
     }\r
   }\r
   \r
-  private String updateRecord(String recId) {    \r
-    setCommandParameter("record",new CommandParameter("id","=",recId));    \r
-    return doCommand("record");    \r
-  }\r
-  \r
+  @Override\r
   public boolean hasRecord (String recId) {\r
-    return getCommand("record").hasParameters() && getRecord().getRecId().equals(recId);\r
+    return req.getCommandReadOnly("record").hasParameters() && getRecord().getRecId().equals(recId);\r
   }\r
       \r
   public ShowResponse getShow () {\r
@@ -288,11 +207,11 @@ public class Pz2Session implements Pz2Interface {
   \r
   \r
   public String getCurrentStateKey () {    \r
-    return queryStates.getCurrentStateKey();\r
+    return stateMgr.getCurrentState().getKey();\r
   }\r
       \r
   public void setCurrentStateKey(String key) {       \r
-    queryStates.setCurrentStateKey(key);\r
+    stateMgr.setCurrentStateKey(key);\r
   }\r
   \r
   public boolean hasConfigurationErrors () {\r
@@ -344,14 +263,9 @@ public class Pz2Session implements Pz2Interface {
     error.setErrorHelper(errorHelper);\r
     return error;         \r
   }\r
-\r
-    \r
-  private boolean hasTargetFilter(TargetFilter targetFilter) {\r
-    return hasTargetFilter() && targetFilter.equals(this.targetFilter);\r
-  }\r
   \r
-  private boolean hasQuery() {\r
-    return !(getCommand("search").getParameter("query") == null);\r
+  protected boolean hasQuery() {    \r
+    return req.getSearch().getParameter("query") != null && req.getSearch().getParameter("query").getValueWithExpressions().length()>0;\r
   }\r
     \r
   public boolean hasRecords () {\r
@@ -368,7 +282,7 @@ public class Pz2Session implements Pz2Interface {
   }\r
   \r
   public ResultsPager setPager (int pageRange) {\r
-    pager =  new ResultsPager(this,pageRange);\r
+    pager =  new ResultsPager(this,pageRange,req);\r
     return pager;\r
   }\r
   \r
@@ -376,24 +290,24 @@ public class Pz2Session implements Pz2Interface {
     return errorHelper;\r
   }\r
   \r
-  private void handleQueryStateChanges (String commands) {\r
-    if (queryStates.hasPendingStateChange("search")) { \r
-      logger.debug("Found pending search change. Doing search before updating " + commands);\r
+  protected void handleQueryStateChanges (String commands) {\r
+    if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
+      logger.debug("Found pending search change. Doing search before updating " + commands);      \r
       doSearch();\r
     } \r
-    if (queryStates.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
+    if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {        \r
       logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
-      queryStates.hasPendingStateChange("record",false);\r
-      if (getCommand("record").hasParameters()) {\r
-        updateRecord(getCommand("record").getParameter("id").getSimpleValue());\r
+      stateMgr.hasPendingStateChange("record",false);\r
+      if (req.getCommandReadOnly("record").hasParameters()) {\r
+        update("record");\r
       } else {\r
         removeCommand("record");  \r
         dataObjects.put("record", new RecordResponse());\r
       }\r
-    }    \r
+    }\r
   }\r
 \r
-  private String getActiveClients() {    \r
+  protected String getActiveClients() {    \r
     if (getShow()!=null) {\r
       logger.debug("Active clients: "+getShow().getActiveClients());\r
       return getShow().getActiveClients();\r
@@ -402,65 +316,88 @@ public class Pz2Session implements Pz2Interface {
     }\r
   }\r
 \r
-  private Pazpar2Command getCommand(String name) {\r
-    return queryStates.getCurrentState().getCommand(name);\r
+  /**\r
+   * Returns a Pazpar2 command 'detached' from the current Pazpar2 state.\r
+   * \r
+   * 'Detached' is meant to imply that this is a copy of a command in the \r
+   * current state, detached so as to NOT change the current state if \r
+   * modified. It can be viewed and executed, however. \r
+   * \r
+   * In order to modify the command with effect for subsequent searches,\r
+   * it must be checked back into the StateManager, which will\r
+   * then create a new current Pazpar2 state as needed.\r
+   *  \r
+   * @param name\r
+   * @return\r
+   */\r
+  protected Pazpar2Command getCommand(String name) {\r
+    return req.getCommand(name);\r
   }\r
   \r
-  private void setCommandParameter(String commandName, CommandParameter parameter) {\r
+  /** \r
+   * Returns an interface to a Pazpar2Command with only String getters.\r
+   * \r
+   * Since the command cannot be modified (unless it is cast) we can avoid \r
+   * cloning it before returning it from the current state. \r
+   * It can be used for log statements, checks and for performing the \r
+   * actual pazpar2 request. \r
+   * \r
+   * @param name\r
+   * @return\r
+   */\r
+  protected CommandReadOnly getCommandReadOnly(String name) {\r
+    return req.getCommandReadOnly(name);\r
+  }\r
+\r
+  \r
+  protected void setCommandParameter(String commandName, CommandParameter parameter) {\r
     logger.debug("Setting parameter for " + commandName + ": " + parameter);\r
-    queryStates.getCurrentState().setCommandParameter(commandName, parameter, queryStates);    \r
+    Pazpar2Command command = req.getCommand(commandName);\r
+    command.setParameter(parameter);\r
+    stateMgr.checkIn(command);    \r
   }\r
   \r
   \r
-  private void removeCommandParameter(String commandName, String parameterName) {\r
-    queryStates.getCurrentState().removeCommandParameter(commandName,parameterName,queryStates);    \r
+  protected void removeCommandParameter(String commandName, String parameterName) {\r
+    Pazpar2Command command = req.getCommand(commandName);\r
+    command.removeParameter(parameterName);\r
+    stateMgr.checkIn(command);    \r
   }\r
   \r
-  private void removeCommand (String commandName) {\r
-    queryStates.getCurrentState().removeCommand(commandName, queryStates);\r
+  protected void removeCommand (String commandName) {\r
+    Pazpar2Command command = req.getCommand(commandName);\r
+    command.removeParameters();\r
+    stateMgr.checkIn(command);\r
   }\r
     \r
-  private String getCommandParameterValue (String commandName, String parameterName, String defaultValue) {    \r
-    Pazpar2Command command = getCommand(commandName);\r
+  protected String getCommandParameterValue (String commandName, String parameterName, String defaultValue) {    \r
+    CommandReadOnly command = req.getCommandReadOnly(commandName);\r
     if (command != null) {\r
-      CommandParameter parameter = command.getParameter(parameterName);\r
+      String parameter = command.getParameterValue(parameterName);\r
       if (parameter != null) {\r
-        return parameter.getValueWithExpressions();\r
+        return parameter;\r
       }\r
     }\r
     return defaultValue;    \r
   }\r
-  \r
-  private String getCommandParameterValueSimple (String commandName, String parameterName, String defaultValue) {    \r
-    Pazpar2Command command = getCommand(commandName);\r
-    if (command != null) {\r
-      CommandParameter parameter = command.getParameter(parameterName);\r
-      if (parameter != null) {\r
-        return parameter.getSimpleValue();\r
-      }\r
-    }\r
-    return defaultValue;    \r
-  }\r
-\r
-  \r
-  private int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {\r
-    Pazpar2Command command = getCommand(commandName);\r
+    \r
+  protected int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {\r
+    CommandReadOnly command = req.getCommandReadOnly(commandName);\r
     if (command != null) {\r
-      CommandParameter parameter = command.getParameter(parameterName);\r
+      String parameter = command.getParameterValue(parameterName);\r
       if (parameter != null) {\r
-        return Integer.parseInt(parameter.getSimpleValue());\r
+        return Integer.parseInt(parameter);\r
       }\r
     }\r
     return defaultValue;    \r
   }\r
 \r
-  private String doCommand(String commandName) {      \r
-    Pazpar2Command command = getCommand(commandName);    \r
-    logger.debug(command.getEncodedQueryString() + ": Results for "+ getCommand("search").getEncodedQueryString());\r
-    return update(commandName);      \r
+  protected String doCommand(String commandName) {             \r
+    logger.debug(req.getCommandReadOnly(commandName).getEncodedQueryString() + ": Results for "+ req.getCommandReadOnly("search").getEncodedQueryString());\r
+    return update(commandName);\r
   }\r
   \r
-  private void resetDataObjects() {\r
+  protected void resetDataObjects() {\r
     logger.debug("Resetting show,stat,termlist,bytarget,search response objects.");\r
     dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
     dataObjects.put("show", new ShowResponse());\r
@@ -471,4 +408,14 @@ public class Pz2Session implements Pz2Interface {
     dataObjects.put("search", new SearchResponse());\r
   }\r
   \r
+\r
+  @Override\r
+  public void stateUpdated(String commandName) {\r
+    logger.debug("State change reported for [" + commandName + "]");\r
+    if (commandName.equals("show")) {\r
+      logger.debug("Updating show");\r
+      update(commandName);\r
+    } \r
+  }\r
+  \r
 }\r