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
197 pzresp.getSearch().setIsNew(false);
\r
199 } else if (commands.equals("record")) {
\r
200 pzreq.getRecord().run();
\r
201 return pzresp.getRecord().getActiveClients();
\r
202 } else if (pzresp.getSearch().isNew()) {
\r
203 // For returning notification of 'search started' quickly to UI
\r
204 logger.info("New search. Marking it old, then returning 'new' to trigger another round-trip.");
\r
205 pzresp.getSearch().setIsNew(false);
\r
208 handleQueryStateChanges(commands);
\r
209 if (pzresp.getSearch().hasApplicationError()) {
\r
210 logger.error("The command(s) " + commands + " cancelled because the latest search command had an error.");
\r
212 } else if (errors.hasConfigurationErrors()) {
\r
213 logger.error("The command(s) " + commands + " cancelled due to configuration errors.");
\r
216 logger.debug("Processing request for " + commands);
\r
217 List<CommandThread> threadList = new ArrayList<CommandThread>();
\r
218 StringTokenizer tokens = new StringTokenizer(commands,",");
\r
219 while (tokens.hasMoreElements()) {
\r
220 threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient,Pz2Service.get().getPzresp()));
\r
222 for (CommandThread thread : threadList) {
\r
225 for (CommandThread thread : threadList) {
\r
228 } catch (InterruptedException e) {
\r
229 e.printStackTrace();
\r
232 return pzresp.getActiveClients();
\r
235 } catch (ClassCastException cce) {
\r
236 cce.printStackTrace();
\r
238 } catch (NullPointerException npe) {
\r
239 npe.printStackTrace();
\r
241 } catch (Exception e) {
\r
242 e.printStackTrace();
\r
249 * This methods main purpose is to support browser history.
\r
251 * When the browsers back or forward buttons are pressed, a
\r
252 * re-search /might/ be required - namely if the query changes.
\r
253 * So, as the UI requests updates of the page (show,facets,
\r
254 * etc) this method checks if a search must be executed
\r
255 * before those updates are performed.
\r
257 * @see {@link com.indexdata.mkjsf.pazpar2.state.StateManager#setCurrentStateKey}
\r
260 protected void handleQueryStateChanges (String commands) {
\r
261 if (stateMgr.hasPendingStateChange("search") && hasQuery()) {
\r
262 logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands);
\r
263 pzreq.getSearch().run();
\r
264 pzresp.getSearch().setIsNew(false);
\r
266 if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {
\r
267 logger.debug("Found pending record ID change. Doing record before updating " + commands);
\r
268 stateMgr.hasPendingStateChange("record",false);
\r
269 pzreq.getRecord().run();
\r
274 public void stateUpdated(String commandName) {
\r
275 logger.debug("State change reported for [" + commandName + "]");
\r
276 if (commandName.equals("show")) {
\r
277 logger.debug("Updating show");
\r
278 update(commandName);
\r
284 * Will retrieve -- or alternatively remove -- the record with the given
\r
285 * recid from memory.
\r
287 * A pazpar2 'record' command will then be issued. The part of the UI
\r
288 * showing record data should thus be re-rendered.
\r
293 public String toggleRecord (String recId) {
\r
294 if (hasRecord(recId)) {
\r
295 pzreq.getRecord().removeParameters();
\r
296 pzresp.put("record", new RecordResponse());
\r
299 pzreq.getRecord().setId(recId);
\r
300 pzreq.getRecord().run();
\r
301 // doCommand("record");
\r
302 return pzresp.getRecord().getActiveClients();
\r
307 * Resolves whether the backend has a record with the given recid in memory
\r
309 * @return true if the bean currently holds the record with recid
\r
311 public boolean hasRecord (String recId) {
\r
312 return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId);
\r
316 * Returns the current hash key, used for internal session state tracking
\r
317 * and potentially for browser history entries
\r
319 * A UI author would not normally be concerned with retrieving this. It's used by the
\r
320 * framework internally
\r
322 * @return string that can be used for browsers window.location.hash
\r
324 public String getCurrentStateKey () {
\r
325 return stateMgr.getCurrentState().getKey();
\r
329 * Sets the current state key, i.e. when user clicks back or forward in browser history.
\r
330 * Would normally be automatically handled by the frameworks components.
\r
332 * @param key corresponding to browsers hash string
\r
334 public void setCurrentStateKey(String key) {
\r
335 stateMgr.setCurrentStateKey(key);
\r
338 protected boolean hasQuery() {
\r
339 return pzreq.getCommand("search").hasParameterValue("query");
\r
343 * Returns a component for drawing a pager to navigate by.
\r
344 * @return ResultsPager pager component
\r
346 public ResultsPager getPager () {
\r
347 if (pager == null) {
\r
348 pager = new ResultsPager(pzresp);
\r
354 * Initiates a pager object, a component holding the data to draw a sequence
\r
355 * of page numbers to navigate by and mechanisms to navigate with
\r
357 * @param pageRange number of pages to display in the pager
\r
358 * @return ResultsPager the initiated pager component
\r
360 public ResultsPager setPager (int pageRange) {
\r
361 pager = new ResultsPager(pzresp,pageRange,pzreq);
\r
365 public void setServiceProxyUrl(String url) {
\r
366 searchClient = spClient;
\r
367 setServiceType(SERVICE_TYPE_SP);
\r
368 setServiceUrl(url);
\r
371 public String getServiceProxyUrl () {
\r
372 if (isServiceProxyService()) {
\r
373 return spClient.getServiceUrl();
\r
379 public void setPazpar2Url(String url) {
\r
380 searchClient = pz2Client;
\r
381 setServiceType(SERVICE_TYPE_PZ2);
\r
382 setServiceUrl(url);
\r
385 public String getPazpar2Url() {
\r
386 if (isPazpar2Service()) {
\r
387 return pz2Client.getServiceUrl();
\r
393 public void setServiceUrl(String url) {
\r
394 if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {
\r
395 pzreq.getRecord().removeParametersInState();
\r
396 pzreq.getSearch().removeParametersInState();
\r
397 pzresp.getSp().resetAuthAndBeyond(true);
\r
398 searchClient.setServiceUrl(url);
\r
402 public String getServiceUrl() {
\r
403 return (searchClient!=null ? searchClient.getServiceUrl() : "");
\r
406 public void setServiceId () {
\r
407 pzreq.getRecord().removeParametersInState();
\r
408 pzreq.getSearch().removeParametersInState();
\r
409 pzresp.resetSearchAndBeyond();
\r
410 pz2Client.setServiceId(pzreq.getInit().getService());
\r
413 public String getServiceId () {
\r
414 return pzreq.getInit().getService();
\r
417 public boolean getServiceUrlIsDefined() {
\r
418 return (searchClient != null && searchClient.hasServiceUrl());
\r
421 public List<String> getServiceProxyUrls() {
\r
422 List<String> urls = new ArrayList<String>();
\r
424 urls.addAll(serviceProxyUrls);
\r
428 public List<String> getPazpar2Urls () {
\r
429 List<String> urls = new ArrayList<String>();
\r
431 urls.addAll(pazpar2Urls);
\r
435 public String getServiceType () {
\r
436 return serviceType;
\r
439 public boolean isPazpar2Service () {
\r
440 return serviceType.equals(SERVICE_TYPE_PZ2);
\r
443 public boolean isServiceProxyService() {
\r
444 return serviceType.equals(SERVICE_TYPE_SP);
\r
447 public boolean serviceIsToBeDecided () {
\r
448 return serviceType.equals(SERVICE_TYPE_TBD);
\r
451 public ServiceProxyClient getSpClient () {
\r
455 public boolean getAuthenticationRequired () {
\r
456 return spClient.isAuthenticatingClient();
\r
459 public String getCheckHistory () {
\r
460 return ":pz2watch:stateForm:windowlocationhash";
\r
463 public String getWatchActiveclients () {
\r
464 return ":pz2watch:activeclientsForm:activeclientsField";
\r
467 public String getWatchActiveclientsRecord () {
\r
468 return ":pz2watch:activeclientsForm:activeclientsFieldRecord";
\r
472 public void configure(ConfigurationReader reader)
\r
473 throws ConfigurationException {
\r
474 Configuration config = reader.getConfiguration(this);
\r
475 if (config == null) {
\r
476 serviceType = SERVICE_TYPE_TBD;
\r
478 String service = config.get("TYPE");
\r
479 if (service == null || service.length()==0) {
\r
480 serviceType = SERVICE_TYPE_TBD;
\r
481 } else if (serviceTypes.contains(service.toUpperCase())) {
\r
482 setServiceType(service.toUpperCase());
\r
484 logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);
\r
485 serviceType = SERVICE_TYPE_TBD;
\r
487 serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");
\r
488 pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");
\r
490 logger.info(reader.document());
\r
491 logger.info("Service Type is configured to " + serviceType);
\r
496 public Map<String, String> getDefaults() {
\r
497 return new HashMap<String,String>();
\r
501 public String getModuleName() {
\r
502 return MODULE_NAME;
\r
506 public List<String> documentConfiguration() {
\r
507 return new ArrayList<String>();
\r
510 public void setServiceTypePZ2() {
\r
511 setServiceType(SERVICE_TYPE_PZ2);
\r
514 public void setServiceTypeSP() {
\r
515 setServiceType(SERVICE_TYPE_SP);
\r
518 public void setServiceTypeTBD() {
\r
519 setServiceType(SERVICE_TYPE_TBD);
\r
522 private void setServiceType(String type) {
\r
523 if (!serviceType.equals(type) &&
\r
524 !serviceType.equals(SERVICE_TYPE_TBD)) {
\r
525 resetSearchAndRecordCommands();
\r
526 pzresp.getSp().resetAuthAndBeyond(true);
\r
528 serviceType = type;
\r
529 if (serviceType.equals(SERVICE_TYPE_PZ2)) {
\r
530 searchClient = pz2Client;
\r
531 logger.info("Setting a Pazpar2 client to serve requests.");
\r
532 } else if (serviceType.equals(SERVICE_TYPE_SP)) {
\r
533 searchClient = spClient;
\r
534 logger.info("Setting a Service Proxy client to serve requests.");
\r
536 logger.info("Clearing search client. No client defined to serve requests at this point.");
\r
537 searchClient = null;
\r
541 public SearchClient getSearchClient() {
\r
542 return searchClient;
\r