1 package com.indexdata.mkjsf.pazpar2;
\r
3 import java.io.Serializable;
\r
4 import java.lang.annotation.Retention;
\r
5 import java.lang.annotation.Target;
\r
6 import java.util.ArrayList;
\r
7 import java.util.Arrays;
\r
8 import java.util.HashMap;
\r
9 import java.util.List;
\r
10 import java.util.Map;
\r
11 import java.util.StringTokenizer;
\r
13 import javax.annotation.PostConstruct;
\r
14 import javax.enterprise.context.SessionScoped;
\r
15 import javax.enterprise.inject.Produces;
\r
16 import javax.faces.context.FacesContext;
\r
17 import javax.inject.Inject;
\r
18 import javax.inject.Named;
\r
19 import javax.inject.Qualifier;
\r
21 import org.apache.log4j.Logger;
\r
23 import com.indexdata.mkjsf.config.Configurable;
\r
24 import com.indexdata.mkjsf.config.Configuration;
\r
25 import com.indexdata.mkjsf.config.ConfigurationReader;
\r
26 import com.indexdata.mkjsf.controls.ResultsPager;
\r
27 import com.indexdata.mkjsf.errors.ConfigurationError;
\r
28 import com.indexdata.mkjsf.errors.ConfigurationException;
\r
29 import com.indexdata.mkjsf.errors.ErrorCentral;
\r
30 import com.indexdata.mkjsf.errors.ErrorHelper;
\r
31 import com.indexdata.mkjsf.errors.MissingConfigurationContextException;
\r
32 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands;
\r
33 import com.indexdata.mkjsf.pazpar2.data.RecordResponse;
\r
34 import com.indexdata.mkjsf.pazpar2.data.Responses;
\r
35 import com.indexdata.mkjsf.pazpar2.state.StateListener;
\r
36 import com.indexdata.mkjsf.pazpar2.state.StateManager;
\r
37 import com.indexdata.mkjsf.utils.Utils;
\r
39 @Named("pz2") @SessionScoped
\r
40 public class Pz2Service implements StateListener, Configurable, Serializable {
\r
42 private static final String MODULE_NAME = "service";
\r
43 private static String SERVICE_TYPE_TBD = "TBD", SERVICE_TYPE_PZ2 = "PZ2", SERVICE_TYPE_SP = "SP";
\r
44 private static final List<String> serviceTypes =
\r
45 Arrays.asList(SERVICE_TYPE_PZ2,SERVICE_TYPE_SP,SERVICE_TYPE_TBD);
\r
46 private String serviceType = SERVICE_TYPE_TBD;
\r
47 private List<String> serviceProxyUrls = new ArrayList<String>();
\r
48 public static final String SERVICE_PROXY_URL_LIST = "SERVICE_PROXY_URL_LIST";
\r
49 private List<String> pazpar2Urls = new ArrayList<String>();
\r
50 public static final String PAZPAR2_URL_LIST = "PAZPAR2_URL_LIST";
\r
52 private static final long serialVersionUID = 3440277287081557861L;
\r
53 private static Logger logger = Logger.getLogger(Pz2Service.class);
\r
54 protected Pz2Client pz2Client = null;
\r
55 protected ServiceProxyClient spClient = null;
\r
56 protected SearchClient searchClient = null;
\r
58 @Inject ConfigurationReader configurator;
\r
60 private StateManager stateMgr = null;
\r
61 private Pazpar2Commands pzreq = null;
\r
62 private Responses pzresp = null;
\r
63 private ErrorCentral errors = null;
\r
65 protected ResultsPager pager = null;
\r
67 protected ErrorHelper errorHelper = null;
\r
69 public Pz2Service () {
\r
70 logger.info("Instantiating pz2 bean [" + Utils.objectId(this) + "]");
\r
73 public static Pz2Service get() {
\r
74 FacesContext context = FacesContext.getCurrentInstance();
\r
75 return (Pz2Service) context.getApplication().evaluateExpressionGet(context, "#{pz2}", Object.class);
\r
79 public void postConstruct() throws MissingConfigurationContextException {
\r
80 logger.info("Pz2Service PostConstruct of " + this);
\r
81 stateMgr = new StateManager();
\r
82 pzreq = new Pazpar2Commands();
\r
83 pzresp = new Responses();
\r
84 errors = new ErrorCentral();
\r
85 pzresp.setErrorHelper(errors.getHelper());
\r
87 logger.debug("Pz2Service PostConstruct: Configurator is " + configurator);
\r
88 logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next.");
\r
89 pz2Client = new Pz2Client();
\r
90 spClient = new ServiceProxyClient();
\r
91 stateMgr.addStateListener(this);
\r
93 configureClient(pz2Client,configurator);
\r
94 configureClient(spClient,configurator);
\r
95 this.configure(configurator);
\r
96 } catch (MissingConfigurationContextException mcc) {
\r
97 logger.info("No configuration context available at this point");
\r
98 logger.debug("Configuration invoked from a Servlet filter before application start?");
\r
100 } catch (ConfigurationException e) {
\r
101 logger.warn("There was a problem configuring the Pz2Service and/or clients (\"pz2\")");
\r
102 e.printStackTrace();
\r
107 @Target({java.lang.annotation.ElementType.TYPE,
\r
108 java.lang.annotation.ElementType.METHOD,
\r
109 java.lang.annotation.ElementType.PARAMETER,
\r
110 java.lang.annotation.ElementType.FIELD})
\r
111 @Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
\r
112 public @interface Preferred{}
\r
114 @Produces @Preferred @SessionScoped @Named("pzresp") public Responses getPzresp () {
\r
115 logger.trace("Producing pzresp");
\r
119 @Produces @Preferred @SessionScoped @Named("pzreq") public Pazpar2Commands getPzreq () {
\r
120 logger.trace("Producing pzreq");
\r
124 @Produces @Preferred @SessionScoped @Named("errors") public ErrorCentral getErrors() {
\r
125 logger.trace("Producing errors");
\r
129 @Produces @Preferred @SessionScoped @Named("stateMgr") public StateManager getStateMgr() {
\r
130 logger.trace("Producing stateMgr");
\r
134 public void configureClient(SearchClient client, ConfigurationReader configReader) throws MissingConfigurationContextException {
\r
135 logger.debug(Utils.objectId(this) + " will configure search client for the session");
\r
137 client.configure(configReader);
\r
138 } catch (MissingConfigurationContextException mcce) {
\r
139 logger.info("No Faces context is available to the configurator at this time of invocation");
\r
141 } catch (ConfigurationException e) {
\r
142 logger.debug("Pz2Service adding configuration error");
\r
143 errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage()));
\r
145 logger.info(configReader.document());
\r
146 pzresp.getSp().resetAuthAndBeyond(true);
\r
149 public void resetSearchAndRecordCommands () {
\r
150 pzreq.getRecord().removeParametersInState();
\r
151 pzreq.getSearch().removeParametersInState();
\r
156 * Updates display data objects by issuing the following pazpar2 commands:
\r
157 * 'show', 'stat', 'termlist' and 'bytarget'.
\r
159 * If there is an outstanding change to the search command, a search
\r
160 * will be issued before the updates are performed.
\r
162 * Returns a count of the remaining active clients from the most recent search.
\r
164 * After refreshing the data from pazpar2 the UI components displaying those
\r
165 * data should be re-rendered.
\r
167 * @return count of activeclients
\r
169 public String update () {
\r
170 logger.debug("Updating show,stat,termlist,bytarget from pazpar2");
\r
171 if (errors.hasConfigurationErrors()) {
\r
172 logger.error("Ignoring show,stat,termlist,bytarget commands due to configuration errors.");
\r
174 } else if (pzresp.getSearch().hasApplicationError()) {
\r
175 logger.error("Ignoring show,stat,termlist,bytarget commands due to problem with most recent search.");
\r
177 } else if (!hasQuery()) {
\r
178 logger.debug("Ignoring show,stat,termlist,bytarget commands because there is not yet a query.");
\r
181 return update("show,stat,termlist,bytarget");
\r
186 * Refreshes the data objects listed in 'commands' from pazpar2
\r
189 * @return Number of activeclients at the time of the 'show' command,
\r
190 * or 'new' if search was just initiated.
\r
192 public String update (String commands) {
\r
193 logger.debug("Request to update: " + commands);
\r
195 if (commands.equals("search")) {
\r
196 pzreq.getSearch().run();
\r
198 } else if (commands.equals("record")) {
\r
199 pzreq.getRecord().run();
\r
200 return pzresp.getRecord().getActiveClients();
\r
201 } else if (pzresp.getSearch().isNew()) {
\r
202 // For returning notification of 'search started' quickly to UI
\r
203 logger.info("New search. Marking it old, then returning 'new' to trigger another round-trip.");
\r
204 pzresp.getSearch().setIsNew(false);
\r
207 handleQueryStateChanges(commands);
\r
208 if (pzresp.getSearch().hasApplicationError()) {
\r
209 logger.error("The command(s) " + commands + " cancelled because the latest search command had an error.");
\r
211 } else if (errors.hasConfigurationErrors()) {
\r
212 logger.error("The command(s) " + commands + " cancelled due to configuration errors.");
\r
215 logger.debug("Processing request for " + commands);
\r
216 List<CommandThread> threadList = new ArrayList<CommandThread>();
\r
217 StringTokenizer tokens = new StringTokenizer(commands,",");
\r
218 while (tokens.hasMoreElements()) {
\r
219 threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient,Pz2Service.get().getPzresp()));
\r
221 for (CommandThread thread : threadList) {
\r
224 for (CommandThread thread : threadList) {
\r
227 } catch (InterruptedException e) {
\r
228 e.printStackTrace();
\r
231 return pzresp.getActiveClients();
\r
234 } catch (ClassCastException cce) {
\r
235 cce.printStackTrace();
\r
237 } catch (NullPointerException npe) {
\r
238 npe.printStackTrace();
\r
240 } catch (Exception e) {
\r
241 e.printStackTrace();
\r
248 * This methods main purpose is to support browser history.
\r
250 * When the browsers back or forward buttons are pressed, a
\r
251 * re-search /might/ be required - namely if the query changes.
\r
252 * So, as the UI requests updates of the page (show,facets,
\r
253 * etc) this method checks if a search must be executed
\r
254 * before those updates are performed.
\r
256 * @see {@link com.indexdata.mkjsf.pazpar2.state.StateManager#setCurrentStateKey}
\r
259 protected void handleQueryStateChanges (String commands) {
\r
260 if (stateMgr.hasPendingStateChange("search") && hasQuery()) {
\r
261 logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands);
\r
262 pzreq.getSearch().run();
\r
264 if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {
\r
265 logger.debug("Found pending record ID change. Doing record before updating " + commands);
\r
266 stateMgr.hasPendingStateChange("record",false);
\r
267 pzreq.getRecord().run();
\r
272 public void stateUpdated(String commandName) {
\r
273 logger.debug("State change reported for [" + commandName + "]");
\r
274 if (commandName.equals("show")) {
\r
275 logger.debug("Updating show");
\r
276 update(commandName);
\r
282 * Will retrieve -- or alternatively remove -- the record with the given
\r
283 * recid from memory.
\r
285 * A pazpar2 'record' command will then be issued. The part of the UI
\r
286 * showing record data should thus be re-rendered.
\r
291 public String toggleRecord (String recId) {
\r
292 if (hasRecord(recId)) {
\r
293 pzreq.getRecord().removeParameters();
\r
294 pzresp.put("record", new RecordResponse());
\r
297 pzreq.getRecord().setId(recId);
\r
298 pzreq.getRecord().run();
\r
299 // doCommand("record");
\r
300 return pzresp.getRecord().getActiveClients();
\r
305 * Resolves whether the backend has a record with the given recid in memory
\r
307 * @return true if the bean currently holds the record with recid
\r
309 public boolean hasRecord (String recId) {
\r
310 return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId);
\r
314 * Returns the current hash key, used for internal session state tracking
\r
315 * and potentially for browser history entries
\r
317 * A UI author would not normally be concerned with retrieving this. It's used by the
\r
318 * framework internally
\r
320 * @return string that can be used for browsers window.location.hash
\r
322 public String getCurrentStateKey () {
\r
323 return stateMgr.getCurrentState().getKey();
\r
327 * Sets the current state key, i.e. when user clicks back or forward in browser history.
\r
328 * Would normally be automatically handled by the frameworks components.
\r
330 * @param key corresponding to browsers hash string
\r
332 public void setCurrentStateKey(String key) {
\r
333 stateMgr.setCurrentStateKey(key);
\r
336 protected boolean hasQuery() {
\r
337 return pzreq.getCommand("search").hasParameterValue("query");
\r
341 * Returns a component for drawing a pager to navigate by.
\r
342 * @return ResultsPager pager component
\r
344 public ResultsPager getPager () {
\r
345 if (pager == null) {
\r
346 pager = new ResultsPager(pzresp);
\r
352 * Initiates a pager object, a component holding the data to draw a sequence
\r
353 * of page numbers to navigate by and mechanisms to navigate with
\r
355 * @param pageRange number of pages to display in the pager
\r
356 * @return ResultsPager the initiated pager component
\r
358 public ResultsPager setPager (int pageRange) {
\r
359 pager = new ResultsPager(pzresp,pageRange,pzreq);
\r
363 public void setServiceProxyUrl(String url) {
\r
364 searchClient = spClient;
\r
365 setServiceType(SERVICE_TYPE_SP);
\r
366 setServiceUrl(url);
\r
369 public String getServiceProxyUrl () {
\r
370 if (isServiceProxyService()) {
\r
371 return spClient.getServiceUrl();
\r
377 public void setPazpar2Url(String url) {
\r
378 searchClient = pz2Client;
\r
379 setServiceType(SERVICE_TYPE_PZ2);
\r
380 setServiceUrl(url);
\r
383 public String getPazpar2Url() {
\r
384 if (isPazpar2Service()) {
\r
385 return pz2Client.getServiceUrl();
\r
391 public void setServiceUrl(String url) {
\r
392 if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {
\r
393 pzreq.getRecord().removeParametersInState();
\r
394 pzreq.getSearch().removeParametersInState();
\r
395 pzresp.getSp().resetAuthAndBeyond(true);
\r
396 searchClient.setServiceUrl(url);
\r
400 public String getServiceUrl() {
\r
401 return (searchClient!=null ? searchClient.getServiceUrl() : "");
\r
404 public void setServiceId () {
\r
405 pzreq.getRecord().removeParametersInState();
\r
406 pzreq.getSearch().removeParametersInState();
\r
407 pzresp.resetSearchAndBeyond();
\r
408 pz2Client.setServiceId(pzreq.getInit().getService());
\r
411 public String getServiceId () {
\r
412 return pzreq.getInit().getService();
\r
415 public boolean getServiceUrlIsDefined() {
\r
416 return (searchClient != null && searchClient.hasServiceUrl());
\r
419 public List<String> getServiceProxyUrls() {
\r
420 List<String> urls = new ArrayList<String>();
\r
422 urls.addAll(serviceProxyUrls);
\r
426 public List<String> getPazpar2Urls () {
\r
427 List<String> urls = new ArrayList<String>();
\r
429 urls.addAll(pazpar2Urls);
\r
433 public String getServiceType () {
\r
434 return serviceType;
\r
437 public boolean isPazpar2Service () {
\r
438 return serviceType.equals(SERVICE_TYPE_PZ2);
\r
441 public boolean isServiceProxyService() {
\r
442 return serviceType.equals(SERVICE_TYPE_SP);
\r
445 public boolean serviceIsToBeDecided () {
\r
446 return serviceType.equals(SERVICE_TYPE_TBD);
\r
449 public ServiceProxyClient getSpClient () {
\r
453 public boolean getAuthenticationRequired () {
\r
454 return spClient.isAuthenticatingClient();
\r
457 public String getCheckHistory () {
\r
458 return ":pz2watch:stateForm:windowlocationhash";
\r
461 public String getWatchActiveclients () {
\r
462 return ":pz2watch:activeclientsForm:activeclientsField";
\r
465 public String getWatchActiveclientsRecord () {
\r
466 return ":pz2watch:activeclientsForm:activeclientsFieldRecord";
\r
470 public void configure(ConfigurationReader reader)
\r
471 throws ConfigurationException {
\r
472 Configuration config = reader.getConfiguration(this);
\r
473 if (config == null) {
\r
474 serviceType = SERVICE_TYPE_TBD;
\r
476 String service = config.get("TYPE");
\r
477 if (service == null || service.length()==0) {
\r
478 serviceType = SERVICE_TYPE_TBD;
\r
479 } else if (serviceTypes.contains(service.toUpperCase())) {
\r
480 setServiceType(service.toUpperCase());
\r
482 logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);
\r
483 serviceType = SERVICE_TYPE_TBD;
\r
485 serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");
\r
486 pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");
\r
488 logger.info(reader.document());
\r
489 logger.info("Service Type is configured to " + serviceType);
\r
494 public Map<String, String> getDefaults() {
\r
495 return new HashMap<String,String>();
\r
499 public String getModuleName() {
\r
500 return MODULE_NAME;
\r
504 public List<String> documentConfiguration() {
\r
505 return new ArrayList<String>();
\r
508 public void setServiceTypePZ2() {
\r
509 setServiceType(SERVICE_TYPE_PZ2);
\r
512 public void setServiceTypeSP() {
\r
513 setServiceType(SERVICE_TYPE_SP);
\r
516 public void setServiceTypeTBD() {
\r
517 setServiceType(SERVICE_TYPE_TBD);
\r
520 private void setServiceType(String type) {
\r
521 if (!serviceType.equals(type) &&
\r
522 !serviceType.equals(SERVICE_TYPE_TBD)) {
\r
523 resetSearchAndRecordCommands();
\r
524 pzresp.getSp().resetAuthAndBeyond(true);
\r
526 serviceType = type;
\r
527 if (serviceType.equals(SERVICE_TYPE_PZ2)) {
\r
528 searchClient = pz2Client;
\r
529 logger.info("Setting a Pazpar2 client to serve requests.");
\r
530 } else if (serviceType.equals(SERVICE_TYPE_SP)) {
\r
531 searchClient = spClient;
\r
532 logger.info("Setting a Service Proxy client to serve requests.");
\r
534 logger.info("Clearing search client. No client defined to serve requests at this point.");
\r
535 searchClient = null;
\r
539 public SearchClient getSearchClient() {
\r
540 return searchClient;
\r