\r
import java.io.Serializable;\r
import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.HashMap;\r
import java.util.List;\r
+import java.util.Map;\r
import java.util.StringTokenizer;\r
\r
import javax.annotation.PostConstruct;\r
import javax.enterprise.context.SessionScoped;\r
-import javax.enterprise.inject.Alternative;\r
import javax.inject.Inject;\r
import javax.inject.Named;\r
\r
import org.apache.log4j.Logger;\r
\r
+import com.indexdata.mkjsf.config.Configurable;\r
+import com.indexdata.mkjsf.config.Configuration;\r
import com.indexdata.mkjsf.config.ConfigurationReader;\r
import com.indexdata.mkjsf.controls.ResultsPager;\r
import com.indexdata.mkjsf.errors.ConfigurationError;\r
import com.indexdata.mkjsf.errors.ErrorCentral;\r
import com.indexdata.mkjsf.errors.ErrorHelper;\r
import com.indexdata.mkjsf.pazpar2.commands.CommandParameter;\r
+import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;\r
import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands;\r
-import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData;\r
-import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseParser;\r
-import com.indexdata.mkjsf.pazpar2.data.Pazpar2Responses;\r
+import com.indexdata.mkjsf.pazpar2.commands.sp.ServiceProxyCommand;\r
import com.indexdata.mkjsf.pazpar2.data.RecordResponse;\r
+import com.indexdata.mkjsf.pazpar2.data.ResponseDataObject;\r
+import com.indexdata.mkjsf.pazpar2.data.ResponseParser;\r
+import com.indexdata.mkjsf.pazpar2.data.Responses;\r
+import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser;\r
import com.indexdata.mkjsf.pazpar2.state.StateListener;\r
import com.indexdata.mkjsf.pazpar2.state.StateManager;\r
import com.indexdata.mkjsf.utils.Utils;\r
\r
-@Named("pz2") @SessionScoped @Alternative\r
-public class Pz2Bean implements Pz2Interface, StateListener, Serializable {\r
+@Named("pz2") @SessionScoped\r
+public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Serializable {\r
+\r
+ private static final String MODULE_NAME = "service";\r
+ private static String SERVICE_TYPE_TBD = "TBD", SERVICE_TYPE_PZ2 = "PZ2", SERVICE_TYPE_SP = "SP";\r
+ private static final List<String> serviceTypes = \r
+ Arrays.asList(SERVICE_TYPE_PZ2,SERVICE_TYPE_SP,SERVICE_TYPE_TBD);\r
+ private String serviceType = SERVICE_TYPE_TBD;\r
+ private List<String> serviceProxyUrls = new ArrayList<String>();\r
+ public static final String SERVICE_PROXY_URL_LIST = "SERVICE_PROXY_URL_LIST";\r
+ private List<String> pazpar2Urls = new ArrayList<String>();\r
+ public static final String PAZPAR2_URL_LIST = "PAZPAR2_URL_LIST";\r
+\r
\r
private static final long serialVersionUID = 3440277287081557861L;\r
private static Logger logger = Logger.getLogger(Pz2Bean.class);\r
- private static Logger responseLogger = Logger.getLogger("com.indexdata.mkjsf.pazpar2.responses");\r
- \r
- protected SearchClient searchClient = null;\r
- \r
+ private static Logger responseLogger = Logger.getLogger("com.indexdata.mkjsf.pazpar2.responses"); \r
+ protected Pz2Client pz2Client = null;\r
+ protected ServiceProxyClient spClient = null;\r
+ protected SearchClient searchClient = null; \r
+ \r
@Inject ConfigurationReader configurator;\r
@Inject StateManager stateMgr;\r
@Inject Pazpar2Commands pzreq;\r
- @Inject Pazpar2Responses pzresp;\r
+ @Inject Responses pzresp;\r
@Inject ErrorCentral errors;\r
+ @Inject ServiceProxyUser user;\r
\r
protected ResultsPager pager = null; \r
-\r
\r
protected ErrorHelper errorHelper = null;\r
\r
\r
@PostConstruct\r
public void postConstruct() { \r
- logger.debug("in start of Pz2Bean post-construct configurator is " + configurator);\r
+ logger.debug("Pz2Bean post-construct: Configurator is " + configurator);\r
logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next.");\r
- searchClient = new Pz2Client();\r
- logger.info("Using [" + Utils.objectId(searchClient) + "] configured by [" \r
- + Utils.objectId(configurator) + "]" ); \r
- configureClient(searchClient,configurator); \r
+ pz2Client = new Pz2Client();\r
+ configureClient(pz2Client,configurator);\r
+ spClient = new ServiceProxyClient();\r
+ configureClient(spClient,configurator);\r
+ try {\r
+ this.configure(configurator);\r
+ } catch (ConfigurationException e) {\r
+ logger.error("There was a problem configuring the Pz2Bean (\"pz2\")");\r
+ e.printStackTrace();\r
+ } \r
stateMgr.addStateListener(this); \r
} \r
\r
- public void configureClient(SearchClient searchClient, ConfigurationReader configReader) {\r
+ public void configureClient(SearchClient client, ConfigurationReader configReader) {\r
logger.debug(Utils.objectId(this) + " will configure search client for the session");\r
try {\r
- searchClient.configure(configReader); \r
+ client.configure(configReader); \r
} catch (ConfigurationException e) {\r
logger.debug("Pz2Bean adding configuration error");\r
errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage())); \r
} \r
logger.info(configReader.document());\r
- pzresp.reset(); \r
+ pzresp.resetAllSessionData(); \r
+ }\r
+ \r
+ public void resetSearchAndRecordCommands () {\r
+ pzreq.getRecord().removeParametersInState();\r
+ pzreq.getSearch().removeParametersInState(); \r
}\r
-\r
\r
public void doSearch(String query) {\r
pzreq.getSearch().setParameter(new CommandParameter("query","=",query)); \r
doSearch();\r
}\r
\r
- public void doSearch() { \r
- stateMgr.hasPendingStateChange("search",false);\r
- pzresp.reset();\r
- // resets some record and show command parameters without \r
- // changing state or creating state change feedback\r
- pzreq.getRecord().removeParametersInState(); \r
- pzreq.getShow().setParameterInState(new CommandParameter("start","=",0)); \r
- logger.debug(Utils.objectId(this) + " is searching using "+pzreq.getCommand("search").getUrlEncodedParameterValue("query"));\r
- doCommand("search"); \r
+ public void doSearch() {\r
+ if (errors.hasConfigurationErrors()) {\r
+ logger.error("Ignoring search request due to configuration errors.");\r
+ } else if (searchClient == null){\r
+ logger.error("No search client defined. A client must either be pre-configured or selected before searching.");\r
+ errors.addConfigurationError(new ConfigurationError("No client defined","Client is null","No search client defined. A client must be pre-configured or selected runtime, prior to searching."));\r
+ } else {\r
+ stateMgr.hasPendingStateChange("search",false);\r
+ pzresp.resetSearchResponses();\r
+ // resets some record and show command parameters without \r
+ // changing state or creating state change feedback\r
+ pzreq.getRecord().removeParametersInState(); \r
+ pzreq.getShow().setParameterInState(new CommandParameter("start","=",0)); \r
+ logger.debug(Utils.objectId(this) + " is searching using "+pzreq.getCommand("search").getUrlEncodedParameterValue("query"));\r
+ searchClient.setSearchCommand(pzreq.getCommand("search"));\r
+ doCommand("search");\r
+ }\r
+ }\r
+ \r
+ public String doRecord() {\r
+ if (errors.hasConfigurationErrors()) {\r
+ logger.error("Ignoring record request due to configuration errors.");\r
+ return "";\r
+ } else if (!pzreq.getCommand("record").hasParameterValue("id")) {\r
+ logger.debug("Ignoring record request due to no id parameter.");\r
+ return "";\r
+ } else if (pzresp.getSearch().hasApplicationError()) {\r
+ logger.debug("Ignoring record request due search error.");\r
+ return "";\r
+ } else {\r
+ logger.debug("Executing record command");\r
+ doCommand("record");\r
+ return pzresp.getRecord().getActiveClients();\r
+ }\r
}\r
\r
/**\r
*/\r
public String update () {\r
logger.debug("Updating show,stat,termlist,bytarget from pazpar2");\r
- return update("show,stat,termlist,bytarget");\r
+ if (errors.hasConfigurationErrors()) {\r
+ logger.error("Ignoring show,stat,termlist,bytarget commands due to configuration errors.");\r
+ return "";\r
+ } else if (pzresp.getSearch().hasApplicationError()) {\r
+ logger.error("Ignoring show,stat,termlist,bytarget commands due to problem with most recent search.");\r
+ return "";\r
+ } else if (!hasQuery()) {\r
+ logger.debug("Ignoring show,stat,termlist,bytarget commands because there is not yet a query.");\r
+ return "";\r
+ } else {\r
+ return update("show,stat,termlist,bytarget");\r
+ }\r
}\r
- \r
+ \r
/**\r
* Refreshes the data objects listed in 'commands' from pazpar2\r
* \r
* @return Number of activeclients at the time of the 'show' command\r
*/\r
public String update (String commands) {\r
+ logger.debug("Request to update: " + commands);\r
try {\r
- if (! errors.hasConfigurationErrors()) {\r
- if (commandsAreValid(commands)) {\r
- if (hasQuery() || (commands.equals("record") && pzreq.getCommand("record").hasParameterValue("recordquery"))) {\r
- handleQueryStateChanges(commands);\r
+ if (commands.equals("search")) {\r
+ doSearch();\r
+ return "";\r
+ } else if (commands.equals("record")) {\r
+ return doRecord();\r
+ } else if (pzresp.getSearch().isNew()) {\r
+ logger.info("New search. Marking it old, then returning 'new' to trigger another round-trip.");\r
+ pzresp.getSearch().setIsNew(false);\r
+ return "new";\r
+ } else {\r
+ handleQueryStateChanges(commands);\r
+ if (pzresp.getSearch().hasApplicationError()) {\r
+ logger.error("The command(s) " + commands + " cancelled because the latest search command had an error.");\r
+ return "0";\r
+ } else if (errors.hasConfigurationErrors()) {\r
+ logger.error("The command(s) " + commands + " cancelled due to configuration errors.");\r
+ return "0";\r
+ } else {\r
logger.debug("Processing request for " + commands); \r
List<CommandThread> threadList = new ArrayList<CommandThread>();\r
StringTokenizer tokens = new StringTokenizer(commands,",");\r
}\r
}\r
for (CommandThread thread : threadList) {\r
- String commandName = thread.getCommand().getName();\r
- String response = thread.getResponse();\r
- responseLogger.debug("Response was: " + response);\r
- Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(response);\r
- if (Pazpar2ResponseParser.docTypes.contains(responseObject.getType())) {\r
+ String commandName = thread.getCommand().getCommandName();\r
+ ClientCommandResponse response = (ClientCommandResponse) thread.getCommandResponse();\r
+ responseLogger.debug("Response was: " + response.getResponseString());\r
+ ResponseDataObject responseObject = ResponseParser.getParser().getDataObject(response);\r
+ if (ResponseParser.docTypes.contains(responseObject.getType())) {\r
pzresp.put(commandName, responseObject);\r
} else {\r
- if (commandName.equals("record") && \r
- (pzreq.getRecord().hasParameterValue("offset") ||\r
- pzreq.getRecord().hasParameterValue("checksum"))) {\r
- RecordResponse recordResponse = new RecordResponse();\r
- recordResponse.setType("record");\r
- recordResponse.setXml(responseObject.getXml());\r
- recordResponse.setAttribute("activeclients", "0");\r
- pzresp.put(commandName, recordResponse);\r
- }\r
+ logger.info("Unknown doc type [" + responseObject.getType() + "]. Was not cached.");\r
}\r
}\r
- if (commands.equals("record")) {\r
- return pzresp.getRecord().getActiveClients();\r
- } else {\r
- return pzresp.getActiveClients();\r
- } \r
- } else {\r
- logger.debug("Skipped requests for " + commands + " as there's not yet a query."); \r
- pzresp.reset();\r
- return "0";\r
+ return pzresp.getActiveClients();\r
}\r
- } else {\r
- logger.error("Did not attemt to run command(s) due to a validation error.");\r
- return "0";\r
- }\r
- } else { \r
- logger.error("Did not attempt to execute query since there are configuration errors.");\r
- return "0";\r
- }\r
+ } \r
} catch (ClassCastException cce) {\r
cce.printStackTrace(); \r
return "";\r
} catch (NullPointerException npe) {\r
npe.printStackTrace();\r
return "";\r
+ } catch (Exception e) {\r
+ e.printStackTrace();\r
+ return "";\r
}\r
\r
}\r
- \r
- public boolean commandsAreValid(String commands) {\r
- if (commands.equals("record")) {\r
- if (!pzreq.getCommand("record").hasParameterValue("id")) {\r
- logger.error("Attempt to send record command without the id parameter");\r
- return false;\r
- }\r
- }\r
- return true;\r
- }\r
- \r
+ \r
public String toggleRecord (String recId) {\r
if (hasRecord(recId)) {\r
pzreq.getRecord().removeParameters(); \r
return "";\r
} else {\r
pzreq.getRecord().setId(recId);\r
- return doCommand("record");\r
+ doCommand("record");\r
+ return pzresp.getRecord().getActiveClients();\r
}\r
}\r
\r
pager = new ResultsPager(pzresp,pageRange,pzreq);\r
return pager;\r
}\r
- \r
+ \r
+ /**\r
+ * This methods main purpose is to support browser history.\r
+ * \r
+ * When the browsers back or forward buttons are pressed, a \r
+ * re-search /might/ be required - namely if the query changes.\r
+ * So, as the UI requests updates of the page (show,facets,\r
+ * etc) this method checks if a search must be executed\r
+ * before those updates are performed.\r
+ * \r
+ * @see {@link com.indexdata.mkjsf.pazpar2.state.StateManager#setCurrentStateKey} \r
+ * @param commands\r
+ */\r
protected void handleQueryStateChanges (String commands) {\r
if (stateMgr.hasPendingStateChange("search") && hasQuery()) { \r
- logger.debug("Found pending search change. Doing search before updating " + commands); \r
+ logger.info("Triggered search: Found pending search change [" + pzreq.getCommand("search").toString() + "], doing search before updating " + commands); \r
doSearch();\r
} \r
if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) { \r
logger.debug("Found pending record ID change. Doing record before updating " + commands);\r
stateMgr.hasPendingStateChange("record",false);\r
if (pzreq.getCommand("record").hasParameterValue("id")) {\r
- update("record");\r
+ doRecord();\r
} else { \r
pzresp.put("record", new RecordResponse());\r
}\r
}\r
}\r
\r
- protected String doCommand(String commandName) { \r
- logger.debug(pzreq.getCommand(commandName).getEncodedQueryString() + ": Results for "+ pzreq.getCommand("search").getEncodedQueryString());\r
- return update(commandName);\r
+ /**\r
+ * Executes the command and parses the response to create data objects.\r
+ * If the parsed response is of a known type it will be cached in 'pzresp'\r
+ * \r
+ * @param commandName The command to be executed\r
+ * @return An XML response parsed to form a response data object\r
+ */\r
+ protected ResponseDataObject doCommand(String commandName) {\r
+ if (pzreq.getCommand(commandName).spOnly() && isPazpar2Service()) {\r
+ logger.warn("Skipping " + commandName + " - SP-only command, un-supported by Pazpar2");\r
+ return new ResponseDataObject();\r
+ } else {\r
+ ResponseDataObject responseObject = null; \r
+ logger.info("Request "+commandName + ": "+ pzreq.getCommand("search").toString());\r
+ Pazpar2Command command = pzreq.getCommand(commandName);\r
+ long start = System.currentTimeMillis();\r
+ HttpResponseWrapper commandResponse = searchClient.executeCommand(command);\r
+ long end = System.currentTimeMillis();\r
+ logger.debug("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );\r
+ responseLogger.debug("Response was: " + commandResponse.getResponseString());\r
+ if (commandResponse.getContentType().contains("xml")) {\r
+ responseObject = ResponseParser.getParser().getDataObject((ClientCommandResponse)commandResponse);\r
+ if (ResponseParser.docTypes.contains(responseObject.getType())) {\r
+ logger.debug("Storing " + responseObject.getType() + " in pzresp. ");\r
+ pzresp.put(commandName, responseObject);\r
+ } else {\r
+ if (commandName.equals("record")) {\r
+ logger.debug("Command was 'record' but response not '<record>' - assuming raw record response.");\r
+ ResponseDataObject recordResponse = new RecordResponse(); \r
+ recordResponse.setType("record");\r
+ recordResponse.setXml(responseObject.getXml()); \r
+ recordResponse.setAttribute("activeclients", "0");\r
+ pzresp.put("record", recordResponse); \r
+ } \r
+ }\r
+ } else if (commandResponse.isBinary()) {\r
+ responseObject = new RecordResponse(); \r
+ responseObject.setType(commandName);\r
+ logger.info("Binary response");\r
+ responseObject.setAttribute("activeclients", "0");\r
+ responseObject.setXml("<record>binary response</record>");\r
+ responseObject.setBinary(commandResponse.getBytes());\r
+ pzresp.put("record", responseObject);\r
+ } else {\r
+ logger.error("Response was not found to be XML or binary. The response was not handled.");\r
+ }\r
+ return responseObject;\r
+ }\r
}\r
- \r
+ \r
@Override\r
public void stateUpdated(String commandName) {\r
logger.debug("State change reported for [" + commandName + "]");\r
} \r
}\r
\r
+ public void setServiceProxyUrl(String url) {\r
+ searchClient = spClient;\r
+ setServiceType(SERVICE_TYPE_SP);\r
+ setServiceUrl(url);\r
+ }\r
+ \r
+ public String getServiceProxyUrl () {\r
+ if (isServiceProxyService()) {\r
+ return spClient.getServiceUrl();\r
+ } else {\r
+ return "";\r
+ }\r
+ }\r
+ \r
+ public void setPazpar2Url(String url) {\r
+ searchClient = pz2Client;\r
+ setServiceType(SERVICE_TYPE_PZ2);\r
+ setServiceUrl(url);\r
+ }\r
+ \r
+ public String getPazpar2Url() {\r
+ if (isPazpar2Service()) {\r
+ return pz2Client.getServiceUrl();\r
+ } else {\r
+ return "";\r
+ }\r
+ }\r
+\r
+ \r
+ @Override\r
+ public void setServiceUrl(String url) {\r
+ if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) {\r
+ pzreq.getRecord().removeParametersInState();\r
+ pzreq.getSearch().removeParametersInState();\r
+ pzresp.resetAllSessionData();\r
+ user.clear();\r
+ searchClient.setServiceUrl(url);\r
+ } \r
+ }\r
+ \r
+ public String getServiceUrl() {\r
+ return (searchClient!=null ? searchClient.getServiceUrl() : "");\r
+ }\r
+ \r
+ public void setServiceId () {\r
+ pzreq.getRecord().removeParametersInState();\r
+ pzreq.getSearch().removeParametersInState();\r
+ pzresp.resetSearchResponses();\r
+ pz2Client.setServiceId(pzreq.getInit().getService());\r
+ }\r
+ \r
+ public String getServiceId () {\r
+ return pzreq.getInit().getService();\r
+ }\r
+ \r
+ public boolean getServiceUrlIsDefined() {\r
+ return (searchClient != null && searchClient.hasServiceUrl());\r
+ }\r
+ \r
+ public List<String> getServiceProxyUrls() {\r
+ List<String> urls = new ArrayList<String>();\r
+ urls.add("");\r
+ urls.addAll(serviceProxyUrls);\r
+ return urls;\r
+ }\r
+ \r
+ public List<String> getPazpar2Urls () {\r
+ List<String> urls = new ArrayList<String>();\r
+ urls.add("");\r
+ urls.addAll(pazpar2Urls);\r
+ return urls;\r
+ }\r
+ \r
+ public String getServiceType () {\r
+ return serviceType;\r
+ }\r
+ \r
+ public boolean isPazpar2Service () {\r
+ return serviceType.equals(SERVICE_TYPE_PZ2);\r
+ }\r
+ \r
+ public boolean isServiceProxyService() {\r
+ return serviceType.equals(SERVICE_TYPE_SP);\r
+ }\r
+ \r
+ public boolean serviceIsToBeDecided () {\r
+ return serviceType.equals(SERVICE_TYPE_TBD);\r
+ }\r
+ \r
+ public ServiceProxyClient getSpClient () {\r
+ return spClient;\r
+ } \r
+ \r
@Override\r
public boolean getAuthenticationRequired () {\r
- return searchClient.isAuthenticatingClient();\r
+ return spClient.isAuthenticatingClient();\r
}\r
\r
@Override\r
public String getWatchActiveclientsRecord () {\r
return ":pz2watch:activeclientsForm:activeclientsFieldRecord";\r
}\r
+\r
+ @Override\r
+ public void configure(ConfigurationReader reader)\r
+ throws ConfigurationException {\r
+ Configuration config = reader.getConfiguration(this);\r
+ if (config == null) {\r
+ serviceType = SERVICE_TYPE_TBD;\r
+ } else {\r
+ String service = config.get("TYPE");\r
+ if (service == null || service.length()==0) {\r
+ serviceType = SERVICE_TYPE_TBD;\r
+ } else if (serviceTypes.contains(service.toUpperCase())) { \r
+ setServiceType(service.toUpperCase());\r
+ } else {\r
+ logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes);\r
+ serviceType = SERVICE_TYPE_TBD;\r
+ }\r
+ serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,",");\r
+ pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ",");\r
+ }\r
+ logger.info(reader.document());\r
+ logger.info("Service Type is configured to " + serviceType);\r
+ \r
+ }\r
+\r
+ @Override\r
+ public Map<String, String> getDefaults() {\r
+ return new HashMap<String,String>();\r
+ }\r
+\r
+ @Override\r
+ public String getModuleName() {\r
+ return MODULE_NAME;\r
+ }\r
+\r
+ @Override\r
+ public List<String> documentConfiguration() {\r
+ return new ArrayList<String>();\r
+ }\r
+\r
+ @Override\r
+ public void setServiceTypePZ2() {\r
+ setServiceType(SERVICE_TYPE_PZ2); \r
+ }\r
+\r
+ @Override\r
+ public void setServiceTypeSP() {\r
+ setServiceType(SERVICE_TYPE_SP); \r
+ }\r
+\r
+ @Override\r
+ public void setServiceTypeTBD() {\r
+ setServiceType(SERVICE_TYPE_TBD); \r
+ }\r
+ \r
+ private void setServiceType(String type) {\r
+ if (!serviceType.equals(type) &&\r
+ !serviceType.equals(SERVICE_TYPE_TBD)) {\r
+ resetSearchAndRecordCommands();\r
+ pzresp.resetAllSessionData();\r
+ }\r
+ serviceType = type;\r
+ if (serviceType.equals(SERVICE_TYPE_PZ2)) {\r
+ searchClient = pz2Client;\r
+ logger.info("Setting a Pazpar2 client to serve requests.");\r
+ } else if (serviceType.equals(SERVICE_TYPE_SP)) {\r
+ searchClient = spClient;\r
+ logger.info("Setting a Service Proxy client to serve requests.");\r
+ } else {\r
+ logger.info("Clearing search client. No client defined to serve requests at this point.");\r
+ searchClient = null;\r
+ }\r
+ }\r
\r
}\r