1 package com.indexdata.pz2utils4jsf.pazpar2;
\r
3 import java.util.ArrayList;
\r
4 import java.util.List;
\r
5 import java.util.Map;
\r
6 import java.util.StringTokenizer;
\r
7 import java.util.concurrent.ConcurrentHashMap;
\r
9 import javax.annotation.PostConstruct;
\r
10 import javax.inject.Inject;
\r
12 import org.apache.log4j.Logger;
\r
14 import com.indexdata.pz2utils4jsf.config.ConfigurationReader;
\r
15 import com.indexdata.pz2utils4jsf.controls.ResultsPager;
\r
16 import com.indexdata.pz2utils4jsf.errors.ConfigurationError;
\r
17 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;
\r
18 import com.indexdata.pz2utils4jsf.errors.ErrorHelper;
\r
19 import com.indexdata.pz2utils4jsf.errors.ErrorInterface;
\r
20 import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter;
\r
21 import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandReadOnly;
\r
22 import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command;
\r
23 import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Commands;
\r
24 import com.indexdata.pz2utils4jsf.pazpar2.commands.SearchCommand;
\r
25 import com.indexdata.pz2utils4jsf.pazpar2.data.ByTarget;
\r
26 import com.indexdata.pz2utils4jsf.pazpar2.data.CommandError;
\r
27 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData;
\r
28 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseParser;
\r
29 import com.indexdata.pz2utils4jsf.pazpar2.data.RecordResponse;
\r
30 import com.indexdata.pz2utils4jsf.pazpar2.data.SearchResponse;
\r
31 import com.indexdata.pz2utils4jsf.pazpar2.data.ShowResponse;
\r
32 import com.indexdata.pz2utils4jsf.pazpar2.data.StatResponse;
\r
33 import com.indexdata.pz2utils4jsf.pazpar2.data.TermListsResponse;
\r
34 import com.indexdata.pz2utils4jsf.pazpar2.data.TermResponse;
\r
35 import com.indexdata.pz2utils4jsf.pazpar2.state.StateListener;
\r
36 import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager;
\r
37 import com.indexdata.pz2utils4jsf.utils.Utils;
\r
40 public class Pz2Session implements Pz2Interface, StateListener {
\r
42 private static final long serialVersionUID = 3947514708343320514L;
\r
43 private static Logger logger = Logger.getLogger(Pz2Session.class);
\r
45 protected Map<String,Pazpar2ResponseData> dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();
\r
47 @Inject StateManager stateMgr;
\r
48 @Inject Pazpar2Commands req;
\r
50 protected ErrorHelper errorHelper = null;
\r
52 protected List<ErrorInterface> configurationErrors = null;
\r
53 protected SearchClient searchClient = null;
\r
54 protected SingleTargetFilter singleTargetFilter = null;
\r
55 protected ResultsPager pager = null;
\r
57 public Pz2Session () {
\r
58 logger.info("Instantiating pz2 session object [" + Utils.objectId(this) + "]");
\r
62 public void listenToStateManager() {
\r
63 logger.debug("in post-construct of Pz2Session stateMgr is " + stateMgr);
\r
64 logger.debug("in post-construct req is " + req);
\r
65 stateMgr.addStateListener(this);
\r
68 public void configureClient(SearchClient searchClient, ConfigurationReader configReader) {
\r
69 configurationErrors = new ArrayList<ErrorInterface>();
\r
70 errorHelper = new ErrorHelper(configReader);
\r
71 logger.debug(Utils.objectId(this) + " will configure search client for the session");
\r
73 searchClient.configure(configReader);
\r
74 // At the time of writing this search client is injected using Weld.
\r
75 // However, the client is used for asynchronously sending off requests
\r
76 // to the server AND propagation of context to threads is currently
\r
77 // not supported. Trying to do so throws a WELD-001303 error.
\r
78 // To avoid that, a context free client is cloned from the context
\r
80 // If propagation to threads gets supported, the cloning can go.
\r
81 this.searchClient = searchClient.cloneMe();
\r
82 } catch (ConfigurationException e) {
\r
83 configurationErrors.add(new ConfigurationError("Search Client","Configuration",e.getMessage(),new ErrorHelper(configReader)));
\r
85 logger.info(configReader.document());
\r
89 public void doSearch(String query) {
\r
90 setCommandParameter("search",new CommandParameter("query","=",query));
\r
94 public void doSearch() {
\r
95 stateMgr.hasPendingStateChange("search",false);
\r
97 removeCommand("record");
\r
98 setCommandParameter("show",new CommandParameter("start","=",0));
\r
99 logger.debug(Utils.objectId(this) + " is searching using "+req.getCommandReadOnly("search").getUrlEncodedParameterValue("query"));
\r
100 doCommand("search");
\r
104 * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2
\r
106 * @return Number of activeclients at the time of the 'show' command.
\r
108 public String update () {
\r
109 logger.debug("Updating show,stat,termlist,bytarget from pazpar2");
\r
110 return update("show,stat,termlist,bytarget");
\r
114 * Refreshes the data objects listed in 'commands' from pazpar2
\r
117 * @return Number of activeclients at the time of the 'show' command
\r
119 public String update (String commands) {
\r
120 if (! hasConfigurationErrors()) {
\r
122 handleQueryStateChanges(commands);
\r
123 logger.debug("Processing request for " + commands);
\r
124 List<CommandThread> threadList = new ArrayList<CommandThread>();
\r
125 StringTokenizer tokens = new StringTokenizer(commands,",");
\r
126 while (tokens.hasMoreElements()) {
\r
127 threadList.add(new CommandThread(req.getCommandReadOnly(tokens.nextToken()),searchClient));
\r
129 for (CommandThread thread : threadList) {
\r
132 for (CommandThread thread : threadList) {
\r
135 } catch (InterruptedException e) {
\r
136 e.printStackTrace();
\r
139 for (CommandThread thread : threadList) {
\r
140 String commandName = thread.getCommand().getName();
\r
141 String response = thread.getResponse();
\r
142 logger.debug("Response was: " + response);
\r
143 Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(response);
\r
144 dataObjects.put(commandName, responseObject);
\r
146 if (commands.equals("record")) {
\r
147 logger.debug("Record: Active clients: "+getRecord().getActiveClients());
\r
148 return getRecord().getActiveClients();
\r
150 return getActiveClients();
\r
153 logger.debug("Skipped requests for " + commands + " as there's not yet a query.");
\r
154 resetDataObjects();
\r
158 logger.error("Did not attempt to execute query since there are configuration errors.");
\r
165 public void setQuery (String query) {
\r
166 logger.debug("Creating new command parameter for " + query);
\r
167 setCommandParameter("search",new CommandParameter("query","=",query));
\r
170 public String getQuery () {
\r
171 return getCommandParameterValueSimple("search","query",null);
\r
175 public void setFacet (String facetKey, String term) {
\r
176 if (term != null && term.length()>0) {
\r
177 Pazpar2Command command = req.getCommand("search");
\r
178 command.getParameter("query").addExpression(new Expression(facetKey,"=",term));
\r
179 stateMgr.checkIn(command);
\r
184 public void setFacetOnQuery (String facetKey, String term) {
\r
185 String facetExpression = facetKey + "=" + term;
\r
186 if (term != null && term.length()>0) {
\r
187 String currentQuery= req.getCommandReadOnly("search").getParameterValue("query");
\r
188 setCommandParameter("search",new CommandParameter("query","=", currentQuery + " and " + facetExpression));
\r
193 public void removeFacet(String facetKey, String term) {
\r
194 SearchCommand command = req.getSearch();
\r
195 command.getParameter("query").removeExpression(new Expression(facetKey,"=",term));
\r
196 stateMgr.checkIn(command);
\r
200 public void setSingleTargetFilter (String targetId, String targetName) {
\r
201 if (hasSingleTargetFilter(new SingleTargetFilter(targetId,targetName))) {
\r
202 logger.debug("Already using target filter " + this.singleTargetFilter.getFilterExpression());
\r
204 this.singleTargetFilter = new SingleTargetFilter(targetId,targetName);
\r
205 setCommandParameter("search",new CommandParameter("filter","=",this.singleTargetFilter.getFilterExpression()));
\r
210 public SingleTargetFilter getSingleTargetFilter () {
\r
211 return singleTargetFilter;
\r
214 public void removeSingleTargetFilter () {
\r
215 logger.debug("Removing target filter " + singleTargetFilter.getFilterExpression());
\r
216 this.singleTargetFilter = null;
\r
217 removeCommandParameter("search","filter");
\r
221 public boolean hasSingleTargetFilter() {
\r
222 return singleTargetFilter != null;
\r
225 public String toggleRecord (String recId) {
\r
226 if (hasRecord(recId)) {
\r
227 removeCommand("record");
\r
228 dataObjects.put("record", new RecordResponse());
\r
231 setRecordId(recId);
\r
232 return doCommand("record");
\r
237 public void setRecordId(String recId) {
\r
238 setCommandParameter("record",new CommandParameter("id","=",recId));
\r
242 public String getRecordId () {
\r
243 return getCommandParameterValue("record","recid","");
\r
247 public boolean hasRecord (String recId) {
\r
248 return req.getCommandReadOnly("record").hasParameters() && getRecord().getRecId().equals(recId);
\r
251 public ShowResponse getShow () {
\r
252 return ((ShowResponse) dataObjects.get("show"));
\r
255 public StatResponse getStat () {
\r
256 return ((StatResponse) dataObjects.get("stat"));
\r
259 public RecordResponse getRecord() {
\r
260 return ((RecordResponse) dataObjects.get("record"));
\r
263 public TermListsResponse getTermLists () {
\r
264 return ((TermListsResponse) dataObjects.get("termlist"));
\r
267 public List<TermResponse> getFacetTerms (String facet, int count) {
\r
268 return (getTermLists().getTermList(facet).getTerms(count));
\r
271 public List<TermResponse> getFacetTerms (String facet) {
\r
272 return (getTermLists().getTermList(facet).getTerms());
\r
275 public ByTarget getByTarget() {
\r
276 return ((ByTarget) dataObjects.get("bytarget"));
\r
280 public String getCurrentStateKey () {
\r
281 return stateMgr.getCurrentState().getKey();
\r
284 public void setCurrentStateKey(String key) {
\r
285 stateMgr.setCurrentStateKey(key);
\r
288 public boolean hasConfigurationErrors () {
\r
289 return (configurationErrors.size()>0);
\r
292 public boolean hasCommandErrors () {
\r
293 if (dataObjects.get("search").hasApplicationError()) {
\r
294 logger.info("Error detected in search");
\r
297 for (String name : dataObjects.keySet()) {
\r
298 if (dataObjects.get(name).hasApplicationError()) {
\r
299 logger.info("Error detected in " + name);
\r
307 * Returns true if application error found in any response data objects
\r
309 public boolean hasErrors () {
\r
310 return hasConfigurationErrors() || hasCommandErrors();
\r
313 public List<ErrorInterface> getConfigurationErrors() {
\r
314 return configurationErrors;
\r
318 * Returns a search command error, if any, otherwise the first
\r
319 * error found for an arbitrary command, if any, otherwise
\r
320 * an empty dummy error.
\r
322 public ErrorInterface getCommandError() {
\r
323 CommandError error = new CommandError();
\r
324 if (dataObjects.get("search").hasApplicationError()) {
\r
325 error = dataObjects.get("search").getApplicationError();
\r
327 for (String name : dataObjects.keySet()) {
\r
328 if (dataObjects.get(name).hasApplicationError()) {
\r
329 error = dataObjects.get(name).getApplicationError();
\r
334 error.setErrorHelper(errorHelper);
\r
339 protected boolean hasSingleTargetFilter(SingleTargetFilter targetFilter) {
\r
340 return hasSingleTargetFilter() && targetFilter.equals(this.singleTargetFilter);
\r
343 protected boolean hasQuery() {
\r
344 return req.getSearch().getParameter("query") != null && req.getSearch().getParameter("query").getValueWithExpressions().length()>0;
\r
347 public boolean hasRecords () {
\r
348 return getStat().getRecords() > 0
\r
349 && getShow().getHits() != null
\r
350 && getShow().getHits().size()>0;
\r
353 public ResultsPager getPager () {
\r
354 if (pager == null) {
\r
355 pager = new ResultsPager(this);
\r
360 public ResultsPager setPager (int pageRange) {
\r
361 pager = new ResultsPager(this,pageRange,req);
\r
365 protected ErrorHelper getTroubleshooter() {
\r
366 return errorHelper;
\r
369 protected void handleQueryStateChanges (String commands) {
\r
370 if (stateMgr.hasPendingStateChange("search") && hasQuery()) {
\r
371 logger.debug("Found pending search change. Doing search before updating " + commands);
\r
374 if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {
\r
375 logger.debug("Found pending record ID change. Doing record before updating " + commands);
\r
376 stateMgr.hasPendingStateChange("record",false);
\r
377 if (req.getCommandReadOnly("record").hasParameters()) {
\r
380 removeCommand("record");
\r
381 dataObjects.put("record", new RecordResponse());
\r
386 protected String getActiveClients() {
\r
387 if (getShow()!=null) {
\r
388 logger.debug("Active clients: "+getShow().getActiveClients());
\r
389 return getShow().getActiveClients();
\r
396 * Returns a Pazpar2 command 'detached' from the current Pazpar2 state.
\r
398 * 'Detached' is meant to imply that this is a copy of a command in the
\r
399 * current state, detached so as to NOT change the current state if
\r
400 * modified. It can be viewed and executed, however.
\r
402 * In order to modify the command with effect for subsequent searches,
\r
403 * it must be checked back into the StateManager, which will
\r
404 * then create a new current Pazpar2 state as needed.
\r
409 protected Pazpar2Command getCommand(String name) {
\r
410 return req.getCommand(name);
\r
414 * Returns an interface to a Pazpar2Command with only String getters.
\r
416 * Since the command cannot be modified (unless it is cast) we can avoid
\r
417 * cloning it before returning it from the current state.
\r
418 * It can be used for log statements, checks and for performing the
\r
419 * actual pazpar2 request.
\r
424 protected CommandReadOnly getCommandReadOnly(String name) {
\r
425 return req.getCommandReadOnly(name);
\r
429 protected void setCommandParameter(String commandName, CommandParameter parameter) {
\r
430 logger.debug("Setting parameter for " + commandName + ": " + parameter);
\r
431 Pazpar2Command command = req.getCommand(commandName);
\r
432 command.setParameter(parameter);
\r
433 stateMgr.checkIn(command);
\r
437 protected void removeCommandParameter(String commandName, String parameterName) {
\r
438 Pazpar2Command command = req.getCommand(commandName);
\r
439 command.removeParameter(parameterName);
\r
440 stateMgr.checkIn(command);
\r
443 protected void removeCommand (String commandName) {
\r
444 Pazpar2Command command = req.getCommand(commandName);
\r
445 command.removeParameters();
\r
446 stateMgr.checkIn(command);
\r
449 protected String getCommandParameterValue (String commandName, String parameterName, String defaultValue) {
\r
450 CommandReadOnly command = req.getCommandReadOnly(commandName);
\r
451 if (command != null) {
\r
452 String parameter = command.getParameterValue(parameterName);
\r
453 if (parameter != null) {
\r
457 return defaultValue;
\r
460 protected int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {
\r
461 CommandReadOnly command = req.getCommandReadOnly(commandName);
\r
462 if (command != null) {
\r
463 String parameter = command.getParameterValue(parameterName);
\r
464 if (parameter != null) {
\r
465 return Integer.parseInt(parameter);
\r
468 return defaultValue;
\r
471 protected String doCommand(String commandName) {
\r
472 logger.debug(req.getCommandReadOnly(commandName).getEncodedQueryString() + ": Results for "+ req.getCommandReadOnly("search").getEncodedQueryString());
\r
473 return update(commandName);
\r
476 protected void resetDataObjects() {
\r
477 logger.debug("Resetting show,stat,termlist,bytarget,search response objects.");
\r
478 dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();
\r
479 dataObjects.put("show", new ShowResponse());
\r
480 dataObjects.put("stat", new StatResponse());
\r
481 dataObjects.put("termlist", new TermListsResponse());
\r
482 dataObjects.put("bytarget", new ByTarget());
\r
483 dataObjects.put("record", new RecordResponse());
\r
484 dataObjects.put("search", new SearchResponse());
\r
488 public void setFilter(String filterExpression) {
\r
489 logger.debug("Setting filter to " + filterExpression);
\r
490 setCommandParameter("search",new CommandParameter("filter","=",filterExpression));
\r
493 public String getFilter() {
\r
494 return getCommandParameterValue("search", "filter", "");
\r
497 public boolean hasFilter () {
\r
498 return getFilter().length()>0;
\r
502 public void stateUpdate(String commandName) {
\r
503 logger.debug("State change reported for [" + commandName + "]");
\r
504 if (commandName.equals("show")) {
\r
505 logger.debug("Updating show");
\r
506 update(commandName);
\r