1 package com.indexdata.mkjsf.pazpar2;
\r
3 import java.io.Serializable;
\r
4 import java.util.ArrayList;
\r
5 import java.util.Arrays;
\r
6 import java.util.HashMap;
\r
7 import java.util.List;
\r
8 import java.util.Map;
\r
9 import java.util.StringTokenizer;
\r
11 import javax.annotation.PostConstruct;
\r
12 import javax.enterprise.context.SessionScoped;
\r
13 import javax.inject.Inject;
\r
14 import javax.inject.Named;
\r
16 import org.apache.log4j.Logger;
\r
18 import com.indexdata.mkjsf.config.Configurable;
\r
19 import com.indexdata.mkjsf.config.Configuration;
\r
20 import com.indexdata.mkjsf.config.ConfigurationReader;
\r
21 import com.indexdata.mkjsf.controls.ResultsPager;
\r
22 import com.indexdata.mkjsf.errors.ConfigurationError;
\r
23 import com.indexdata.mkjsf.errors.ConfigurationException;
\r
24 import com.indexdata.mkjsf.errors.ErrorCentral;
\r
25 import com.indexdata.mkjsf.errors.ErrorHelper;
\r
26 import com.indexdata.mkjsf.pazpar2.commands.CommandParameter;
\r
27 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;
\r
28 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands;
\r
29 import com.indexdata.mkjsf.pazpar2.data.RecordResponse;
\r
30 import com.indexdata.mkjsf.pazpar2.data.ResponseDataObject;
\r
31 import com.indexdata.mkjsf.pazpar2.data.ResponseParser;
\r
32 import com.indexdata.mkjsf.pazpar2.data.Responses;
\r
33 import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser;
\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 Pz2Bean implements Pz2Interface, 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(Pz2Bean.class);
\r
54 private static Logger responseLogger = Logger.getLogger("com.indexdata.mkjsf.pazpar2.responses");
\r
55 protected Pz2Client pz2Client = null;
\r
56 protected ServiceProxyClient spClient = null;
\r
57 protected SearchClient searchClient = null;
\r
59 @Inject ConfigurationReader configurator;
\r
60 @Inject StateManager stateMgr;
\r
61 @Inject Pazpar2Commands pzreq;
\r
62 @Inject Responses pzresp;
\r
63 @Inject ErrorCentral errors;
\r
64 @Inject ServiceProxyUser user;
\r
66 protected ResultsPager pager = null;
\r
68 protected ErrorHelper errorHelper = null;
\r
71 logger.info("Instantiating pz2 bean [" + Utils.objectId(this) + "]");
\r
75 public void postConstruct() {
\r
76 logger.debug("Pz2Bean post-construct: Configurator is " + configurator);
\r
77 logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next.");
\r
78 pz2Client = new Pz2Client();
\r
79 configureClient(pz2Client,configurator);
\r
80 spClient = new ServiceProxyClient();
\r
81 configureClient(spClient,configurator);
\r
83 this.configure(configurator);
\r
84 } catch (ConfigurationException e) {
\r
85 logger.error("There was a problem configuring the Pz2Bean (\"pz2\")");
\r
86 e.printStackTrace();
\r
88 stateMgr.addStateListener(this);
\r
91 public void configureClient(SearchClient client, ConfigurationReader configReader) {
\r
92 logger.debug(Utils.objectId(this) + " will configure search client for the session");
\r
94 client.configure(configReader);
\r
95 } catch (ConfigurationException e) {
\r
96 logger.debug("Pz2Bean adding configuration error");
\r
97 errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage()));
\r
99 logger.info(configReader.document());
\r
100 pzresp.resetAllSessionData();
\r
103 public void resetSearchAndRecordCommands () {
\r
104 pzreq.getRecord().removeParametersInState();
\r
105 pzreq.getSearch().removeParametersInState();
\r
109 public void doSearch(String query) {
\r
110 pzreq.getSearch().setParameter(new CommandParameter("query","=",query));
\r
114 public void doSearch() {
\r
115 stateMgr.hasPendingStateChange("search",false);
\r
116 pzresp.resetSearchResponses();
\r
117 // resets some record and show command parameters without
\r
118 // changing state or creating state change feedback
\r
119 pzreq.getRecord().removeParametersInState();
\r
120 pzreq.getShow().setParameterInState(new CommandParameter("start","=",0));
\r
121 logger.debug(Utils.objectId(this) + " is searching using "+pzreq.getCommand("search").getUrlEncodedParameterValue("query"));
\r
122 doCommand("search");
\r
125 public String doRecord() {
\r
126 ResponseDataObject responseObject = doCommand("record");
\r
127 if (pzreq.getRecord().hasParameterValue("offset") ||
\r
128 pzreq.getRecord().hasParameterValue("checksum")) {
\r
129 RecordResponse recordResponse = new RecordResponse();
\r
130 recordResponse.setType("record");
\r
131 recordResponse.setXml(responseObject.getXml());
\r
132 recordResponse.setAttribute("activeclients", "0");
\r
133 pzresp.put("record", recordResponse);
\r
135 return pzresp.getRecord().getActiveClients();
\r
139 * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2
\r
141 * @return Number of activeclients at the time of the 'show' command.
\r
143 public String update () {
\r
144 logger.debug("Updating show,stat,termlist,bytarget from pazpar2");
\r
145 return update("show,stat,termlist,bytarget");
\r
148 public boolean validateUpdateRequest(String commands) {
\r
149 if (errors.hasConfigurationErrors()) {
\r
150 logger.error("The command(s) " + commands + " are cancelled due to configuration errors.");
\r
152 } else if (!commands.equals("search") && pzresp.getSearch().hasApplicationError()) {
\r
153 logger.error("The command(s) " + commands + " are cancelled because the latest search command had an error.");
\r
155 } else if (!commandsAreValid(commands)) {
\r
156 logger.debug("The command(s) " + commands + " are cancelled because the were not found to be ready/valid.");
\r
158 } else if (!hasQuery() && !(commands.equals("record") && pzreq.getCommand("record").hasParameterValue("recordquery"))) {
\r
159 logger.debug("The command(s) " + commands + " are held off because there's not yet a query.");
\r
169 * Refreshes the data objects listed in 'commands' from pazpar2
\r
172 * @return Number of activeclients at the time of the 'show' command
\r
174 public String update (String commands) {
\r
175 logger.info("Request to update: " + commands);
\r
177 if (!validateUpdateRequest(commands)) {
\r
179 } else if (commands.equals("search")) {
\r
182 } else if (commands.equals("record")) {
\r
184 } else if (pzresp.getSearch().isNew()) {
\r
185 logger.info("New search. Marking it old, then returning 'new' to trigger another round-trip.");
\r
186 pzresp.getSearch().setIsNew(false);
\r
189 handleQueryStateChanges(commands);
\r
190 if (pzresp.getSearch().hasApplicationError()) {
\r
191 logger.error("The command(s) " + commands + " are cancelled because the latest search command had an error.");
\r
194 logger.debug("Processing request for " + commands);
\r
196 List<CommandThread> threadList = new ArrayList<CommandThread>();
\r
197 StringTokenizer tokens = new StringTokenizer(commands,",");
\r
198 while (tokens.hasMoreElements()) {
\r
199 threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient));
\r
201 for (CommandThread thread : threadList) {
\r
204 for (CommandThread thread : threadList) {
\r
207 } catch (InterruptedException e) {
\r
208 e.printStackTrace();
\r
211 for (CommandThread thread : threadList) {
\r
212 String commandName = thread.getCommand().getCommandName();
\r
213 ClientCommandResponse response = (ClientCommandResponse) thread.getCommandResponse();
\r
214 responseLogger.debug("Response was: " + response.getResponseString());
\r
215 ResponseDataObject responseObject = ResponseParser.getParser().getDataObject(response);
\r
216 if (ResponseParser.docTypes.contains(responseObject.getType())) {
\r
217 pzresp.put(commandName, responseObject);
\r
219 logger.info("Unknown doc type [" + responseObject.getType() + "]. Was not cached.");
\r
222 return pzresp.getActiveClients();
\r
225 } catch (ClassCastException cce) {
\r
226 cce.printStackTrace();
\r
228 } catch (NullPointerException npe) {
\r
229 npe.printStackTrace();
\r
231 } catch (Exception e) {
\r
232 e.printStackTrace();
\r
238 public boolean commandsAreValid(String commands) {
\r
239 if (commands.equals("record")) {
\r
240 if (!pzreq.getCommand("record").hasParameterValue("id")) {
\r
241 logger.debug("Skips sending record command due to lacking id parameter");
\r
248 public String toggleRecord (String recId) {
\r
249 if (hasRecord(recId)) {
\r
250 pzreq.getRecord().removeParameters();
\r
251 pzresp.put("record", new RecordResponse());
\r
254 pzreq.getRecord().setId(recId);
\r
255 doCommand("record");
\r
256 return pzresp.getRecord().getActiveClients();
\r
261 public boolean hasRecord (String recId) {
\r
262 return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId);
\r
265 public String getCurrentStateKey () {
\r
266 return stateMgr.getCurrentState().getKey();
\r
269 public void setCurrentStateKey(String key) {
\r
270 stateMgr.setCurrentStateKey(key);
\r
273 protected boolean hasQuery() {
\r
274 return pzreq.getCommand("search").hasParameterValue("query");
\r
279 public ResultsPager getPager () {
\r
280 if (pager == null) {
\r
281 pager = new ResultsPager(pzresp);
\r
287 public ResultsPager setPager (int pageRange) {
\r
288 pager = new ResultsPager(pzresp,pageRange,pzreq);
\r
292 protected void handleQueryStateChanges (String commands) {
\r
293 if (stateMgr.hasPendingStateChange("search") && hasQuery()) {
\r
294 logger.info("Triggered search: Found pending search change, doing search before updating " + commands);
\r
297 if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) {
\r
298 logger.debug("Found pending record ID change. Doing record before updating " + commands);
\r
299 stateMgr.hasPendingStateChange("record",false);
\r
300 if (pzreq.getCommand("record").hasParameterValue("id")) {
\r
303 pzresp.put("record", new RecordResponse());
\r
309 * Validates the request then executes the command and parses the response.
\r
310 * If the parsed response is of a known type it will be cached in 'pzresp'
\r
312 * @param commandName The command to be executed
\r
313 * @return An XML response parsed to form a response data object
\r
315 protected ResponseDataObject doCommand(String commandName) {
\r
316 ResponseDataObject responseObject = null;
\r
317 if (validateUpdateRequest(commandName)) {
\r
318 logger.debug(pzreq.getCommand(commandName).getEncodedQueryString() + ": Results for "+ pzreq.getCommand("search").getEncodedQueryString());
\r
319 Pazpar2Command command = pzreq.getCommand(commandName);
\r
320 long start = System.currentTimeMillis();
\r
321 HttpResponseWrapper commandResponse = searchClient.executeCommand(command);
\r
322 long end = System.currentTimeMillis();
\r
323 logger.debug("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );
\r
324 responseLogger.debug("Response was: " + commandResponse.getResponseString());
\r
325 responseObject = ResponseParser.getParser().getDataObject((ClientCommandResponse)commandResponse);
\r
326 if (ResponseParser.docTypes.contains(responseObject.getType())) {
\r
327 pzresp.put(commandName, responseObject);
\r
330 return responseObject;
\r
334 public void stateUpdated(String commandName) {
\r
335 logger.debug("State change reported for [" + commandName + "]");
\r
336 if (commandName.equals("show")) {
\r
337 logger.debug("Updating show");
\r
338 update(commandName);
\r
342 public void setServiceProxyUrl(String url) {
\r
343 searchClient = spClient;
\r
344 setServiceType(SERVICE_TYPE_SP);
\r
345 setServiceUrl(url);
\r
348 public String getServiceProxyUrl () {
\r
349 if (isServiceProxyService()) {
\r
350 return spClient.getServiceUrl();
\r
356 public void setPazpar2Url(String url) {
\r
357 searchClient = pz2Client;
\r
358 setServiceType(SERVICE_TYPE_PZ2);
\r
359 setServiceUrl(url);
\r
362 public String getPazpar2Url() {
\r
363 if (isPazpar2Service()) {
\r
364 return pz2Client.getServiceUrl();
\r
372 public void setServiceUrl(String url) {
\r
373 if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {
\r
374 pzreq.getRecord().removeParametersInState();
\r
375 pzreq.getSearch().removeParametersInState();
\r
376 pzresp.resetAllSessionData();
\r
378 searchClient.setServiceUrl(url);
\r
382 public String getServiceUrl() {
\r
383 return (searchClient!=null ? searchClient.getServiceUrl() : "");
\r
386 public boolean getServiceUrlIsDefined() {
\r
387 return (searchClient != null && searchClient.hasServiceUrl());
\r
390 public List<String> getServiceProxyUrls() {
\r
391 List<String> urls = new ArrayList<String>();
\r
393 urls.addAll(serviceProxyUrls);
\r
397 public List<String> getPazpar2Urls () {
\r
398 List<String> urls = new ArrayList<String>();
\r
400 urls.addAll(pazpar2Urls);
\r
404 public String getServiceType () {
\r
405 return serviceType;
\r
408 public boolean isPazpar2Service () {
\r
409 return serviceType.equals(SERVICE_TYPE_PZ2);
\r
412 public boolean isServiceProxyService() {
\r
413 return serviceType.equals(SERVICE_TYPE_SP);
\r
416 public boolean serviceIsToBeDecided () {
\r
417 return serviceType.equals(SERVICE_TYPE_TBD);
\r
420 public ServiceProxyClient getSpClient () {
\r
425 public boolean getAuthenticationRequired () {
\r
426 return spClient.isAuthenticatingClient();
\r
430 public String getCheckHistory () {
\r
431 return ":pz2watch:stateForm:windowlocationhash";
\r
435 public String getWatchActiveclients () {
\r
436 return ":pz2watch:activeclientsForm:activeclientsField";
\r
440 public String getWatchActiveclientsRecord () {
\r
441 return ":pz2watch:activeclientsForm:activeclientsFieldRecord";
\r
445 public void configure(ConfigurationReader reader)
\r
446 throws ConfigurationException {
\r
447 Configuration config = reader.getConfiguration(this);
\r
448 if (config == null) {
\r
449 serviceType = SERVICE_TYPE_TBD;
\r
451 String service = config.get("TYPE");
\r
452 if (service == null || service.length()==0) {
\r
453 serviceType = SERVICE_TYPE_TBD;
\r
454 } else if (serviceTypes.contains(service.toUpperCase())) {
\r
455 setServiceType(service.toUpperCase());
\r
457 logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);
\r
458 serviceType = SERVICE_TYPE_TBD;
\r
460 serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");
\r
461 pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");
\r
463 logger.info("Service Type is configured to " + serviceType);
\r
468 public Map<String, String> getDefaults() {
\r
469 return new HashMap<String,String>();
\r
473 public String getModuleName() {
\r
474 return MODULE_NAME;
\r
478 public List<String> documentConfiguration() {
\r
479 return new ArrayList<String>();
\r
483 public void setServiceTypePZ2() {
\r
484 setServiceType(SERVICE_TYPE_PZ2);
\r
488 public void setServiceTypeSP() {
\r
489 setServiceType(SERVICE_TYPE_SP);
\r
493 public void setServiceTypeTBD() {
\r
494 setServiceType(SERVICE_TYPE_TBD);
\r
497 private void setServiceType(String type) {
\r
498 if (!serviceType.equals(type) &&
\r
499 !serviceType.equals(SERVICE_TYPE_TBD)) {
\r
500 resetSearchAndRecordCommands();
\r
501 pzresp.resetAllSessionData();
\r
503 serviceType = type;
\r
504 if (serviceType.equals(SERVICE_TYPE_PZ2)) {
\r
505 searchClient = pz2Client;
\r
506 logger.info("Setting a Pazpar2 client to serve requests.");
\r
507 } else if (serviceType.equals(SERVICE_TYPE_SP)) {
\r
508 searchClient = spClient;
\r
509 logger.info("Setting a Service Proxy client to serve requests.");
\r
511 logger.info("Clearing search client. No client defined to serve requests at this point.");
\r
512 searchClient = null;
\r