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.pazpar2.commands.Pazpar2Commands;
\r
32 import com.indexdata.mkjsf.pazpar2.data.RecordResponse;
\r
33 import com.indexdata.mkjsf.pazpar2.data.Responses;
\r
34 import com.indexdata.mkjsf.pazpar2.state.StateListener;
\r
35 import com.indexdata.mkjsf.pazpar2.state.StateManager;
\r
36 import com.indexdata.mkjsf.utils.Utils;
\r
38 @Named("pz2") @SessionScoped
\r
39 public class Pz2Service implements StateListener, Configurable, Serializable {
\r
41 private static final String MODULE_NAME = "service";
\r
42 private static String SERVICE_TYPE_TBD = "TBD", SERVICE_TYPE_PZ2 = "PZ2", SERVICE_TYPE_SP = "SP";
\r
43 private static final List<String> serviceTypes =
\r
44 Arrays.asList(SERVICE_TYPE_PZ2,SERVICE_TYPE_SP,SERVICE_TYPE_TBD);
\r
45 private String serviceType = SERVICE_TYPE_TBD;
\r
46 private List<String> serviceProxyUrls = new ArrayList<String>();
\r
47 public static final String SERVICE_PROXY_URL_LIST = "SERVICE_PROXY_URL_LIST";
\r
48 private List<String> pazpar2Urls = new ArrayList<String>();
\r
49 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() {
\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 configureClient(pz2Client,configurator);
\r
91 spClient = new ServiceProxyClient();
\r
92 configureClient(spClient,configurator);
\r
94 this.configure(configurator);
\r
95 } catch (ConfigurationException e) {
\r
96 logger.error("There was a problem configuring the Pz2Service (\"pz2\")");
\r
97 e.printStackTrace();
\r
99 stateMgr.addStateListener(this);
\r
103 @Target({java.lang.annotation.ElementType.TYPE,
\r
104 java.lang.annotation.ElementType.METHOD,
\r
105 java.lang.annotation.ElementType.PARAMETER,
\r
106 java.lang.annotation.ElementType.FIELD})
\r
107 @Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
\r
108 public @interface Preferred{}
\r
110 @Produces @Preferred @SessionScoped @Named("pzresp") public Responses getPzresp () {
\r
111 logger.trace("Producing pzresp");
\r
115 @Produces @Preferred @SessionScoped @Named("pzreq") public Pazpar2Commands getPzreq () {
\r
116 logger.trace("Producing pzreq");
\r
120 @Produces @Preferred @SessionScoped @Named("errors") public ErrorCentral getErrors() {
\r
121 logger.trace("Producing errors");
\r
125 @Produces @Preferred @SessionScoped @Named("stateMgr") public StateManager getStateMgr() {
\r
126 logger.trace("Producing stateMgr");
\r
130 public void configureClient(SearchClient client, ConfigurationReader configReader) {
\r
131 logger.debug(Utils.objectId(this) + " will configure search client for the session");
\r
133 client.configure(configReader);
\r
134 } catch (ConfigurationException e) {
\r
135 logger.debug("Pz2Service adding configuration error");
\r
136 errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage()));
\r
138 logger.info(configReader.document());
\r
139 pzresp.getSp().resetAuthAndBeyond(true);
\r
142 public void resetSearchAndRecordCommands () {
\r
143 pzreq.getRecord().removeParametersInState();
\r
144 pzreq.getSearch().removeParametersInState();
\r
149 * Updates display data objects by issuing the following pazpar2 commands:
\r
150 * 'show', 'stat', 'termlist' and 'bytarget'.
\r
152 * If there is an outstanding change to the search command, a search
\r
153 * will be issued before the updates are performed.
\r
155 * Returns a count of the remaining active clients from the most recent search.
\r
157 * After refreshing the data from pazpar2 the UI components displaying those
\r
158 * data should be re-rendered.
\r
160 * @return count of activeclients
\r
162 public String update () {
\r
163 logger.debug("Updating show,stat,termlist,bytarget from pazpar2");
\r
164 if (errors.hasConfigurationErrors()) {
\r
165 logger.error("Ignoring show,stat,termlist,bytarget commands due to configuration errors.");
\r
167 } else if (pzresp.getSearch().hasApplicationError()) {
\r
168 logger.error("Ignoring show,stat,termlist,bytarget commands due to problem with most recent search.");
\r
170 } else if (!hasQuery()) {
\r
171 logger.debug("Ignoring show,stat,termlist,bytarget commands because there is not yet a query.");
\r
174 return update("show,stat,termlist,bytarget");
\r
179 * Refreshes the data objects listed in 'commands' from pazpar2
\r
182 * @return Number of activeclients at the time of the 'show' command,
\r
183 * or 'new' if search was just initiated.
\r
185 public String update (String commands) {
\r
186 logger.debug("Request to update: " + commands);
\r
188 if (commands.equals("search")) {
\r
189 pzreq.getSearch().run();
\r
191 } else if (commands.equals("record")) {
\r
192 pzreq.getRecord().run();
\r
193 return pzresp.getRecord().getActiveClients();
\r
194 } else if (pzresp.getSearch().isNew()) {
\r
195 // For returning notification of 'search started' quickly to UI
\r
196 logger.info("New search. Marking it old, then returning 'new' to trigger another round-trip.");
\r
197 pzresp.getSearch().setIsNew(false);
\r
200 handleQueryStateChanges(commands);
\r
201 if (pzresp.getSearch().hasApplicationError()) {
\r
202 logger.error("The command(s) " + commands + " cancelled because the latest search command had an error.");
\r
204 } else if (errors.hasConfigurationErrors()) {
\r
205 logger.error("The command(s) " + commands + " cancelled due to configuration errors.");
\r
208 logger.debug("Processing request for " + commands);
\r
209 List<CommandThread> threadList = new ArrayList<CommandThread>();
\r
210 StringTokenizer tokens = new StringTokenizer(commands,",");
\r
211 while (tokens.hasMoreElements()) {
\r
212 threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient,Pz2Service.get().getPzresp()));
\r
214 for (CommandThread thread : threadList) {
\r
217 for (CommandThread thread : threadList) {
\r
220 } catch (InterruptedException e) {
\r
221 e.printStackTrace();
\r
224 return pzresp.getActiveClients();
\r
227 } catch (ClassCastException cce) {
\r
228 cce.printStackTrace();
\r
230 } catch (NullPointerException npe) {
\r
231 npe.printStackTrace();
\r
233 } catch (Exception e) {
\r
234 e.printStackTrace();
\r
241 * Will retrieve -- or alternatively remove -- the record with the given
\r
242 * recid from memory.
\r
244 * A pazpar2 'record' command will then be issued. The part of the UI
\r
245 * showing record data should thus be re-rendered.
\r
250 public String toggleRecord (String recId) {
\r
251 if (hasRecord(recId)) {
\r
252 pzreq.getRecord().removeParameters();
\r
253 pzresp.put("record", new RecordResponse());
\r
256 pzreq.getRecord().setId(recId);
\r
257 pzreq.getRecord().run();
\r
258 // doCommand("record");
\r
259 return pzresp.getRecord().getActiveClients();
\r
264 * Resolves whether the backend has a record with the given recid in memory
\r
266 * @return true if the bean currently holds the record with recid
\r
268 public boolean hasRecord (String recId) {
\r
269 return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId);
\r
273 * Returns the current hash key, used for internal session state tracking
\r
274 * and potentially for browser history entries
\r
276 * A UI author would not normally be concerned with retrieving this. It's used by the
\r
277 * framework internally
\r
279 * @return string that can be used for browsers window.location.hash
\r
281 public String getCurrentStateKey () {
\r
282 return stateMgr.getCurrentState().getKey();
\r
286 * Sets the current state key, i.e. when user clicks back or forward in browser history.
\r
287 * Would normally be automatically handled by the frameworks components.
\r
289 * @param key corresponding to browsers hash string
\r
291 public void setCurrentStateKey(String key) {
\r
292 stateMgr.setCurrentStateKey(key);
\r
295 protected boolean hasQuery() {
\r
296 return pzreq.getCommand("search").hasParameterValue("query");
\r
300 * Returns a component for drawing a pager to navigate by.
\r
301 * @return ResultsPager pager component
\r
303 public ResultsPager getPager () {
\r
304 if (pager == null) {
\r
305 pager = new ResultsPager(pzresp);
\r
311 * Initiates a pager object, a component holding the data to draw a sequence
\r
312 * of page numbers to navigate by and mechanisms to navigate with
\r
314 * @param pageRange number of pages to display in the pager
\r
315 * @return ResultsPager the initiated pager component
\r
317 public ResultsPager setPager (int pageRange) {
\r
318 pager = new ResultsPager(pzresp,pageRange,pzreq);
\r
323 * This methods main purpose is to support browser history.
\r
325 * When the browsers back or forward buttons are pressed, a
\r
326 * re-search /might/ be required - namely if the query changes.
\r
327 * So, as the UI requests updates of the page (show,facets,
\r
328 * etc) this method checks if a search must be executed
\r
329 * before those updates are performed.
\r
331 * @see {@link com.indexdata.mkjsf.pazpar2.state.StateManager#setCurrentStateKey}
\r
334 protected void handleQueryStateChanges (String commands) {
\r
335 if (stateMgr.hasPendingStateChange("search") && hasQuery()) {
\r
336 logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands);
\r
337 pzreq.getSearch().run();
\r
339 if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {
\r
340 logger.debug("Found pending record ID change. Doing record before updating " + commands);
\r
341 stateMgr.hasPendingStateChange("record",false);
\r
342 pzreq.getRecord().run();
\r
347 * Executes the command and parses the response to create data objects.
\r
348 * If the parsed response is of a known type it will be cached in 'pzresp'
\r
350 * @param commandName The command to be executed
\r
351 * @return An XML response parsed to form a response data object
\r
354 protected ResponseDataObject doCommand(String commandName) {
\r
355 Pazpar2Command command = pzreq.getCommand(commandName);
\r
356 if (command.spOnly() && isPazpar2Service()) {
\r
357 logger.warn("Skipping " + commandName + " - SP-only command, not supported by Pazpar2");
\r
358 return new ResponseDataObject();
\r
360 logger.info("Request "+commandName + ". Search command is: "+ pzreq.getCommand("search").toString());
\r
361 long start = System.currentTimeMillis();
\r
362 ResponseDataObject responseObject = command.run();
\r
363 long end = System.currentTimeMillis();
\r
364 logger.debug("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );
\r
365 return responseObject;
\r
371 public void stateUpdated(String commandName) {
\r
372 logger.debug("State change reported for [" + commandName + "]");
\r
373 if (commandName.equals("show")) {
\r
374 logger.debug("Updating show");
\r
375 update(commandName);
\r
379 public void setServiceProxyUrl(String url) {
\r
380 searchClient = spClient;
\r
381 setServiceType(SERVICE_TYPE_SP);
\r
382 setServiceUrl(url);
\r
385 public String getServiceProxyUrl () {
\r
386 if (isServiceProxyService()) {
\r
387 return spClient.getServiceUrl();
\r
393 public void setPazpar2Url(String url) {
\r
394 searchClient = pz2Client;
\r
395 setServiceType(SERVICE_TYPE_PZ2);
\r
396 setServiceUrl(url);
\r
399 public String getPazpar2Url() {
\r
400 if (isPazpar2Service()) {
\r
401 return pz2Client.getServiceUrl();
\r
407 public void setServiceUrl(String url) {
\r
408 if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {
\r
409 pzreq.getRecord().removeParametersInState();
\r
410 pzreq.getSearch().removeParametersInState();
\r
411 pzresp.getSp().resetAuthAndBeyond(true);
\r
412 searchClient.setServiceUrl(url);
\r
416 public String getServiceUrl() {
\r
417 return (searchClient!=null ? searchClient.getServiceUrl() : "");
\r
420 public void setServiceId () {
\r
421 pzreq.getRecord().removeParametersInState();
\r
422 pzreq.getSearch().removeParametersInState();
\r
423 pzresp.resetSearchAndBeyond();
\r
424 pz2Client.setServiceId(pzreq.getInit().getService());
\r
427 public String getServiceId () {
\r
428 return pzreq.getInit().getService();
\r
431 public boolean getServiceUrlIsDefined() {
\r
432 return (searchClient != null && searchClient.hasServiceUrl());
\r
435 public List<String> getServiceProxyUrls() {
\r
436 List<String> urls = new ArrayList<String>();
\r
438 urls.addAll(serviceProxyUrls);
\r
442 public List<String> getPazpar2Urls () {
\r
443 List<String> urls = new ArrayList<String>();
\r
445 urls.addAll(pazpar2Urls);
\r
449 public String getServiceType () {
\r
450 return serviceType;
\r
453 public boolean isPazpar2Service () {
\r
454 return serviceType.equals(SERVICE_TYPE_PZ2);
\r
457 public boolean isServiceProxyService() {
\r
458 return serviceType.equals(SERVICE_TYPE_SP);
\r
461 public boolean serviceIsToBeDecided () {
\r
462 return serviceType.equals(SERVICE_TYPE_TBD);
\r
465 public ServiceProxyClient getSpClient () {
\r
469 public boolean getAuthenticationRequired () {
\r
470 return spClient.isAuthenticatingClient();
\r
473 public String getCheckHistory () {
\r
474 return ":pz2watch:stateForm:windowlocationhash";
\r
477 public String getWatchActiveclients () {
\r
478 return ":pz2watch:activeclientsForm:activeclientsField";
\r
481 public String getWatchActiveclientsRecord () {
\r
482 return ":pz2watch:activeclientsForm:activeclientsFieldRecord";
\r
486 public void configure(ConfigurationReader reader)
\r
487 throws ConfigurationException {
\r
488 Configuration config = reader.getConfiguration(this);
\r
489 if (config == null) {
\r
490 serviceType = SERVICE_TYPE_TBD;
\r
492 String service = config.get("TYPE");
\r
493 if (service == null || service.length()==0) {
\r
494 serviceType = SERVICE_TYPE_TBD;
\r
495 } else if (serviceTypes.contains(service.toUpperCase())) {
\r
496 setServiceType(service.toUpperCase());
\r
498 logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);
\r
499 serviceType = SERVICE_TYPE_TBD;
\r
501 serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");
\r
502 pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");
\r
504 logger.info(reader.document());
\r
505 logger.info("Service Type is configured to " + serviceType);
\r
510 public Map<String, String> getDefaults() {
\r
511 return new HashMap<String,String>();
\r
515 public String getModuleName() {
\r
516 return MODULE_NAME;
\r
520 public List<String> documentConfiguration() {
\r
521 return new ArrayList<String>();
\r
524 public void setServiceTypePZ2() {
\r
525 setServiceType(SERVICE_TYPE_PZ2);
\r
528 public void setServiceTypeSP() {
\r
529 setServiceType(SERVICE_TYPE_SP);
\r
532 public void setServiceTypeTBD() {
\r
533 setServiceType(SERVICE_TYPE_TBD);
\r
536 private void setServiceType(String type) {
\r
537 if (!serviceType.equals(type) &&
\r
538 !serviceType.equals(SERVICE_TYPE_TBD)) {
\r
539 resetSearchAndRecordCommands();
\r
540 pzresp.getSp().resetAuthAndBeyond(true);
\r
542 serviceType = type;
\r
543 if (serviceType.equals(SERVICE_TYPE_PZ2)) {
\r
544 searchClient = pz2Client;
\r
545 logger.info("Setting a Pazpar2 client to serve requests.");
\r
546 } else if (serviceType.equals(SERVICE_TYPE_SP)) {
\r
547 searchClient = spClient;
\r
548 logger.info("Setting a Service Proxy client to serve requests.");
\r
550 logger.info("Clearing search client. No client defined to serve requests at this point.");
\r
551 searchClient = null;
\r
555 public SearchClient getSearchClient() {
\r
556 return searchClient;
\r