-package com.indexdata.pz2utils4jsf.pazpar2;\r
-\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.annotation.PostConstruct;\r
-import javax.inject.Inject;\r
-\r
-import org.apache.log4j.Logger;\r
-\r
-import com.indexdata.pz2utils4jsf.config.ConfigurationReader;\r
-import com.indexdata.pz2utils4jsf.controls.ResultsPager;\r
-import com.indexdata.pz2utils4jsf.errors.ConfigurationError;\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
-import com.indexdata.pz2utils4jsf.pazpar2.data.SearchResponse;\r
-import com.indexdata.pz2utils4jsf.pazpar2.data.ShowResponse;\r
-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.StateListener;\r
-import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager;\r
-import com.indexdata.pz2utils4jsf.utils.Utils;\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
- protected Map<String,Pazpar2ResponseData> dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();\r
- \r
- @Inject StateManager stateMgr;\r
- @Inject Pazpar2Commands req;\r
- \r
- protected ErrorHelper errorHelper = null;\r
- \r
- protected List<ErrorInterface> configurationErrors = null;\r
- protected SearchClient searchClient = null; \r
- protected ResultsPager pager = null; \r
- \r
- public Pz2Session () {\r
- logger.info("Instantiating pz2 session object [" + Utils.objectId(this) + "]"); \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
- 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 "+req.getCommandReadOnly("search").getUrlEncodedParameterValue("query"));\r
- doCommand("search"); \r
- }\r
- \r
- /**\r
- * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2\r
- * \r
- * @return Number of activeclients at the time of the 'show' command.\r
- */\r
- public String update () {\r
- logger.debug("Updating show,stat,termlist,bytarget from pazpar2");\r
- return update("show,stat,termlist,bytarget");\r
- }\r
- \r
- /**\r
- * Refreshes the data objects listed in 'commands' from pazpar2\r
- * \r
- * @param commands\r
- * @return Number of activeclients at the time of the 'show' command\r
- */\r
- public String update (String commands) {\r
- if (! hasConfigurationErrors()) {\r
- if (hasQuery()) {\r
- handleQueryStateChanges(commands);\r
- 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(req.getCommandReadOnly(tokens.nextToken()),searchClient)); \r
- }\r
- for (CommandThread thread : threadList) {\r
- thread.start();\r
- }\r
- for (CommandThread thread : threadList) {\r
- try {\r
- thread.join();\r
- } catch (InterruptedException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- for (CommandThread thread : threadList) {\r
- String commandName = thread.getCommand().getName();\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
- 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
- return "0";\r
- }\r
- } else {\r
- logger.error("Did not attempt to execute query since there are configuration errors.");\r
- return "0";\r
- }\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
- req.getRecord().setRecordId(recId);\r
- return doCommand("record");\r
- }\r
- }\r
- \r
- @Override\r
- public boolean hasRecord (String recId) {\r
- return req.getCommandReadOnly("record").hasParameters() && getRecord().getRecId().equals(recId);\r
- }\r
- \r
- public ShowResponse getShow () {\r
- return ((ShowResponse) dataObjects.get("show"));\r
- }\r
- \r
- public StatResponse getStat () {\r
- return ((StatResponse) dataObjects.get("stat"));\r
- }\r
- \r
- public RecordResponse getRecord() {\r
- return ((RecordResponse) dataObjects.get("record"));\r
- }\r
- \r
- public TermListsResponse getTermLists () {\r
- return ((TermListsResponse) dataObjects.get("termlist"));\r
- }\r
- \r
- public List<TermResponse> getFacetTerms (String facet, int count) {\r
- return (getTermLists().getTermList(facet).getTerms(count));\r
- }\r
- \r
- public List<TermResponse> getFacetTerms (String facet) {\r
- return (getTermLists().getTermList(facet).getTerms());\r
- }\r
- \r
- public ByTarget getByTarget() {\r
- return ((ByTarget) dataObjects.get("bytarget"));\r
- }\r
- \r
- \r
- public String getCurrentStateKey () { \r
- return stateMgr.getCurrentState().getKey();\r
- }\r
- \r
- public void setCurrentStateKey(String key) { \r
- stateMgr.setCurrentStateKey(key);\r
- }\r
- \r
- public boolean hasConfigurationErrors () {\r
- return (configurationErrors.size()>0); \r
- }\r
- \r
- public boolean hasCommandErrors () {\r
- if (dataObjects.get("search").hasApplicationError()) {\r
- logger.info("Error detected in search");\r
- return true;\r
- }\r
- for (String name : dataObjects.keySet()) {\r
- if (dataObjects.get(name).hasApplicationError()) {\r
- logger.info("Error detected in " + name);\r
- return true;\r
- }\r
- } \r
- return false; \r
- }\r
- \r
- /**\r
- * Returns true if application error found in any response data objects \r
- */\r
- public boolean hasErrors () {\r
- return hasConfigurationErrors() || hasCommandErrors();\r
- }\r
-\r
- public List<ErrorInterface> getConfigurationErrors() { \r
- return configurationErrors;\r
- }\r
- \r
- /**\r
- * Returns a search command error, if any, otherwise the first\r
- * error found for an arbitrary command, if any, otherwise\r
- * an empty dummy error. \r
- */ \r
- public ErrorInterface getCommandError() {\r
- CommandError error = new CommandError(); \r
- if (dataObjects.get("search").hasApplicationError()) {\r
- error = dataObjects.get("search").getApplicationError(); \r
- } else {\r
- for (String name : dataObjects.keySet()) { \r
- if (dataObjects.get(name).hasApplicationError()) { \r
- error = dataObjects.get(name).getApplicationError(); \r
- break;\r
- } \r
- }\r
- }\r
- error.setErrorHelper(errorHelper);\r
- return error; \r
- }\r
- \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
- return getStat().getRecords() > 0 \r
- && getShow().getHits() != null \r
- && getShow().getHits().size()>0;\r
- }\r
- \r
- public ResultsPager getPager () {\r
- if (pager == null) {\r
- pager = new ResultsPager(this); \r
- } \r
- return pager; \r
- }\r
- \r
- public ResultsPager setPager (int pageRange) {\r
- pager = new ResultsPager(this,pageRange,req);\r
- return pager;\r
- }\r
- \r
- protected ErrorHelper getTroubleshooter() {\r
- return errorHelper;\r
- }\r
- \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 (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) { \r
- logger.debug("Found pending record ID change. Doing record before updating " + commands);\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
- protected String getActiveClients() { \r
- if (getShow()!=null) {\r
- logger.debug("Active clients: "+getShow().getActiveClients());\r
- return getShow().getActiveClients();\r
- } else {\r
- return "";\r
- }\r
- }\r
-\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
- /** \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
- Pazpar2Command command = req.getCommand(commandName);\r
- command.setParameter(parameter);\r
- stateMgr.checkIn(command); \r
- }\r
- \r
- \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
- protected void removeCommand (String commandName) {\r
- Pazpar2Command command = req.getCommand(commandName);\r
- command.removeParameters();\r
- stateMgr.checkIn(command);\r
- }\r
- \r
- protected String getCommandParameterValue (String commandName, String parameterName, String defaultValue) { \r
- CommandReadOnly command = req.getCommandReadOnly(commandName);\r
- if (command != null) {\r
- String parameter = command.getParameterValue(parameterName);\r
- if (parameter != null) {\r
- return parameter;\r
- }\r
- }\r
- return defaultValue; \r
- }\r
- \r
- protected int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {\r
- CommandReadOnly command = req.getCommandReadOnly(commandName);\r
- if (command != null) {\r
- String parameter = command.getParameterValue(parameterName);\r
- if (parameter != null) {\r
- return Integer.parseInt(parameter);\r
- }\r
- }\r
- return defaultValue; \r
- }\r
-\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
- 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
- dataObjects.put("stat", new StatResponse());\r
- dataObjects.put("termlist", new TermListsResponse());\r
- dataObjects.put("bytarget", new ByTarget());\r
- dataObjects.put("record", new RecordResponse());\r
- 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