1 package com.indexdata.pz2utils4jsf.pazpar2;
\r
3 import java.io.IOException;
\r
4 import java.util.ArrayList;
\r
5 import java.util.List;
\r
6 import java.util.Map;
\r
7 import java.util.StringTokenizer;
\r
8 import java.util.concurrent.ConcurrentHashMap;
\r
10 import javax.enterprise.context.SessionScoped;
\r
11 import javax.inject.Named;
\r
13 import org.apache.log4j.Logger;
\r
15 import com.indexdata.masterkey.pazpar2.client.Pazpar2Client;
\r
16 import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientConfiguration;
\r
17 import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientGeneric;
\r
18 import com.indexdata.masterkey.pazpar2.client.exceptions.ProxyErrorException;
\r
19 import com.indexdata.pz2utils4jsf.config.Pz2Configurator;
\r
20 import com.indexdata.pz2utils4jsf.controls.ResultsPager;
\r
21 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;
\r
22 import com.indexdata.pz2utils4jsf.errors.ErrorInterface;
\r
23 import com.indexdata.pz2utils4jsf.errors.ErrorHelper;
\r
24 import com.indexdata.pz2utils4jsf.errors.ConfigurationError;
\r
25 import com.indexdata.pz2utils4jsf.pazpar2.data.CommandError;
\r
26 import com.indexdata.pz2utils4jsf.pazpar2.data.ByTarget;
\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.QueryStates;
\r
36 import com.indexdata.pz2utils4jsf.utils.Utils;
\r
38 @Named @SessionScoped
\r
39 public class Pz2Session implements Pz2Interface {
\r
41 private static Logger logger = Logger.getLogger(Pz2Session.class);
\r
43 private Map<String,Pazpar2ResponseData> dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();
\r
44 private QueryStates queryStates = new QueryStates();
\r
46 private static final long serialVersionUID = 3947514708343320514L;
\r
47 private Pazpar2ClientConfiguration cfg = null;
\r
48 private Pazpar2Client client = null;
\r
49 private TargetFilter targetFilter = null;
\r
50 private ResultsPager pager = null;
\r
51 private ErrorHelper errorHelper = null;
\r
52 private List<ErrorInterface> configurationErrors = null;
\r
54 public Pz2Session () {
\r
55 logger.info("Instantiating pz2 session object [" + Utils.objectId(this) + "]");
\r
58 public void init(Pz2Configurator pz2conf) {
\r
60 configurationErrors = new ArrayList<ErrorInterface>();
\r
61 errorHelper = new ErrorHelper(pz2conf);
\r
62 logger.info(Utils.objectId(this) + " is configuring itself using the provided " + Utils.objectId(pz2conf));
\r
64 cfg = new Pazpar2ClientConfiguration(pz2conf.getConfig());
\r
65 } catch (ProxyErrorException pe) {
\r
66 logger.error("Could not configure Pazpar2 client: " + pe.getMessage());
\r
67 configurationErrors.add(new ConfigurationError("Pz2Client Config","ProxyError","Could not configure Pazpar2 client: " + pe.getMessage(),errorHelper));
\r
68 } catch (ConfigurationException io) {
\r
69 logger.error("Could not configure Pazpar2 client: " + io.getMessage());
\r
70 configurationErrors.add(new ConfigurationError("Pz2Client Config","ProxyError","Could not configure Pazpar2 client: " + io.getMessage(),errorHelper));
\r
74 client = new Pazpar2ClientGeneric(cfg);
\r
75 } catch (ProxyErrorException pe) {
\r
76 logger.error("Could not instantiate Pazpar2 client: " + pe.getMessage());
\r
77 configurationErrors.add(new ConfigurationError("Pz2Client error","ProxyError","Could not create Pazpar2 client: " +pe.getMessage(),errorHelper));
\r
79 logger.info("Found " + configurationErrors.size() + " configuration errors");
\r
83 logger.warn("Attempt to configure session but it already has a configured client");
\r
87 public void doSearch(String query) {
\r
88 setCommandParameter("search",new CommandParameter("query","=",query));
\r
92 public void doSearch() {
\r
93 queryStates.hasPendingStateChange("search",false);
\r
95 setCommandParameter("show",new CommandParameter("start","=",0));
\r
96 logger.debug(Utils.objectId(this) + " is searching using "+getCommand("search").getParameter("query").getEncodedQueryString());
\r
97 doCommand("search");
\r
101 * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2
\r
103 * @return Number of activeclients at the time of the 'show' command.
\r
105 public String update () {
\r
106 logger.debug("Updating show,stat,termlist,bytarget from pazpar2");
\r
107 return update("show,stat,termlist,bytarget");
\r
111 * Refreshes the data objects listed in 'commands' from pazpar2
\r
114 * @return Number of activeclients at the time of the 'show' command
\r
116 public String update (String commands) {
\r
117 if (! hasConfigurationErrors()) {
\r
119 handleQueryStateChanges(commands);
\r
120 logger.debug("Processing request for " + commands);
\r
121 List<CommandThread> threadList = new ArrayList<CommandThread>();
\r
122 StringTokenizer tokens = new StringTokenizer(commands,",");
\r
123 while (tokens.hasMoreElements()) {
\r
124 threadList.add(new CommandThread(getCommand(tokens.nextToken()),client));
\r
126 for (CommandThread thread : threadList) {
\r
129 for (CommandThread thread : threadList) {
\r
132 } catch (InterruptedException e) {
\r
133 e.printStackTrace();
\r
136 for (CommandThread thread : threadList) {
\r
137 String commandName = thread.getCommand().getName();
\r
138 Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(thread.getResponse());
\r
139 dataObjects.put(commandName, responseObject);
\r
141 return getActiveClients();
\r
143 logger.debug("Skipped requests for " + commands + " as there's not yet a query.");
\r
144 resetDataObjects();
\r
148 logger.error("Did not attempt to execute query since there are configuration errors.");
\r
154 public void setQuery (String query) {
\r
155 logger.debug("Creating new command parameter for " + query);
\r
156 setCommandParameter("search",new CommandParameter("query","=",query));
\r
159 public String getQuery () {
\r
160 return getCommandParameterValueSimple("search","query",null);
\r
163 public void setFacet (String facetKey, String term) {
\r
164 if (term != null && term.length()>0) {
\r
165 queryStates.getCurrentState().setCommandParameterExpression("search","query",new Expression(facetKey,"=",term),queryStates);
\r
170 public void setFacetOnQuery (String facetKey, String term) {
\r
171 String facetExpression = facetKey + "=" + term;
\r
172 if (term != null && term.length()>0) {
\r
173 setCommandParameter("search",new CommandParameter("query","=", getQuery() + " and " + facetExpression));
\r
178 public void removeFacet(String facetKey, String term) {
\r
179 queryStates.getCurrentState().removeCommandParameterExpression("search","query",new Expression(facetKey,"=",term),queryStates);
\r
183 public void setTargetFilter (String targetId, String targetName) {
\r
184 if (hasTargetFilter(new TargetFilter(targetId,targetName))) {
\r
185 logger.debug("Already using target filter " + this.targetFilter.getFilterExpression());
\r
187 this.targetFilter = new TargetFilter(targetId,targetName);
\r
188 setCommandParameter("search",new CommandParameter("filter","=",this.targetFilter.getFilterExpression()));
\r
193 public TargetFilter getTargetFilter () {
\r
194 return targetFilter;
\r
197 public void removeTargetFilter () {
\r
198 logger.debug("Removing target filter " + targetFilter.getFilterExpression());
\r
199 this.targetFilter = null;
\r
200 removeCommandParameter("search","filter");
\r
204 public boolean hasTargetFilter() {
\r
205 return targetFilter != null;
\r
208 public void setSort (String sortOption) {
\r
209 logger.debug("Setting sort option: " + sortOption);
\r
210 setCommandParameter("show",new CommandParameter("sort","=",sortOption));
\r
214 public String getSort () {
\r
215 return getCommandParameterValue("show","sort","relevance");
\r
218 public void setPageSize (int perPageOption) {
\r
219 if (getPageSize()!=perPageOption) {
\r
220 logger.debug("Setting perpage option to " + perPageOption + " and resetting start page.");
\r
221 setCommandParameter("show",new CommandParameter("num","=",perPageOption));
\r
222 setCommandParameter("show",new CommandParameter("start","=",0));
\r
225 logger.debug("Not updating page size, already is " + perPageOption);
\r
229 public int getPageSize () {
\r
230 return getCommandParameterValue("show","num",20);
\r
233 public void setStart (int start) {
\r
234 logger.debug("Setting start num to " + start);
\r
235 setCommandParameter("show", new CommandParameter("start","=",start));
\r
239 public int getStart() {
\r
240 return getCommandParameterValue("show","start",0);
\r
243 public String toggleRecord (String recId) {
\r
244 if (hasRecord(recId)) {
\r
245 removeCommand("record");
\r
246 dataObjects.put("record", new RecordResponse());
\r
249 return updateRecord(recId);
\r
253 private String updateRecord(String recId) {
\r
254 setCommandParameter("record",new CommandParameter("id","=",recId));
\r
255 return doCommand("record");
\r
258 public boolean hasRecord (String recId) {
\r
259 return getCommand("record").hasParameters() && getRecord().getRecId().equals(recId);
\r
262 public ShowResponse getShow () {
\r
263 return ((ShowResponse) dataObjects.get("show"));
\r
266 public StatResponse getStat () {
\r
267 return ((StatResponse) dataObjects.get("stat"));
\r
270 public RecordResponse getRecord() {
\r
271 return ((RecordResponse) dataObjects.get("record"));
\r
274 public TermListsResponse getTermLists () {
\r
275 return ((TermListsResponse) dataObjects.get("termlist"));
\r
278 public List<TermResponse> getFacetTerms (String facet, int count) {
\r
279 return (getTermLists().getTermList(facet).getTerms(count));
\r
282 public List<TermResponse> getFacetTerms (String facet) {
\r
283 return (getTermLists().getTermList(facet).getTerms());
\r
286 public ByTarget getByTarget() {
\r
287 return ((ByTarget) dataObjects.get("bytarget"));
\r
291 public String getCurrentStateKey () {
\r
292 return queryStates.getCurrentStateKey();
\r
295 public void setCurrentStateKey(String key) {
\r
296 queryStates.setCurrentStateKey(key);
\r
299 public boolean hasConfigurationErrors () {
\r
300 return (configurationErrors.size()>0);
\r
303 public boolean hasCommandErrors () {
\r
304 if (dataObjects.get("search").hasApplicationError()) {
\r
305 logger.info("Error detected in search");
\r
308 for (String name : dataObjects.keySet()) {
\r
309 if (dataObjects.get(name).hasApplicationError()) {
\r
310 logger.info("Error detected in " + name);
\r
318 * Returns true if application error found in any response data objects
\r
320 public boolean hasErrors () {
\r
321 return hasConfigurationErrors() || hasCommandErrors();
\r
324 public List<ErrorInterface> getConfigurationErrors() {
\r
325 return configurationErrors;
\r
329 * Returns a search command error, if any, otherwise the first
\r
330 * error found for an arbitrary command, if any, otherwise
\r
331 * an empty dummy error.
\r
333 public ErrorInterface getCommandError() {
\r
334 CommandError error = new CommandError();
\r
335 if (dataObjects.get("search").hasApplicationError()) {
\r
336 error = dataObjects.get("search").getApplicationError();
\r
338 for (String name : dataObjects.keySet()) {
\r
339 if (dataObjects.get(name).hasApplicationError()) {
\r
340 error = dataObjects.get(name).getApplicationError();
\r
345 error.setErrorHelper(errorHelper);
\r
350 private boolean hasTargetFilter(TargetFilter targetFilter) {
\r
351 return hasTargetFilter() && targetFilter.equals(this.targetFilter);
\r
354 private boolean hasQuery() {
\r
355 return !(getCommand("search").getParameter("query") == null);
\r
358 public boolean hasRecords () {
\r
359 return getStat().getRecords() > 0
\r
360 && getShow().getHits() != null
\r
361 && getShow().getHits().size()>0;
\r
364 public ResultsPager getPager () {
\r
365 if (pager == null) {
\r
366 pager = new ResultsPager(this);
\r
371 public ResultsPager setPager (int pageRange) {
\r
372 pager = new ResultsPager(this,pageRange);
\r
376 protected ErrorHelper getTroubleshooter() {
\r
377 return errorHelper;
\r
380 private void handleQueryStateChanges (String commands) {
\r
381 if (queryStates.hasPendingStateChange("search")) {
\r
382 logger.debug("Found pending search change. Doing search before updating " + commands);
\r
385 if (queryStates.hasPendingStateChange("record") && ! commands.equals("record")) {
\r
386 logger.debug("Found pending record ID change. Doing record before updating " + commands);
\r
387 queryStates.hasPendingStateChange("record",false);
\r
388 if (getCommand("record").hasParameters()) {
\r
389 updateRecord(getCommand("record").getParameter("id").getSimpleValue());
\r
391 removeCommand("record");
\r
392 dataObjects.put("record", new RecordResponse());
\r
397 private String getActiveClients() {
\r
398 if (getShow()!=null) {
\r
399 logger.debug("Active clients: "+getShow().getActiveClients());
\r
400 return getShow().getActiveClients();
\r
406 private Pazpar2Command getCommand(String name) {
\r
407 return queryStates.getCurrentState().getCommand(name);
\r
410 private void setCommandParameter(String commandName, CommandParameter parameter) {
\r
411 logger.debug("Setting parameter for " + commandName + ": " + parameter);
\r
412 queryStates.getCurrentState().setCommandParameter(commandName, parameter, queryStates);
\r
416 private void removeCommandParameter(String commandName, String parameterName) {
\r
417 queryStates.getCurrentState().removeCommandParameter(commandName,parameterName,queryStates);
\r
420 private void removeCommand (String commandName) {
\r
421 queryStates.getCurrentState().removeCommand(commandName, queryStates);
\r
424 private String getCommandParameterValue (String commandName, String parameterName, String defaultValue) {
\r
425 Pazpar2Command command = getCommand(commandName);
\r
426 if (command != null) {
\r
427 CommandParameter parameter = command.getParameter(parameterName);
\r
428 if (parameter != null) {
\r
429 return parameter.getValueWithExpressions();
\r
432 return defaultValue;
\r
435 private String getCommandParameterValueSimple (String commandName, String parameterName, String defaultValue) {
\r
436 Pazpar2Command command = getCommand(commandName);
\r
437 if (command != null) {
\r
438 CommandParameter parameter = command.getParameter(parameterName);
\r
439 if (parameter != null) {
\r
440 return parameter.getSimpleValue();
\r
443 return defaultValue;
\r
447 private int getCommandParameterValue (String commandName, String parameterName, int defaultValue) {
\r
448 Pazpar2Command command = getCommand(commandName);
\r
449 if (command != null) {
\r
450 CommandParameter parameter = command.getParameter(parameterName);
\r
451 if (parameter != null) {
\r
452 return Integer.parseInt(parameter.getSimpleValue());
\r
455 return defaultValue;
\r
458 private String doCommand(String commandName) {
\r
459 Pazpar2Command command = getCommand(commandName);
\r
460 logger.debug(command.getEncodedQueryString() + ": Results for "+ getCommand("search").getEncodedQueryString());
\r
461 return update(commandName);
\r
464 private void resetDataObjects() {
\r
465 logger.debug("Resetting show,stat,termlist,bytarget,search response objects.");
\r
466 dataObjects = new ConcurrentHashMap<String,Pazpar2ResponseData>();
\r
467 dataObjects.put("show", new ShowResponse());
\r
468 dataObjects.put("stat", new StatResponse());
\r
469 dataObjects.put("termlist", new TermListsResponse());
\r
470 dataObjects.put("bytarget", new ByTarget());
\r
471 dataObjects.put("record", new RecordResponse());
\r
472 dataObjects.put("search", new SearchResponse());
\r