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.enterprise.context.SessionScoped;
\r
11 import javax.inject.Inject;
\r
13 import org.apache.log4j.Logger;
\r
15 import com.indexdata.pz2utils4jsf.config.ConfigurationReader;
\r
16 import com.indexdata.pz2utils4jsf.controls.ResultsPager;
\r
17 import com.indexdata.pz2utils4jsf.errors.ConfigurationError;
\r
18 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;
\r
19 import com.indexdata.pz2utils4jsf.errors.ErrorHelper;
\r
20 import com.indexdata.pz2utils4jsf.errors.ErrorInterface;
\r
21 import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter;
\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.data.ByTarget;
\r
25 import com.indexdata.pz2utils4jsf.pazpar2.data.CommandError;
\r
26 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData;
\r
27 import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseParser;
\r
28 import com.indexdata.pz2utils4jsf.pazpar2.data.RecordResponse;
\r
29 import com.indexdata.pz2utils4jsf.pazpar2.data.SearchResponse;
\r
30 import com.indexdata.pz2utils4jsf.pazpar2.data.ShowResponse;
\r
31 import com.indexdata.pz2utils4jsf.pazpar2.data.StatResponse;
\r
32 import com.indexdata.pz2utils4jsf.pazpar2.data.TermListsResponse;
\r
33 import com.indexdata.pz2utils4jsf.pazpar2.data.TermResponse;
\r
34 import com.indexdata.pz2utils4jsf.pazpar2.state.StateListener;
\r
35 import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager;
\r
36 import com.indexdata.pz2utils4jsf.utils.Utils;
\r
39 public class Pz2Session implements Pz2Interface, StateListener {
\r
41 private static final long serialVersionUID = 3947514708343320514L;
\r
42 private static Logger logger = Logger.getLogger(Pz2Session.class);
\r
44 protected Map<String,Pazpar2ResponseData> dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();
\r
46 @Inject StateManager stateMgr;
\r
47 @Inject Pazpar2Commands req;
\r
49 protected ErrorHelper errorHelper = null;
\r
51 protected List<ErrorInterface> configurationErrors = null;
\r
52 protected SearchClient searchClient = null;
\r
53 protected SingleTargetFilter singleTargetFilter = null;
\r
54 protected ResultsPager pager = null;
\r
56 public Pz2Session () {
\r
57 logger.info("Instantiating pz2 session object [" + Utils.objectId(this) + "]");
\r
61 public void listenToStateManager() {
\r
62 logger.debug("in post-construct of Pz2Session stateMgr is " + stateMgr);
\r
63 logger.debug("in post-construct req is " + req);
\r
64 stateMgr.addStateListener(this);
\r
67 public void configureClient(SearchClient searchClient, ConfigurationReader configReader) {
\r
68 configurationErrors = new ArrayList<ErrorInterface>();
\r
69 errorHelper = new ErrorHelper(configReader);
\r
70 logger.debug(Utils.objectId(this) + " will configure search client for the session");
\r
72 searchClient.configure(configReader);
\r
73 // At the time of writing this search client is injected using Weld.
\r
74 // However, the client is used for asynchronously sending off requests
\r
75 // to the server AND propagation of context to threads is currently
\r
76 // not supported. Trying to do so throws a WELD-001303 error.
\r
77 // To avoid that, a context free client is cloned from the context
\r
79 // If propagation to threads gets supported, the cloning can go.
\r
80 this.searchClient = searchClient.cloneMe();
\r
81 } catch (ConfigurationException e) {
\r
82 configurationErrors.add(new ConfigurationError("Search Client","Configuration",e.getMessage(),new ErrorHelper(configReader)));
\r
84 logger.info(configReader.document());
\r
88 public void doSearch(String query) {
\r
89 setCommandParameter("search",new CommandParameter("query","=",query));
\r
93 public void doSearch() {
\r
94 stateMgr.hasPendingStateChange("search",false);
\r
96 removeCommand("record");
\r
97 setCommandParameter("show",new CommandParameter("start","=",0));
\r
98 logger.debug(Utils.objectId(this) + " is searching using "+getCommand("search").getParameter("query").getEncodedQueryString());
\r
99 doCommand("search");
\r
103 * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2
\r
105 * @return Number of activeclients at the time of the 'show' command.
\r
107 public String update () {
\r
108 logger.debug("Updating show,stat,termlist,bytarget from pazpar2");
\r
109 return update("show,stat,termlist,bytarget");
\r
113 * Refreshes the data objects listed in 'commands' from pazpar2
\r
116 * @return Number of activeclients at the time of the 'show' command
\r
118 public String update (String commands) {
\r
119 if (! hasConfigurationErrors()) {
\r
121 handleQueryStateChanges(commands);
\r
122 logger.debug("Processing request for " + commands);
\r
123 List<CommandThread> threadList = new ArrayList<CommandThread>();
\r
124 StringTokenizer tokens = new StringTokenizer(commands,",");
\r
125 while (tokens.hasMoreElements()) {
\r
126 threadList.add(new CommandThread(getCommand(tokens.nextToken()),searchClient));
\r
128 for (CommandThread thread : threadList) {
\r
131 for (CommandThread thread : threadList) {
\r
134 } catch (InterruptedException e) {
\r
135 e.printStackTrace();
\r
138 for (CommandThread thread : threadList) {
\r
139 String commandName = thread.getCommand().getName();
\r
140 String response = thread.getResponse();
\r
141 logger.debug("Response was: " + response);
\r
142 Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(response);
\r
143 dataObjects.put(commandName, responseObject);
\r
145 if (commands.equals("record")) {
\r
146 logger.debug("Record: Active clients: "+getRecord().getActiveClients());
\r
147 return getRecord().getActiveClients();
\r
149 return getActiveClients();
\r
152 logger.debug("Skipped requests for " + commands + " as there's not yet a query.");
\r
153 resetDataObjects();
\r
157 logger.error("Did not attempt to execute query since there are configuration errors.");
\r
163 public void setQuery (String query) {
\r
164 logger.debug("Creating new command parameter for " + query);
\r
165 setCommandParameter("search",new CommandParameter("query","=",query));
\r
168 public String getQuery () {
\r
169 return getCommandParameterValueSimple("search","query",null);
\r
172 public void setFacet (String facetKey, String term) {
\r
173 if (term != null && term.length()>0) {
\r
174 Pazpar2Command command = getCommand("search");
\r
175 command.getParameter("query").addExpression(new Expression(facetKey,"=",term));
\r
176 stateMgr.checkIn(command);
\r
181 public void setFacetOnQuery (String facetKey, String term) {
\r
182 String facetExpression = facetKey + "=" + term;
\r
183 if (term != null && term.length()>0) {
\r
184 setCommandParameter("search",new CommandParameter("query","=", getQuery() + " and " + facetExpression));
\r
189 public void removeFacet(String facetKey, String term) {
\r
190 Pazpar2Command command = getCommand("search");
\r
191 command.getParameter("query").removeExpression(new Expression(facetKey,"=",term));
\r
192 stateMgr.checkIn(command);
\r
196 public void setSingleTargetFilter (String targetId, String targetName) {
\r
197 if (hasSingleTargetFilter(new SingleTargetFilter(targetId,targetName))) {
\r
198 logger.debug("Already using target filter " + this.singleTargetFilter.getFilterExpression());
\r
200 this.singleTargetFilter = new SingleTargetFilter(targetId,targetName);
\r
201 setCommandParameter("search",new CommandParameter("filter","=",this.singleTargetFilter.getFilterExpression()));
\r
206 public SingleTargetFilter getSingleTargetFilter () {
\r
207 return singleTargetFilter;
\r
210 public void removeSingleTargetFilter () {
\r
211 logger.debug("Removing target filter " + singleTargetFilter.getFilterExpression());
\r
212 this.singleTargetFilter = null;
\r
213 removeCommandParameter("search","filter");
\r
217 public boolean hasSingleTargetFilter() {
\r
218 return singleTargetFilter != null;
\r
221 public void setSort (String sortOption) {
\r
222 logger.debug("Setting sort option: " + sortOption);
\r
223 setCommandParameter("show",new CommandParameter("sort","=",sortOption));
\r
227 public String getSort () {
\r
228 return getCommandParameterValue("show","sort","relevance");
\r
231 public void setPageSize (int perPageOption) {
\r
232 if (getPageSize()!=perPageOption) {
\r
233 logger.debug("Setting perpage option to " + perPageOption + " and resetting start page.");
\r
234 setCommandParameter("show",new CommandParameter("num","=",perPageOption));
\r
235 setCommandParameter("show",new CommandParameter("start","=",0));
\r
238 logger.debug("Not updating page size, already is " + perPageOption);
\r
242 public int getPageSize () {
\r
243 return getCommandParameterValue("show","num",20);
\r
246 public void setStart (int start) {
\r
247 logger.debug("Setting start num to " + start);
\r
248 setCommandParameter("show", new CommandParameter("start","=",start));
\r
252 public int getStart() {
\r
253 return getCommandParameterValue("show","start",0);
\r
256 public String toggleRecord (String recId) {
\r
257 if (hasRecord(recId)) {
\r
258 removeCommand("record");
\r
259 dataObjects.put("record", new RecordResponse());
\r
262 setRecordId(recId);
\r
263 return doCommand("record");
\r
268 public void setRecordId(String recId) {
\r
269 setCommandParameter("record",new CommandParameter("id","=",recId));
\r
273 public String getRecordId () {
\r
274 return getCommandParameterValue("record","recid","");
\r
278 public boolean hasRecord (String recId) {
\r
279 return getCommand("record").hasParameters() && getRecord().getRecId().equals(recId);
\r
282 public ShowResponse getShow () {
\r
283 return ((ShowResponse) dataObjects.get("show"));
\r
286 public StatResponse getStat () {
\r
287 return ((StatResponse) dataObjects.get("stat"));
\r
290 public RecordResponse getRecord() {
\r
291 return ((RecordResponse) dataObjects.get("record"));
\r
294 public TermListsResponse getTermLists () {
\r
295 return ((TermListsResponse) dataObjects.get("termlist"));
\r
298 public List<TermResponse> getFacetTerms (String facet, int count) {
\r
299 return (getTermLists().getTermList(facet).getTerms(count));
\r
302 public List<TermResponse> getFacetTerms (String facet) {
\r
303 return (getTermLists().getTermList(facet).getTerms());
\r
306 public ByTarget getByTarget() {
\r
307 return ((ByTarget) dataObjects.get("bytarget"));
\r
311 public String getCurrentStateKey () {
\r
312 return stateMgr.getCurrentState().getKey();
\r
315 public void setCurrentStateKey(String key) {
\r
316 stateMgr.setCurrentStateKey(key);
\r
319 public boolean hasConfigurationErrors () {
\r
320 return (configurationErrors.size()>0);
\r
323 public boolean hasCommandErrors () {
\r
324 if (dataObjects.get("search").hasApplicationError()) {
\r
325 logger.info("Error detected in search");
\r
328 for (String name : dataObjects.keySet()) {
\r
329 if (dataObjects.get(name).hasApplicationError()) {
\r
330 logger.info("Error detected in " + name);
\r
338 * Returns true if application error found in any response data objects
\r
340 public boolean hasErrors () {
\r
341 return hasConfigurationErrors() || hasCommandErrors();
\r
344 public List<ErrorInterface> getConfigurationErrors() {
\r
345 return configurationErrors;
\r
349 * Returns a search command error, if any, otherwise the first
\r
350 * error found for an arbitrary command, if any, otherwise
\r
351 * an empty dummy error.
\r
353 public ErrorInterface getCommandError() {
\r
354 CommandError error = new CommandError();
\r
355 if (dataObjects.get("search").hasApplicationError()) {
\r
356 error = dataObjects.get("search").getApplicationError();
\r
358 for (String name : dataObjects.keySet()) {
\r
359 if (dataObjects.get(name).hasApplicationError()) {
\r
360 error = dataObjects.get(name).getApplicationError();
\r
365 error.setErrorHelper(errorHelper);
\r
370 protected boolean hasSingleTargetFilter(SingleTargetFilter targetFilter) {
\r
371 return hasSingleTargetFilter() && targetFilter.equals(this.singleTargetFilter);
\r
374 protected boolean hasQuery() {
\r
375 logger.debug("req is " + req);
\r
376 return req.getSearch().getParameter("query") != null && req.getSearch().getParameter("query").getValueWithExpressions().length()>0;
\r
379 public boolean hasRecords () {
\r
380 return getStat().getRecords() > 0
\r
381 && getShow().getHits() != null
\r
382 && getShow().getHits().size()>0;
\r
385 public ResultsPager getPager () {
\r
386 if (pager == null) {
\r
387 pager = new ResultsPager(this);
\r
392 public ResultsPager setPager (int pageRange) {
\r
393 pager = new ResultsPager(this,pageRange);
\r
397 protected ErrorHelper getTroubleshooter() {
\r
398 return errorHelper;
\r
401 protected void handleQueryStateChanges (String commands) {
\r
402 if (stateMgr.hasPendingStateChange("search") && hasQuery()) {
\r
403 logger.debug("Found pending search change. Doing search before updating " + commands);
\r
406 if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {
\r
407 logger.debug("Found pending record ID change. Doing record before updating " + commands);
\r
408 stateMgr.hasPendingStateChange("record",false);
\r
409 if (getCommand("record").hasParameters()) {
\r
412 removeCommand("record");
\r
413 dataObjects.put("record", new RecordResponse());
\r
418 protected String getActiveClients() {
\r
419 if (getShow()!=null) {
\r
420 logger.debug("Active clients: "+getShow().getActiveClients());
\r
421 return getShow().getActiveClients();
\r
428 * Returns a Pazpar2 command 'detached' from the current Pazpar2 state.
\r
430 * 'Detached' is meant to imply that this is a copy of a command in the
\r
431 * current state, detached so as to NOT change the current state if
\r
432 * modified. It can be viewed and executed, however.
\r
434 * In order to modify the command with effect for subsequent searches,
\r
435 * it must be checked back into the StateManager, which will
\r
436 * then create a new current Pazpar2 state as needed.
\r
441 protected Pazpar2Command getCommand(String name) {
\r
442 return stateMgr.checkOut(name);
\r
445 protected void setCommandParameter(String commandName, CommandParameter parameter) {
\r
446 logger.debug("Setting parameter for " + commandName + ": " + parameter);
\r
447 Pazpar2Command command = getCommand(commandName);
\r
448 command.setParameter(parameter);
\r
449 stateMgr.checkIn(command);
\r
453 protected void removeCommandParameter(String commandName, String parameterName) {
\r
454 Pazpar2Command command = getCommand(commandName);
\r
455 command.removeParameter(parameterName);
\r
456 stateMgr.checkIn(command);
\r
459 protected void removeCommand (String commandName) {
\r
460 Pazpar2Command command = getCommand(commandName);
\r
461 command.removeParameters();
\r
462 stateMgr.checkIn(command);
\r
465 protected String getCommandParameterValue (String commandName, String parameterName, String defaultValue) {
\r
466 Pazpar2Command command = getCommand(commandName);
\r
467 if (command != null) {
\r
468 CommandParameter parameter = command.getParameter(parameterName);
\r
469 if (parameter != null) {
\r
470 return parameter.getValueWithExpressions();
\r
473 return defaultValue;
\r
476 protected String getCommandParameterValueSimple (String commandName, String parameterName, String defaultValue) {
\r
477 Pazpar2Command command = getCommand(commandName);
\r
478 if (command != null) {
\r
479 CommandParameter parameter = command.getParameter(parameterName);
\r
480 if (parameter != null) {
\r
481 return parameter.getSimpleValue();
\r
484 return defaultValue;
\r
488 protected int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {
\r
489 Pazpar2Command command = getCommand(commandName);
\r
490 if (command != null) {
\r
491 CommandParameter parameter = command.getParameter(parameterName);
\r
492 if (parameter != null) {
\r
493 return Integer.parseInt(parameter.getSimpleValue());
\r
496 return defaultValue;
\r
499 protected String doCommand(String commandName) {
\r
500 Pazpar2Command command = req.getCommand(commandName);
\r
501 logger.debug(command.getEncodedQueryString() + ": Results for "+ getCommand("search").getEncodedQueryString());
\r
502 return update(commandName);
\r
505 protected void resetDataObjects() {
\r
506 logger.debug("Resetting show,stat,termlist,bytarget,search response objects.");
\r
507 dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();
\r
508 dataObjects.put("show", new ShowResponse());
\r
509 dataObjects.put("stat", new StatResponse());
\r
510 dataObjects.put("termlist", new TermListsResponse());
\r
511 dataObjects.put("bytarget", new ByTarget());
\r
512 dataObjects.put("record", new RecordResponse());
\r
513 dataObjects.put("search", new SearchResponse());
\r
517 public void setFilter(String filterExpression) {
\r
518 logger.debug("Setting filter to " + filterExpression);
\r
519 setCommandParameter("search",new CommandParameter("filter","=",filterExpression));
\r
522 public String getFilter() {
\r
523 return getCommandParameterValueSimple("search", "filter", "");
\r
526 public boolean hasFilter () {
\r
527 return getFilter().length()>0;
\r
531 public void stateUpdate(String commandName) {
\r
532 logger.debug("State change reported for [" + commandName + "]");
\r
533 if (commandName.equals("show")) {
\r
534 logger.debug("Updating show");
\r
535 update(commandName);
\r