From: Niels Erik G. Nielsen Date: Mon, 15 Apr 2013 23:31:43 +0000 (-0400) Subject: Renames pz2utils4jsf package to mkjsf X-Git-Tag: v0.0.7~153 X-Git-Url: http://git.indexdata.com/?p=mkjsf-moved-to-github.git;a=commitdiff_plain;h=ccb28ae8d5d46d29c40bd8b1637522c212b80636 Renames pz2utils4jsf package to mkjsf --- diff --git a/src/main/java/com/indexdata/mkjsf/config/Configurable.java b/src/main/java/com/indexdata/mkjsf/config/Configurable.java new file mode 100644 index 0000000..34f841c --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/config/Configurable.java @@ -0,0 +1,48 @@ +package com.indexdata.mkjsf.config; + +import java.util.List; +import java.util.Map; + +import com.indexdata.mkjsf.errors.ConfigurationException; + +/** + * Interface to be implemented by any part of an application that wish to + * use a ConfigurationReader for it's configuration. The Configurables that + * come with the project are a Pazpar2 client and a Service Proxy client + * + * @author Niels Erik + * + */ +public interface Configurable { + + /** + * Configures the Configurable using the configuration obtained by the + * provided configuration reader + * @param reader used for reading the configuration + * @throws ConfigurationException + */ + public void configure(ConfigurationReader reader) throws ConfigurationException; + + /** + * Returns the default parameters that the configurable has defined for itself + * Should be invoked by the configuration reader before it possibly overrides + * some parameters obtained from the external configuration source + * @return + */ + public Map getDefaults(); + + /** + * Returns the name of the module, can be used by a configuration reader that + * has distinguishes between sets of configuration properties by component name + * @return name of the part that is to be configured + */ + public String getModuleName(); + + /** + * The components documentation of how it was configured. + * + * @return a list of Strings describing configuration details + */ + public List documentConfiguration(); + +} diff --git a/src/main/java/com/indexdata/mkjsf/config/Configuration.java b/src/main/java/com/indexdata/mkjsf/config/Configuration.java new file mode 100644 index 0000000..f375318 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/config/Configuration.java @@ -0,0 +1,79 @@ +package com.indexdata.mkjsf.config; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.indexdata.masterkey.config.MissingMandatoryParameterException; +import com.indexdata.mkjsf.utils.Utils; + +/** + * Represents a configuration as a set of key-value pairs + * + * @author Niels Erik + * + */ +public class Configuration implements Serializable { + + private static final long serialVersionUID = -6801241975338182197L; + private static Logger logger = Logger.getLogger(Configuration.class); + Map properties = new HashMap(); + + public Configuration () { + logger.debug(Utils.objectId(this) + " being constructed with no argument"); + } + + public Configuration(Map parameters) { + addAll(parameters); + } + + public void addAll(Map parameters) { + for (String key : parameters.keySet()) { + properties.put(key, parameters.get(key)); + } + } + + public void addAll(Map defaults, Map parameters) { + for (String key : defaults.keySet()) { + properties.put(key, defaults.get(key)); + } + for (String key : parameters.keySet()) { + properties.put(key, parameters.get(key)); + } + } + + public String get(String key) { + return properties.get(key); + } + + public void set(String key, String value) { + properties.put(key, value); + } + + public String get(String key, String defaultValue) { + if (properties.containsKey(key)) { + return properties.get(key); + } else { + return defaultValue; + } + } + + public String getMandatory(String key) throws MissingMandatoryParameterException { + if (properties.containsKey(key)) { + return properties.get(key); + } + throw new MissingMandatoryParameterException("Missing mandatory parameter: " + key); + } + + public String getConfigFilePath() { + return get("configpath","nopathgiven"); + } + + public Map getConfigMap() { + return properties; + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/config/ConfigurationReader.java b/src/main/java/com/indexdata/mkjsf/config/ConfigurationReader.java new file mode 100644 index 0000000..cb0df8b --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/config/ConfigurationReader.java @@ -0,0 +1,31 @@ +package com.indexdata.mkjsf.config; + +import java.io.Serializable; +import java.util.List; + +import com.indexdata.mkjsf.errors.ConfigurationException; + +/** + * Interface to be implemented by classes that read configurations from a source - + * i.e. from web.xml, the file system, a database or hard-coded. + * + * @author Niels Erik + * + */ +public interface ConfigurationReader extends Serializable { + + /** + * Returns a Configuration to be used by the given Configurable + * + * @param configurable the configurable to be configured by a configuration obtained by this reader + * @return a Configuration, basically a set of key-value pairs + * @throws ConfigurationException + */ + public Configuration getConfiguration(Configurable configurable) throws ConfigurationException; + + /** + * Returns documentation for the key-value pairs obtained by this reader + * @return + */ + public List document(); +} diff --git a/src/main/java/com/indexdata/mkjsf/config/Mk2ConfigReader.java b/src/main/java/com/indexdata/mkjsf/config/Mk2ConfigReader.java new file mode 100644 index 0000000..bc57467 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/config/Mk2ConfigReader.java @@ -0,0 +1,94 @@ +package com.indexdata.mkjsf.config; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.Alternative; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.inject.Named; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; + +import org.apache.log4j.Logger; + +import com.indexdata.masterkey.config.MasterkeyConfiguration; +import com.indexdata.masterkey.config.ModuleConfiguration; +import com.indexdata.mkjsf.errors.ConfigurationException; +import com.indexdata.mkjsf.utils.Utils; + +import static com.indexdata.mkjsf.utils.Utils.nl; + +/** + * Reads configuration from a MasterKey configuration scheme + * + * + * @author Niels Erik + * + */ +@Named @SessionScoped @Alternative +public class Mk2ConfigReader implements ConfigurationReader { + + private static final long serialVersionUID = 8865086878660568870L; + private static Logger logger = Logger.getLogger(Mk2ConfigReader.class); + private Map configs = new HashMap(); + private Map configurables = new HashMap(); + + public Mk2ConfigReader () throws IOException { + logger.info(Utils.objectId(this) + " is instantiating Pazpar2 service configuration by MasterKey configuration scheme."); + } + + @Override + public Configuration getConfiguration(Configurable configurable) throws ConfigurationException { + if (configs.get(configurable.getModuleName()) == null) { + Configuration config = readConfig(configurable); + configs.put(configurable.getModuleName(), config); + configurables.put(configurable.getModuleName(), configurable); + } + return configs.get(configurable.getModuleName()); + } + + private Configuration readConfig (Configurable configurable) throws ConfigurationException { + Configuration config = new Configuration(); + ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); + ServletContext servletContext = (ServletContext) externalContext.getContext(); + MasterkeyConfiguration mkConfigContext; + try { + mkConfigContext = MasterkeyConfiguration.getInstance(servletContext, + "pazpar-application-jsf", ((HttpServletRequest) externalContext.getRequest()).getServerName()); + } catch (IOException e) { + throw new ConfigurationException(Mk2ConfigReader.class + " could not read configuration for '" + configurable.getModuleName() + "' using MasterKey configuration scheme: "+e.getMessage(),e); + } + try { + ModuleConfiguration moduleConfig = mkConfigContext.getModuleConfiguration(configurable.getModuleName()); + config.addAll(configurable.getDefaults(),moduleConfig.getConfigMap()); + config.set("configpath", moduleConfig.getConfigFilePath()); + } catch (IOException e) { + throw new ConfigurationException(Mk2ConfigReader.class + " could not read configuration for '"+ configurable.getModuleName() + "': "+e.getMessage(),e); + } + return config; + } + + public List document() { + List doc = new ArrayList(); + doc.add("Application properties as read by " + this.getClass()); + for (String moduleName : configs.keySet()) { + doc.add(nl+"Module: " + moduleName); + Configurable module = configurables.get(moduleName); + Map map = configs.get(moduleName).getConfigMap(); + for (String key : map.keySet()) { + doc.add(nl+key+": "+ map.get(key) + + (module.getDefaults().containsKey(key) ? + (module.getDefaults().get(key).equals(map.get(key)) ? " [default]" : " [override]") + : "")); + } + } + return doc; + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/config/WebXmlConfigReader.java b/src/main/java/com/indexdata/mkjsf/config/WebXmlConfigReader.java new file mode 100644 index 0000000..7be0261 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/config/WebXmlConfigReader.java @@ -0,0 +1,69 @@ +package com.indexdata.mkjsf.config; + +import static com.indexdata.mkjsf.utils.Utils.nl; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.Alternative; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.inject.Named; +import javax.servlet.ServletContext; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.errors.ConfigurationException; + +/** + * Reads a configuration from the context parameters of the deployment descriptor (web.xml) + * + * @author Niels Erik + * + */ +@Named @SessionScoped @Alternative +public class WebXmlConfigReader implements ConfigurationReader { + + private static final long serialVersionUID = 144390224959311772L; + private static Logger logger = Logger.getLogger(WebXmlConfigReader.class); + private Configuration config = null; + private Map parameters = new HashMap(); + + public WebXmlConfigReader () { + logger.info("Instantiating Pazpar2 service configuration by web.xml parameters"); + } + + public Configuration getConfiguration(Configurable configurable) throws ConfigurationException { + if (config == null) { + parameters.putAll(configurable.getDefaults()); + parameters.putAll(readConfig()); + config = new Configuration(parameters); + } + return config; + } + + private Map readConfig () throws ConfigurationException { + Map map = new HashMap(); + ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); + ServletContext servletContext = (ServletContext) externalContext.getContext(); + Enumeration enumer = servletContext.getInitParameterNames(); + while (enumer.hasMoreElements()) { + String name = enumer.nextElement(); + map.put(name,servletContext.getInitParameter(name)); + } + return map; + } + + public List document() { + List doc = new ArrayList(); + doc.add("Application properties as read by " + this.getClass()); + for (String key : parameters.keySet()) { + doc.add(nl+key+": "+ parameters.get(key)); + } + return doc; + } +} diff --git a/src/main/java/com/indexdata/mkjsf/controls/PageLink.java b/src/main/java/com/indexdata/mkjsf/controls/PageLink.java new file mode 100644 index 0000000..ea1a5f1 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/controls/PageLink.java @@ -0,0 +1,38 @@ +package com.indexdata.mkjsf.controls; + +import java.io.Serializable; + +import com.indexdata.mkjsf.controls.ResultsPager; + +public class PageLink implements Serializable { + + private static final long serialVersionUID = -468888598965842949L; + String text = ""; + int page = 0; + ResultsPager pager; + public PageLink(String text, int page, ResultsPager pager) { + this.text = text; + this.page = page; + this.pager = pager; + } + + public boolean isLink() { + return page>0; + } + + public boolean isCurrent() { + return (pager.getCurrentPageNum()==page); + } + + public String getText() { + return text; + } + + public int getPage() { + return page; + } + + public int getStart() { + return pager.getPageSize()*(page-1); + } +} diff --git a/src/main/java/com/indexdata/mkjsf/controls/ResultsPager.java b/src/main/java/com/indexdata/mkjsf/controls/ResultsPager.java new file mode 100644 index 0000000..3825d1e --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/controls/ResultsPager.java @@ -0,0 +1,141 @@ +package com.indexdata.mkjsf.controls; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2Responses; + +public class ResultsPager implements Serializable { + + private static final long serialVersionUID = 8854795222615583071L; + private Pazpar2Responses data = null; + private int pageRangeLength = 13; + private Pazpar2Commands req; + + public ResultsPager(Pazpar2Responses data) { + this.data = data; + } + + public ResultsPager(Pazpar2Responses data, int pageRange, Pazpar2Commands req) { + this.data = data; + this.pageRangeLength = pageRange; + this.req = req; + } + + private boolean hasHits () { + return (data.getShow().getMerged()>0); + } + + public int getCurrentPageNum () { + if (hasHits() && data.getShow().getNum()>0) { + return (data.getShow().getStart()/data.getShow().getNum())+1; + } else { + return 0; + } + } + + public int getPageSize() { + return data.getShow().getNum(); + } + + public int getFirstDisplayedPageNum () { + if (hasHits()) { + if (getCurrentPageNum() - (pageRangeLength/2) < 1) { + return 1; + } else { + return (getCurrentPageNum()-(pageRangeLength/2)); + } + } else { + return 0; + } + } + + public int getLastDisplayedPageNum () { + if (hasHits()) { + if ((getFirstDisplayedPageNum() + pageRangeLength-1) > getLastPageNum()) { + return getLastPageNum(); + } else { + return getFirstDisplayedPageNum() + pageRangeLength - 1; + } + } else { + return 0; + } + } + + public int getLastPageNum () { + if (hasHits()) { + return (int) Math.ceil(new Double(data.getShow().getMerged())/new Double(data.getShow().getNum())); + } else { + return 0; + } + } + + public List setPageLinks (int rangeLength) { + this.pageRangeLength = rangeLength; + return getPageLinks(); + } + + public List getPageLinks () { + ArrayList range = new ArrayList(); + if (hasHits()) { + for (int i = getFirstDisplayedPageNum(); i>0 && i<=getLastDisplayedPageNum();i++) { + range.add(new PageLink(i+"",i,this)); + } + } + return range; + } + + + public PageLink getPreviousPageLink (String text) { + String linkText = (text!=null && text.length()>0 ? text : "Prev"); + if (hasHits() && getCurrentPageNum()>1) { + return new PageLink(linkText,getCurrentPageNum()-1,this); + } else { + return new PageLink(linkText,0,this); + } + } + + public PageLink getNextPageLink (String text) { + String linkText = (text!=null && text.length()>0 ? text : "Next"); + if (hasHits() && getCurrentPageNum()1; + } + + public boolean hasNextPage () { + return getCurrentPage() < getLastPageNum(); + } + + public boolean hasPageAfterLastDisplayed() { + return getLastDisplayedPageNum() < getLastPageNum(); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/errors/ConfigurationError.java b/src/main/java/com/indexdata/mkjsf/errors/ConfigurationError.java new file mode 100644 index 0000000..575893b --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/errors/ConfigurationError.java @@ -0,0 +1,66 @@ +package com.indexdata.mkjsf.errors; + +import java.util.List; + +import com.indexdata.mkjsf.errors.ErrorHelper.ErrorCode; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2Error; + + +public class ConfigurationError implements ErrorInterface { + + private static final long serialVersionUID = -6599667223782130838L; + private String label; + private String message; + private String exception; + private ErrorHelper helper; + private ErrorCode applicationErrorCode; + + public ConfigurationError(String label, String exception, String message) { + this.label = label; + this.message = message; + this.exception = exception; + } + + public List getSuggestions() { + return helper.getSuggestions(this); + } + + @Override + public String getLabel() { + return label; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public String getException() { + return exception; + } + + @Override + public void setErrorHelper (ErrorHelper helper) { + this.helper = helper; + } + + @Override + public void setApplicationErrorCode(ErrorCode code) { + this.applicationErrorCode = code; + } + + @Override + public ErrorCode getApplicationErrorCode() { + return applicationErrorCode; + } + + public boolean hasPazpar2Error () { + return false; + } + + public Pazpar2Error getPazpar2Error() { + return null; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/errors/ConfigurationException.java b/src/main/java/com/indexdata/mkjsf/errors/ConfigurationException.java new file mode 100644 index 0000000..5aded06 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/errors/ConfigurationException.java @@ -0,0 +1,27 @@ +package com.indexdata.mkjsf.errors; + +public class ConfigurationException extends Exception { + + private static final long serialVersionUID = -2406313397798065423L; + + public ConfigurationException() { + // TODO Auto-generated constructor stub + } + + public ConfigurationException(String message) { + super(message); + // TODO Auto-generated constructor stub + } + + public ConfigurationException(Throwable cause) { + super(cause); + // TODO Auto-generated constructor stub + } + + public ConfigurationException(String message, Throwable cause) { + super(message, cause); + // TODO Auto-generated constructor stub + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/errors/ErrorCentral.java b/src/main/java/com/indexdata/mkjsf/errors/ErrorCentral.java new file mode 100644 index 0000000..5a0875f --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/errors/ErrorCentral.java @@ -0,0 +1,67 @@ +package com.indexdata.mkjsf.errors; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.enterprise.context.SessionScoped; +import javax.inject.Inject; +import javax.inject.Named; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.config.ConfigurationReader; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2Responses; + +@Named("errors") @SessionScoped +public class ErrorCentral implements Serializable { + + private static final long serialVersionUID = -1658192041068396628L; + private static Logger logger = Logger.getLogger(ErrorCentral.class); + private ErrorHelper errorHelper = null; + + @Inject Pazpar2Responses pzresp; + @Inject ConfigurationReader configurator; + + private List configurationErrors = new ArrayList(); + + public ErrorCentral() {} + + @PostConstruct + public void postConstruct() { + errorHelper = new ErrorHelper(configurator); + pzresp.setErrorHelper(errorHelper); + } + + public void addConfigurationError (ErrorInterface configError) { + configError.setErrorHelper(errorHelper); + configurationErrors.add(configError); + } + + public boolean hasConfigurationErrors () { + return (configurationErrors.size()>0); + } + + public boolean hasCommandErrors () { + return pzresp.hasApplicationError(); + } + + public ErrorInterface getCommandError () { + return pzresp.getCommandError(); + } + + /** + * Returns true if application error found in any response data objects + */ + public boolean hasErrors () { + logger.debug("Checking for configuration errors or command errors."); + return hasConfigurationErrors() || hasCommandErrors(); + } + + public List getConfigurationErrors() { + return configurationErrors; + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/errors/ErrorHelper.java b/src/main/java/com/indexdata/mkjsf/errors/ErrorHelper.java new file mode 100644 index 0000000..e75d663 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/errors/ErrorHelper.java @@ -0,0 +1,164 @@ +package com.indexdata.mkjsf.errors; + +import static com.indexdata.mkjsf.utils.Utils.nl; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.config.ConfigurationReader; +import com.indexdata.mkjsf.utils.Utils; + +public class ErrorHelper implements Serializable { + + public enum ErrorCode {PAZPAR2_404, + PAZPAR2_UNEXPECTED_RESPONSE, + PAZPAR2_ERRORS, + LOCAL_SERVICE_DEF_FILE_NOT_FOUND, + REMOTE_SERVICE_DEF_NOT_FOUND, + LOCAL_SETTINGS_FILE_NOT_FOUND, + MASTERKEY_CONFIG_FILE_NOT_FOUND, + MISSING_MANDATORY_PROPERTY, + MISSING_MK2_CONFIG_INIT_PARAMETER, + MISSING_CONTEXT_PARAMETER, + NOT_RESOLVED, + SKIP_SUGGESTIONS}; + + private static final long serialVersionUID = 2860804561068279131L; + private static Pattern httpResponsePattern = Pattern.compile("Unexpected HTTP response code \\(([0-9]*)\\).*"); + + private static Logger logger = Logger.getLogger(ErrorHelper.class); + + private ConfigurationReader configurator = null; + + public ErrorHelper(ConfigurationReader configurator) { + this.configurator = configurator; + } + + public ErrorHelper.ErrorCode getErrorCode(ErrorInterface appError) { + String errmsg = appError.getMessage(); + if (appError.hasPazpar2Error()) { + if (appError.getPazpar2Error().getMsg().contains("target settings from file")) { + return ErrorCode.LOCAL_SETTINGS_FILE_NOT_FOUND; + } else { + return ErrorCode.PAZPAR2_ERRORS; + } + } else if (errmsg.startsWith("Unexpected HTTP response")) { + Matcher m = httpResponsePattern.matcher(appError.getMessage()); + if (m.matches()) { + String errorCode = m.group(1); + if (errorCode.equals("404")) { + return ErrorCode.PAZPAR2_404; + } else { + return ErrorCode.PAZPAR2_UNEXPECTED_RESPONSE; + } + } + } else if (errmsg.contains("Configuration file") & appError.getMessage().contains("properties")) { + return ErrorCode.MASTERKEY_CONFIG_FILE_NOT_FOUND; + } else if (errmsg.contains("Error reading service definition XML")) { + return ErrorCode.LOCAL_SERVICE_DEF_FILE_NOT_FOUND; + } else if (errmsg.contains("Cannot query Pazpar2 while there are configuration errors")) { + return ErrorCode.SKIP_SUGGESTIONS; + } else if (errmsg.contains("Missing mandatory parameter")) { + return ErrorCode.MISSING_MANDATORY_PROPERTY; + } else if (errmsg.contains("ConfigureByMk2Config") && errmsg.contains("Init parameter") && (errmsg.contains("missing"))) { + return ErrorCode.MISSING_MK2_CONFIG_INIT_PARAMETER; + } else if (appError.getMessage().contains("WebXmlConfigReader could not find mandatory context-param")) { + return ErrorCode.MISSING_CONTEXT_PARAMETER; + } + return ErrorCode.NOT_RESOLVED; + } + + public ArrayList getSuggestions(ErrorInterface error) { + ArrayList suggestions = new ArrayList(); + ErrorCode code = getErrorCode(error); + switch (code) { + case MISSING_MK2_CONFIG_INIT_PARAMETER: + suggestions.add("A mandatory init parameter (context-param) was not found in the deployment descriptor (web.xml)." + + " Following init parameters must be present when using the MasterKey configuration scheme (ConfigureByMk2Config):" + + " MASTERKEY_ROOT_CONFIG_DIR (i.e. '/etc/masterkey'), MASTERKEY_COMPONENT_CONFIG_DIR (i.e. '/myapp'), " + + " MASTERKEY_CONFIG_FILE_NAME (i.e. 'myapp.properties'"); + break; + case MISSING_CONTEXT_PARAMETER: + suggestions.add("A mandatory init parameter (context-param) was not found in the deployment descriptor (web.xml)." + + " Following init parameters must be present when using WebXmlConfigReader:" + + " PAZPAR2_URL, PAZPAR2_SERVICE_ID"); + break; + case MISSING_MANDATORY_PROPERTY: + suggestions.add("A mandatory configuration parameter was not found in the MK2 config properties" + + " file used. Please check the property file for the parameter given in the error message "); + addConfigurationDocumentation(suggestions); + break; + case MASTERKEY_CONFIG_FILE_NOT_FOUND: + suggestions.add("The main configuration file that is looked up using parameters" + + " in web.xml (MASTERKEY_ROOT_CONFIG_DIR,MASTERKEY_COMPONENT_CONFIG_DIR,MASTERKEY_CONFIG_FILE_NAME)" + + " could not be found. Please check the web.xml parameters and the expected file system location. "); + break; + case LOCAL_SERVICE_DEF_FILE_NOT_FOUND: + suggestions.add("The service definition file could not be loaded."); + suggestions.add("Please check the configuration and verify that the file exists"); + addConfigurationDocumentation(suggestions); + break; + case REMOTE_SERVICE_DEF_NOT_FOUND: + break; + case LOCAL_SETTINGS_FILE_NOT_FOUND: + suggestions.add("A configuration using local target settings file was found, but " + + " the file itself could not be found. Please check the configuration."); + addConfigurationDocumentation(suggestions); + break; + case PAZPAR2_404: + suggestions.add("Pazpar2 service not found (404). "); + suggestions.add("Please check the PAZPAR2_URL configuration and verify " + + "that a pazpar2 service is running at the given address."); + addConfigurationDocumentation(suggestions); + break; + case PAZPAR2_UNEXPECTED_RESPONSE: + suggestions.add("Unexpected response code from Pazpar2. " + nl + + "Please check the PAZPAR2_URL configuration and verify " + + "that a pazpar2 service is running at the given address." + nl); + break; + case PAZPAR2_ERRORS: + if (error.hasPazpar2Error()) { + int pz2code = Integer.parseInt(error.getPazpar2Error().getCode()); + switch (pz2code) { + case 3: + suggestions.add("The search experienced a problem with the query terms."); + break; + case 12: + suggestions.add("The Pazpar2 server does not have a service defined by the requested ID "); + suggestions.add("Please check the service ID set in the configuration and compare it with the " + + " configuration on the Pazpar2 server-side."); + addConfigurationDocumentation(suggestions); + break; + case 100: + suggestions.add("Pazpar2 Service Proxy error"); + suggestions.add("A request was made to the Pazpar2 Service Proxy, but the Service Proxy reports "); + suggestions.add(" that authentication is lacking. Could be no successful authentication request was made or"); + suggestions.add(" that the Service Proxy session timed out."); + break; + default: + suggestions.add("Pazpar2 error: " + error.getPazpar2Error().getMsg() + " (Pazpar2 # "+error.getPazpar2Error().getCode()+")"); + } + break; + } else { + logger.error("Programming problem. An application error was categorized as a Papzar2 error yet does not have Pazpar2 error information as expected."); + } + break; + case SKIP_SUGGESTIONS: + break; + case NOT_RESOLVED: + suggestions.add("Sorry, no troubleshooting suggestions were written for this error scenario just yet."); + break; + } + return suggestions; + } + + private void addConfigurationDocumentation (ArrayList suggestions) { + suggestions.add("The application was configured using the configurator " + Utils.baseObjectName(configurator)); + suggestions.add("This configurator reports that following configuration was used: "); + suggestions.addAll(configurator.document()); + } +} diff --git a/src/main/java/com/indexdata/mkjsf/errors/ErrorInterface.java b/src/main/java/com/indexdata/mkjsf/errors/ErrorInterface.java new file mode 100644 index 0000000..feb578c --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/errors/ErrorInterface.java @@ -0,0 +1,22 @@ +package com.indexdata.mkjsf.errors; + +import java.io.Serializable; +import java.util.List; + +import com.indexdata.mkjsf.errors.ErrorHelper.ErrorCode; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2Error; + + +public interface ErrorInterface extends Serializable { + + public String getLabel(); + public String getMessage(); + public String getException(); + public void setApplicationErrorCode(ErrorCode code); + public ErrorCode getApplicationErrorCode(); + public List getSuggestions(); + public void setErrorHelper(ErrorHelper helper); + public boolean hasPazpar2Error(); + public Pazpar2Error getPazpar2Error(); + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/CommandResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/CommandResponse.java new file mode 100644 index 0000000..dc8d8c0 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/CommandResponse.java @@ -0,0 +1,7 @@ +package com.indexdata.mkjsf.pazpar2; + +public interface CommandResponse { + public int getStatusCode(); + public String getContentType(); + public String getResponseString(); +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/CommandThread.java b/src/main/java/com/indexdata/mkjsf/pazpar2/CommandThread.java new file mode 100644 index 0000000..ce3df29 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/CommandThread.java @@ -0,0 +1,79 @@ +package com.indexdata.mkjsf.pazpar2; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.apache.log4j.Logger; + +import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException; +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command; +import com.indexdata.mkjsf.pazpar2.data.CommandError; + +public class CommandThread extends Thread { + + private static Logger logger = Logger.getLogger(CommandThread.class); + Pazpar2Command command; + SearchClient client; + private ByteArrayOutputStream baos = new ByteArrayOutputStream(); + private StringBuilder response = new StringBuilder(""); + + public CommandThread (Pazpar2Command command, SearchClient client) { + this.command = command; + this.client = client; + } + + /** + * Runs the specified command using the specified Pazpar2 client + * Sets the Pazpar2 response as an XML response string to be retrieved by + * getResponse(). + * + * In case of an exception, an error response is generated, the document + * element being the same as it would have been if successful (named after + * the command, that is). + * + */ + public void run() { + + if (command.getName().equals("search")) { + client.setSearchCommand(command); + } + try { + long start = System.currentTimeMillis(); + CommandResponse commandResponse = client.executeCommand(command, baos); + if (commandResponse.getStatusCode()==200) { + response.append(commandResponse.getResponseString()); + } else if (commandResponse.getStatusCode()==417) { + logger.error("Pazpar2 status code 417: " + baos.toString("UTF-8")); + response.append(CommandError.insertPazpar2ErrorXml(command.getName(), "Expectation failed (417)", commandResponse.getResponseString())); + } else { + String resp = baos.toString("UTF-8"); + logger.error("Pazpar2 status code was " + commandResponse.getStatusCode() + ": " + resp); + throw new Pazpar2ErrorException(resp,commandResponse.getStatusCode(),resp,null); + } + long end = System.currentTimeMillis(); + logger.debug("Executed " + command.getName() + " in " + (end-start) + " ms." ); + } catch (IOException e) { + response.append(CommandError.createErrorXml(command.getName(), "io", e.getMessage())); + logger.error(response.toString()); + } catch (Pazpar2ErrorException e) { + response.append(CommandError.createErrorXml(command.getName(), "pazpar2error", e.getMessage())); + logger.error(response.toString()); + } catch (Exception e) { + response.append(CommandError.createErrorXml(command.getName(), "general", e.getMessage())); + logger.error(response.toString()); + } + } + + /** + * + * @return Pazpar2 response as an XML string, possibly a generated error XML + */ + public String getResponse () { + return response.toString(); + } + + public Pazpar2Command getCommand() { + return command; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java new file mode 100644 index 0000000..43578f8 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java @@ -0,0 +1,246 @@ +package com.indexdata.mkjsf.pazpar2; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import javax.annotation.PostConstruct; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.Alternative; +import javax.inject.Inject; +import javax.inject.Named; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.config.ConfigurationReader; +import com.indexdata.mkjsf.controls.ResultsPager; +import com.indexdata.mkjsf.errors.ConfigurationError; +import com.indexdata.mkjsf.errors.ConfigurationException; +import com.indexdata.mkjsf.errors.ErrorCentral; +import com.indexdata.mkjsf.errors.ErrorHelper; +import com.indexdata.mkjsf.pazpar2.commands.CommandParameter; +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseParser; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2Responses; +import com.indexdata.mkjsf.pazpar2.data.RecordResponse; +import com.indexdata.mkjsf.pazpar2.state.StateListener; +import com.indexdata.mkjsf.pazpar2.state.StateManager; +import com.indexdata.mkjsf.utils.Utils; + +@Named("pz2") @SessionScoped @Alternative +public class Pz2Bean implements Pz2Interface, StateListener, Serializable { + + private static final long serialVersionUID = 3440277287081557861L; + private static Logger logger = Logger.getLogger(Pz2Bean.class); + private static Logger responseLogger = Logger.getLogger("com.indexdata.mkjsf.pazpar2.responses"); + + protected SearchClient searchClient = null; + + @Inject ConfigurationReader configurator; + @Inject StateManager stateMgr; + @Inject Pazpar2Commands pzreq; + @Inject Pazpar2Responses pzresp; + @Inject ErrorCentral errors; + + protected ResultsPager pager = null; + + + protected ErrorHelper errorHelper = null; + + public Pz2Bean () { + logger.info("Instantiating pz2 bean [" + Utils.objectId(this) + "]"); + } + + @PostConstruct + public void postConstruct() { + logger.debug("in start of Pz2Bean post-construct configurator is " + configurator); + logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next."); + searchClient = new Pz2Client(); + logger.info("Using [" + Utils.objectId(searchClient) + "] configured by [" + + Utils.objectId(configurator) + "]" ); + configureClient(searchClient,configurator); + stateMgr.addStateListener(this); + } + + public void configureClient(SearchClient searchClient, ConfigurationReader configReader) { + logger.debug(Utils.objectId(this) + " will configure search client for the session"); + try { + searchClient.configure(configReader); + } catch (ConfigurationException e) { + logger.debug("Pz2Bean adding configuration error"); + errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage())); + } + logger.info(configReader.document()); + pzresp.reset(); + } + + + public void doSearch(String query) { + pzreq.getSearch().setParameter(new CommandParameter("query","=",query)); + doSearch(); + } + + public void doSearch() { + stateMgr.hasPendingStateChange("search",false); + pzresp.reset(); + // resets some record and show command parameters without + // changing state or creating state change feedback + pzreq.getRecord().removeParametersInState(); + pzreq.getShow().setParameterInState(new CommandParameter("start","=",0)); + logger.debug(Utils.objectId(this) + " is searching using "+pzreq.getCommand("search").getUrlEncodedParameterValue("query")); + doCommand("search"); + } + + /** + * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2 + * + * @return Number of activeclients at the time of the 'show' command. + */ + public String update () { + logger.debug("Updating show,stat,termlist,bytarget from pazpar2"); + return update("show,stat,termlist,bytarget"); + } + + /** + * Refreshes the data objects listed in 'commands' from pazpar2 + * + * @param commands + * @return Number of activeclients at the time of the 'show' command + */ + public String update (String commands) { + if (! errors.hasConfigurationErrors()) { + if (commandsAreValid(commands)) { + if (hasQuery()) { + handleQueryStateChanges(commands); + logger.debug("Processing request for " + commands); + List threadList = new ArrayList(); + StringTokenizer tokens = new StringTokenizer(commands,","); + while (tokens.hasMoreElements()) { + threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient)); + } + for (CommandThread thread : threadList) { + thread.start(); + } + for (CommandThread thread : threadList) { + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + for (CommandThread thread : threadList) { + String commandName = thread.getCommand().getName(); + String response = thread.getResponse(); + responseLogger.debug("Response was: " + response); + Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(response); + pzresp.put(commandName, responseObject); + } + if (commands.equals("record")) { + logger.debug("Record: Active clients: "+pzresp.getRecord().getActiveClients()); + return pzresp.getRecord().getActiveClients(); + } else { + return pzresp.getActiveClients(); + } + } else { + logger.debug("Skipped requests for " + commands + " as there's not yet a query."); + pzresp.reset(); + return "0"; + } + } else { + logger.error("Did not attemt to run command(s) due to a validation error."); + return "0"; + } + } else { + logger.error("Did not attempt to execute query since there are configuration errors."); + return "0"; + } + + } + + public boolean commandsAreValid(String commands) { + if (commands.equals("record")) { + if (!pzreq.getCommand("record").hasParameterSet("id")) { + logger.error("Attempt to send record command without the id parameter"); + return false; + } + } + return true; + } + + public String toggleRecord (String recId) { + if (hasRecord(recId)) { + pzreq.getRecord().removeParameters(); + pzresp.put("record", new RecordResponse()); + return ""; + } else { + pzreq.getRecord().setId(recId); + return doCommand("record"); + } + } + + @Override + public boolean hasRecord (String recId) { + return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId); + } + + public String getCurrentStateKey () { + return stateMgr.getCurrentState().getKey(); + } + + public void setCurrentStateKey(String key) { + stateMgr.setCurrentStateKey(key); + } + + + + protected boolean hasQuery() { + return pzreq.getCommand("search").hasParameterSet("query"); + } + + + public ResultsPager getPager () { + if (pager == null) { + pager = new ResultsPager(pzresp); + } + return pager; + } + + public ResultsPager setPager (int pageRange) { + pager = new ResultsPager(pzresp,pageRange,pzreq); + return pager; + } + + protected void handleQueryStateChanges (String commands) { + if (stateMgr.hasPendingStateChange("search") && hasQuery()) { + logger.debug("Found pending search change. Doing search before updating " + commands); + doSearch(); + } + if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) { + logger.debug("Found pending record ID change. Doing record before updating " + commands); + stateMgr.hasPendingStateChange("record",false); + if (pzreq.getCommand("record").hasParameterSet("id")) { + update("record"); + } else { + pzresp.put("record", new RecordResponse()); + } + } + } + + protected String doCommand(String commandName) { + logger.debug(pzreq.getCommand(commandName).getEncodedQueryString() + ": Results for "+ pzreq.getCommand("search").getEncodedQueryString()); + return update(commandName); + } + + @Override + public void stateUpdated(String commandName) { + logger.debug("State change reported for [" + commandName + "]"); + if (commandName.equals("show")) { + logger.debug("Updating show"); + update(commandName); + } + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Client.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Client.java new file mode 100644 index 0000000..2d03830 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Client.java @@ -0,0 +1,150 @@ +package com.indexdata.mkjsf.pazpar2; + +import static com.indexdata.mkjsf.utils.Utils.nl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.indexdata.masterkey.config.MissingMandatoryParameterException; +import com.indexdata.masterkey.config.ModuleConfigurationGetter; +import com.indexdata.masterkey.pazpar2.client.ClientCommand; +import com.indexdata.masterkey.pazpar2.client.Pazpar2Client; +import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientConfiguration; +import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientGeneric; +import com.indexdata.masterkey.pazpar2.client.Pazpar2HttpResponse; +import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException; +import com.indexdata.masterkey.pazpar2.client.exceptions.ProxyErrorException; +import com.indexdata.mkjsf.config.Configuration; +import com.indexdata.mkjsf.config.ConfigurationReader; +import com.indexdata.mkjsf.errors.ConfigurationException; +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command; +import com.indexdata.mkjsf.utils.Utils; + +public class Pz2Client implements SearchClient { + + private static final long serialVersionUID = 5414266730169982028L; + private static Logger logger = Logger.getLogger(Pz2Client.class); + private Pazpar2Client client = null; + private Pazpar2ClientConfiguration cfg = null; + public static final String MODULENAME = "pz2client"; + public static Map DEFAULTS = new HashMap(); + Configuration config = null; + + static { + DEFAULTS.put("PROXY_MODE","1"); + DEFAULTS.put("SERIALIZE_REQUESTS", "false"); + DEFAULTS.put("STREAMBUFF_SIZE", "4096"); + DEFAULTS.put("PARSE_RESPONSES", "true"); + } + + public Pz2Client() {} + + @Override + public void configure(ConfigurationReader configReader) throws ConfigurationException { + logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader)); + try { + config = configReader.getConfiguration(this); + cfg = new Pazpar2ClientConfiguration(new ConfigurationGetter(config)); + } catch (ProxyErrorException pe) { + logger.error("Could not configure Pazpar2 client: " + pe.getMessage()); + throw new ConfigurationException("Could not configure Pz2Client: "+ pe.getMessage(),pe); + } + if (cfg != null) { + try { + client = new Pazpar2ClientGeneric(cfg); + } catch (ProxyErrorException pe) { + logger.error("Could not configure Pazpar2 client: " + pe.getMessage()); + throw new ConfigurationException("Could not configure Pz2Client: "+ pe.getMessage(),pe); + } + } else { + logger.error("There was a problem creating Pz2Client. Client is null after configuration."); + throw new ConfigurationException("Pazpar2Client is null after configuration"); + } + } + + public boolean isAuthenticatingClient () { + return false; + } + + public boolean isAuthenticated() { + return false; + } + + public boolean authenticate() { + throw new UnsupportedOperationException("No authentication mechanism for straight pazpar2 client"); + } + + @Override + public void setSearchCommand(Pazpar2Command command) { + ClientCommand clientCommand = new ClientCommand(command.getName(), command.getEncodedQueryString()); + client.setSearchCommand(clientCommand); + } + + @Override + public CommandResponse executeCommand(Pazpar2Command command, ByteArrayOutputStream baos) + throws Pazpar2ErrorException, IOException { + ClientCommand clientCommand = new ClientCommand(command.getName(), command.getEncodedQueryString()); + Pazpar2HttpResponse pz2HttpResponse = client.executeCommand(clientCommand, baos); + return new Pz2CommandResponse(pz2HttpResponse,baos); + } + + public Pz2Client cloneMe() { + logger.debug("Cloning Pz2Client"); + Pz2Client clone = new Pz2Client(); + clone.client = this.client; + clone.cfg = this.cfg; + return clone; + } + + @Override + public Map getDefaults() { + return DEFAULTS; + } + + @Override + public String getModuleName() { + return MODULENAME; + } + + class ConfigurationGetter implements ModuleConfigurationGetter { + Configuration config = null; + ConfigurationGetter(Configuration configuration) { + config = configuration; + } + @Override + public String get(String value) { + return config.get(value); + } + @Override + public String get(String value, String defaultValue) { + return config.get(value,defaultValue); + } + @Override + public String getMandatory(String name) + throws MissingMandatoryParameterException { + return config.getMandatory(name); + } + @Override + public String getConfigFilePath() { + return config.getConfigFilePath(); + } + } + + @Override + public List documentConfiguration() { + List doc = new ArrayList(); + doc.add(nl+ MODULENAME + " was configured to access Pazpar2 at : " + cfg.PAZPAR2_URL); + return new ArrayList(); + } + + public Configuration getConfiguration () { + return config; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2CommandResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2CommandResponse.java new file mode 100644 index 0000000..0471b66 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2CommandResponse.java @@ -0,0 +1,39 @@ +package com.indexdata.mkjsf.pazpar2; + +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; + +import com.indexdata.masterkey.pazpar2.client.Pazpar2HttpResponse; + +public class Pz2CommandResponse implements CommandResponse { + + private Pazpar2HttpResponse pz2httpResponse = null; + private ByteArrayOutputStream content = null; + + public Pz2CommandResponse(Pazpar2HttpResponse pz2response, ByteArrayOutputStream content) { + pz2httpResponse = pz2response; + this.content = content; + } + + @Override + public int getStatusCode() { + return pz2httpResponse.getStatusCode(); + } + + @Override + public String getContentType() { + return pz2httpResponse.getContentType(); + } + + @Override + public String getResponseString() { + try { + return content.toString("UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return null; + } + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Interface.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Interface.java new file mode 100644 index 0000000..1ffd33c --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Interface.java @@ -0,0 +1,101 @@ +package com.indexdata.mkjsf.pazpar2; + +import java.io.Serializable; + +import com.indexdata.mkjsf.controls.ResultsPager; + +public interface Pz2Interface extends Serializable { + + /** + * Executes a Pazpar2 search using the given query string + * + * @param query + */ + public void doSearch(String query); + + /** + * Executes a Pazpar2 search using the current query + */ + public void doSearch(); + + /** + * Updates display data objects by issuing the following pazpar2 commands: + * 'show', 'stat', 'termlist' and 'bytarget'. + * + * Returns a count of the remaining active clients from the most recent search. + * + * After refreshing the data from pazpar2 the UI components displaying those + * data should be re-rendered. + * + * @return count of activeclients + */ + public String update(); + + /** + * Updates the data objects given by a comma separated list of one or more commands - + * i.e. "show,state,termlist,bytarget". + * + * May not be useful for the UI directly. + * + * @param commands Command separated list of pazpar2 commands. + * @return count of activeclients + * + */ + public String update (String commands); + + /** + * Will retrieve or remove the record with the given recid from memory. + * + * A pazpar2 'record' command will then be issued. The part of the UI + * showing record data should thus be re-rendered. + * + * @param recid + * @return + */ + public String toggleRecord(String recid); + + /** + * Resolves whether the backend has a record with the given recid in memory + * + * @return true if the bean currently holds the record with recid + */ + public boolean hasRecord (String recId); + + + /** + * Initiates a pager object, a component holding the data to draw a sequence + * of page numbers to navigate by and mechanisms to navigate with + * + * @param pageRange number of pages to display in the pager + * @return ResultsPager the initiated pager component + */ + public ResultsPager setPager(int pageRange); + + /** + * Gives a component for drawing a pager to navigate by. + * @return ResultsPager pager component + */ + public ResultsPager getPager(); + + /** + * Returns the current hash key used, as used for internal session state tracking + * and potentially for browser history entries as well + * + * A UI author would not normally be concerned with retrieving this. It's used by the + * framework internally + * + * @return string that can be used for browsers window.location.hash + */ + public String getCurrentStateKey (); + + /** + * Sets the current state key, i.e. when user clicks back or forward in browser history. + * Would normally be automatically handled by the frameworks components. + * + * @param key corresponding to browsers hash string + */ + public void setCurrentStateKey(String key); + + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java new file mode 100644 index 0000000..16b4319 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java @@ -0,0 +1,123 @@ +package com.indexdata.mkjsf.pazpar2; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import javax.annotation.PostConstruct; +import javax.enterprise.context.SessionScoped; +import javax.enterprise.inject.Alternative; +import javax.inject.Inject; +import javax.inject.Named; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.config.ConfigurationReader; +import com.indexdata.mkjsf.pazpar2.sp.ServiceProxyClient; +import com.indexdata.mkjsf.pazpar2.sp.ServiceProxyInterface; +import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser; +import com.indexdata.mkjsf.utils.Utils; + +@Named("pz2") @SessionScoped @Alternative +public class Pz2ProxyBean extends Pz2Bean implements ServiceProxyInterface { + + private static final long serialVersionUID = 4221824985678758225L; + private static Logger logger = Logger.getLogger(Pz2ProxyBean.class); + private String initDocFileName = ""; + private String initDocResponse = ""; + private String serviceProxyUrl = ""; + + @Inject ConfigurationReader configurator; + @Inject ServiceProxyUser user; + + public Pz2ProxyBean() { + } + + @PostConstruct + public void postConstruct() { + if (searchClient == null) { + logger.debug(Utils.objectId(this) + " will instantiate a ServiceProxyClient next."); + searchClient = new ServiceProxyClient(); + logger.info("Using [" + Utils.objectId(searchClient) + "] configured by [" + + Utils.objectId(configurator) + "]" ); + configureClient(searchClient,configurator); + stateMgr.addStateListener(this); + } else { + logger.debug("Pz2ProxyBean:postConstruct: searchClient already instantiated " + + "during construction of parent object Pz2Bean."); + } + } + + @Override + public String login(String navigateTo) { + logger.info("doing login"); + ((ServiceProxyClient)searchClient).authenticate(user); + pzreq.getRecord().removeParametersInState(); + pzreq.getSearch().removeParametersInState(); + pzresp.reset(); + return navigateTo; + } + + @Override + public void setServiceProxyUrl(String url) { + logger.info("Setting Service Proxy url: " + url); + serviceProxyUrl = url; + pzreq.getRecord().removeParametersInState(); + pzreq.getSearch().removeParametersInState(); + pzresp.reset(); + } + + public String getServiceProxyUrl() { + return serviceProxyUrl; + } + + public String getInitDocPath () { + return searchClient.getConfiguration().get("INIT_DOC_PATH"); + } + + @Override + public void setInitFileName(String fileName) { + this.initDocFileName = fileName; + + } + + @Override + public String getInitFileName() { + return initDocFileName; + } + + @Override + public String postInit() throws UnsupportedEncodingException, IOException { + String initDocPath = ((ServiceProxyClient)searchClient).getInitDocPaths()[0]; + logger.info("Paths: " + ((ServiceProxyClient)searchClient).getInitDocPaths()); + logger.info("Path: " + initDocPath); + pzresp.reset(); + byte[] response = ((ServiceProxyClient)searchClient).postInitDoc(initDocPath + getInitFileName()); + initDocResponse = new String(response,"UTF-8"); + return initDocResponse; + } + + @Override + public String postInit(byte[] initDoc) throws UnsupportedEncodingException, IOException { + pzresp.reset(); + byte[] response = ((ServiceProxyClient)searchClient).postInitDoc(initDoc); + initDocResponse = new String(response,"UTF-8"); + return initDocResponse; + } + + + @Override + public String getInitResponse() { + return initDocResponse; + } + + public void setAceFilter(String filterExpression) { + //setCommandParameter("record",new CommandParameter("acefilter","=",filterExpression)); + } + + public String getAceFilter () { + return null; + // return getCommandParameterValue("record","acefilter",""); + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/SearchClient.java b/src/main/java/com/indexdata/mkjsf/pazpar2/SearchClient.java new file mode 100644 index 0000000..1a67522 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/SearchClient.java @@ -0,0 +1,26 @@ +package com.indexdata.mkjsf.pazpar2; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.Serializable; + +import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException; +import com.indexdata.mkjsf.config.Configurable; +import com.indexdata.mkjsf.config.Configuration; +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command; + +public interface SearchClient extends Configurable, Serializable { + + public void setSearchCommand(Pazpar2Command command); + public CommandResponse executeCommand(Pazpar2Command command, ByteArrayOutputStream baos) throws Pazpar2ErrorException, IOException; + + // Use cloneMe() method if injecting the client with CDI. + // The client is used for asynchronously sending off requests + // to the server AND propagation of context to threads is currently + // not supported. Trying to do so throws a WELD-001303 error. + // If propagation to threads gets supported, the cloning can go. + public SearchClient cloneMe(); + + public boolean isAuthenticatingClient(); + public Configuration getConfiguration(); +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/BytargetCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/BytargetCommand.java new file mode 100644 index 0000000..57c66de --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/BytargetCommand.java @@ -0,0 +1,13 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class BytargetCommand extends Pazpar2Command { + + private static final long serialVersionUID = 9070458716105294392L; + + public BytargetCommand(StateManager stateMgr) { + super("bytarget",stateMgr); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/CommandParameter.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/CommandParameter.java new file mode 100644 index 0000000..69c224a --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/CommandParameter.java @@ -0,0 +1,124 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import java.io.Serializable; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.pazpar2.commands.CommandParameter; + +public class CommandParameter implements Serializable { + + private static Logger logger = Logger.getLogger(CommandParameter.class); + + private static final long serialVersionUID = 625502285668766749L; + String name = null; + String operator = null; + String value = null; + Map expressions = new HashMap(); + + public CommandParameter (String name) { + logger.debug("Instantiating command parameter '" + name + "'"); + this.name = name; + } + + public CommandParameter (String name, String operator, String value, Expression... expressions) { + logger.debug("Instantiating command parameter " + name + " with expressions: [" + expressions + "]"); + this.name = name; + this.operator = operator; + this.value = value; + for (Expression expr : expressions) { + this.expressions.put(expr.toString(), expr); + } + } + + public CommandParameter (String name, String operator, String value) { + logger.debug("Instantiating command parameter '" + name + "' with String: [" + value + "]"); + this.name = name; + this.operator = operator; + this.value = value; + } + + public CommandParameter (String name, String operator, int value) { + logger.debug("Instantiating command parameter '" + name + "' with int: [" + value + "]"); + this.name = name; + this.operator = operator; + this.value = value+""; + } + + + public String getName () { + return name; + } + + public Map getExpressions () { + return expressions; + } + + public void addExpression(Expression expression) { + logger.debug("Adding expression [" + expression + "] to '" + name + "'"); + this.expressions.put(expression.toString(),expression); + } + + public void removeExpression(Expression expression) { + this.expressions.remove(expression.toString()); + } + + + public boolean hasOperator() { + return operator != null; + } + + public String getEncodedQueryString () { + try { + return name + operator + URLEncoder.encode(getValueWithExpressions(),"UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return null; + } + } + + public String getSimpleValue() { + return value; + } + + public String getValueWithExpressions () { + StringBuilder completeValue = new StringBuilder((value==null ? "" : value)); + for (String key : expressions.keySet()) { + completeValue.append(" and " + expressions.get(key)); + } + return completeValue.toString(); + + } + + @Override + public boolean equals (Object otherParameter) { + return + ((otherParameter instanceof CommandParameter) + && this.getValueWithExpressions().equals(((CommandParameter) otherParameter).getValueWithExpressions())); + } + + @Override + public int hashCode () { + return getValueWithExpressions().hashCode(); + } + + public String toString() { + return getValueWithExpressions(); + } + + public CommandParameter copy() { + logger.debug("Copying parameter '"+ name + "' for modification"); + CommandParameter newParam = new CommandParameter(name); + newParam.value = this.value; + newParam.operator = this.operator; + for (String key : expressions.keySet()) { + newParam.addExpression(expressions.get(key).copy()); + } + return newParam; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Expression.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Expression.java new file mode 100644 index 0000000..d95ff64 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Expression.java @@ -0,0 +1,25 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.commands.Expression; + +public class Expression { + + String leftEntity; + String operator; + String rightEntity; + public Expression (String leftEntity, String operator, String rightEntity) { + this.leftEntity = leftEntity; + this.operator = operator; + this.rightEntity = rightEntity; + } + + public Expression copy() { + return new Expression(leftEntity,operator,rightEntity); + } + + public String toString() { + return leftEntity + operator + rightEntity; + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/InitCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/InitCommand.java new file mode 100644 index 0000000..f1f31ef --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/InitCommand.java @@ -0,0 +1,31 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class InitCommand extends Pazpar2Command { + + private static final long serialVersionUID = -4915976465898889987L; + + public InitCommand(StateManager stateMgr) { + super("init",stateMgr); + } + + public void setClear(String clear) { + setParameter(new CommandParameter("clear","=",clear)); + } + + public void setService(String serviceId) { + setParameter(new CommandParameter("service","=",serviceId)); + } + + @Override + public void setSession (String sessionId) { + throw new UnsupportedOperationException("Cannot set session id on init command"); + } + + @Override + public String getSession () { + throw new UnsupportedOperationException("Cannot set or get session id on init command"); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Pazpar2Command.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Pazpar2Command.java new file mode 100644 index 0000000..4fbe159 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Pazpar2Command.java @@ -0,0 +1,148 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class Pazpar2Command implements Serializable { + + private static Logger logger = Logger.getLogger(Pazpar2Command.class); + private static final long serialVersionUID = -6825491856480675917L; + private String name = ""; + protected Map parameters = new HashMap(); + + StateManager stateMgr; + + public Pazpar2Command (String name, StateManager stateMgr) { + this.name = name; + if (stateMgr == null) { + // Sets throw-away state + this.stateMgr = new StateManager(); + } else { + this.stateMgr = stateMgr; + } + } + + public Pazpar2Command copy () { + Pazpar2Command newCommand = new Pazpar2Command(name,stateMgr); + for (String parameterName : parameters.keySet()) { + newCommand.setParameterInState(parameters.get(parameterName).copy()); + } + return newCommand; + } + + public String getName() { + return name; + } + + public void setParameter (CommandParameter parameter) { + Pazpar2Command copy = this.copy(); + logger.debug(name + " command: setting parameter [" + parameter.getName() + "=" + parameter.getValueWithExpressions() + "]"); + copy.parameters.put(parameter.getName(),parameter); + stateMgr.checkIn(copy); + } + + public void setParameters (CommandParameter... params) { + Pazpar2Command copy = this.copy(); + for (CommandParameter param : params) { + logger.debug(name + " command: setting parameter [" + param.getName() + "=" + param.getValueWithExpressions() + "]"); + copy.parameters.put(param.getName(),param); + } + stateMgr.checkIn(copy); + } + + public void setParametersInState (CommandParameter... params) { + for (CommandParameter param : params) { + logger.debug(name + " command: setting parameter [" + param.getName() + "=" + param.getValueWithExpressions() + "] silently"); + parameters.put(param.getName(),param); + } + } + + public void setParameterInState (CommandParameter parameter) { + logger.debug(name + " command: setting parameter [" + parameter.getName() + "=" + parameter.getValueWithExpressions() + "] silently"); + parameters.put(parameter.getName(),parameter); + } + + + public CommandParameter getParameter (String name) { + return parameters.get(name); + } + + public void removeParameter (String name) { + Pazpar2Command copy = this.copy(); + copy.parameters.remove(name); + stateMgr.checkIn(copy); + } + + public void removeParameters() { + Pazpar2Command copy = this.copy(); + copy.parameters = new HashMap(); + stateMgr.checkIn(copy); + } + + public void removeParametersInState() { + parameters = new HashMap(); + } + + + public boolean hasParameters () { + return (parameters.keySet().size()>0); + } + + public boolean hasParameterSet(String parameterName) { + return (parameters.get(parameterName) != null); + } + + public String getEncodedQueryString () { + StringBuilder queryString = new StringBuilder("command="+name); + for (CommandParameter parameter : parameters.values()) { + queryString.append("&"+parameter.getEncodedQueryString()); + } + return queryString.toString(); + } + + public String getValueWithExpressions() { + StringBuilder value = new StringBuilder(""); + for (CommandParameter parameter : parameters.values()) { + value.append("&" + parameter.getName() + parameter.operator + parameter.getValueWithExpressions()); + } + return value.toString(); + } + + @Override + public boolean equals (Object otherCommand) { + return + ((otherCommand instanceof Pazpar2Command) + && this.getValueWithExpressions().equals(((Pazpar2Command) otherCommand).getValueWithExpressions())); + } + + @Override + public int hashCode () { + return getValueWithExpressions().hashCode(); + } + + public String toString () { + return parameters.toString(); + } + + public String getParameterValue(String parameterName) { + return getParameter(parameterName).getValueWithExpressions(); + + } + + public String getUrlEncodedParameterValue(String parameterName) { + return getParameter(parameterName).getEncodedQueryString(); + } + + public void setSession (String sessionId) { + setParameter(new CommandParameter("session","=",sessionId)); + } + + public String getSession() { + return getParameterValue("session"); + } +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Pazpar2Commands.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Pazpar2Commands.java new file mode 100644 index 0000000..9e04d6e --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/Pazpar2Commands.java @@ -0,0 +1,82 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import java.io.Serializable; + +import javax.annotation.PostConstruct; +import javax.enterprise.context.SessionScoped; +import javax.inject.Inject; +import javax.inject.Named; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; +import com.indexdata.mkjsf.utils.Utils; + +@Named("pzreq") @SessionScoped +public class Pazpar2Commands implements Serializable { + + private static final long serialVersionUID = -5172466320351302413L; + private static Logger logger = Logger.getLogger(Pazpar2Commands.class); + + public static final String INIT = "init"; + public static final String PING = "ping"; + public static final String SETTINGS = "settings"; + public static final String SEARCH = "search"; + public static final String STAT = "stat"; + public static final String SHOW = "show"; + public static final String RECORD = "record"; + public static final String TERMLIST = "termlist"; + public static final String BYTARGET = "bytarget"; + + @Inject StateManager stateMgr; + + public Pazpar2Commands() { + logger.info("Initializing Pazpar2Commands [" + Utils.objectId(this) + "]"); + } + + @PostConstruct + public void postConstruct() { + logger.info("in post-construct stateMgr is " + stateMgr); + } + + public InitCommand getInit() { + return (InitCommand) (stateMgr.getCommand(INIT)); + } + + public PingCommand getPing() { + return (PingCommand) (stateMgr.getCommand(PING)); + } + + public SettingsCommand getSettings() { + return (SettingsCommand) (stateMgr.getCommand(SETTINGS)); + } + + public SearchCommand getSearch() { + return (SearchCommand) (stateMgr.getCommand(SEARCH)); + } + + public StatCommand getStat() { + return (StatCommand) (stateMgr.getCommand(STAT)); + } + + public ShowCommand getShow() { + return (ShowCommand) (stateMgr.getCommand(SHOW)); + } + + public RecordCommand getRecord() { + return (RecordCommand) (stateMgr.getCommand(RECORD)); + } + + public TermlistCommand getTermlist() { + return (TermlistCommand) (stateMgr.getCommand(TERMLIST)); + } + + public BytargetCommand getBytarget() { + return (BytargetCommand) (stateMgr.getCommand(BYTARGET)); + } + + public Pazpar2Command getCommand(String name) { + return stateMgr.getCommand(name); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/PingCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/PingCommand.java new file mode 100644 index 0000000..05c1934 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/PingCommand.java @@ -0,0 +1,13 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class PingCommand extends Pazpar2Command { + + private static final long serialVersionUID = 8876721711326535847L; + + public PingCommand(StateManager stateMgr) { + super("ping",stateMgr); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/RecordCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/RecordCommand.java new file mode 100644 index 0000000..78d192e --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/RecordCommand.java @@ -0,0 +1,29 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class RecordCommand extends Pazpar2Command { + + private static final long serialVersionUID = 2817539422114569506L; + + public RecordCommand(StateManager stateMgr) { + super("record",stateMgr); + } + + public void setId(String recId) { + setParameter(new CommandParameter("id","=",recId)); + } + + public String getId () { + return getParameterValue("id"); + } + + @Override + public RecordCommand copy () { + RecordCommand newCommand = new RecordCommand(stateMgr); + for (String parameterName : parameters.keySet()) { + newCommand.setParameterInState(parameters.get(parameterName).copy()); + } + return newCommand; + } +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SearchCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SearchCommand.java new file mode 100644 index 0000000..749742e --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SearchCommand.java @@ -0,0 +1,202 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import javax.enterprise.context.SessionScoped; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +@SessionScoped +public class SearchCommand extends Pazpar2Command { + + private static final long serialVersionUID = -1888520867838597236L; + private static Logger logger = Logger.getLogger(SearchCommand.class); + private SingleTargetFilter singleTargetFilter = null; + + public SearchCommand(StateManager stateMgr) { + super("search",stateMgr); + } + + public void setQuery(String query) { + setParameter(new CommandParameter("query","=",query)); + } + + public String getQuery () { + return getParameter("query") == null ? null : getParameter("query").getValueWithExpressions(); + } + + public void setFilter(String filterExpression) { + setParameter(new CommandParameter("filter","=",filterExpression)); + } + + public String getFilter() { + return getParameter("filter") == null ? null : getParameter("filter").getValueWithExpressions(); + } + + public void addFilter(String filterExpression) { + // TODO: implement + if (hasParameterSet("filter")) { + setFilter(filterExpression); + } else { + getParameter("filter"); + } + throw new UnsupportedOperationException("removeFilter(filterExpression) yet to be implemented."); + } + + public void removeFilters () { + removeParameter("filter"); + } + + public void removeFilter(String filterExpression) { + // TODO: implement + throw new UnsupportedOperationException("removeFilter(filterExpression) yet to be implemented."); + } + + public boolean hasFilter () { + return getFilter().length()>0; + } + + public void setLimit (String limitExpression) { + setParameter(new CommandParameter("limit","=",limitExpression)); + } + + public String getLimit () { + return getParameterValue("limit"); + } + + public void setStartrecs (String startrecs) { + setParameter(new CommandParameter("startrecs","=",startrecs)); + } + + public String getStartrecs () { + return getParameterValue("startrecs"); + } + + public void setMaxrecs (String maxrecs) { + setParameter(new CommandParameter("maxrecs","=",maxrecs)); + } + + public String getMaxrecs () { + return getParameterValue("maxrecs"); + } + + public void setSort () { + setParameter(new CommandParameter("sort","=","sort")); + } + + public String getSort () { + return getParameterValue("sort"); + } + + /** + * Sets a facet, in CQL, to restrict the current results, + * then executes the search + * + * @param facetKey i.e. 'au' for author + * @param term i.e. 'Dickens, Charles' + */ + public void setFacet(String facetKey, String term) { + if (term != null && term.length()>0) { + getParameter("query").addExpression(new Expression(facetKey,"=",term)); + } + } + + /** + * Sets a facet to limit the current query by. The + * facet is appended to the query string itself (rather + * as a separately managed entity. It will thus appear + * in a query field as retrieved by getQuery(). It will + * not be removed by removeFacet(...) + * + * @param facetKey i.e. 'au' for author + * @param term i.e. 'Dickens, Charles' + */ + public void setFacetOnQuery (String facetKey, String term) { + String facetExpression = facetKey + "=" + term; + if (term != null && term.length()>0) { + String currentQuery= getParameterValue("query"); + setParameter(new CommandParameter("query","=", currentQuery + " and " + facetExpression)); + } + } + + /** + * Removes a facet set by setFacet(...), then executes + * the search. + * + * Will not remove facets set by setFacetOnQuery(...) + * + * @param facetKey i.e. 'au' for author + * @param term i.e. 'Dickens, Charles' + */ + public void removeFacet(String facetKey, String term) { + if (getParameter("query") != null) { + getParameter("query").removeExpression(new Expression(facetKey,"=",term)); + } + } + + + /** + * Adds a single target filter to restrict the current query by, + * then executes the current search. + * + * This is a special case of the general setFilter function, + * allowing to associate a descriptive target name with the + * filter expression for display in UI. + * + * @param targetId pazpar2's ID for the target to limit by + * @param targetName a descriptive name for the target + */ + public void setSingleTargetFilter (String targetId, String targetName) { + if (hasSingleTargetFilter(new SingleTargetFilter(targetId,targetName))) { + logger.debug("Already using target filter " + this.singleTargetFilter.getFilterExpression()); + } else { + this.singleTargetFilter = new SingleTargetFilter(targetId,targetName); + setParameter(new CommandParameter("filter","=",this.singleTargetFilter.getFilterExpression())); + } + } + + public SingleTargetFilter getSingleTargetFilter () { + logger.debug("request to get the current single target filter"); + return singleTargetFilter; + } + + /** + * Removes the current target filter from the search + * + */ + public void removeSingleTargetFilter () { + logger.debug("Removing target filter " + singleTargetFilter.getFilterExpression()); + this.singleTargetFilter = null; + removeParameter("filter"); + } + + /** + * + * @return The target filter set on the current search command + */ + public boolean hasSingleTargetFilter() { + logger.debug("Checking if a single target filter is set: " + (singleTargetFilter != null)); + return singleTargetFilter != null; + } + + /** + * Resolves if the current search command has a target filter - to + * be used by the UI for conditional rendering of target filter info. + * + * @return true if the current search command is limited by a target + * filter + */ + protected boolean hasSingleTargetFilter(SingleTargetFilter targetFilter) { + return hasSingleTargetFilter() && targetFilter.equals(this.singleTargetFilter); + } + + public SearchCommand copy () { + SearchCommand newCommand = new SearchCommand(stateMgr); + for (String parameterName : parameters.keySet()) { + newCommand.setParameterInState(parameters.get(parameterName).copy()); + } + newCommand.singleTargetFilter = this.singleTargetFilter; + return newCommand; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SettingsCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SettingsCommand.java new file mode 100644 index 0000000..55a417e --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SettingsCommand.java @@ -0,0 +1,14 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class SettingsCommand extends Pazpar2Command { + + private static final long serialVersionUID = 2291179325470387102L; + + public SettingsCommand(StateManager stateMgr) { + super("settings",stateMgr); + // TODO Auto-generated constructor stub + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/ShowCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/ShowCommand.java new file mode 100644 index 0000000..a4e9047 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/ShowCommand.java @@ -0,0 +1,98 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class ShowCommand extends Pazpar2Command { + + private static final long serialVersionUID = -8242768313266051307L; + + public ShowCommand(StateManager stateMgr) { + super("show",stateMgr); + setParameterInState(new CommandParameter("start","=","0")); + } + + /** + * Sets the sort order for results, the updates the 'show' data object + * from pazpar2. Set valid sort options in the documentation for pazpar2. + * + * The parts of the UI that display 'show' data should be rendered following + * this request. + * + * @param sortOption + */ + public void setSort (String sort) { + setParameter(new CommandParameter("sort","=",sort)); + } + + /** + * Retrieves the current sort order for results + * @return sort order - i.e. 'relevance' + */ + public String getSort () { + return getParameter("sort") != null ? getParameter("sort").value : "relevance"; + } + + /** + * Sets the number of records that pazpar2 should show at a time. Is + * followed by an update of the show data object from pazpar2. + * + * To be used by the UI for paging. After setting page size the parts + * of the UI that displays 'show' data should be rendered. + * + * @param perPageOption i.e. 10, default is 20. + */ + public void setPageSize (String perPageOption) { + setParameters(new CommandParameter("num","=",perPageOption), + new CommandParameter("start","=",0)); + } + + /** + * Retrieves the currently defined number of items to show at a time + * + * @return number of result records that will be shown from pazpar2 + */ + public String getPageSize () { + return getParameter("num") != null ? getParameter("num").value : "20"; + } + + /** + * Sets the first record to show - starting at record '0'. After setting + * first record number, the 'show' data object will be updated from pazpar2, + * and the parts of the UI displaying show data should be re-rendered. + * + * To be used by the UI for paging. + * + * @param start first record to show + */ + public void setStart (int start) { + setParameter(new CommandParameter("start","=",start)); + } + + /** + * Retrieves the sequence number of the record that pazpaz2 will return as + * the first record in 'show' + * + * @return sequence number of the first record to be shown (numbering starting at '0') + * + */ + public int getStart() { + return getParameter("start") != null ? Integer.parseInt(getParameter("start").value) : 0; + } + + public void setNum (int num) { + setParameter(new CommandParameter("num","=",num)); + } + + public int getNum () { + return getParameter("num") != null ? Integer.parseInt(getParameter("num").value) : 0; + } + + public ShowCommand copy () { + ShowCommand newCommand = new ShowCommand(stateMgr); + for (String parameterName : parameters.keySet()) { + newCommand.setParameterInState(parameters.get(parameterName).copy()); + } + return newCommand; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SingleTargetFilter.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SingleTargetFilter.java new file mode 100644 index 0000000..4aea8a2 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/SingleTargetFilter.java @@ -0,0 +1,47 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import java.io.Serializable; + +import com.indexdata.mkjsf.pazpar2.commands.SingleTargetFilter; + +public class SingleTargetFilter implements Serializable { + + private static final long serialVersionUID = 2389085467202526537L; + + private String targetName; + private String targetId; + + public SingleTargetFilter (String targetId, String targetName) { + this.targetId = targetId; + this.targetName = targetName; + } + + public String getTargetName () { + return targetName; + } + + public String getTargetId () { + return targetId; + } + + public String getFilterExpression () { + return "pz:id="+targetId; + } + + @Override + public boolean equals(Object o) { + if (o instanceof SingleTargetFilter) { + return targetName.equals(((SingleTargetFilter) o).getTargetName()) && + targetId.equals(((SingleTargetFilter) o).getTargetId()); + } else { + return false; + } + } + + @Override + public int hashCode () { + return (targetId+targetName).hashCode(); + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/StatCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/StatCommand.java new file mode 100644 index 0000000..6b885bc --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/StatCommand.java @@ -0,0 +1,13 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class StatCommand extends Pazpar2Command { + + private static final long serialVersionUID = 3980630346114157336L; + + public StatCommand(StateManager stateMgr) { + super("stat",stateMgr); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/TermlistCommand.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/TermlistCommand.java new file mode 100644 index 0000000..789186c --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/TermlistCommand.java @@ -0,0 +1,13 @@ +package com.indexdata.mkjsf.pazpar2.commands; + +import com.indexdata.mkjsf.pazpar2.state.StateManager; + +public class TermlistCommand extends Pazpar2Command { + + private static final long serialVersionUID = -7067878552863021727L; + + public TermlistCommand(StateManager stateMgr) { + super("termlist",stateMgr); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/ByTarget.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/ByTarget.java new file mode 100644 index 0000000..e684f9e --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/ByTarget.java @@ -0,0 +1,22 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.util.ArrayList; +import java.util.List; + +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; +import com.indexdata.mkjsf.pazpar2.data.Target; + +public class ByTarget extends Pazpar2ResponseData { + + private static final long serialVersionUID = 3960644950805644518L; + + public List getTargets() { + List targets = new ArrayList(); + if (getElements("target") != null) { + for (Pazpar2ResponseData element : getElements("target")) { + targets.add((Target)element); + } + } + return targets; + } +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/CommandError.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/CommandError.java new file mode 100644 index 0000000..5e07207 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/CommandError.java @@ -0,0 +1,137 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import static com.indexdata.mkjsf.utils.Utils.nl; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +import com.indexdata.mkjsf.errors.ErrorHelper; +import com.indexdata.mkjsf.errors.ErrorInterface; +import com.indexdata.mkjsf.errors.ErrorHelper.ErrorCode; +import com.indexdata.utils.XmlUtils; + +/** + * Holds an error encountered during the execution of a command. + * + * An error can be received by a command thread as an exception message + * or as an error XML. In both cases the error (string or xml) will be embedded + * in a new 'applicationerror' element which in turn will be embedded in a + * command XML (i.e. a 'search' or a 'show' response XML) + * + * The command response XML is subsequently parsed by Pazpar2ResponseParser, + * which will then create the CommandError object. + * + * @author Niels Erik + * + */ +public class CommandError extends Pazpar2ResponseData implements ErrorInterface { + + private static final long serialVersionUID = 8878776025779714122L; + private static Pattern xmlDeclaration = Pattern.compile("<\\?xml.*\\?>"); + private ErrorCode applicationErrorCode; + private ErrorHelper errorHelper = null; + + + public CommandError () { + } + + public String getLabel() { + return getOneElementValue("commandname"); + } + + public String getMessage() { + if (hasPazpar2Error()) { + return getPazpar2Error().getMsg(); + } else { + return getOneElementValue("errormessage"); + } + } + + public String getException () { + return getOneElementValue("exception"); + } + + public List getSuggestions() { + if (errorHelper!=null) { + return errorHelper.getSuggestions(this); + } else { + List nohelper = new ArrayList(); + nohelper.add("Tips: could not generate tips due to a programming error, error helper was not set"); + return nohelper; + } + } + + /** + * Creates an XML string error message, embedded in an XML string document named by the command + * This is the XML that Pazpar2ResponseParser will turn into a CommandError object. + * @param commandName + * @param exceptionName + * @param errorMessage + * @return + */ + public static String createErrorXml (String commandName, String exceptionName, String errorMessage) { + StringBuilder errorXml = new StringBuilder(""); + errorXml.append("<" + commandName + ">"+nl); + errorXml.append(" "+nl); + errorXml.append(" " + commandName + ""+nl); + errorXml.append(" " + XmlUtils.escape(exceptionName) + ""+nl); + errorXml.append(" " + XmlUtils.escape(errorMessage) + ""+nl); + errorXml.append(" "+nl); + errorXml.append(""+nl); + return errorXml.toString(); + } + + /** + * Embeds a Pazpar2 (or Pazpar2 client) error response document as a child element of + * a command response document (like 'search' or 'show'). + * This is the XML that Pazpar2ResponseParser will turn into a CommandError object. + * + * + * @param commandName The name of the command during which's execution the error was encountered + * @param exceptionName The (possibly loosely defined) name of the exception that was thrown + * @param pazpar2ErrorXml The error document as created by Pazpar2, or the Service Proxy or + * by the Pazpar2 client itself. + * @return + */ + public static String insertPazpar2ErrorXml (String commandName, String exceptionName, String pazpar2ErrorXml) { + StringBuilder errorXml = new StringBuilder(""); + errorXml.append("<" + commandName + ">"+nl); + errorXml.append(" "+nl); + errorXml.append(" " + commandName + ""+nl); + errorXml.append(" " + XmlUtils.escape(exceptionName) + ""+nl); + errorXml.append(xmlDeclaration.matcher(pazpar2ErrorXml).replaceAll("")+nl); + errorXml.append(" "+nl); + errorXml.append(""+nl); + return errorXml.toString(); + + } + + /** + * Sets the object that should be used to analyze the error + * + */ + public void setErrorHelper (ErrorHelper errorHelper) { + this.errorHelper = errorHelper; + } + + @Override + public void setApplicationErrorCode(ErrorCode code) { + this.applicationErrorCode = code; + } + + @Override + public ErrorCode getApplicationErrorCode() { + return applicationErrorCode; + } + + public boolean hasPazpar2Error () { + return ( getOneElement("error") != null); + } + + public Pazpar2Error getPazpar2Error() { + return (Pazpar2Error) getOneElement("error"); + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/Hit.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Hit.java new file mode 100644 index 0000000..8f16eee --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Hit.java @@ -0,0 +1,47 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.util.ArrayList; +import java.util.List; + +import com.indexdata.mkjsf.pazpar2.data.Location; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; + +public class Hit extends Pazpar2ResponseData { + + + private static final long serialVersionUID = 9039281987691623220L; + + public List getLocations() { + List locations = new ArrayList(); + for (Pazpar2ResponseData element : getElements("location")) { + locations.add((Location)element); + } + return locations; + } + + public String getTitle () { + return getOneElementValue("md-title"); + } + + public String getTitleRemainder() { + return getOneElementValue("md-title-remainder"); + } + + public String getAuthor (String prefix) { + return getOneElement("md-author") != null ? prefix + getOneElement("md-author").getValue() : ""; + } + + public String getAuthor () { + return getOneElementValue("md-author"); + } + + public String getTitleResponsibility() { + return getOneElementValue("md-title-responsibility"); + } + + public String getRecId() { + return getOneElementValue("recid"); + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/Location.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Location.java new file mode 100644 index 0000000..a3e6441 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Location.java @@ -0,0 +1,54 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; + + +public class Location extends Pazpar2ResponseData { + + private static final long serialVersionUID = -1386527442857478225L; + + public String getId() { + return getAttribute("id"); + } + + public String getName () { + return getAttribute("name"); + } + + public String getSubject() { + return getOneElementValue("md-subject"); + } + + public String getSubjects() { + StringBuilder builder = new StringBuilder(""); + for (Pazpar2ResponseData data : getElements("md-subject")) { + if (builder.length()==0) { + builder.append(data.getValue()); + } else { + builder.append(", "); + builder.append(data.getValue()); + } + } + return builder.toString(); + } + + public String getAuthor() { + return getOneElementValue("md-author"); + } + + public String getAuthors() { + StringBuilder builder = new StringBuilder(""); + if (getElements("md-author") != null) { + for (Pazpar2ResponseData data : getElements("md-author")) { + if (builder.length()==0) { + builder.append(data.getValue()); + } else { + builder.append(", "); + builder.append(data.getValue()); + } + } + } + return builder.toString(); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2Error.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2Error.java new file mode 100644 index 0000000..76a54f3 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2Error.java @@ -0,0 +1,14 @@ +package com.indexdata.mkjsf.pazpar2.data; + +public class Pazpar2Error extends Pazpar2ResponseData { + + private static final long serialVersionUID = -7060267782024414318L; + + public String getCode() { + return getAttribute("code"); + } + + public String getMsg() { + return getAttribute("msg"); + } +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2ResponseData.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2ResponseData.java new file mode 100644 index 0000000..10451ea --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2ResponseData.java @@ -0,0 +1,124 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; + +public class Pazpar2ResponseData implements Serializable { + + Logger logger = Logger.getLogger(Pazpar2ResponseData.class); + private static final long serialVersionUID = -3909755656714679959L; + String type = null; + HashMap attributes = new HashMap(); + HashMap> elements = new HashMap>(); + String textContent = ""; + CommandError error = null; + String xml = null; + + public void setType (String type) { + this.type = type; + } + + public String getType () { + return type; + } + + public void setAttribute (String name, String value) { + attributes.put(name, value); + } + + public String getAttribute (String name) { + return attributes.get(name); + } + + public void addElement (String name, Pazpar2ResponseData value) { + if (elements.containsKey(name)) { + elements.get(name).add(value); + } else { + List list = new ArrayList(); + list.add(value); + elements.put(name,list); + } + } + + public List getElements (String name) { + return elements.get(name); + } + + public Pazpar2ResponseData getOneElement (String name) { + if (elements.get(name) != null) { + return elements.get(name).get(0); + } else { + return null; + } + } + + /** + * Returns the text content of the first element found with the given + * name + * @param name of the element + * @return text value, empty string if none found + */ + public String getOneElementValue (String name) { + if (getOneElement(name)!=null && getOneElement(name).getValue().length()>0) { + return getOneElement(name).getValue(); + } else { + return ""; + } + } + + public void appendContent (String content) { + textContent = textContent + content; + } + + public String getValue () { + return textContent; + } + + public String getProperty(String name) { + List els = elements.get(name); + if (els != null) { + return els.get(0).getValue(); + } else { + return null; + } + } + + public int getIntValue(String name) { + String val = getOneElementValue(name); + if (val.length()==0) { + return 0; + } else { + return Integer.parseInt(val); + } + } + + public boolean hasApplicationError () { + return (getOneElement("applicationerror") != null); + } + + public CommandError getApplicationError() { + return (CommandError) getOneElement("applicationerror"); + } + + public boolean hasPazpar2Error() { + return hasApplicationError() && getApplicationError().hasPazpar2Error(); + } + + public void setXml(String xml) { + this.xml = xml; + } + + public String getXml() { + if (type != null && type.equals("record")) { + logger.debug("Getting XML for "+type + ": "+xml); + } + return xml == null ? "" : xml; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2ResponseParser.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2ResponseParser.java new file mode 100644 index 0000000..7cf41df --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2ResponseParser.java @@ -0,0 +1,162 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.List; +import java.util.Stack; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + +import com.indexdata.mkjsf.pazpar2.data.ByTarget; +import com.indexdata.mkjsf.pazpar2.data.Hit; +import com.indexdata.mkjsf.pazpar2.data.Location; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; +import com.indexdata.mkjsf.pazpar2.data.RecordResponse; +import com.indexdata.mkjsf.pazpar2.data.ShowResponse; +import com.indexdata.mkjsf.pazpar2.data.StatResponse; +import com.indexdata.mkjsf.pazpar2.data.Target; +import com.indexdata.mkjsf.pazpar2.data.TermListResponse; +import com.indexdata.mkjsf.pazpar2.data.TermListsResponse; +import com.indexdata.mkjsf.pazpar2.data.TermResponse; +import com.indexdata.mkjsf.pazpar2.data.TermXTargetResponse; + +public class Pazpar2ResponseParser extends DefaultHandler { + + private XMLReader xmlReader = null; + private Pazpar2ResponseData currentElement = null; + private Stack dataElements = new Stack(); + private Pazpar2ResponseData result = null; + private String xml = null; + + private static final List docTypes = + Arrays.asList("bytarget","termlist","show","stat","record","search"); + + public Pazpar2ResponseParser() { + try { + initSax(); + } catch (ParserConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static Pazpar2ResponseParser getParser() { + return new Pazpar2ResponseParser(); + } + + private void initSax() throws ParserConfigurationException, SAXException { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxParser = spf.newSAXParser(); + xmlReader = saxParser.getXMLReader(); + xmlReader.setContentHandler(this); + } + + /** + * Parses a Pazpar2 XML response -- or an error response as XML -- and produces a + * Pazpar2ResponseData object, i.e. a 'show' object + * + * @param response XML response string from Pazpar2 + * @return Response data object + */ + public Pazpar2ResponseData getDataObject (String response) { + this.xml = response; + try { + xmlReader.parse(new InputSource(new ByteArrayInputStream(response.getBytes("UTF-8")))); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return result; + } + + /** + * Receive notification at the start of element + * + */ + @Override + public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { + if (localName.equals("show")) { + currentElement = new ShowResponse(); + } else if (localName.equals("hit")) { + currentElement = new Hit(); + } else if (localName.equals("location")) { + currentElement = new Location(); + } else if (localName.equals("bytarget")) { + currentElement = new ByTarget(); + } else if (localName.equals("target")) { + currentElement = new Target(); + } else if (localName.equals("stat")) { + currentElement = new StatResponse(); + } else if (localName.equals("termlist")) { + currentElement = new TermListsResponse(); + } else if (localName.equals("list")) { + currentElement = new TermListResponse(); + ((TermListResponse)currentElement).setName(atts.getValue("name")); + ((TermListsResponse)dataElements.peek()).addTermList((TermListResponse)currentElement); + } else if (localName.equals("term")) { + if (dataElements.peek().getAttribute("name").equals("xtargets")) { + currentElement = new TermXTargetResponse(); + } else { + currentElement = new TermResponse(); + } + ((TermListResponse)dataElements.peek()).addTerm((TermResponse)currentElement); + } else if (localName.equals("record")) { + currentElement = new RecordResponse(); + } else if (localName.equals("search")) { + currentElement = new SearchResponse(); + } else if (localName.equals("applicationerror")) { + currentElement = new CommandError(); + } else if (localName.equals("error") && dataElements.peek().getType().equals("applicationerror")) { + currentElement = new Pazpar2Error(); + } else { + currentElement = new Pazpar2ResponseData(); + } + currentElement.setType(localName); + for (int i=0; i< atts.getLength(); i++) { + currentElement.setAttribute(atts.getLocalName(i), atts.getValue(i)); + } + if (!docTypes.contains(localName)) { + dataElements.peek().addElement(localName, currentElement); + } + if (this.xml != null) { // Store XML for doc level elements + currentElement.setXml(xml); + xml = null; + } + dataElements.push(currentElement); + } + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + String data = new String(ch, start, length); + dataElements.peek().appendContent(data); + } + + @Override + public void endElement(String namespaceURI, String localName, String qName) throws SAXException { + if (dataElements.size()==1) { + result = dataElements.pop(); + } else { + dataElements.pop(); + } + } +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2Responses.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2Responses.java new file mode 100644 index 0000000..b3748f8 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Pazpar2Responses.java @@ -0,0 +1,130 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.enterprise.context.SessionScoped; +import javax.inject.Named; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.errors.ErrorHelper; +import com.indexdata.mkjsf.errors.ErrorInterface; + +@Named("pzresp") @SessionScoped +public class Pazpar2Responses implements Serializable { + + private static final long serialVersionUID = -7543231258346154642L; + protected Map dataObjects = new ConcurrentHashMap(); + private static Logger logger = Logger.getLogger(Pazpar2Responses.class); + private ErrorHelper errorHelper = null; + + public Pazpar2Responses() { + } + + public void put(String name, Pazpar2ResponseData responseData) { + dataObjects.put(name, responseData); + } + + public void setErrorHelper(ErrorHelper helper) { + this.errorHelper = helper; + } + + public boolean hasApplicationError () { + if (getSearch().hasApplicationError()) { + logger.info("Error detected in search"); + return true; + } + for (String name : dataObjects.keySet()) { + if (dataObjects.get(name).hasApplicationError()) { + logger.info("Error detected in " + name); + return true; + } + } + return false; + } + + /** + * Returns a search command error, if any, otherwise the first + * error found for an arbitrary command, if any, otherwise + * an empty dummy error. + */ + public ErrorInterface getCommandError() { + CommandError error = new CommandError(); + if (dataObjects.get("search").hasApplicationError()) { + error = dataObjects.get("search").getApplicationError(); + error.setErrorHelper(errorHelper); + } else { + for (String name : dataObjects.keySet()) { + if (dataObjects.get(name).hasApplicationError()) { + error = dataObjects.get(name).getApplicationError(); + error.setErrorHelper(errorHelper); + break; + } + } + } + return error; + } + + public void reset() { + logger.debug("Resetting show,stat,termlist,bytarget,search response objects."); + dataObjects = new ConcurrentHashMap(); + dataObjects.put("show", new ShowResponse()); + dataObjects.put("stat", new StatResponse()); + dataObjects.put("termlist", new TermListsResponse()); + dataObjects.put("bytarget", new ByTarget()); + dataObjects.put("record", new RecordResponse()); + dataObjects.put("search", new SearchResponse()); + } + + public ShowResponse getShow () { + return ((ShowResponse) dataObjects.get("show")); + } + + public StatResponse getStat () { + return ((StatResponse) dataObjects.get("stat")); + } + + public RecordResponse getRecord() { + return ((RecordResponse) dataObjects.get("record")); + } + + public SearchResponse getSearch() { + return ((SearchResponse) dataObjects.get("search")); + } + + public TermListsResponse getTermLists () { + return ((TermListsResponse) dataObjects.get("termlist")); + } + + public List getFacetTerms (String facet, int count) { + return (getTermLists().getTermList(facet).getTerms(count)); + } + + public List getFacetTerms (String facet) { + return (getTermLists().getTermList(facet).getTerms()); + } + + public ByTarget getByTarget() { + return ((ByTarget) dataObjects.get("bytarget")); + } + + public boolean hasRecords () { + return getStat().getRecords() > 0 + && getShow().getHits() != null + && getShow().getHits().size()>0; + } + + public String getActiveClients() { + if (getShow()!=null) { + logger.debug("Active clients: "+getShow().getActiveClients()); + return getShow().getActiveClients(); + } else { + return ""; + } + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/RecordResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/RecordResponse.java new file mode 100644 index 0000000..0ba7988 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/RecordResponse.java @@ -0,0 +1,63 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.util.ArrayList; +import java.util.List; + +import com.indexdata.mkjsf.pazpar2.data.Location; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; + +public class RecordResponse extends Pazpar2ResponseData { + + private static final long serialVersionUID = 6682722004285796002L; + + public String getRecId () { + return getOneElementValue("recid"); + } + + public List getLocations() { + List locations = new ArrayList(); + for (Pazpar2ResponseData element : getElements("location")) { + locations.add((Location)element); + } + return locations; + } + + public String getTitle() { + return getOneElementValue("md-title"); + } + + public String getDate() { + return getOneElementValue("md-date"); + } + + public String getAuthor() { + return getOneElementValue("md-author"); + } + + public String getSubject() { + return getOneElementValue("md-subject"); + } + + public String getSubjects() { + StringBuilder builder = new StringBuilder(""); + for (Pazpar2ResponseData data : getElements("md-subject")) { + if (builder.length()==0) { + builder.append(data.getValue()); + } else { + builder.append(", "); + builder.append(data.getValue()); + } + } + return builder.toString(); + } + + public Location getFirstLocation () { + return getLocations().size()>0 ? getLocations().get(0) : null; + } + + public String getActiveClients () { + return getOneElementValue("activeclients"); + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/SearchResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/SearchResponse.java new file mode 100644 index 0000000..27706af --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/SearchResponse.java @@ -0,0 +1,7 @@ +package com.indexdata.mkjsf.pazpar2.data; + +public class SearchResponse extends Pazpar2ResponseData { + + private static final long serialVersionUID = -3320013021497018972L; + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/ShowResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/ShowResponse.java new file mode 100644 index 0000000..066a831 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/ShowResponse.java @@ -0,0 +1,49 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.util.ArrayList; +import java.util.List; + +import com.indexdata.mkjsf.pazpar2.data.Hit; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; + +public class ShowResponse extends Pazpar2ResponseData { + + private static final long serialVersionUID = 7103554232106330370L; + + + public String getStatus() { + return getOneElementValue("status"); + } + + public String getActiveClients () { + return getOneElementValue("activeclients"); + } + + public int getMerged () { + return getIntValue("merged"); + } + + public String getTotal () { + return getOneElementValue("total"); + } + + public int getStart () { + return getIntValue("start"); + } + + public int getNum () { + return getIntValue("num"); + } + + public List getHits() { + List hits = new ArrayList(); + if (getElements("hit") != null) { + for (Pazpar2ResponseData element : getElements("hit")) { + hits.add((Hit)element); + } + } + return hits; + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/StatResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/StatResponse.java new file mode 100644 index 0000000..9f808b1 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/StatResponse.java @@ -0,0 +1,53 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; + +public class StatResponse extends Pazpar2ResponseData { + + private static final long serialVersionUID = -6578979787689458761L; + + public int getHits() { + return getProperty("hits")==null ? 0 : Integer.parseInt(getProperty("hits")); + } + + public int getClients () { + return getIntValue("clients"); + } + + public int getActiveClients () { + return getIntValue("activeclients"); + } + + public int getRecords () { + return getIntValue("records"); + } + + public String getUnconnected() { + return getOneElementValue("unconnected"); + } + + public String getConnecting() { + return getOneElementValue("connecting"); + } + + public String getWorking() { + return getOneElementValue("working"); + } + + public String getIdle() { + return getOneElementValue("idle"); + } + + public String getFailed() { + return getOneElementValue("failed"); + } + + public String getError() { + return getOneElementValue("error"); + } + + public String getProgress() { + return getOneElementValue("progress"); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/Target.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Target.java new file mode 100644 index 0000000..59dd6f7 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/Target.java @@ -0,0 +1,33 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; + +public class Target extends Pazpar2ResponseData { + + private static final long serialVersionUID = 3343881183545520108L; + + public String getId () { + return getOneElementValue("id"); + } + + public String getName() { + return getOneElementValue("name"); + } + + public String getHits() { + return getOneElementValue("hits"); + } + + public String getDiagnostic() { + return getOneElementValue("diagnostic"); + } + + public String getRecords() { + return getOneElementValue("records"); + } + + public String getState () { + return getOneElementValue("state"); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermListResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermListResponse.java new file mode 100644 index 0000000..4c00a92 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermListResponse.java @@ -0,0 +1,52 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; +import com.indexdata.mkjsf.pazpar2.data.TermListResponse; +import com.indexdata.mkjsf.pazpar2.data.TermResponse; + +public class TermListResponse extends Pazpar2ResponseData { + + private static Logger logger = Logger.getLogger(TermListResponse.class); + private static final long serialVersionUID = 3838585739723097393L; + String name = ""; + List terms = new ArrayList(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getTerms() { + return terms; + } + + public List getTerms(int count) { + List firstTerms = new ArrayList(); + for (int i=0; i terms) { + this.terms = terms; + } + + public void addTerm(TermResponse term) { + terms.add(term); + } + + public String toString () { + return terms.toString(); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermListsResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermListsResponse.java new file mode 100644 index 0000000..27e3e1e --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermListsResponse.java @@ -0,0 +1,30 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import java.util.HashMap; +import java.util.Map; + +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; +import com.indexdata.mkjsf.pazpar2.data.TermListResponse; + +public class TermListsResponse extends Pazpar2ResponseData { + + private static final long serialVersionUID = -1370643625715834978L; + private int activeClients = -1; + private Map termLists = new HashMap(); + + public int getActiveClients() { + return activeClients; + } + public void setActiveClients(int activeClients) { + this.activeClients = activeClients; + } + + public void addTermList(TermListResponse termList) { + this.termLists.put(termList.getName(),termList); + } + public TermListResponse getTermList(String name) { + return termLists.get(name); + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermResponse.java new file mode 100644 index 0000000..e4a40cb --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermResponse.java @@ -0,0 +1,22 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import com.indexdata.mkjsf.pazpar2.data.Pazpar2ResponseData; + +public class TermResponse extends Pazpar2ResponseData { + + private static final long serialVersionUID = -8323959763575180678L; + + protected int frequency = -1; + + public String getName() { + return getProperty("name"); + } + public int getFrequency() { + return Integer.parseInt(getProperty("frequency")); + } + + public String toString() { + return getProperty("name"); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermXTargetResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermXTargetResponse.java new file mode 100644 index 0000000..c244516 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/data/TermXTargetResponse.java @@ -0,0 +1,28 @@ +package com.indexdata.mkjsf.pazpar2.data; + +import com.indexdata.mkjsf.pazpar2.data.TermResponse; + +public class TermXTargetResponse extends TermResponse { + + private static final long serialVersionUID = 5201902652960804977L; + + public String getId() { + return getOneElement("id").getValue(); + } + public int getApproximation () { + return Integer.parseInt(getOneElement("approximation").getValue()); + } + public int getRecords () { + return Integer.parseInt(getOneElement("records").getValue()); + } + public int getFiltered () { + return Integer.parseInt(getOneElement("filtered").getValue()); + } + public String getState () { + return getOneElement("state").getValue(); + } + public String getDiagnostic () { + return getOneElement("diagnostic").getValue(); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java new file mode 100644 index 0000000..3724362 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java @@ -0,0 +1,277 @@ +package com.indexdata.mkjsf.pazpar2.sp; + +import static com.indexdata.mkjsf.utils.Utils.nl; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.entity.ByteArrayEntity; +import org.apache.http.entity.FileEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.util.EntityUtils; +import org.apache.log4j.Logger; + +import com.indexdata.masterkey.config.MissingMandatoryParameterException; +import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException; +import com.indexdata.mkjsf.config.Configuration; +import com.indexdata.mkjsf.config.ConfigurationReader; +import com.indexdata.mkjsf.errors.ConfigurationException; +import com.indexdata.mkjsf.pazpar2.CommandResponse; +import com.indexdata.mkjsf.pazpar2.SearchClient; +import com.indexdata.mkjsf.pazpar2.commands.CommandParameter; +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command; +import com.indexdata.mkjsf.pazpar2.sp.auth.AuthenticationEntity; +import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser; +import com.indexdata.mkjsf.utils.Utils; + + +public class ServiceProxyClient implements SearchClient { + + private static final long serialVersionUID = -4031644009579840277L; + private static Logger logger = Logger.getLogger(ServiceProxyClient.class); + public static final String MODULENAME = "proxyclient"; + public static final String SERVICE_PROXY_URL = "SERVICE_PROXY_URL"; + public static final String SP_INIT_DOC_PATHS = "SP_INIT_DOC_PATHS"; + private String serviceUrl = "undefined"; + private String[] initDocPaths = null; + private Configuration config = null; + + ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler(); + private HttpClient client; + private ServiceProxyUser user; + + public ServiceProxyClient () { + SchemeRegistry schemeRegistry = new SchemeRegistry(); + schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); + ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); + client = new DefaultHttpClient(cm); + } + + @Override + public void configure (ConfigurationReader configReader) { + logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader)); + try { + config = configReader.getConfiguration(this); + serviceUrl = config.getMandatory(SERVICE_PROXY_URL); + this.initDocPaths = getMultiProperty(config.get(SP_INIT_DOC_PATHS)); + } catch (ConfigurationException c) { + c.printStackTrace(); + } catch (MissingMandatoryParameterException mmp) { + mmp.printStackTrace(); + } + } + + private String[] getMultiProperty(String prop) { + if (prop != null) { + return prop.split(","); + } else { + return null; + } + } + + public boolean authenticate (AuthenticationEntity user) { + try { + logger.info("Authenticating [" + user.getProperty("name") + "]"); + this.user = (ServiceProxyUser) user; + Pazpar2Command auth = new Pazpar2Command("auth",null); + auth.setParametersInState(new CommandParameter("action","=","login"), + new CommandParameter("username","=",user.getProperty("name")), + new CommandParameter("password","=",user.getProperty("password"))); + byte[] response = send(auth); + String responseStr = new String(response,"UTF-8"); + logger.info(responseStr); + if (responseStr.contains("FAIL")) { + return false; + } else { + return true; + } + } catch (ClientProtocolException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } + } + + public boolean checkAuthentication () { + try { + Pazpar2Command check = new Pazpar2Command("auth",null); + check.setParameter(new CommandParameter("action","=","check")); + byte[] response = send(check); + logger.info(new String(response,"UTF-8")); + } catch (ClientProtocolException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } + return true; + + } + + public boolean isAuthenticatingClient () { + return true; + } + + public boolean isAuthenticated () { + if (user.getProperty("name") != null && user.getProperty("password") != null) { + return checkAuthentication(); + } else { + return false; + } + } + + /** + * Makes the request + * @param request + * @return HTTP response as a String + * @throws ClientProtocolException + * @throws IOException + */ + private byte[] send(Pazpar2Command command) throws ClientProtocolException, IOException { + String url = serviceUrl + "?" + command.getEncodedQueryString(); + logger.info("Sending request "+url); + HttpGet httpget = new HttpGet(url); + byte[] response = client.execute(httpget, handler); + return response; + } + + public class ProxyPz2ResponseHandler implements ResponseHandler { + private StatusLine statusLine = null; + public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { + byte[] resp = null; + HttpEntity entity = response.getEntity(); + statusLine = response.getStatusLine(); + if (entity != null) { + resp = EntityUtils.toByteArray(entity); + } + EntityUtils.consume(entity); + return resp; + } + public int getStatusCode() { + return statusLine.getStatusCode(); + } + public String getReasonPhrase() { + return statusLine.getReasonPhrase(); + } + } + + public int getStatusCode () { + return handler.getStatusCode(); + } + + public String getReasonPhrase() { + return handler.getReasonPhrase(); + } + + @Override + public void setSearchCommand(Pazpar2Command command) { + // Do nothing, Service Proxy is handling this + } + + @Override + public CommandResponse executeCommand(Pazpar2Command command, + ByteArrayOutputStream baos) throws Pazpar2ErrorException, IOException { + byte[] response = send(command); + baos.write(response); + return new ServiceProxyClientCommandResponse(getStatusCode(), new String(response,"UTF-8")); + } + + public ServiceProxyClient cloneMe() { + logger.debug("Cloning Pz2Client"); + ServiceProxyClient clone = new ServiceProxyClient(); + clone.client = this.client; + clone.serviceUrl = this.serviceUrl; + clone.initDocPaths = this.initDocPaths; + return clone; + } + + @Override + public Map getDefaults() { + return new HashMap(); + } + + @Override + public String getModuleName() { + return MODULENAME; + } + + @Override + public List documentConfiguration () { + List doc = new ArrayList(); + doc.add(nl+ MODULENAME + " was configured to access the Pazpar2 service proxy at: " + serviceUrl); + return null; + } + + public byte[] postInitDoc (String filePath) throws IOException { + logger.info("Looking to post the file in : [" + filePath +"]"); + HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes"); + File initDoc = new File(filePath); + logger.info("Posting to SP: "); + if (logger.isDebugEnabled()) { + BufferedReader reader = new BufferedReader(new FileReader(initDoc)); + String line; + while ( (line = reader.readLine()) != null) { + System.out.println(line); + } + reader.close(); + } + post.setEntity(new FileEntity(initDoc)); + byte[] response = client.execute(post, handler); + logger.debug("Response on POST was: " + new String(response,"UTF-8")); + return response; + } + + public String[] getInitDocPaths () { + logger.debug("Get init doc paths "); + logger.debug("length: " + initDocPaths.length); + return initDocPaths; + } + + public byte[] postInitDoc(byte[] initDoc) throws IOException { + HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes"); + post.setEntity(new ByteArrayEntity(initDoc)); + byte[] response = client.execute(post, handler); + logger.debug("Response on POST was: " + new String(response,"UTF-8")); + return response; + } + + public void setServiceProxyUrl (String url) { + serviceUrl = url; + } + + public String getServiceProxyUrl () { + return serviceUrl; + } + + public Configuration getConfiguration () { + return config; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClientCommandResponse.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClientCommandResponse.java new file mode 100644 index 0000000..982233e --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClientCommandResponse.java @@ -0,0 +1,30 @@ +package com.indexdata.mkjsf.pazpar2.sp; + +import com.indexdata.mkjsf.pazpar2.CommandResponse; + +public class ServiceProxyClientCommandResponse implements CommandResponse { + + private int statusCode = 0; + private String content = null; + + public ServiceProxyClientCommandResponse(int statusCode, String content) { + this.statusCode = statusCode; + this.content = content; + } + + @Override + public int getStatusCode() { + return statusCode; + } + + @Override + public String getContentType() { + return "text/xml;charset=UTF-8"; + } + + @Override + public String getResponseString() { + return content; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java new file mode 100644 index 0000000..46d4e77 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java @@ -0,0 +1,17 @@ +package com.indexdata.mkjsf.pazpar2.sp; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import com.indexdata.mkjsf.pazpar2.Pz2Interface; + +public interface ServiceProxyInterface extends Pz2Interface { + public String login(String navigateTo); + public void setInitFileName (String fileName); + public String getInitFileName(); + public String postInit() throws UnsupportedEncodingException, IOException; + public String postInit(byte[] initDoc) throws UnsupportedEncodingException, IOException; + public String getInitResponse(); + public void setServiceProxyUrl(String url); + public String getServiceProxyUrl(); +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/auth/AuthenticationEntity.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/auth/AuthenticationEntity.java new file mode 100644 index 0000000..9f8b0cb --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/auth/AuthenticationEntity.java @@ -0,0 +1,16 @@ +package com.indexdata.mkjsf.pazpar2.sp.auth; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +public interface AuthenticationEntity extends Serializable{ + + + public String getProperty(String key); + + public Map getPropertyMap(); + + public List getPossibleProperties(); + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/auth/ServiceProxyUser.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/auth/ServiceProxyUser.java new file mode 100644 index 0000000..ea0be27 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/auth/ServiceProxyUser.java @@ -0,0 +1,65 @@ +package com.indexdata.mkjsf.pazpar2.sp.auth; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.enterprise.context.SessionScoped; +import javax.inject.Named; + +@Named("user") @SessionScoped +public class ServiceProxyUser implements AuthenticationEntity { + + private static final long serialVersionUID = 2351542518778803071L; + private List possibleProperties = Arrays.asList("name","password","realm"); + private Map actualProperties = new HashMap(); + + public ServiceProxyUser() {} + + public void setAuthenticationMethod() { + + } + + public String getName() { + return actualProperties.get("name"); + } + + public void setName(String newValue) { + actualProperties.put("name", newValue); + } + + public String getPassword() { + return actualProperties.get("password"); + } + + public void setPassword(String newValue) { + actualProperties.put("password", newValue); + } + + public void setRealm(String realm) { + actualProperties.put("realm", realm); + } + + public String getRealm() { + return actualProperties.get("realm"); + } + + + @Override + public String getProperty(String key) { + return actualProperties.get(key); + } + + @Override + public Map getPropertyMap() { + return actualProperties; + } + + @Override + public List getPossibleProperties() { + return possibleProperties; + } + + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/state/Pazpar2State.java b/src/main/java/com/indexdata/mkjsf/pazpar2/state/Pazpar2State.java new file mode 100644 index 0000000..e983d5c --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/state/Pazpar2State.java @@ -0,0 +1,107 @@ +package com.indexdata.mkjsf.pazpar2.state; + +import java.util.HashMap; +import java.util.Map; + +import com.indexdata.mkjsf.pazpar2.commands.BytargetCommand; +import com.indexdata.mkjsf.pazpar2.commands.InitCommand; +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command; +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Commands; +import com.indexdata.mkjsf.pazpar2.commands.PingCommand; +import com.indexdata.mkjsf.pazpar2.commands.RecordCommand; +import com.indexdata.mkjsf.pazpar2.commands.SearchCommand; +import com.indexdata.mkjsf.pazpar2.commands.SettingsCommand; +import com.indexdata.mkjsf.pazpar2.commands.ShowCommand; +import com.indexdata.mkjsf.pazpar2.commands.StatCommand; +import com.indexdata.mkjsf.pazpar2.commands.TermlistCommand; + +/** + * Holds a 'pazpar2 state', understood as a full set of pazpar2 commands and + * all their parameter settings at a given point in time. + * + * @author Niels Erik + * + */ +public class Pazpar2State { + + String key = null; + Map commands = new HashMap();; + + public Pazpar2State (StateManager mgr) { + commands.put(Pazpar2Commands.INIT, new InitCommand(mgr)); + commands.put(Pazpar2Commands.PING, new PingCommand(mgr)); + commands.put(Pazpar2Commands.SETTINGS, new SettingsCommand(mgr)); + commands.put(Pazpar2Commands.SEARCH, new SearchCommand(mgr)); + commands.put(Pazpar2Commands.STAT, new StatCommand(mgr)); + commands.put(Pazpar2Commands.SHOW, new ShowCommand(mgr)); + commands.put(Pazpar2Commands.RECORD, new RecordCommand(mgr)); + commands.put(Pazpar2Commands.TERMLIST, new TermlistCommand(mgr)); + commands.put(Pazpar2Commands.BYTARGET, new BytargetCommand(mgr)); + key = "#1"; + } + + /** + * Creates new state by cloning all commands of the provided state and + * then overriding one of them with the provided state changing command. + * + * @param previousState + * @param newCommand + */ + public Pazpar2State (Pazpar2State previousState, Pazpar2Command newCommand) { + for (String commandName : previousState.commands.keySet()) { + this.commands.put(commandName, previousState.commands.get(commandName).copy()); + } + this.commands.put(newCommand.getName(),newCommand); + this.key = getKey(); + } + + /** + * Generates a state key that can be used by the browser to pick + * up this state again at a later point in time. + * + * @return + */ + public String getKey() { + if (key == null) { + StringBuilder querystatebuilder = new StringBuilder(""); + for (Pazpar2Command command : commands.values()) { + if (command.hasParameters()) { + querystatebuilder.append("||"+command.getName()+"::"); + querystatebuilder.append(command.getValueWithExpressions()); + } + } + key = "#"+querystatebuilder.toString().hashCode(); + return key; + } else { + return key; + } + } + + /** + * Checks if a command represents a change of this state + * + * @param command + * @return true if the command causes a change of state + */ + public boolean stateMutating (Pazpar2Command command) { + if (command == null) { + return true; + } else if (commands.get(command.getName()) == null) { + return true; + } else if ((command.equals(commands.get(command.getName())))) { + return false; + } else { + return true; + } + } + + /** + * Returns a command from this state + * + * @param name + * @return + */ + public Pazpar2Command getCommand(String name) { + return commands.get(name); + } +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/state/StateListener.java b/src/main/java/com/indexdata/mkjsf/pazpar2/state/StateListener.java new file mode 100644 index 0000000..d157e47 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/state/StateListener.java @@ -0,0 +1,7 @@ +package com.indexdata.mkjsf.pazpar2.state; + +public interface StateListener { + + public void stateUpdated(String commandName); + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/state/StateManager.java b/src/main/java/com/indexdata/mkjsf/pazpar2/state/StateManager.java new file mode 100644 index 0000000..f150dd8 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/state/StateManager.java @@ -0,0 +1,138 @@ +package com.indexdata.mkjsf.pazpar2.state; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.enterprise.context.SessionScoped; + +import org.apache.log4j.Logger; + +import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command; +import com.indexdata.mkjsf.utils.Utils; + +@SessionScoped +public class StateManager implements Serializable { + + private static final long serialVersionUID = 8152558351351730035L; + + Map states = new HashMap(); + String currentKey = ""; + private static List allCommands = new ArrayList(Arrays.asList("init","ping","settings","search","stat","show","record","termlist","bytarget")); + Map pendingStateChanges = new HashMap(); + private static Logger logger = Logger.getLogger(StateManager.class); + private List listeners = new ArrayList(); + + public StateManager () { + logger.info("Initializing a Pazpar2 state manager [" + Utils.objectId(this) + "]"); + Pazpar2State initialState = new Pazpar2State(this); + states.put(initialState.getKey(), initialState); + currentKey = initialState.getKey(); + for (String command : allCommands) { + pendingStateChanges.put(command, new Boolean(false)); + } + } + + public void addStateListener(StateListener listener) { + listeners.add(listener); + } + + public void removeStateListener (StateListener listener) { + listeners.remove(listener); + } + + private void updateListeners (String command) { + for (StateListener lsnr : listeners) { + lsnr.stateUpdated(command); + } + } + + /** + * Registers a Pazpar2 command for execution. + * + * The state manager will update current state and flag that + * a request change was made but that it was not yet carried + * out against Pazpar2. + * + * Any command that is created or modified must be checked in + * like this to come into effect. + * + * @param command + */ + public void checkIn(Pazpar2Command command) { + if (getCurrentState().stateMutating(command)) { + logger.debug("State changed by: " + command.getName()); + Pazpar2State state = new Pazpar2State(getCurrentState(),command); + states.put(state.getKey(), state); + currentKey = state.getKey(); + hasPendingStateChange(command.getName(),new Boolean(true)); + logger.debug("Updating " + listeners.size() + " listener(s) with state change from " + command); + updateListeners(command.getName()); + } else { + logger.debug("Command " + command.getName() + " not found to change the state [" + command.getEncodedQueryString() + "]"); + } + } + + public Pazpar2Command getCommand (String commandName) { + return getCurrentState().getCommand(commandName); + } + + public Pazpar2State getCurrentState () { + return states.get(currentKey); + } + + /** + * Changes the current state key. Invoked from the UI to have the state + * manager switch to another state than the current one. + * + * @param key + */ + public void setCurrentStateKey(String key) { + if (currentKey.equals(key)) { + logger.debug("setCurrentStateKey: no key change detected"); + } else { + logger.debug("State key change. Was: [" + currentKey + "]. Will be ["+key+"]"); + if (states.get(key)==null) { + logger.error("The back-end received an unknow state key."); + } else { + if (states.get(key).getCommand("search").equals(states.get(currentKey).getCommand("search"))) { + logger.debug("No search change detected"); + } else { + hasPendingStateChange("search",true); + } + if (states.get(key).getCommand("record").equals(states.get(currentKey).getCommand("record"))) { + logger.debug("No record change detected"); + } else { + hasPendingStateChange("record",true); + } + currentKey = key; + } + } + } + + /** + * Sets a pending-state-change flag for the given command and notifies + * registered listeners. + * + * It is up to the listener to reset the flag as needed. + * + * @param command + * @param bool + */ + public void hasPendingStateChange(String command, boolean bool) { + pendingStateChanges.put(command, new Boolean(bool)); + } + + /** + * + * @param command + * @return true if there is a non-executed command change in this state + */ + public boolean hasPendingStateChange (String command) { + return pendingStateChanges.get(command).booleanValue(); + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pz2utils/ListenerFieldIds.java b/src/main/java/com/indexdata/mkjsf/pz2utils/ListenerFieldIds.java new file mode 100644 index 0000000..df3652f --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pz2utils/ListenerFieldIds.java @@ -0,0 +1,30 @@ +package com.indexdata.mkjsf.pz2utils; + +import java.io.Serializable; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Named; + +@Named("pz2watch") +@ApplicationScoped +public class ListenerFieldIds implements Serializable { + + private static final long serialVersionUID = -57079241763914538L; + + public String getHistory () { + return ":pz2watch:stateForm:windowlocationhash"; + } + + public String getActiveclients () { + return ":pz2watch:activeclientsForm:activeclientsField"; + } + + public String getActiveclientsRecord () { + return ":pz2watch:activeclientsForm:activeclientsFieldRecord"; + } + + public String getErrorMessages () { + return ":pz2watch:activeclientsForm:errorMessages"; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/utils/Utils.java b/src/main/java/com/indexdata/mkjsf/utils/Utils.java new file mode 100644 index 0000000..4b09747 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/utils/Utils.java @@ -0,0 +1,24 @@ +package com.indexdata.mkjsf.utils; + +public class Utils { + + public static String nl = System.getProperty("line.separator"); + + public static String objectId(Object o) { + int lastdot = o.toString().lastIndexOf('.'); + if (lastdot>-1 && lastdot+1 getDefaults(); - - /** - * Returns the name of the module, can be used by a configuration reader that - * has distinguishes between sets of configuration properties by component name - * @return name of the part that is to be configured - */ - public String getModuleName(); - - /** - * The components documentation of how it was configured. - * - * @return a list of Strings describing configuration details - */ - public List documentConfiguration(); - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/config/Configuration.java b/src/main/java/com/indexdata/pz2utils4jsf/config/Configuration.java deleted file mode 100644 index 67106c3..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/config/Configuration.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.indexdata.pz2utils4jsf.config; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.Logger; - -import com.indexdata.masterkey.config.MissingMandatoryParameterException; -import com.indexdata.pz2utils4jsf.utils.Utils; - -/** - * Represents a configuration as a set of key-value pairs - * - * @author Niels Erik - * - */ -public class Configuration implements Serializable { - - private static final long serialVersionUID = -6801241975338182197L; - private static Logger logger = Logger.getLogger(Configuration.class); - Map properties = new HashMap(); - - public Configuration () { - logger.debug(Utils.objectId(this) + " being constructed with no argument"); - } - - public Configuration(Map parameters) { - addAll(parameters); - } - - public void addAll(Map parameters) { - for (String key : parameters.keySet()) { - properties.put(key, parameters.get(key)); - } - } - - public void addAll(Map defaults, Map parameters) { - for (String key : defaults.keySet()) { - properties.put(key, defaults.get(key)); - } - for (String key : parameters.keySet()) { - properties.put(key, parameters.get(key)); - } - } - - public String get(String key) { - return properties.get(key); - } - - public void set(String key, String value) { - properties.put(key, value); - } - - public String get(String key, String defaultValue) { - if (properties.containsKey(key)) { - return properties.get(key); - } else { - return defaultValue; - } - } - - public String getMandatory(String key) throws MissingMandatoryParameterException { - if (properties.containsKey(key)) { - return properties.get(key); - } - throw new MissingMandatoryParameterException("Missing mandatory parameter: " + key); - } - - public String getConfigFilePath() { - return get("configpath","nopathgiven"); - } - - public Map getConfigMap() { - return properties; - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/config/ConfigurationReader.java b/src/main/java/com/indexdata/pz2utils4jsf/config/ConfigurationReader.java deleted file mode 100644 index ea94af5..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/config/ConfigurationReader.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.indexdata.pz2utils4jsf.config; - -import java.io.Serializable; -import java.util.List; - -import com.indexdata.pz2utils4jsf.errors.ConfigurationException; - -/** - * Interface to be implemented by classes that read configurations from a source - - * i.e. from web.xml, the file system, a database or hard-coded. - * - * @author Niels Erik - * - */ -public interface ConfigurationReader extends Serializable { - - /** - * Returns a Configuration to be used by the given Configurable - * - * @param configurable the configurable to be configured by a configuration obtained by this reader - * @return a Configuration, basically a set of key-value pairs - * @throws ConfigurationException - */ - public Configuration getConfiguration(Configurable configurable) throws ConfigurationException; - - /** - * Returns documentation for the key-value pairs obtained by this reader - * @return - */ - public List document(); -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/config/Mk2ConfigReader.java b/src/main/java/com/indexdata/pz2utils4jsf/config/Mk2ConfigReader.java deleted file mode 100644 index 554f931..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/config/Mk2ConfigReader.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.indexdata.pz2utils4jsf.config; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.enterprise.context.SessionScoped; -import javax.enterprise.inject.Alternative; -import javax.faces.context.ExternalContext; -import javax.faces.context.FacesContext; -import javax.inject.Named; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -import org.apache.log4j.Logger; - -import com.indexdata.masterkey.config.MasterkeyConfiguration; -import com.indexdata.masterkey.config.ModuleConfiguration; -import com.indexdata.pz2utils4jsf.errors.ConfigurationException; -import com.indexdata.pz2utils4jsf.utils.Utils; -import static com.indexdata.pz2utils4jsf.utils.Utils.nl; - -/** - * Reads configuration from a MasterKey configuration scheme - * - * - * @author Niels Erik - * - */ -@Named @SessionScoped @Alternative -public class Mk2ConfigReader implements ConfigurationReader { - - private static final long serialVersionUID = 8865086878660568870L; - private static Logger logger = Logger.getLogger(Mk2ConfigReader.class); - private Map configs = new HashMap(); - private Map configurables = new HashMap(); - - public Mk2ConfigReader () throws IOException { - logger.info(Utils.objectId(this) + " is instantiating Pazpar2 service configuration by MasterKey configuration scheme."); - } - - @Override - public Configuration getConfiguration(Configurable configurable) throws ConfigurationException { - if (configs.get(configurable.getModuleName()) == null) { - Configuration config = readConfig(configurable); - configs.put(configurable.getModuleName(), config); - configurables.put(configurable.getModuleName(), configurable); - } - return configs.get(configurable.getModuleName()); - } - - private Configuration readConfig (Configurable configurable) throws ConfigurationException { - Configuration config = new Configuration(); - ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); - ServletContext servletContext = (ServletContext) externalContext.getContext(); - MasterkeyConfiguration mkConfigContext; - try { - mkConfigContext = MasterkeyConfiguration.getInstance(servletContext, - "pazpar-application-jsf", ((HttpServletRequest) externalContext.getRequest()).getServerName()); - } catch (IOException e) { - throw new ConfigurationException(Mk2ConfigReader.class + " could not read configuration for '" + configurable.getModuleName() + "' using MasterKey configuration scheme: "+e.getMessage(),e); - } - try { - ModuleConfiguration moduleConfig = mkConfigContext.getModuleConfiguration(configurable.getModuleName()); - config.addAll(configurable.getDefaults(),moduleConfig.getConfigMap()); - config.set("configpath", moduleConfig.getConfigFilePath()); - } catch (IOException e) { - throw new ConfigurationException(Mk2ConfigReader.class + " could not read configuration for '"+ configurable.getModuleName() + "': "+e.getMessage(),e); - } - return config; - } - - public List document() { - List doc = new ArrayList(); - doc.add("Application properties as read by " + this.getClass()); - for (String moduleName : configs.keySet()) { - doc.add(nl+"Module: " + moduleName); - Configurable module = configurables.get(moduleName); - Map map = configs.get(moduleName).getConfigMap(); - for (String key : map.keySet()) { - doc.add(nl+key+": "+ map.get(key) + - (module.getDefaults().containsKey(key) ? - (module.getDefaults().get(key).equals(map.get(key)) ? " [default]" : " [override]") - : "")); - } - } - return doc; - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/config/WebXmlConfigReader.java b/src/main/java/com/indexdata/pz2utils4jsf/config/WebXmlConfigReader.java deleted file mode 100644 index ac0e045..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/config/WebXmlConfigReader.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.indexdata.pz2utils4jsf.config; - -import static com.indexdata.pz2utils4jsf.utils.Utils.nl; - -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.enterprise.context.SessionScoped; -import javax.enterprise.inject.Alternative; -import javax.faces.context.ExternalContext; -import javax.faces.context.FacesContext; -import javax.inject.Named; -import javax.servlet.ServletContext; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.errors.ConfigurationException; - -/** - * Reads a configuration from the context parameters of the deployment descriptor (web.xml) - * - * @author Niels Erik - * - */ -@Named @SessionScoped @Alternative -public class WebXmlConfigReader implements ConfigurationReader { - - private static final long serialVersionUID = 144390224959311772L; - private static Logger logger = Logger.getLogger(WebXmlConfigReader.class); - private Configuration config = null; - private Map parameters = new HashMap(); - - public WebXmlConfigReader () { - logger.info("Instantiating Pazpar2 service configuration by web.xml parameters"); - } - - public Configuration getConfiguration(Configurable configurable) throws ConfigurationException { - if (config == null) { - parameters.putAll(configurable.getDefaults()); - parameters.putAll(readConfig()); - config = new Configuration(parameters); - } - return config; - } - - private Map readConfig () throws ConfigurationException { - Map map = new HashMap(); - ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); - ServletContext servletContext = (ServletContext) externalContext.getContext(); - Enumeration enumer = servletContext.getInitParameterNames(); - while (enumer.hasMoreElements()) { - String name = enumer.nextElement(); - map.put(name,servletContext.getInitParameter(name)); - } - return map; - } - - public List document() { - List doc = new ArrayList(); - doc.add("Application properties as read by " + this.getClass()); - for (String key : parameters.keySet()) { - doc.add(nl+key+": "+ parameters.get(key)); - } - return doc; - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/controls/PageLink.java b/src/main/java/com/indexdata/pz2utils4jsf/controls/PageLink.java deleted file mode 100644 index e9c4ac0..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/controls/PageLink.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.indexdata.pz2utils4jsf.controls; - -import java.io.Serializable; - -import com.indexdata.pz2utils4jsf.controls.ResultsPager; - -public class PageLink implements Serializable { - - private static final long serialVersionUID = -468888598965842949L; - String text = ""; - int page = 0; - ResultsPager pager; - public PageLink(String text, int page, ResultsPager pager) { - this.text = text; - this.page = page; - this.pager = pager; - } - - public boolean isLink() { - return page>0; - } - - public boolean isCurrent() { - return (pager.getCurrentPageNum()==page); - } - - public String getText() { - return text; - } - - public int getPage() { - return page; - } - - public int getStart() { - return pager.getPageSize()*(page-1); - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/controls/ResultsPager.java b/src/main/java/com/indexdata/pz2utils4jsf/controls/ResultsPager.java deleted file mode 100644 index e80e1b6..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/controls/ResultsPager.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.indexdata.pz2utils4jsf.controls; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Commands; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2Responses; - -public class ResultsPager implements Serializable { - - private static final long serialVersionUID = 8854795222615583071L; - private Pazpar2Responses data = null; - private int pageRangeLength = 13; - private Pazpar2Commands req; - - public ResultsPager(Pazpar2Responses data) { - this.data = data; - } - - public ResultsPager(Pazpar2Responses data, int pageRange, Pazpar2Commands req) { - this.data = data; - this.pageRangeLength = pageRange; - this.req = req; - } - - private boolean hasHits () { - return (data.getShow().getMerged()>0); - } - - public int getCurrentPageNum () { - if (hasHits() && data.getShow().getNum()>0) { - return (data.getShow().getStart()/data.getShow().getNum())+1; - } else { - return 0; - } - } - - public int getPageSize() { - return data.getShow().getNum(); - } - - public int getFirstDisplayedPageNum () { - if (hasHits()) { - if (getCurrentPageNum() - (pageRangeLength/2) < 1) { - return 1; - } else { - return (getCurrentPageNum()-(pageRangeLength/2)); - } - } else { - return 0; - } - } - - public int getLastDisplayedPageNum () { - if (hasHits()) { - if ((getFirstDisplayedPageNum() + pageRangeLength-1) > getLastPageNum()) { - return getLastPageNum(); - } else { - return getFirstDisplayedPageNum() + pageRangeLength - 1; - } - } else { - return 0; - } - } - - public int getLastPageNum () { - if (hasHits()) { - return (int) Math.ceil(new Double(data.getShow().getMerged())/new Double(data.getShow().getNum())); - } else { - return 0; - } - } - - public List setPageLinks (int rangeLength) { - this.pageRangeLength = rangeLength; - return getPageLinks(); - } - - public List getPageLinks () { - ArrayList range = new ArrayList(); - if (hasHits()) { - for (int i = getFirstDisplayedPageNum(); i>0 && i<=getLastDisplayedPageNum();i++) { - range.add(new PageLink(i+"",i,this)); - } - } - return range; - } - - - public PageLink getPreviousPageLink (String text) { - String linkText = (text!=null && text.length()>0 ? text : "Prev"); - if (hasHits() && getCurrentPageNum()>1) { - return new PageLink(linkText,getCurrentPageNum()-1,this); - } else { - return new PageLink(linkText,0,this); - } - } - - public PageLink getNextPageLink (String text) { - String linkText = (text!=null && text.length()>0 ? text : "Next"); - if (hasHits() && getCurrentPageNum()1; - } - - public boolean hasNextPage () { - return getCurrentPage() < getLastPageNum(); - } - - public boolean hasPageAfterLastDisplayed() { - return getLastDisplayedPageNum() < getLastPageNum(); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/errors/ConfigurationError.java b/src/main/java/com/indexdata/pz2utils4jsf/errors/ConfigurationError.java deleted file mode 100644 index ef2969d..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/errors/ConfigurationError.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.indexdata.pz2utils4jsf.errors; - -import java.util.List; - -import com.indexdata.pz2utils4jsf.errors.ErrorHelper.ErrorCode; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2Error; - - -public class ConfigurationError implements ErrorInterface { - - private static final long serialVersionUID = -6599667223782130838L; - private String label; - private String message; - private String exception; - private ErrorHelper helper; - private ErrorCode applicationErrorCode; - - public ConfigurationError(String label, String exception, String message) { - this.label = label; - this.message = message; - this.exception = exception; - } - - public List getSuggestions() { - return helper.getSuggestions(this); - } - - @Override - public String getLabel() { - return label; - } - - @Override - public String getMessage() { - return message; - } - - @Override - public String getException() { - return exception; - } - - @Override - public void setErrorHelper (ErrorHelper helper) { - this.helper = helper; - } - - @Override - public void setApplicationErrorCode(ErrorCode code) { - this.applicationErrorCode = code; - } - - @Override - public ErrorCode getApplicationErrorCode() { - return applicationErrorCode; - } - - public boolean hasPazpar2Error () { - return false; - } - - public Pazpar2Error getPazpar2Error() { - return null; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/errors/ConfigurationException.java b/src/main/java/com/indexdata/pz2utils4jsf/errors/ConfigurationException.java deleted file mode 100644 index b1336d2..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/errors/ConfigurationException.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.indexdata.pz2utils4jsf.errors; - -public class ConfigurationException extends Exception { - - private static final long serialVersionUID = -2406313397798065423L; - - public ConfigurationException() { - // TODO Auto-generated constructor stub - } - - public ConfigurationException(String message) { - super(message); - // TODO Auto-generated constructor stub - } - - public ConfigurationException(Throwable cause) { - super(cause); - // TODO Auto-generated constructor stub - } - - public ConfigurationException(String message, Throwable cause) { - super(message, cause); - // TODO Auto-generated constructor stub - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorCentral.java b/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorCentral.java deleted file mode 100644 index a143517..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorCentral.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.indexdata.pz2utils4jsf.errors; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.enterprise.context.SessionScoped; -import javax.inject.Inject; -import javax.inject.Named; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.config.ConfigurationReader; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2Responses; - -@Named("errors") @SessionScoped -public class ErrorCentral implements Serializable { - - private static final long serialVersionUID = -1658192041068396628L; - private static Logger logger = Logger.getLogger(ErrorCentral.class); - private ErrorHelper errorHelper = null; - - @Inject Pazpar2Responses pzresp; - @Inject ConfigurationReader configurator; - - private List configurationErrors = new ArrayList(); - - public ErrorCentral() {} - - @PostConstruct - public void postConstruct() { - errorHelper = new ErrorHelper(configurator); - pzresp.setErrorHelper(errorHelper); - } - - public void addConfigurationError (ErrorInterface configError) { - configError.setErrorHelper(errorHelper); - configurationErrors.add(configError); - } - - public boolean hasConfigurationErrors () { - return (configurationErrors.size()>0); - } - - public boolean hasCommandErrors () { - return pzresp.hasApplicationError(); - } - - public ErrorInterface getCommandError () { - return pzresp.getCommandError(); - } - - /** - * Returns true if application error found in any response data objects - */ - public boolean hasErrors () { - logger.debug("Checking for configuration errors or command errors."); - return hasConfigurationErrors() || hasCommandErrors(); - } - - public List getConfigurationErrors() { - return configurationErrors; - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorHelper.java b/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorHelper.java deleted file mode 100644 index 086cd84..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorHelper.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.indexdata.pz2utils4jsf.errors; - -import static com.indexdata.pz2utils4jsf.utils.Utils.nl; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.config.ConfigurationReader; -import com.indexdata.pz2utils4jsf.utils.Utils; - -public class ErrorHelper implements Serializable { - - public enum ErrorCode {PAZPAR2_404, - PAZPAR2_UNEXPECTED_RESPONSE, - PAZPAR2_ERRORS, - LOCAL_SERVICE_DEF_FILE_NOT_FOUND, - REMOTE_SERVICE_DEF_NOT_FOUND, - LOCAL_SETTINGS_FILE_NOT_FOUND, - MASTERKEY_CONFIG_FILE_NOT_FOUND, - MISSING_MANDATORY_PROPERTY, - MISSING_MK2_CONFIG_INIT_PARAMETER, - MISSING_CONTEXT_PARAMETER, - NOT_RESOLVED, - SKIP_SUGGESTIONS}; - - private static final long serialVersionUID = 2860804561068279131L; - private static Pattern httpResponsePattern = Pattern.compile("Unexpected HTTP response code \\(([0-9]*)\\).*"); - - private static Logger logger = Logger.getLogger(ErrorHelper.class); - - private ConfigurationReader configurator = null; - - public ErrorHelper(ConfigurationReader configurator) { - this.configurator = configurator; - } - - public ErrorHelper.ErrorCode getErrorCode(ErrorInterface appError) { - String errmsg = appError.getMessage(); - if (appError.hasPazpar2Error()) { - if (appError.getPazpar2Error().getMsg().contains("target settings from file")) { - return ErrorCode.LOCAL_SETTINGS_FILE_NOT_FOUND; - } else { - return ErrorCode.PAZPAR2_ERRORS; - } - } else if (errmsg.startsWith("Unexpected HTTP response")) { - Matcher m = httpResponsePattern.matcher(appError.getMessage()); - if (m.matches()) { - String errorCode = m.group(1); - if (errorCode.equals("404")) { - return ErrorCode.PAZPAR2_404; - } else { - return ErrorCode.PAZPAR2_UNEXPECTED_RESPONSE; - } - } - } else if (errmsg.contains("Configuration file") & appError.getMessage().contains("properties")) { - return ErrorCode.MASTERKEY_CONFIG_FILE_NOT_FOUND; - } else if (errmsg.contains("Error reading service definition XML")) { - return ErrorCode.LOCAL_SERVICE_DEF_FILE_NOT_FOUND; - } else if (errmsg.contains("Cannot query Pazpar2 while there are configuration errors")) { - return ErrorCode.SKIP_SUGGESTIONS; - } else if (errmsg.contains("Missing mandatory parameter")) { - return ErrorCode.MISSING_MANDATORY_PROPERTY; - } else if (errmsg.contains("ConfigureByMk2Config") && errmsg.contains("Init parameter") && (errmsg.contains("missing"))) { - return ErrorCode.MISSING_MK2_CONFIG_INIT_PARAMETER; - } else if (appError.getMessage().contains("WebXmlConfigReader could not find mandatory context-param")) { - return ErrorCode.MISSING_CONTEXT_PARAMETER; - } - return ErrorCode.NOT_RESOLVED; - } - - public ArrayList getSuggestions(ErrorInterface error) { - ArrayList suggestions = new ArrayList(); - ErrorCode code = getErrorCode(error); - switch (code) { - case MISSING_MK2_CONFIG_INIT_PARAMETER: - suggestions.add("A mandatory init parameter (context-param) was not found in the deployment descriptor (web.xml)." + - " Following init parameters must be present when using the MasterKey configuration scheme (ConfigureByMk2Config):" + - " MASTERKEY_ROOT_CONFIG_DIR (i.e. '/etc/masterkey'), MASTERKEY_COMPONENT_CONFIG_DIR (i.e. '/myapp'), " + - " MASTERKEY_CONFIG_FILE_NAME (i.e. 'myapp.properties'"); - break; - case MISSING_CONTEXT_PARAMETER: - suggestions.add("A mandatory init parameter (context-param) was not found in the deployment descriptor (web.xml)." + - " Following init parameters must be present when using WebXmlConfigReader:" + - " PAZPAR2_URL, PAZPAR2_SERVICE_ID"); - break; - case MISSING_MANDATORY_PROPERTY: - suggestions.add("A mandatory configuration parameter was not found in the MK2 config properties" + - " file used. Please check the property file for the parameter given in the error message "); - addConfigurationDocumentation(suggestions); - break; - case MASTERKEY_CONFIG_FILE_NOT_FOUND: - suggestions.add("The main configuration file that is looked up using parameters" + - " in web.xml (MASTERKEY_ROOT_CONFIG_DIR,MASTERKEY_COMPONENT_CONFIG_DIR,MASTERKEY_CONFIG_FILE_NAME)" + - " could not be found. Please check the web.xml parameters and the expected file system location. "); - break; - case LOCAL_SERVICE_DEF_FILE_NOT_FOUND: - suggestions.add("The service definition file could not be loaded."); - suggestions.add("Please check the configuration and verify that the file exists"); - addConfigurationDocumentation(suggestions); - break; - case REMOTE_SERVICE_DEF_NOT_FOUND: - break; - case LOCAL_SETTINGS_FILE_NOT_FOUND: - suggestions.add("A configuration using local target settings file was found, but " + - " the file itself could not be found. Please check the configuration."); - addConfigurationDocumentation(suggestions); - break; - case PAZPAR2_404: - suggestions.add("Pazpar2 service not found (404). "); - suggestions.add("Please check the PAZPAR2_URL configuration and verify " - + "that a pazpar2 service is running at the given address."); - addConfigurationDocumentation(suggestions); - break; - case PAZPAR2_UNEXPECTED_RESPONSE: - suggestions.add("Unexpected response code from Pazpar2. " + nl - + "Please check the PAZPAR2_URL configuration and verify " - + "that a pazpar2 service is running at the given address." + nl); - break; - case PAZPAR2_ERRORS: - if (error.hasPazpar2Error()) { - int pz2code = Integer.parseInt(error.getPazpar2Error().getCode()); - switch (pz2code) { - case 3: - suggestions.add("The search experienced a problem with the query terms."); - break; - case 12: - suggestions.add("The Pazpar2 server does not have a service defined by the requested ID "); - suggestions.add("Please check the service ID set in the configuration and compare it with the " + - " configuration on the Pazpar2 server-side."); - addConfigurationDocumentation(suggestions); - break; - case 100: - suggestions.add("Pazpar2 Service Proxy error"); - suggestions.add("A request was made to the Pazpar2 Service Proxy, but the Service Proxy reports "); - suggestions.add(" that authentication is lacking. Could be no successful authentication request was made or"); - suggestions.add(" that the Service Proxy session timed out."); - break; - default: - suggestions.add("Pazpar2 error: " + error.getPazpar2Error().getMsg() + " (Pazpar2 # "+error.getPazpar2Error().getCode()+")"); - } - break; - } else { - logger.error("Programming problem. An application error was categorized as a Papzar2 error yet does not have Pazpar2 error information as expected."); - } - break; - case SKIP_SUGGESTIONS: - break; - case NOT_RESOLVED: - suggestions.add("Sorry, no troubleshooting suggestions were written for this error scenario just yet."); - break; - } - return suggestions; - } - - private void addConfigurationDocumentation (ArrayList suggestions) { - suggestions.add("The application was configured using the configurator " + Utils.baseObjectName(configurator)); - suggestions.add("This configurator reports that following configuration was used: "); - suggestions.addAll(configurator.document()); - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorInterface.java b/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorInterface.java deleted file mode 100644 index c529651..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/errors/ErrorInterface.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.indexdata.pz2utils4jsf.errors; - -import java.io.Serializable; -import java.util.List; - -import com.indexdata.pz2utils4jsf.errors.ErrorHelper.ErrorCode; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2Error; - - -public interface ErrorInterface extends Serializable { - - public String getLabel(); - public String getMessage(); - public String getException(); - public void setApplicationErrorCode(ErrorCode code); - public ErrorCode getApplicationErrorCode(); - public List getSuggestions(); - public void setErrorHelper(ErrorHelper helper); - public boolean hasPazpar2Error(); - public Pazpar2Error getPazpar2Error(); - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/CommandResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/CommandResponse.java deleted file mode 100644 index 7a92019..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/CommandResponse.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2; - -public interface CommandResponse { - public int getStatusCode(); - public String getContentType(); - public String getResponseString(); -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/CommandThread.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/CommandThread.java deleted file mode 100644 index 323ef78..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/CommandThread.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.log4j.Logger; - -import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException; -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command; -import com.indexdata.pz2utils4jsf.pazpar2.data.CommandError; - -public class CommandThread extends Thread { - - private static Logger logger = Logger.getLogger(CommandThread.class); - Pazpar2Command command; - SearchClient client; - private ByteArrayOutputStream baos = new ByteArrayOutputStream(); - private StringBuilder response = new StringBuilder(""); - - public CommandThread (Pazpar2Command command, SearchClient client) { - this.command = command; - this.client = client; - } - - /** - * Runs the specified command using the specified Pazpar2 client - * Sets the Pazpar2 response as an XML response string to be retrieved by - * getResponse(). - * - * In case of an exception, an error response is generated, the document - * element being the same as it would have been if successful (named after - * the command, that is). - * - */ - public void run() { - - if (command.getName().equals("search")) { - client.setSearchCommand(command); - } - try { - long start = System.currentTimeMillis(); - CommandResponse commandResponse = client.executeCommand(command, baos); - if (commandResponse.getStatusCode()==200) { - response.append(commandResponse.getResponseString()); - } else if (commandResponse.getStatusCode()==417) { - logger.error("Pazpar2 status code 417: " + baos.toString("UTF-8")); - response.append(CommandError.insertPazpar2ErrorXml(command.getName(), "Expectation failed (417)", commandResponse.getResponseString())); - } else { - String resp = baos.toString("UTF-8"); - logger.error("Pazpar2 status code was " + commandResponse.getStatusCode() + ": " + resp); - throw new Pazpar2ErrorException(resp,commandResponse.getStatusCode(),resp,null); - } - long end = System.currentTimeMillis(); - logger.debug("Executed " + command.getName() + " in " + (end-start) + " ms." ); - } catch (IOException e) { - response.append(CommandError.createErrorXml(command.getName(), "io", e.getMessage())); - logger.error(response.toString()); - } catch (Pazpar2ErrorException e) { - response.append(CommandError.createErrorXml(command.getName(), "pazpar2error", e.getMessage())); - logger.error(response.toString()); - } catch (Exception e) { - response.append(CommandError.createErrorXml(command.getName(), "general", e.getMessage())); - logger.error(response.toString()); - } - } - - /** - * - * @return Pazpar2 response as an XML string, possibly a generated error XML - */ - public String getResponse () { - return response.toString(); - } - - public Pazpar2Command getCommand() { - return command; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Bean.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Bean.java deleted file mode 100644 index b12082b..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Bean.java +++ /dev/null @@ -1,246 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import javax.annotation.PostConstruct; -import javax.enterprise.context.SessionScoped; -import javax.enterprise.inject.Alternative; -import javax.inject.Inject; -import javax.inject.Named; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.config.ConfigurationReader; -import com.indexdata.pz2utils4jsf.controls.ResultsPager; -import com.indexdata.pz2utils4jsf.errors.ConfigurationError; -import com.indexdata.pz2utils4jsf.errors.ConfigurationException; -import com.indexdata.pz2utils4jsf.errors.ErrorHelper; -import com.indexdata.pz2utils4jsf.errors.ErrorCentral; -import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter; -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Commands; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseParser; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2Responses; -import com.indexdata.pz2utils4jsf.pazpar2.data.RecordResponse; -import com.indexdata.pz2utils4jsf.pazpar2.state.StateListener; -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; -import com.indexdata.pz2utils4jsf.utils.Utils; - -@Named("pz2") @SessionScoped @Alternative -public class Pz2Bean implements Pz2Interface, StateListener, Serializable { - - private static final long serialVersionUID = 3440277287081557861L; - private static Logger logger = Logger.getLogger(Pz2Bean.class); - private static Logger responseLogger = Logger.getLogger("com.indexdata.pz2utils4jsf.pazpar2.responses"); - - protected SearchClient searchClient = null; - - @Inject ConfigurationReader configurator; - @Inject StateManager stateMgr; - @Inject Pazpar2Commands pzreq; - @Inject Pazpar2Responses pzresp; - @Inject ErrorCentral errors; - - protected ResultsPager pager = null; - - - protected ErrorHelper errorHelper = null; - - public Pz2Bean () { - logger.info("Instantiating pz2 bean [" + Utils.objectId(this) + "]"); - } - - @PostConstruct - public void postConstruct() { - logger.debug("in start of Pz2Bean post-construct configurator is " + configurator); - logger.debug(Utils.objectId(this) + " will instantiate a Pz2Client next."); - searchClient = new Pz2Client(); - logger.info("Using [" + Utils.objectId(searchClient) + "] configured by [" - + Utils.objectId(configurator) + "]" ); - configureClient(searchClient,configurator); - stateMgr.addStateListener(this); - } - - public void configureClient(SearchClient searchClient, ConfigurationReader configReader) { - logger.debug(Utils.objectId(this) + " will configure search client for the session"); - try { - searchClient.configure(configReader); - } catch (ConfigurationException e) { - logger.debug("Pz2Bean adding configuration error"); - errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage())); - } - logger.info(configReader.document()); - pzresp.reset(); - } - - - public void doSearch(String query) { - pzreq.getSearch().setParameter(new CommandParameter("query","=",query)); - doSearch(); - } - - public void doSearch() { - stateMgr.hasPendingStateChange("search",false); - pzresp.reset(); - // resets some record and show command parameters without - // changing state or creating state change feedback - pzreq.getRecord().removeParametersInState(); - pzreq.getShow().setParameterInState(new CommandParameter("start","=",0)); - logger.debug(Utils.objectId(this) + " is searching using "+pzreq.getCommand("search").getUrlEncodedParameterValue("query")); - doCommand("search"); - } - - /** - * Refreshes 'show', 'stat', 'termlist', and 'bytarget' data object from pazpar2 - * - * @return Number of activeclients at the time of the 'show' command. - */ - public String update () { - logger.debug("Updating show,stat,termlist,bytarget from pazpar2"); - return update("show,stat,termlist,bytarget"); - } - - /** - * Refreshes the data objects listed in 'commands' from pazpar2 - * - * @param commands - * @return Number of activeclients at the time of the 'show' command - */ - public String update (String commands) { - if (! errors.hasConfigurationErrors()) { - if (commandsAreValid(commands)) { - if (hasQuery()) { - handleQueryStateChanges(commands); - logger.debug("Processing request for " + commands); - List threadList = new ArrayList(); - StringTokenizer tokens = new StringTokenizer(commands,","); - while (tokens.hasMoreElements()) { - threadList.add(new CommandThread(pzreq.getCommand(tokens.nextToken()),searchClient)); - } - for (CommandThread thread : threadList) { - thread.start(); - } - for (CommandThread thread : threadList) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - for (CommandThread thread : threadList) { - String commandName = thread.getCommand().getName(); - String response = thread.getResponse(); - responseLogger.debug("Response was: " + response); - Pazpar2ResponseData responseObject = Pazpar2ResponseParser.getParser().getDataObject(response); - pzresp.put(commandName, responseObject); - } - if (commands.equals("record")) { - logger.debug("Record: Active clients: "+pzresp.getRecord().getActiveClients()); - return pzresp.getRecord().getActiveClients(); - } else { - return pzresp.getActiveClients(); - } - } else { - logger.debug("Skipped requests for " + commands + " as there's not yet a query."); - pzresp.reset(); - return "0"; - } - } else { - logger.error("Did not attemt to run command(s) due to a validation error."); - return "0"; - } - } else { - logger.error("Did not attempt to execute query since there are configuration errors."); - return "0"; - } - - } - - public boolean commandsAreValid(String commands) { - if (commands.equals("record")) { - if (!pzreq.getCommand("record").hasParameterSet("id")) { - logger.error("Attempt to send record command without the id parameter"); - return false; - } - } - return true; - } - - public String toggleRecord (String recId) { - if (hasRecord(recId)) { - pzreq.getRecord().removeParameters(); - pzresp.put("record", new RecordResponse()); - return ""; - } else { - pzreq.getRecord().setId(recId); - return doCommand("record"); - } - } - - @Override - public boolean hasRecord (String recId) { - return pzreq.getCommand("record").hasParameters() && pzresp.getRecord().getRecId().equals(recId); - } - - public String getCurrentStateKey () { - return stateMgr.getCurrentState().getKey(); - } - - public void setCurrentStateKey(String key) { - stateMgr.setCurrentStateKey(key); - } - - - - protected boolean hasQuery() { - return pzreq.getCommand("search").hasParameterSet("query"); - } - - - public ResultsPager getPager () { - if (pager == null) { - pager = new ResultsPager(pzresp); - } - return pager; - } - - public ResultsPager setPager (int pageRange) { - pager = new ResultsPager(pzresp,pageRange,pzreq); - return pager; - } - - protected void handleQueryStateChanges (String commands) { - if (stateMgr.hasPendingStateChange("search") && hasQuery()) { - logger.debug("Found pending search change. Doing search before updating " + commands); - doSearch(); - } - if (stateMgr.hasPendingStateChange("record") && ! commands.equals("record")) { - logger.debug("Found pending record ID change. Doing record before updating " + commands); - stateMgr.hasPendingStateChange("record",false); - if (pzreq.getCommand("record").hasParameterSet("id")) { - update("record"); - } else { - pzresp.put("record", new RecordResponse()); - } - } - } - - protected String doCommand(String commandName) { - logger.debug(pzreq.getCommand(commandName).getEncodedQueryString() + ": Results for "+ pzreq.getCommand("search").getEncodedQueryString()); - return update(commandName); - } - - @Override - public void stateUpdated(String commandName) { - logger.debug("State change reported for [" + commandName + "]"); - if (commandName.equals("show")) { - logger.debug("Updating show"); - update(commandName); - } - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Client.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Client.java deleted file mode 100644 index a00f2d5..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Client.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2; - -import static com.indexdata.pz2utils4jsf.utils.Utils.nl; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Logger; - -import com.indexdata.masterkey.config.MissingMandatoryParameterException; -import com.indexdata.masterkey.config.ModuleConfigurationGetter; -import com.indexdata.masterkey.pazpar2.client.ClientCommand; -import com.indexdata.masterkey.pazpar2.client.Pazpar2Client; -import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientConfiguration; -import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientGeneric; -import com.indexdata.masterkey.pazpar2.client.Pazpar2HttpResponse; -import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException; -import com.indexdata.masterkey.pazpar2.client.exceptions.ProxyErrorException; -import com.indexdata.pz2utils4jsf.config.Configuration; -import com.indexdata.pz2utils4jsf.config.ConfigurationReader; -import com.indexdata.pz2utils4jsf.errors.ConfigurationException; -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command; -import com.indexdata.pz2utils4jsf.utils.Utils; - -public class Pz2Client implements SearchClient { - - private static final long serialVersionUID = 5414266730169982028L; - private static Logger logger = Logger.getLogger(Pz2Client.class); - private Pazpar2Client client = null; - private Pazpar2ClientConfiguration cfg = null; - public static final String MODULENAME = "pz2client"; - public static Map DEFAULTS = new HashMap(); - Configuration config = null; - - static { - DEFAULTS.put("PROXY_MODE","1"); - DEFAULTS.put("SERIALIZE_REQUESTS", "false"); - DEFAULTS.put("STREAMBUFF_SIZE", "4096"); - DEFAULTS.put("PARSE_RESPONSES", "true"); - } - - public Pz2Client() {} - - @Override - public void configure(ConfigurationReader configReader) throws ConfigurationException { - logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader)); - try { - config = configReader.getConfiguration(this); - cfg = new Pazpar2ClientConfiguration(new ConfigurationGetter(config)); - } catch (ProxyErrorException pe) { - logger.error("Could not configure Pazpar2 client: " + pe.getMessage()); - throw new ConfigurationException("Could not configure Pz2Client: "+ pe.getMessage(),pe); - } - if (cfg != null) { - try { - client = new Pazpar2ClientGeneric(cfg); - } catch (ProxyErrorException pe) { - logger.error("Could not configure Pazpar2 client: " + pe.getMessage()); - throw new ConfigurationException("Could not configure Pz2Client: "+ pe.getMessage(),pe); - } - } else { - logger.error("There was a problem creating Pz2Client. Client is null after configuration."); - throw new ConfigurationException("Pazpar2Client is null after configuration"); - } - } - - public boolean isAuthenticatingClient () { - return false; - } - - public boolean isAuthenticated() { - return false; - } - - public boolean authenticate() { - throw new UnsupportedOperationException("No authentication mechanism for straight pazpar2 client"); - } - - @Override - public void setSearchCommand(Pazpar2Command command) { - ClientCommand clientCommand = new ClientCommand(command.getName(), command.getEncodedQueryString()); - client.setSearchCommand(clientCommand); - } - - @Override - public CommandResponse executeCommand(Pazpar2Command command, ByteArrayOutputStream baos) - throws Pazpar2ErrorException, IOException { - ClientCommand clientCommand = new ClientCommand(command.getName(), command.getEncodedQueryString()); - Pazpar2HttpResponse pz2HttpResponse = client.executeCommand(clientCommand, baos); - return new Pz2CommandResponse(pz2HttpResponse,baos); - } - - public Pz2Client cloneMe() { - logger.debug("Cloning Pz2Client"); - Pz2Client clone = new Pz2Client(); - clone.client = this.client; - clone.cfg = this.cfg; - return clone; - } - - @Override - public Map getDefaults() { - return DEFAULTS; - } - - @Override - public String getModuleName() { - return MODULENAME; - } - - class ConfigurationGetter implements ModuleConfigurationGetter { - Configuration config = null; - ConfigurationGetter(Configuration configuration) { - config = configuration; - } - @Override - public String get(String value) { - return config.get(value); - } - @Override - public String get(String value, String defaultValue) { - return config.get(value,defaultValue); - } - @Override - public String getMandatory(String name) - throws MissingMandatoryParameterException { - return config.getMandatory(name); - } - @Override - public String getConfigFilePath() { - return config.getConfigFilePath(); - } - } - - @Override - public List documentConfiguration() { - List doc = new ArrayList(); - doc.add(nl+ MODULENAME + " was configured to access Pazpar2 at : " + cfg.PAZPAR2_URL); - return new ArrayList(); - } - - public Configuration getConfiguration () { - return config; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2CommandResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2CommandResponse.java deleted file mode 100644 index 0c6ebad..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2CommandResponse.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2; - -import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; - -import com.indexdata.masterkey.pazpar2.client.Pazpar2HttpResponse; - -public class Pz2CommandResponse implements CommandResponse { - - private Pazpar2HttpResponse pz2httpResponse = null; - private ByteArrayOutputStream content = null; - - public Pz2CommandResponse(Pazpar2HttpResponse pz2response, ByteArrayOutputStream content) { - pz2httpResponse = pz2response; - this.content = content; - } - - @Override - public int getStatusCode() { - return pz2httpResponse.getStatusCode(); - } - - @Override - public String getContentType() { - return pz2httpResponse.getContentType(); - } - - @Override - public String getResponseString() { - try { - return content.toString("UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return null; - } - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Interface.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Interface.java deleted file mode 100644 index f0cd6d4..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2Interface.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2; - -import java.io.Serializable; - -import com.indexdata.pz2utils4jsf.controls.ResultsPager; - -public interface Pz2Interface extends Serializable { - - /** - * Executes a Pazpar2 search using the given query string - * - * @param query - */ - public void doSearch(String query); - - /** - * Executes a Pazpar2 search using the current query - */ - public void doSearch(); - - /** - * Updates display data objects by issuing the following pazpar2 commands: - * 'show', 'stat', 'termlist' and 'bytarget'. - * - * Returns a count of the remaining active clients from the most recent search. - * - * After refreshing the data from pazpar2 the UI components displaying those - * data should be re-rendered. - * - * @return count of activeclients - */ - public String update(); - - /** - * Updates the data objects given by a comma separated list of one or more commands - - * i.e. "show,state,termlist,bytarget". - * - * May not be useful for the UI directly. - * - * @param commands Command separated list of pazpar2 commands. - * @return count of activeclients - * - */ - public String update (String commands); - - /** - * Will retrieve or remove the record with the given recid from memory. - * - * A pazpar2 'record' command will then be issued. The part of the UI - * showing record data should thus be re-rendered. - * - * @param recid - * @return - */ - public String toggleRecord(String recid); - - /** - * Resolves whether the backend has a record with the given recid in memory - * - * @return true if the bean currently holds the record with recid - */ - public boolean hasRecord (String recId); - - - /** - * Initiates a pager object, a component holding the data to draw a sequence - * of page numbers to navigate by and mechanisms to navigate with - * - * @param pageRange number of pages to display in the pager - * @return ResultsPager the initiated pager component - */ - public ResultsPager setPager(int pageRange); - - /** - * Gives a component for drawing a pager to navigate by. - * @return ResultsPager pager component - */ - public ResultsPager getPager(); - - /** - * Returns the current hash key used, as used for internal session state tracking - * and potentially for browser history entries as well - * - * A UI author would not normally be concerned with retrieving this. It's used by the - * framework internally - * - * @return string that can be used for browsers window.location.hash - */ - public String getCurrentStateKey (); - - /** - * Sets the current state key, i.e. when user clicks back or forward in browser history. - * Would normally be automatically handled by the frameworks components. - * - * @param key corresponding to browsers hash string - */ - public void setCurrentStateKey(String key); - - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2ProxyBean.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2ProxyBean.java deleted file mode 100644 index 36e472b..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/Pz2ProxyBean.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import javax.annotation.PostConstruct; -import javax.enterprise.context.SessionScoped; -import javax.enterprise.inject.Alternative; -import javax.inject.Inject; -import javax.inject.Named; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.config.ConfigurationReader; -import com.indexdata.pz2utils4jsf.pazpar2.sp.ServiceProxyClient; -import com.indexdata.pz2utils4jsf.pazpar2.sp.ServiceProxyInterface; -import com.indexdata.pz2utils4jsf.pazpar2.sp.auth.ServiceProxyUser; -import com.indexdata.pz2utils4jsf.utils.Utils; - -@Named("pz2") @SessionScoped @Alternative -public class Pz2ProxyBean extends Pz2Bean implements ServiceProxyInterface { - - private static final long serialVersionUID = 4221824985678758225L; - private static Logger logger = Logger.getLogger(Pz2ProxyBean.class); - private String initDocFileName = ""; - private String initDocResponse = ""; - private String serviceProxyUrl = ""; - - @Inject ConfigurationReader configurator; - @Inject ServiceProxyUser user; - - public Pz2ProxyBean() { - } - - @PostConstruct - public void postConstruct() { - if (searchClient == null) { - logger.debug(Utils.objectId(this) + " will instantiate a ServiceProxyClient next."); - searchClient = new ServiceProxyClient(); - logger.info("Using [" + Utils.objectId(searchClient) + "] configured by [" - + Utils.objectId(configurator) + "]" ); - configureClient(searchClient,configurator); - stateMgr.addStateListener(this); - } else { - logger.debug("Pz2ProxyBean:postConstruct: searchClient already instantiated " + - "during construction of parent object Pz2Bean."); - } - } - - @Override - public String login(String navigateTo) { - logger.info("doing login"); - ((ServiceProxyClient)searchClient).authenticate(user); - pzreq.getRecord().removeParametersInState(); - pzreq.getSearch().removeParametersInState(); - pzresp.reset(); - return navigateTo; - } - - @Override - public void setServiceProxyUrl(String url) { - logger.info("Setting Service Proxy url: " + url); - serviceProxyUrl = url; - pzreq.getRecord().removeParametersInState(); - pzreq.getSearch().removeParametersInState(); - pzresp.reset(); - } - - public String getServiceProxyUrl() { - return serviceProxyUrl; - } - - public String getInitDocPath () { - return searchClient.getConfiguration().get("INIT_DOC_PATH"); - } - - @Override - public void setInitFileName(String fileName) { - this.initDocFileName = fileName; - - } - - @Override - public String getInitFileName() { - return initDocFileName; - } - - @Override - public String postInit() throws UnsupportedEncodingException, IOException { - String initDocPath = ((ServiceProxyClient)searchClient).getInitDocPaths()[0]; - logger.info("Paths: " + ((ServiceProxyClient)searchClient).getInitDocPaths()); - logger.info("Path: " + initDocPath); - pzresp.reset(); - byte[] response = ((ServiceProxyClient)searchClient).postInitDoc(initDocPath + getInitFileName()); - initDocResponse = new String(response,"UTF-8"); - return initDocResponse; - } - - @Override - public String postInit(byte[] initDoc) throws UnsupportedEncodingException, IOException { - pzresp.reset(); - byte[] response = ((ServiceProxyClient)searchClient).postInitDoc(initDoc); - initDocResponse = new String(response,"UTF-8"); - return initDocResponse; - } - - - @Override - public String getInitResponse() { - return initDocResponse; - } - - public void setAceFilter(String filterExpression) { - //setCommandParameter("record",new CommandParameter("acefilter","=",filterExpression)); - } - - public String getAceFilter () { - return null; - // return getCommandParameterValue("record","acefilter",""); - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/SearchClient.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/SearchClient.java deleted file mode 100644 index 54b1648..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/SearchClient.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.Serializable; - -import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException; -import com.indexdata.pz2utils4jsf.config.Configurable; -import com.indexdata.pz2utils4jsf.config.Configuration; -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command; - -public interface SearchClient extends Configurable, Serializable { - - public void setSearchCommand(Pazpar2Command command); - public CommandResponse executeCommand(Pazpar2Command command, ByteArrayOutputStream baos) throws Pazpar2ErrorException, IOException; - - // Use cloneMe() method if injecting the client with CDI. - // The client is used for asynchronously sending off requests - // to the server AND propagation of context to threads is currently - // not supported. Trying to do so throws a WELD-001303 error. - // If propagation to threads gets supported, the cloning can go. - public SearchClient cloneMe(); - - public boolean isAuthenticatingClient(); - public Configuration getConfiguration(); -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/BytargetCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/BytargetCommand.java deleted file mode 100644 index 720f0a6..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/BytargetCommand.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class BytargetCommand extends Pazpar2Command { - - private static final long serialVersionUID = 9070458716105294392L; - - public BytargetCommand(StateManager stateMgr) { - super("bytarget",stateMgr); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/CommandParameter.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/CommandParameter.java deleted file mode 100644 index 7630ecd..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/CommandParameter.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import java.io.Serializable; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter; - -public class CommandParameter implements Serializable { - - private static Logger logger = Logger.getLogger(CommandParameter.class); - - private static final long serialVersionUID = 625502285668766749L; - String name = null; - String operator = null; - String value = null; - Map expressions = new HashMap(); - - public CommandParameter (String name) { - logger.debug("Instantiating command parameter '" + name + "'"); - this.name = name; - } - - public CommandParameter (String name, String operator, String value, Expression... expressions) { - logger.debug("Instantiating command parameter " + name + " with expressions: [" + expressions + "]"); - this.name = name; - this.operator = operator; - this.value = value; - for (Expression expr : expressions) { - this.expressions.put(expr.toString(), expr); - } - } - - public CommandParameter (String name, String operator, String value) { - logger.debug("Instantiating command parameter '" + name + "' with String: [" + value + "]"); - this.name = name; - this.operator = operator; - this.value = value; - } - - public CommandParameter (String name, String operator, int value) { - logger.debug("Instantiating command parameter '" + name + "' with int: [" + value + "]"); - this.name = name; - this.operator = operator; - this.value = value+""; - } - - - public String getName () { - return name; - } - - public Map getExpressions () { - return expressions; - } - - public void addExpression(Expression expression) { - logger.debug("Adding expression [" + expression + "] to '" + name + "'"); - this.expressions.put(expression.toString(),expression); - } - - public void removeExpression(Expression expression) { - this.expressions.remove(expression.toString()); - } - - - public boolean hasOperator() { - return operator != null; - } - - public String getEncodedQueryString () { - try { - return name + operator + URLEncoder.encode(getValueWithExpressions(),"UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return null; - } - } - - public String getSimpleValue() { - return value; - } - - public String getValueWithExpressions () { - StringBuilder completeValue = new StringBuilder((value==null ? "" : value)); - for (String key : expressions.keySet()) { - completeValue.append(" and " + expressions.get(key)); - } - return completeValue.toString(); - - } - - @Override - public boolean equals (Object otherParameter) { - return - ((otherParameter instanceof CommandParameter) - && this.getValueWithExpressions().equals(((CommandParameter) otherParameter).getValueWithExpressions())); - } - - @Override - public int hashCode () { - return getValueWithExpressions().hashCode(); - } - - public String toString() { - return getValueWithExpressions(); - } - - public CommandParameter copy() { - logger.debug("Copying parameter '"+ name + "' for modification"); - CommandParameter newParam = new CommandParameter(name); - newParam.value = this.value; - newParam.operator = this.operator; - for (String key : expressions.keySet()) { - newParam.addExpression(expressions.get(key).copy()); - } - return newParam; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Expression.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Expression.java deleted file mode 100644 index d412ac9..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Expression.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.commands.Expression; - -public class Expression { - - String leftEntity; - String operator; - String rightEntity; - public Expression (String leftEntity, String operator, String rightEntity) { - this.leftEntity = leftEntity; - this.operator = operator; - this.rightEntity = rightEntity; - } - - public Expression copy() { - return new Expression(leftEntity,operator,rightEntity); - } - - public String toString() { - return leftEntity + operator + rightEntity; - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/InitCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/InitCommand.java deleted file mode 100644 index 09e1bee..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/InitCommand.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class InitCommand extends Pazpar2Command { - - private static final long serialVersionUID = -4915976465898889987L; - - public InitCommand(StateManager stateMgr) { - super("init",stateMgr); - } - - public void setClear(String clear) { - setParameter(new CommandParameter("clear","=",clear)); - } - - public void setService(String serviceId) { - setParameter(new CommandParameter("service","=",serviceId)); - } - - @Override - public void setSession (String sessionId) { - throw new UnsupportedOperationException("Cannot set session id on init command"); - } - - @Override - public String getSession () { - throw new UnsupportedOperationException("Cannot set or get session id on init command"); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Pazpar2Command.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Pazpar2Command.java deleted file mode 100644 index 7ef96bd..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Pazpar2Command.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class Pazpar2Command implements Serializable { - - private static Logger logger = Logger.getLogger(Pazpar2Command.class); - private static final long serialVersionUID = -6825491856480675917L; - private String name = ""; - protected Map parameters = new HashMap(); - - StateManager stateMgr; - - public Pazpar2Command (String name, StateManager stateMgr) { - this.name = name; - if (stateMgr == null) { - // Sets throw-away state - this.stateMgr = new StateManager(); - } else { - this.stateMgr = stateMgr; - } - } - - public Pazpar2Command copy () { - Pazpar2Command newCommand = new Pazpar2Command(name,stateMgr); - for (String parameterName : parameters.keySet()) { - newCommand.setParameterInState(parameters.get(parameterName).copy()); - } - return newCommand; - } - - public String getName() { - return name; - } - - public void setParameter (CommandParameter parameter) { - Pazpar2Command copy = this.copy(); - logger.debug(name + " command: setting parameter [" + parameter.getName() + "=" + parameter.getValueWithExpressions() + "]"); - copy.parameters.put(parameter.getName(),parameter); - stateMgr.checkIn(copy); - } - - public void setParameters (CommandParameter... params) { - Pazpar2Command copy = this.copy(); - for (CommandParameter param : params) { - logger.debug(name + " command: setting parameter [" + param.getName() + "=" + param.getValueWithExpressions() + "]"); - copy.parameters.put(param.getName(),param); - } - stateMgr.checkIn(copy); - } - - public void setParametersInState (CommandParameter... params) { - for (CommandParameter param : params) { - logger.debug(name + " command: setting parameter [" + param.getName() + "=" + param.getValueWithExpressions() + "] silently"); - parameters.put(param.getName(),param); - } - } - - public void setParameterInState (CommandParameter parameter) { - logger.debug(name + " command: setting parameter [" + parameter.getName() + "=" + parameter.getValueWithExpressions() + "] silently"); - parameters.put(parameter.getName(),parameter); - } - - - public CommandParameter getParameter (String name) { - return parameters.get(name); - } - - public void removeParameter (String name) { - Pazpar2Command copy = this.copy(); - copy.parameters.remove(name); - stateMgr.checkIn(copy); - } - - public void removeParameters() { - Pazpar2Command copy = this.copy(); - copy.parameters = new HashMap(); - stateMgr.checkIn(copy); - } - - public void removeParametersInState() { - parameters = new HashMap(); - } - - - public boolean hasParameters () { - return (parameters.keySet().size()>0); - } - - public boolean hasParameterSet(String parameterName) { - return (parameters.get(parameterName) != null); - } - - public String getEncodedQueryString () { - StringBuilder queryString = new StringBuilder("command="+name); - for (CommandParameter parameter : parameters.values()) { - queryString.append("&"+parameter.getEncodedQueryString()); - } - return queryString.toString(); - } - - public String getValueWithExpressions() { - StringBuilder value = new StringBuilder(""); - for (CommandParameter parameter : parameters.values()) { - value.append("&" + parameter.getName() + parameter.operator + parameter.getValueWithExpressions()); - } - return value.toString(); - } - - @Override - public boolean equals (Object otherCommand) { - return - ((otherCommand instanceof Pazpar2Command) - && this.getValueWithExpressions().equals(((Pazpar2Command) otherCommand).getValueWithExpressions())); - } - - @Override - public int hashCode () { - return getValueWithExpressions().hashCode(); - } - - public String toString () { - return parameters.toString(); - } - - public String getParameterValue(String parameterName) { - return getParameter(parameterName).getValueWithExpressions(); - - } - - public String getUrlEncodedParameterValue(String parameterName) { - return getParameter(parameterName).getEncodedQueryString(); - } - - public void setSession (String sessionId) { - setParameter(new CommandParameter("session","=",sessionId)); - } - - public String getSession() { - return getParameterValue("session"); - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Pazpar2Commands.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Pazpar2Commands.java deleted file mode 100644 index a0397a9..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/Pazpar2Commands.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import java.io.Serializable; - -import javax.annotation.PostConstruct; -import javax.enterprise.context.SessionScoped; -import javax.inject.Inject; -import javax.inject.Named; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; -import com.indexdata.pz2utils4jsf.utils.Utils; - -@Named("pzreq") @SessionScoped -public class Pazpar2Commands implements Serializable { - - private static final long serialVersionUID = -5172466320351302413L; - private static Logger logger = Logger.getLogger(Pazpar2Commands.class); - - public static final String INIT = "init"; - public static final String PING = "ping"; - public static final String SETTINGS = "settings"; - public static final String SEARCH = "search"; - public static final String STAT = "stat"; - public static final String SHOW = "show"; - public static final String RECORD = "record"; - public static final String TERMLIST = "termlist"; - public static final String BYTARGET = "bytarget"; - - @Inject StateManager stateMgr; - - public Pazpar2Commands() { - logger.info("Initializing Pazpar2Commands [" + Utils.objectId(this) + "]"); - } - - @PostConstruct - public void postConstruct() { - logger.info("in post-construct stateMgr is " + stateMgr); - } - - public InitCommand getInit() { - return (InitCommand) (stateMgr.getCommand(INIT)); - } - - public PingCommand getPing() { - return (PingCommand) (stateMgr.getCommand(PING)); - } - - public SettingsCommand getSettings() { - return (SettingsCommand) (stateMgr.getCommand(SETTINGS)); - } - - public SearchCommand getSearch() { - return (SearchCommand) (stateMgr.getCommand(SEARCH)); - } - - public StatCommand getStat() { - return (StatCommand) (stateMgr.getCommand(STAT)); - } - - public ShowCommand getShow() { - return (ShowCommand) (stateMgr.getCommand(SHOW)); - } - - public RecordCommand getRecord() { - return (RecordCommand) (stateMgr.getCommand(RECORD)); - } - - public TermlistCommand getTermlist() { - return (TermlistCommand) (stateMgr.getCommand(TERMLIST)); - } - - public BytargetCommand getBytarget() { - return (BytargetCommand) (stateMgr.getCommand(BYTARGET)); - } - - public Pazpar2Command getCommand(String name) { - return stateMgr.getCommand(name); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/PingCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/PingCommand.java deleted file mode 100644 index e7eda38..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/PingCommand.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class PingCommand extends Pazpar2Command { - - private static final long serialVersionUID = 8876721711326535847L; - - public PingCommand(StateManager stateMgr) { - super("ping",stateMgr); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/RecordCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/RecordCommand.java deleted file mode 100644 index 5e2c03b..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/RecordCommand.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class RecordCommand extends Pazpar2Command { - - private static final long serialVersionUID = 2817539422114569506L; - - public RecordCommand(StateManager stateMgr) { - super("record",stateMgr); - } - - public void setId(String recId) { - setParameter(new CommandParameter("id","=",recId)); - } - - public String getId () { - return getParameterValue("id"); - } - - @Override - public RecordCommand copy () { - RecordCommand newCommand = new RecordCommand(stateMgr); - for (String parameterName : parameters.keySet()) { - newCommand.setParameterInState(parameters.get(parameterName).copy()); - } - return newCommand; - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SearchCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SearchCommand.java deleted file mode 100644 index 9b2cece..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SearchCommand.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import javax.enterprise.context.SessionScoped; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -@SessionScoped -public class SearchCommand extends Pazpar2Command { - - private static final long serialVersionUID = -1888520867838597236L; - private static Logger logger = Logger.getLogger(SearchCommand.class); - private SingleTargetFilter singleTargetFilter = null; - - public SearchCommand(StateManager stateMgr) { - super("search",stateMgr); - } - - public void setQuery(String query) { - setParameter(new CommandParameter("query","=",query)); - } - - public String getQuery () { - return getParameter("query") == null ? null : getParameter("query").getValueWithExpressions(); - } - - public void setFilter(String filterExpression) { - setParameter(new CommandParameter("filter","=",filterExpression)); - } - - public String getFilter() { - return getParameter("filter") == null ? null : getParameter("filter").getValueWithExpressions(); - } - - public void addFilter(String filterExpression) { - // TODO: implement - if (hasParameterSet("filter")) { - setFilter(filterExpression); - } else { - getParameter("filter"); - } - throw new UnsupportedOperationException("removeFilter(filterExpression) yet to be implemented."); - } - - public void removeFilters () { - removeParameter("filter"); - } - - public void removeFilter(String filterExpression) { - // TODO: implement - throw new UnsupportedOperationException("removeFilter(filterExpression) yet to be implemented."); - } - - public boolean hasFilter () { - return getFilter().length()>0; - } - - public void setLimit (String limitExpression) { - setParameter(new CommandParameter("limit","=",limitExpression)); - } - - public String getLimit () { - return getParameterValue("limit"); - } - - public void setStartrecs (String startrecs) { - setParameter(new CommandParameter("startrecs","=",startrecs)); - } - - public String getStartrecs () { - return getParameterValue("startrecs"); - } - - public void setMaxrecs (String maxrecs) { - setParameter(new CommandParameter("maxrecs","=",maxrecs)); - } - - public String getMaxrecs () { - return getParameterValue("maxrecs"); - } - - public void setSort () { - setParameter(new CommandParameter("sort","=","sort")); - } - - public String getSort () { - return getParameterValue("sort"); - } - - /** - * Sets a facet, in CQL, to restrict the current results, - * then executes the search - * - * @param facetKey i.e. 'au' for author - * @param term i.e. 'Dickens, Charles' - */ - public void setFacet(String facetKey, String term) { - if (term != null && term.length()>0) { - getParameter("query").addExpression(new Expression(facetKey,"=",term)); - } - } - - /** - * Sets a facet to limit the current query by. The - * facet is appended to the query string itself (rather - * as a separately managed entity. It will thus appear - * in a query field as retrieved by getQuery(). It will - * not be removed by removeFacet(...) - * - * @param facetKey i.e. 'au' for author - * @param term i.e. 'Dickens, Charles' - */ - public void setFacetOnQuery (String facetKey, String term) { - String facetExpression = facetKey + "=" + term; - if (term != null && term.length()>0) { - String currentQuery= getParameterValue("query"); - setParameter(new CommandParameter("query","=", currentQuery + " and " + facetExpression)); - } - } - - /** - * Removes a facet set by setFacet(...), then executes - * the search. - * - * Will not remove facets set by setFacetOnQuery(...) - * - * @param facetKey i.e. 'au' for author - * @param term i.e. 'Dickens, Charles' - */ - public void removeFacet(String facetKey, String term) { - if (getParameter("query") != null) { - getParameter("query").removeExpression(new Expression(facetKey,"=",term)); - } - } - - - /** - * Adds a single target filter to restrict the current query by, - * then executes the current search. - * - * This is a special case of the general setFilter function, - * allowing to associate a descriptive target name with the - * filter expression for display in UI. - * - * @param targetId pazpar2's ID for the target to limit by - * @param targetName a descriptive name for the target - */ - public void setSingleTargetFilter (String targetId, String targetName) { - if (hasSingleTargetFilter(new SingleTargetFilter(targetId,targetName))) { - logger.debug("Already using target filter " + this.singleTargetFilter.getFilterExpression()); - } else { - this.singleTargetFilter = new SingleTargetFilter(targetId,targetName); - setParameter(new CommandParameter("filter","=",this.singleTargetFilter.getFilterExpression())); - } - } - - public SingleTargetFilter getSingleTargetFilter () { - logger.debug("request to get the current single target filter"); - return singleTargetFilter; - } - - /** - * Removes the current target filter from the search - * - */ - public void removeSingleTargetFilter () { - logger.debug("Removing target filter " + singleTargetFilter.getFilterExpression()); - this.singleTargetFilter = null; - removeParameter("filter"); - } - - /** - * - * @return The target filter set on the current search command - */ - public boolean hasSingleTargetFilter() { - logger.debug("Checking if a single target filter is set: " + (singleTargetFilter != null)); - return singleTargetFilter != null; - } - - /** - * Resolves if the current search command has a target filter - to - * be used by the UI for conditional rendering of target filter info. - * - * @return true if the current search command is limited by a target - * filter - */ - protected boolean hasSingleTargetFilter(SingleTargetFilter targetFilter) { - return hasSingleTargetFilter() && targetFilter.equals(this.singleTargetFilter); - } - - public SearchCommand copy () { - SearchCommand newCommand = new SearchCommand(stateMgr); - for (String parameterName : parameters.keySet()) { - newCommand.setParameterInState(parameters.get(parameterName).copy()); - } - newCommand.singleTargetFilter = this.singleTargetFilter; - return newCommand; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SettingsCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SettingsCommand.java deleted file mode 100644 index 7aa1128..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SettingsCommand.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class SettingsCommand extends Pazpar2Command { - - private static final long serialVersionUID = 2291179325470387102L; - - public SettingsCommand(StateManager stateMgr) { - super("settings",stateMgr); - // TODO Auto-generated constructor stub - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/ShowCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/ShowCommand.java deleted file mode 100644 index 12dad19..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/ShowCommand.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class ShowCommand extends Pazpar2Command { - - private static final long serialVersionUID = -8242768313266051307L; - - public ShowCommand(StateManager stateMgr) { - super("show",stateMgr); - setParameterInState(new CommandParameter("start","=","0")); - } - - /** - * Sets the sort order for results, the updates the 'show' data object - * from pazpar2. Set valid sort options in the documentation for pazpar2. - * - * The parts of the UI that display 'show' data should be rendered following - * this request. - * - * @param sortOption - */ - public void setSort (String sort) { - setParameter(new CommandParameter("sort","=",sort)); - } - - /** - * Retrieves the current sort order for results - * @return sort order - i.e. 'relevance' - */ - public String getSort () { - return getParameter("sort") != null ? getParameter("sort").value : "relevance"; - } - - /** - * Sets the number of records that pazpar2 should show at a time. Is - * followed by an update of the show data object from pazpar2. - * - * To be used by the UI for paging. After setting page size the parts - * of the UI that displays 'show' data should be rendered. - * - * @param perPageOption i.e. 10, default is 20. - */ - public void setPageSize (String perPageOption) { - setParameters(new CommandParameter("num","=",perPageOption), - new CommandParameter("start","=",0)); - } - - /** - * Retrieves the currently defined number of items to show at a time - * - * @return number of result records that will be shown from pazpar2 - */ - public String getPageSize () { - return getParameter("num") != null ? getParameter("num").value : "20"; - } - - /** - * Sets the first record to show - starting at record '0'. After setting - * first record number, the 'show' data object will be updated from pazpar2, - * and the parts of the UI displaying show data should be re-rendered. - * - * To be used by the UI for paging. - * - * @param start first record to show - */ - public void setStart (int start) { - setParameter(new CommandParameter("start","=",start)); - } - - /** - * Retrieves the sequence number of the record that pazpaz2 will return as - * the first record in 'show' - * - * @return sequence number of the first record to be shown (numbering starting at '0') - * - */ - public int getStart() { - return getParameter("start") != null ? Integer.parseInt(getParameter("start").value) : 0; - } - - public void setNum (int num) { - setParameter(new CommandParameter("num","=",num)); - } - - public int getNum () { - return getParameter("num") != null ? Integer.parseInt(getParameter("num").value) : 0; - } - - public ShowCommand copy () { - ShowCommand newCommand = new ShowCommand(stateMgr); - for (String parameterName : parameters.keySet()) { - newCommand.setParameterInState(parameters.get(parameterName).copy()); - } - return newCommand; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SingleTargetFilter.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SingleTargetFilter.java deleted file mode 100644 index d495b70..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/SingleTargetFilter.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import java.io.Serializable; - -import com.indexdata.pz2utils4jsf.pazpar2.commands.SingleTargetFilter; - -public class SingleTargetFilter implements Serializable { - - private static final long serialVersionUID = 2389085467202526537L; - - private String targetName; - private String targetId; - - public SingleTargetFilter (String targetId, String targetName) { - this.targetId = targetId; - this.targetName = targetName; - } - - public String getTargetName () { - return targetName; - } - - public String getTargetId () { - return targetId; - } - - public String getFilterExpression () { - return "pz:id="+targetId; - } - - @Override - public boolean equals(Object o) { - if (o instanceof SingleTargetFilter) { - return targetName.equals(((SingleTargetFilter) o).getTargetName()) && - targetId.equals(((SingleTargetFilter) o).getTargetId()); - } else { - return false; - } - } - - @Override - public int hashCode () { - return (targetId+targetName).hashCode(); - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/StatCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/StatCommand.java deleted file mode 100644 index 4f93e50..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/StatCommand.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class StatCommand extends Pazpar2Command { - - private static final long serialVersionUID = 3980630346114157336L; - - public StatCommand(StateManager stateMgr) { - super("stat",stateMgr); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/TermlistCommand.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/TermlistCommand.java deleted file mode 100644 index cd934b4..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/commands/TermlistCommand.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.commands; - -import com.indexdata.pz2utils4jsf.pazpar2.state.StateManager; - -public class TermlistCommand extends Pazpar2Command { - - private static final long serialVersionUID = -7067878552863021727L; - - public TermlistCommand(StateManager stateMgr) { - super("termlist",stateMgr); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/ByTarget.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/ByTarget.java deleted file mode 100644 index 39ccac0..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/ByTarget.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.util.ArrayList; -import java.util.List; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; -import com.indexdata.pz2utils4jsf.pazpar2.data.Target; - -public class ByTarget extends Pazpar2ResponseData { - - private static final long serialVersionUID = 3960644950805644518L; - - public List getTargets() { - List targets = new ArrayList(); - if (getElements("target") != null) { - for (Pazpar2ResponseData element : getElements("target")) { - targets.add((Target)element); - } - } - return targets; - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/CommandError.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/CommandError.java deleted file mode 100644 index 64080e3..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/CommandError.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import static com.indexdata.pz2utils4jsf.utils.Utils.nl; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -import com.indexdata.pz2utils4jsf.errors.ErrorInterface; -import com.indexdata.pz2utils4jsf.errors.ErrorHelper; -import com.indexdata.pz2utils4jsf.errors.ErrorHelper.ErrorCode; -import com.indexdata.utils.XmlUtils; - -/** - * Holds an error encountered during the execution of a command. - * - * An error can be received by a command thread as an exception message - * or as an error XML. In both cases the error (string or xml) will be embedded - * in a new 'applicationerror' element which in turn will be embedded in a - * command XML (i.e. a 'search' or a 'show' response XML) - * - * The command response XML is subsequently parsed by Pazpar2ResponseParser, - * which will then create the CommandError object. - * - * @author Niels Erik - * - */ -public class CommandError extends Pazpar2ResponseData implements ErrorInterface { - - private static final long serialVersionUID = 8878776025779714122L; - private static Pattern xmlDeclaration = Pattern.compile("<\\?xml.*\\?>"); - private ErrorCode applicationErrorCode; - private ErrorHelper errorHelper = null; - - - public CommandError () { - } - - public String getLabel() { - return getOneElementValue("commandname"); - } - - public String getMessage() { - if (hasPazpar2Error()) { - return getPazpar2Error().getMsg(); - } else { - return getOneElementValue("errormessage"); - } - } - - public String getException () { - return getOneElementValue("exception"); - } - - public List getSuggestions() { - if (errorHelper!=null) { - return errorHelper.getSuggestions(this); - } else { - List nohelper = new ArrayList(); - nohelper.add("Tips: could not generate tips due to a programming error, error helper was not set"); - return nohelper; - } - } - - /** - * Creates an XML string error message, embedded in an XML string document named by the command - * This is the XML that Pazpar2ResponseParser will turn into a CommandError object. - * @param commandName - * @param exceptionName - * @param errorMessage - * @return - */ - public static String createErrorXml (String commandName, String exceptionName, String errorMessage) { - StringBuilder errorXml = new StringBuilder(""); - errorXml.append("<" + commandName + ">"+nl); - errorXml.append(" "+nl); - errorXml.append(" " + commandName + ""+nl); - errorXml.append(" " + XmlUtils.escape(exceptionName) + ""+nl); - errorXml.append(" " + XmlUtils.escape(errorMessage) + ""+nl); - errorXml.append(" "+nl); - errorXml.append(""+nl); - return errorXml.toString(); - } - - /** - * Embeds a Pazpar2 (or Pazpar2 client) error response document as a child element of - * a command response document (like 'search' or 'show'). - * This is the XML that Pazpar2ResponseParser will turn into a CommandError object. - * - * - * @param commandName The name of the command during which's execution the error was encountered - * @param exceptionName The (possibly loosely defined) name of the exception that was thrown - * @param pazpar2ErrorXml The error document as created by Pazpar2, or the Service Proxy or - * by the Pazpar2 client itself. - * @return - */ - public static String insertPazpar2ErrorXml (String commandName, String exceptionName, String pazpar2ErrorXml) { - StringBuilder errorXml = new StringBuilder(""); - errorXml.append("<" + commandName + ">"+nl); - errorXml.append(" "+nl); - errorXml.append(" " + commandName + ""+nl); - errorXml.append(" " + XmlUtils.escape(exceptionName) + ""+nl); - errorXml.append(xmlDeclaration.matcher(pazpar2ErrorXml).replaceAll("")+nl); - errorXml.append(" "+nl); - errorXml.append(""+nl); - return errorXml.toString(); - - } - - /** - * Sets the object that should be used to analyze the error - * - */ - public void setErrorHelper (ErrorHelper errorHelper) { - this.errorHelper = errorHelper; - } - - @Override - public void setApplicationErrorCode(ErrorCode code) { - this.applicationErrorCode = code; - } - - @Override - public ErrorCode getApplicationErrorCode() { - return applicationErrorCode; - } - - public boolean hasPazpar2Error () { - return ( getOneElement("error") != null); - } - - public Pazpar2Error getPazpar2Error() { - return (Pazpar2Error) getOneElement("error"); - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Hit.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Hit.java deleted file mode 100644 index 6c2504e..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Hit.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.util.ArrayList; -import java.util.List; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Location; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; - -public class Hit extends Pazpar2ResponseData { - - - private static final long serialVersionUID = 9039281987691623220L; - - public List getLocations() { - List locations = new ArrayList(); - for (Pazpar2ResponseData element : getElements("location")) { - locations.add((Location)element); - } - return locations; - } - - public String getTitle () { - return getOneElementValue("md-title"); - } - - public String getTitleRemainder() { - return getOneElementValue("md-title-remainder"); - } - - public String getAuthor (String prefix) { - return getOneElement("md-author") != null ? prefix + getOneElement("md-author").getValue() : ""; - } - - public String getAuthor () { - return getOneElementValue("md-author"); - } - - public String getTitleResponsibility() { - return getOneElementValue("md-title-responsibility"); - } - - public String getRecId() { - return getOneElementValue("recid"); - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Location.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Location.java deleted file mode 100644 index 526dda0..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Location.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; - - -public class Location extends Pazpar2ResponseData { - - private static final long serialVersionUID = -1386527442857478225L; - - public String getId() { - return getAttribute("id"); - } - - public String getName () { - return getAttribute("name"); - } - - public String getSubject() { - return getOneElementValue("md-subject"); - } - - public String getSubjects() { - StringBuilder builder = new StringBuilder(""); - for (Pazpar2ResponseData data : getElements("md-subject")) { - if (builder.length()==0) { - builder.append(data.getValue()); - } else { - builder.append(", "); - builder.append(data.getValue()); - } - } - return builder.toString(); - } - - public String getAuthor() { - return getOneElementValue("md-author"); - } - - public String getAuthors() { - StringBuilder builder = new StringBuilder(""); - if (getElements("md-author") != null) { - for (Pazpar2ResponseData data : getElements("md-author")) { - if (builder.length()==0) { - builder.append(data.getValue()); - } else { - builder.append(", "); - builder.append(data.getValue()); - } - } - } - return builder.toString(); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2Error.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2Error.java deleted file mode 100644 index 9c2a725..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2Error.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -public class Pazpar2Error extends Pazpar2ResponseData { - - private static final long serialVersionUID = -7060267782024414318L; - - public String getCode() { - return getAttribute("code"); - } - - public String getMsg() { - return getAttribute("msg"); - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2ResponseData.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2ResponseData.java deleted file mode 100644 index a6e9265..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2ResponseData.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; - -public class Pazpar2ResponseData implements Serializable { - - Logger logger = Logger.getLogger(Pazpar2ResponseData.class); - private static final long serialVersionUID = -3909755656714679959L; - String type = null; - HashMap attributes = new HashMap(); - HashMap> elements = new HashMap>(); - String textContent = ""; - CommandError error = null; - String xml = null; - - public void setType (String type) { - this.type = type; - } - - public String getType () { - return type; - } - - public void setAttribute (String name, String value) { - attributes.put(name, value); - } - - public String getAttribute (String name) { - return attributes.get(name); - } - - public void addElement (String name, Pazpar2ResponseData value) { - if (elements.containsKey(name)) { - elements.get(name).add(value); - } else { - List list = new ArrayList(); - list.add(value); - elements.put(name,list); - } - } - - public List getElements (String name) { - return elements.get(name); - } - - public Pazpar2ResponseData getOneElement (String name) { - if (elements.get(name) != null) { - return elements.get(name).get(0); - } else { - return null; - } - } - - /** - * Returns the text content of the first element found with the given - * name - * @param name of the element - * @return text value, empty string if none found - */ - public String getOneElementValue (String name) { - if (getOneElement(name)!=null && getOneElement(name).getValue().length()>0) { - return getOneElement(name).getValue(); - } else { - return ""; - } - } - - public void appendContent (String content) { - textContent = textContent + content; - } - - public String getValue () { - return textContent; - } - - public String getProperty(String name) { - List els = elements.get(name); - if (els != null) { - return els.get(0).getValue(); - } else { - return null; - } - } - - public int getIntValue(String name) { - String val = getOneElementValue(name); - if (val.length()==0) { - return 0; - } else { - return Integer.parseInt(val); - } - } - - public boolean hasApplicationError () { - return (getOneElement("applicationerror") != null); - } - - public CommandError getApplicationError() { - return (CommandError) getOneElement("applicationerror"); - } - - public boolean hasPazpar2Error() { - return hasApplicationError() && getApplicationError().hasPazpar2Error(); - } - - public void setXml(String xml) { - this.xml = xml; - } - - public String getXml() { - if (type != null && type.equals("record")) { - logger.debug("Getting XML for "+type + ": "+xml); - } - return xml == null ? "" : xml; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2ResponseParser.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2ResponseParser.java deleted file mode 100644 index 73f0cf5..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2ResponseParser.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.List; -import java.util.Stack; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.xml.sax.Attributes; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; - -import com.indexdata.pz2utils4jsf.pazpar2.data.ByTarget; -import com.indexdata.pz2utils4jsf.pazpar2.data.Hit; -import com.indexdata.pz2utils4jsf.pazpar2.data.Location; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; -import com.indexdata.pz2utils4jsf.pazpar2.data.RecordResponse; -import com.indexdata.pz2utils4jsf.pazpar2.data.ShowResponse; -import com.indexdata.pz2utils4jsf.pazpar2.data.StatResponse; -import com.indexdata.pz2utils4jsf.pazpar2.data.Target; -import com.indexdata.pz2utils4jsf.pazpar2.data.TermListResponse; -import com.indexdata.pz2utils4jsf.pazpar2.data.TermListsResponse; -import com.indexdata.pz2utils4jsf.pazpar2.data.TermResponse; -import com.indexdata.pz2utils4jsf.pazpar2.data.TermXTargetResponse; - -public class Pazpar2ResponseParser extends DefaultHandler { - - private XMLReader xmlReader = null; - private Pazpar2ResponseData currentElement = null; - private Stack dataElements = new Stack(); - private Pazpar2ResponseData result = null; - private String xml = null; - - private static final List docTypes = - Arrays.asList("bytarget","termlist","show","stat","record","search"); - - public Pazpar2ResponseParser() { - try { - initSax(); - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SAXException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public static Pazpar2ResponseParser getParser() { - return new Pazpar2ResponseParser(); - } - - private void initSax() throws ParserConfigurationException, SAXException { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - xmlReader = saxParser.getXMLReader(); - xmlReader.setContentHandler(this); - } - - /** - * Parses a Pazpar2 XML response -- or an error response as XML -- and produces a - * Pazpar2ResponseData object, i.e. a 'show' object - * - * @param response XML response string from Pazpar2 - * @return Response data object - */ - public Pazpar2ResponseData getDataObject (String response) { - this.xml = response; - try { - xmlReader.parse(new InputSource(new ByteArrayInputStream(response.getBytes("UTF-8")))); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SAXException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return result; - } - - /** - * Receive notification at the start of element - * - */ - @Override - public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { - if (localName.equals("show")) { - currentElement = new ShowResponse(); - } else if (localName.equals("hit")) { - currentElement = new Hit(); - } else if (localName.equals("location")) { - currentElement = new Location(); - } else if (localName.equals("bytarget")) { - currentElement = new ByTarget(); - } else if (localName.equals("target")) { - currentElement = new Target(); - } else if (localName.equals("stat")) { - currentElement = new StatResponse(); - } else if (localName.equals("termlist")) { - currentElement = new TermListsResponse(); - } else if (localName.equals("list")) { - currentElement = new TermListResponse(); - ((TermListResponse)currentElement).setName(atts.getValue("name")); - ((TermListsResponse)dataElements.peek()).addTermList((TermListResponse)currentElement); - } else if (localName.equals("term")) { - if (dataElements.peek().getAttribute("name").equals("xtargets")) { - currentElement = new TermXTargetResponse(); - } else { - currentElement = new TermResponse(); - } - ((TermListResponse)dataElements.peek()).addTerm((TermResponse)currentElement); - } else if (localName.equals("record")) { - currentElement = new RecordResponse(); - } else if (localName.equals("search")) { - currentElement = new SearchResponse(); - } else if (localName.equals("applicationerror")) { - currentElement = new CommandError(); - } else if (localName.equals("error") && dataElements.peek().getType().equals("applicationerror")) { - currentElement = new Pazpar2Error(); - } else { - currentElement = new Pazpar2ResponseData(); - } - currentElement.setType(localName); - for (int i=0; i< atts.getLength(); i++) { - currentElement.setAttribute(atts.getLocalName(i), atts.getValue(i)); - } - if (!docTypes.contains(localName)) { - dataElements.peek().addElement(localName, currentElement); - } - if (this.xml != null) { // Store XML for doc level elements - currentElement.setXml(xml); - xml = null; - } - dataElements.push(currentElement); - } - - @Override - public void characters(char[] ch, int start, int length) throws SAXException { - String data = new String(ch, start, length); - dataElements.peek().appendContent(data); - } - - @Override - public void endElement(String namespaceURI, String localName, String qName) throws SAXException { - if (dataElements.size()==1) { - result = dataElements.pop(); - } else { - dataElements.pop(); - } - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2Responses.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2Responses.java deleted file mode 100644 index e18d22a..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Pazpar2Responses.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.enterprise.context.SessionScoped; -import javax.inject.Named; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.errors.ErrorHelper; -import com.indexdata.pz2utils4jsf.errors.ErrorInterface; - -@Named("pzresp") @SessionScoped -public class Pazpar2Responses implements Serializable { - - private static final long serialVersionUID = -7543231258346154642L; - protected Map dataObjects = new ConcurrentHashMap(); - private static Logger logger = Logger.getLogger(Pazpar2Responses.class); - private ErrorHelper errorHelper = null; - - public Pazpar2Responses() { - } - - public void put(String name, Pazpar2ResponseData responseData) { - dataObjects.put(name, responseData); - } - - public void setErrorHelper(ErrorHelper helper) { - this.errorHelper = helper; - } - - public boolean hasApplicationError () { - if (getSearch().hasApplicationError()) { - logger.info("Error detected in search"); - return true; - } - for (String name : dataObjects.keySet()) { - if (dataObjects.get(name).hasApplicationError()) { - logger.info("Error detected in " + name); - return true; - } - } - return false; - } - - /** - * Returns a search command error, if any, otherwise the first - * error found for an arbitrary command, if any, otherwise - * an empty dummy error. - */ - public ErrorInterface getCommandError() { - CommandError error = new CommandError(); - if (dataObjects.get("search").hasApplicationError()) { - error = dataObjects.get("search").getApplicationError(); - error.setErrorHelper(errorHelper); - } else { - for (String name : dataObjects.keySet()) { - if (dataObjects.get(name).hasApplicationError()) { - error = dataObjects.get(name).getApplicationError(); - error.setErrorHelper(errorHelper); - break; - } - } - } - return error; - } - - public void reset() { - logger.debug("Resetting show,stat,termlist,bytarget,search response objects."); - dataObjects = new ConcurrentHashMap(); - dataObjects.put("show", new ShowResponse()); - dataObjects.put("stat", new StatResponse()); - dataObjects.put("termlist", new TermListsResponse()); - dataObjects.put("bytarget", new ByTarget()); - dataObjects.put("record", new RecordResponse()); - dataObjects.put("search", new SearchResponse()); - } - - public ShowResponse getShow () { - return ((ShowResponse) dataObjects.get("show")); - } - - public StatResponse getStat () { - return ((StatResponse) dataObjects.get("stat")); - } - - public RecordResponse getRecord() { - return ((RecordResponse) dataObjects.get("record")); - } - - public SearchResponse getSearch() { - return ((SearchResponse) dataObjects.get("search")); - } - - public TermListsResponse getTermLists () { - return ((TermListsResponse) dataObjects.get("termlist")); - } - - public List getFacetTerms (String facet, int count) { - return (getTermLists().getTermList(facet).getTerms(count)); - } - - public List getFacetTerms (String facet) { - return (getTermLists().getTermList(facet).getTerms()); - } - - public ByTarget getByTarget() { - return ((ByTarget) dataObjects.get("bytarget")); - } - - public boolean hasRecords () { - return getStat().getRecords() > 0 - && getShow().getHits() != null - && getShow().getHits().size()>0; - } - - public String getActiveClients() { - if (getShow()!=null) { - logger.debug("Active clients: "+getShow().getActiveClients()); - return getShow().getActiveClients(); - } else { - return ""; - } - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/RecordResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/RecordResponse.java deleted file mode 100644 index 1667c1f..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/RecordResponse.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.util.ArrayList; -import java.util.List; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Location; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; - -public class RecordResponse extends Pazpar2ResponseData { - - private static final long serialVersionUID = 6682722004285796002L; - - public String getRecId () { - return getOneElementValue("recid"); - } - - public List getLocations() { - List locations = new ArrayList(); - for (Pazpar2ResponseData element : getElements("location")) { - locations.add((Location)element); - } - return locations; - } - - public String getTitle() { - return getOneElementValue("md-title"); - } - - public String getDate() { - return getOneElementValue("md-date"); - } - - public String getAuthor() { - return getOneElementValue("md-author"); - } - - public String getSubject() { - return getOneElementValue("md-subject"); - } - - public String getSubjects() { - StringBuilder builder = new StringBuilder(""); - for (Pazpar2ResponseData data : getElements("md-subject")) { - if (builder.length()==0) { - builder.append(data.getValue()); - } else { - builder.append(", "); - builder.append(data.getValue()); - } - } - return builder.toString(); - } - - public Location getFirstLocation () { - return getLocations().size()>0 ? getLocations().get(0) : null; - } - - public String getActiveClients () { - return getOneElementValue("activeclients"); - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/SearchResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/SearchResponse.java deleted file mode 100644 index 528f871..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/SearchResponse.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -public class SearchResponse extends Pazpar2ResponseData { - - private static final long serialVersionUID = -3320013021497018972L; - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/ShowResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/ShowResponse.java deleted file mode 100644 index baed763..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/ShowResponse.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.util.ArrayList; -import java.util.List; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Hit; -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; - -public class ShowResponse extends Pazpar2ResponseData { - - private static final long serialVersionUID = 7103554232106330370L; - - - public String getStatus() { - return getOneElementValue("status"); - } - - public String getActiveClients () { - return getOneElementValue("activeclients"); - } - - public int getMerged () { - return getIntValue("merged"); - } - - public String getTotal () { - return getOneElementValue("total"); - } - - public int getStart () { - return getIntValue("start"); - } - - public int getNum () { - return getIntValue("num"); - } - - public List getHits() { - List hits = new ArrayList(); - if (getElements("hit") != null) { - for (Pazpar2ResponseData element : getElements("hit")) { - hits.add((Hit)element); - } - } - return hits; - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/StatResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/StatResponse.java deleted file mode 100644 index c0df51d..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/StatResponse.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; - -public class StatResponse extends Pazpar2ResponseData { - - private static final long serialVersionUID = -6578979787689458761L; - - public int getHits() { - return getProperty("hits")==null ? 0 : Integer.parseInt(getProperty("hits")); - } - - public int getClients () { - return getIntValue("clients"); - } - - public int getActiveClients () { - return getIntValue("activeclients"); - } - - public int getRecords () { - return getIntValue("records"); - } - - public String getUnconnected() { - return getOneElementValue("unconnected"); - } - - public String getConnecting() { - return getOneElementValue("connecting"); - } - - public String getWorking() { - return getOneElementValue("working"); - } - - public String getIdle() { - return getOneElementValue("idle"); - } - - public String getFailed() { - return getOneElementValue("failed"); - } - - public String getError() { - return getOneElementValue("error"); - } - - public String getProgress() { - return getOneElementValue("progress"); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Target.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Target.java deleted file mode 100644 index 11526f3..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/Target.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; - -public class Target extends Pazpar2ResponseData { - - private static final long serialVersionUID = 3343881183545520108L; - - public String getId () { - return getOneElementValue("id"); - } - - public String getName() { - return getOneElementValue("name"); - } - - public String getHits() { - return getOneElementValue("hits"); - } - - public String getDiagnostic() { - return getOneElementValue("diagnostic"); - } - - public String getRecords() { - return getOneElementValue("records"); - } - - public String getState () { - return getOneElementValue("state"); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermListResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermListResponse.java deleted file mode 100644 index a4a33fb..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermListResponse.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; -import com.indexdata.pz2utils4jsf.pazpar2.data.TermListResponse; -import com.indexdata.pz2utils4jsf.pazpar2.data.TermResponse; - -public class TermListResponse extends Pazpar2ResponseData { - - private static Logger logger = Logger.getLogger(TermListResponse.class); - private static final long serialVersionUID = 3838585739723097393L; - String name = ""; - List terms = new ArrayList(); - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getTerms() { - return terms; - } - - public List getTerms(int count) { - List firstTerms = new ArrayList(); - for (int i=0; i terms) { - this.terms = terms; - } - - public void addTerm(TermResponse term) { - terms.add(term); - } - - public String toString () { - return terms.toString(); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermListsResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermListsResponse.java deleted file mode 100644 index c060579..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermListsResponse.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import java.util.HashMap; -import java.util.Map; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; -import com.indexdata.pz2utils4jsf.pazpar2.data.TermListResponse; - -public class TermListsResponse extends Pazpar2ResponseData { - - private static final long serialVersionUID = -1370643625715834978L; - private int activeClients = -1; - private Map termLists = new HashMap(); - - public int getActiveClients() { - return activeClients; - } - public void setActiveClients(int activeClients) { - this.activeClients = activeClients; - } - - public void addTermList(TermListResponse termList) { - this.termLists.put(termList.getName(),termList); - } - public TermListResponse getTermList(String name) { - return termLists.get(name); - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermResponse.java deleted file mode 100644 index 5b2e90e..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermResponse.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import com.indexdata.pz2utils4jsf.pazpar2.data.Pazpar2ResponseData; - -public class TermResponse extends Pazpar2ResponseData { - - private static final long serialVersionUID = -8323959763575180678L; - - protected int frequency = -1; - - public String getName() { - return getProperty("name"); - } - public int getFrequency() { - return Integer.parseInt(getProperty("frequency")); - } - - public String toString() { - return getProperty("name"); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermXTargetResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermXTargetResponse.java deleted file mode 100644 index a435b34..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/data/TermXTargetResponse.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.data; - -import com.indexdata.pz2utils4jsf.pazpar2.data.TermResponse; - -public class TermXTargetResponse extends TermResponse { - - private static final long serialVersionUID = 5201902652960804977L; - - public String getId() { - return getOneElement("id").getValue(); - } - public int getApproximation () { - return Integer.parseInt(getOneElement("approximation").getValue()); - } - public int getRecords () { - return Integer.parseInt(getOneElement("records").getValue()); - } - public int getFiltered () { - return Integer.parseInt(getOneElement("filtered").getValue()); - } - public String getState () { - return getOneElement("state").getValue(); - } - public String getDiagnostic () { - return getOneElement("diagnostic").getValue(); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyClient.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyClient.java deleted file mode 100644 index 8c2c2e2..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyClient.java +++ /dev/null @@ -1,277 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.sp; - -import static com.indexdata.pz2utils4jsf.utils.Utils.nl; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpClient; -import org.apache.http.client.ResponseHandler; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.entity.FileEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.util.EntityUtils; -import org.apache.log4j.Logger; - -import com.indexdata.masterkey.config.MissingMandatoryParameterException; -import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException; -import com.indexdata.pz2utils4jsf.config.Configuration; -import com.indexdata.pz2utils4jsf.config.ConfigurationReader; -import com.indexdata.pz2utils4jsf.errors.ConfigurationException; -import com.indexdata.pz2utils4jsf.pazpar2.CommandResponse; -import com.indexdata.pz2utils4jsf.pazpar2.SearchClient; -import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter; -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command; -import com.indexdata.pz2utils4jsf.pazpar2.sp.auth.AuthenticationEntity; -import com.indexdata.pz2utils4jsf.pazpar2.sp.auth.ServiceProxyUser; -import com.indexdata.pz2utils4jsf.utils.Utils; - - -public class ServiceProxyClient implements SearchClient { - - private static final long serialVersionUID = -4031644009579840277L; - private static Logger logger = Logger.getLogger(ServiceProxyClient.class); - public static final String MODULENAME = "proxyclient"; - public static final String SERVICE_PROXY_URL = "SERVICE_PROXY_URL"; - public static final String SP_INIT_DOC_PATHS = "SP_INIT_DOC_PATHS"; - private String serviceUrl = "undefined"; - private String[] initDocPaths = null; - private Configuration config = null; - - ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler(); - private HttpClient client; - private ServiceProxyUser user; - - public ServiceProxyClient () { - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); - ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); - client = new DefaultHttpClient(cm); - } - - @Override - public void configure (ConfigurationReader configReader) { - logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader)); - try { - config = configReader.getConfiguration(this); - serviceUrl = config.getMandatory(SERVICE_PROXY_URL); - this.initDocPaths = getMultiProperty(config.get(SP_INIT_DOC_PATHS)); - } catch (ConfigurationException c) { - c.printStackTrace(); - } catch (MissingMandatoryParameterException mmp) { - mmp.printStackTrace(); - } - } - - private String[] getMultiProperty(String prop) { - if (prop != null) { - return prop.split(","); - } else { - return null; - } - } - - public boolean authenticate (AuthenticationEntity user) { - try { - logger.info("Authenticating [" + user.getProperty("name") + "]"); - this.user = (ServiceProxyUser) user; - Pazpar2Command auth = new Pazpar2Command("auth",null); - auth.setParametersInState(new CommandParameter("action","=","login"), - new CommandParameter("username","=",user.getProperty("name")), - new CommandParameter("password","=",user.getProperty("password"))); - byte[] response = send(auth); - String responseStr = new String(response,"UTF-8"); - logger.info(responseStr); - if (responseStr.contains("FAIL")) { - return false; - } else { - return true; - } - } catch (ClientProtocolException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } - } - - public boolean checkAuthentication () { - try { - Pazpar2Command check = new Pazpar2Command("auth",null); - check.setParameter(new CommandParameter("action","=","check")); - byte[] response = send(check); - logger.info(new String(response,"UTF-8")); - } catch (ClientProtocolException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } - return true; - - } - - public boolean isAuthenticatingClient () { - return true; - } - - public boolean isAuthenticated () { - if (user.getProperty("name") != null && user.getProperty("password") != null) { - return checkAuthentication(); - } else { - return false; - } - } - - /** - * Makes the request - * @param request - * @return HTTP response as a String - * @throws ClientProtocolException - * @throws IOException - */ - private byte[] send(Pazpar2Command command) throws ClientProtocolException, IOException { - String url = serviceUrl + "?" + command.getEncodedQueryString(); - logger.info("Sending request "+url); - HttpGet httpget = new HttpGet(url); - byte[] response = client.execute(httpget, handler); - return response; - } - - public class ProxyPz2ResponseHandler implements ResponseHandler { - private StatusLine statusLine = null; - public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { - byte[] resp = null; - HttpEntity entity = response.getEntity(); - statusLine = response.getStatusLine(); - if (entity != null) { - resp = EntityUtils.toByteArray(entity); - } - EntityUtils.consume(entity); - return resp; - } - public int getStatusCode() { - return statusLine.getStatusCode(); - } - public String getReasonPhrase() { - return statusLine.getReasonPhrase(); - } - } - - public int getStatusCode () { - return handler.getStatusCode(); - } - - public String getReasonPhrase() { - return handler.getReasonPhrase(); - } - - @Override - public void setSearchCommand(Pazpar2Command command) { - // Do nothing, Service Proxy is handling this - } - - @Override - public CommandResponse executeCommand(Pazpar2Command command, - ByteArrayOutputStream baos) throws Pazpar2ErrorException, IOException { - byte[] response = send(command); - baos.write(response); - return new ServiceProxyClientCommandResponse(getStatusCode(), new String(response,"UTF-8")); - } - - public ServiceProxyClient cloneMe() { - logger.debug("Cloning Pz2Client"); - ServiceProxyClient clone = new ServiceProxyClient(); - clone.client = this.client; - clone.serviceUrl = this.serviceUrl; - clone.initDocPaths = this.initDocPaths; - return clone; - } - - @Override - public Map getDefaults() { - return new HashMap(); - } - - @Override - public String getModuleName() { - return MODULENAME; - } - - @Override - public List documentConfiguration () { - List doc = new ArrayList(); - doc.add(nl+ MODULENAME + " was configured to access the Pazpar2 service proxy at: " + serviceUrl); - return null; - } - - public byte[] postInitDoc (String filePath) throws IOException { - logger.info("Looking to post the file in : [" + filePath +"]"); - HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes"); - File initDoc = new File(filePath); - logger.info("Posting to SP: "); - if (logger.isDebugEnabled()) { - BufferedReader reader = new BufferedReader(new FileReader(initDoc)); - String line; - while ( (line = reader.readLine()) != null) { - System.out.println(line); - } - reader.close(); - } - post.setEntity(new FileEntity(initDoc)); - byte[] response = client.execute(post, handler); - logger.debug("Response on POST was: " + new String(response,"UTF-8")); - return response; - } - - public String[] getInitDocPaths () { - logger.debug("Get init doc paths "); - logger.debug("length: " + initDocPaths.length); - return initDocPaths; - } - - public byte[] postInitDoc(byte[] initDoc) throws IOException { - HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes"); - post.setEntity(new ByteArrayEntity(initDoc)); - byte[] response = client.execute(post, handler); - logger.debug("Response on POST was: " + new String(response,"UTF-8")); - return response; - } - - public void setServiceProxyUrl (String url) { - serviceUrl = url; - } - - public String getServiceProxyUrl () { - return serviceUrl; - } - - public Configuration getConfiguration () { - return config; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyClientCommandResponse.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyClientCommandResponse.java deleted file mode 100644 index ef0c41d..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyClientCommandResponse.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.sp; - -import com.indexdata.pz2utils4jsf.pazpar2.CommandResponse; - -public class ServiceProxyClientCommandResponse implements CommandResponse { - - private int statusCode = 0; - private String content = null; - - public ServiceProxyClientCommandResponse(int statusCode, String content) { - this.statusCode = statusCode; - this.content = content; - } - - @Override - public int getStatusCode() { - return statusCode; - } - - @Override - public String getContentType() { - return "text/xml;charset=UTF-8"; - } - - @Override - public String getResponseString() { - return content; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyInterface.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyInterface.java deleted file mode 100644 index ef84cea..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/ServiceProxyInterface.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.sp; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import com.indexdata.pz2utils4jsf.pazpar2.Pz2Interface; - -public interface ServiceProxyInterface extends Pz2Interface { - public String login(String navigateTo); - public void setInitFileName (String fileName); - public String getInitFileName(); - public String postInit() throws UnsupportedEncodingException, IOException; - public String postInit(byte[] initDoc) throws UnsupportedEncodingException, IOException; - public String getInitResponse(); - public void setServiceProxyUrl(String url); - public String getServiceProxyUrl(); -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/auth/AuthenticationEntity.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/auth/AuthenticationEntity.java deleted file mode 100644 index cd9ee6c..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/auth/AuthenticationEntity.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.sp.auth; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -public interface AuthenticationEntity extends Serializable{ - - - public String getProperty(String key); - - public Map getPropertyMap(); - - public List getPossibleProperties(); - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/auth/ServiceProxyUser.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/auth/ServiceProxyUser.java deleted file mode 100644 index dbde7bc..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/sp/auth/ServiceProxyUser.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.sp.auth; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.enterprise.context.SessionScoped; -import javax.inject.Named; - -@Named("user") @SessionScoped -public class ServiceProxyUser implements AuthenticationEntity { - - private static final long serialVersionUID = 2351542518778803071L; - private List possibleProperties = Arrays.asList("name","password","realm"); - private Map actualProperties = new HashMap(); - - public ServiceProxyUser() {} - - public void setAuthenticationMethod() { - - } - - public String getName() { - return actualProperties.get("name"); - } - - public void setName(String newValue) { - actualProperties.put("name", newValue); - } - - public String getPassword() { - return actualProperties.get("password"); - } - - public void setPassword(String newValue) { - actualProperties.put("password", newValue); - } - - public void setRealm(String realm) { - actualProperties.put("realm", realm); - } - - public String getRealm() { - return actualProperties.get("realm"); - } - - - @Override - public String getProperty(String key) { - return actualProperties.get(key); - } - - @Override - public Map getPropertyMap() { - return actualProperties; - } - - @Override - public List getPossibleProperties() { - return possibleProperties; - } - - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/Pazpar2State.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/Pazpar2State.java deleted file mode 100644 index 39ac006..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/Pazpar2State.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.state; - -import java.util.HashMap; -import java.util.Map; - -import com.indexdata.pz2utils4jsf.pazpar2.commands.BytargetCommand; -import com.indexdata.pz2utils4jsf.pazpar2.commands.InitCommand; -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command; -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Commands; -import com.indexdata.pz2utils4jsf.pazpar2.commands.PingCommand; -import com.indexdata.pz2utils4jsf.pazpar2.commands.RecordCommand; -import com.indexdata.pz2utils4jsf.pazpar2.commands.SearchCommand; -import com.indexdata.pz2utils4jsf.pazpar2.commands.SettingsCommand; -import com.indexdata.pz2utils4jsf.pazpar2.commands.ShowCommand; -import com.indexdata.pz2utils4jsf.pazpar2.commands.StatCommand; -import com.indexdata.pz2utils4jsf.pazpar2.commands.TermlistCommand; - -/** - * Holds a 'pazpar2 state', understood as a full set of pazpar2 commands and - * all their parameter settings at a given point in time. - * - * @author Niels Erik - * - */ -public class Pazpar2State { - - String key = null; - Map commands = new HashMap();; - - public Pazpar2State (StateManager mgr) { - commands.put(Pazpar2Commands.INIT, new InitCommand(mgr)); - commands.put(Pazpar2Commands.PING, new PingCommand(mgr)); - commands.put(Pazpar2Commands.SETTINGS, new SettingsCommand(mgr)); - commands.put(Pazpar2Commands.SEARCH, new SearchCommand(mgr)); - commands.put(Pazpar2Commands.STAT, new StatCommand(mgr)); - commands.put(Pazpar2Commands.SHOW, new ShowCommand(mgr)); - commands.put(Pazpar2Commands.RECORD, new RecordCommand(mgr)); - commands.put(Pazpar2Commands.TERMLIST, new TermlistCommand(mgr)); - commands.put(Pazpar2Commands.BYTARGET, new BytargetCommand(mgr)); - key = "#1"; - } - - /** - * Creates new state by cloning all commands of the provided state and - * then overriding one of them with the provided state changing command. - * - * @param previousState - * @param newCommand - */ - public Pazpar2State (Pazpar2State previousState, Pazpar2Command newCommand) { - for (String commandName : previousState.commands.keySet()) { - this.commands.put(commandName, previousState.commands.get(commandName).copy()); - } - this.commands.put(newCommand.getName(),newCommand); - this.key = getKey(); - } - - /** - * Generates a state key that can be used by the browser to pick - * up this state again at a later point in time. - * - * @return - */ - public String getKey() { - if (key == null) { - StringBuilder querystatebuilder = new StringBuilder(""); - for (Pazpar2Command command : commands.values()) { - if (command.hasParameters()) { - querystatebuilder.append("||"+command.getName()+"::"); - querystatebuilder.append(command.getValueWithExpressions()); - } - } - key = "#"+querystatebuilder.toString().hashCode(); - return key; - } else { - return key; - } - } - - /** - * Checks if a command represents a change of this state - * - * @param command - * @return true if the command causes a change of state - */ - public boolean stateMutating (Pazpar2Command command) { - if (command == null) { - return true; - } else if (commands.get(command.getName()) == null) { - return true; - } else if ((command.equals(commands.get(command.getName())))) { - return false; - } else { - return true; - } - } - - /** - * Returns a command from this state - * - * @param name - * @return - */ - public Pazpar2Command getCommand(String name) { - return commands.get(name); - } -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/StateListener.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/StateListener.java deleted file mode 100644 index ac7fe8b..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/StateListener.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.state; - -public interface StateListener { - - public void stateUpdated(String commandName); - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/StateManager.java b/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/StateManager.java deleted file mode 100644 index f1ae6b6..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pazpar2/state/StateManager.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.indexdata.pz2utils4jsf.pazpar2.state; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.enterprise.context.SessionScoped; - -import org.apache.log4j.Logger; - -import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command; -import com.indexdata.pz2utils4jsf.utils.Utils; - -@SessionScoped -public class StateManager implements Serializable { - - private static final long serialVersionUID = 8152558351351730035L; - - Map states = new HashMap(); - String currentKey = ""; - private static List allCommands = new ArrayList(Arrays.asList("init","ping","settings","search","stat","show","record","termlist","bytarget")); - Map pendingStateChanges = new HashMap(); - private static Logger logger = Logger.getLogger(StateManager.class); - private List listeners = new ArrayList(); - - public StateManager () { - logger.info("Initializing a Pazpar2 state manager [" + Utils.objectId(this) + "]"); - Pazpar2State initialState = new Pazpar2State(this); - states.put(initialState.getKey(), initialState); - currentKey = initialState.getKey(); - for (String command : allCommands) { - pendingStateChanges.put(command, new Boolean(false)); - } - } - - public void addStateListener(StateListener listener) { - listeners.add(listener); - } - - public void removeStateListener (StateListener listener) { - listeners.remove(listener); - } - - private void updateListeners (String command) { - for (StateListener lsnr : listeners) { - lsnr.stateUpdated(command); - } - } - - /** - * Registers a Pazpar2 command for execution. - * - * The state manager will update current state and flag that - * a request change was made but that it was not yet carried - * out against Pazpar2. - * - * Any command that is created or modified must be checked in - * like this to come into effect. - * - * @param command - */ - public void checkIn(Pazpar2Command command) { - if (getCurrentState().stateMutating(command)) { - logger.debug("State changed by: " + command.getName()); - Pazpar2State state = new Pazpar2State(getCurrentState(),command); - states.put(state.getKey(), state); - currentKey = state.getKey(); - hasPendingStateChange(command.getName(),new Boolean(true)); - logger.debug("Updating " + listeners.size() + " listener(s) with state change from " + command); - updateListeners(command.getName()); - } else { - logger.debug("Command " + command.getName() + " not found to change the state [" + command.getEncodedQueryString() + "]"); - } - } - - public Pazpar2Command getCommand (String commandName) { - return getCurrentState().getCommand(commandName); - } - - public Pazpar2State getCurrentState () { - return states.get(currentKey); - } - - /** - * Changes the current state key. Invoked from the UI to have the state - * manager switch to another state than the current one. - * - * @param key - */ - public void setCurrentStateKey(String key) { - if (currentKey.equals(key)) { - logger.debug("setCurrentStateKey: no key change detected"); - } else { - logger.debug("State key change. Was: [" + currentKey + "]. Will be ["+key+"]"); - if (states.get(key)==null) { - logger.error("The back-end received an unknow state key."); - } else { - if (states.get(key).getCommand("search").equals(states.get(currentKey).getCommand("search"))) { - logger.debug("No search change detected"); - } else { - hasPendingStateChange("search",true); - } - if (states.get(key).getCommand("record").equals(states.get(currentKey).getCommand("record"))) { - logger.debug("No record change detected"); - } else { - hasPendingStateChange("record",true); - } - currentKey = key; - } - } - } - - /** - * Sets a pending-state-change flag for the given command and notifies - * registered listeners. - * - * It is up to the listener to reset the flag as needed. - * - * @param command - * @param bool - */ - public void hasPendingStateChange(String command, boolean bool) { - pendingStateChanges.put(command, new Boolean(bool)); - } - - /** - * - * @param command - * @return true if there is a non-executed command change in this state - */ - public boolean hasPendingStateChange (String command) { - return pendingStateChanges.get(command).booleanValue(); - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/pz2utils/ListenerFieldIds.java b/src/main/java/com/indexdata/pz2utils4jsf/pz2utils/ListenerFieldIds.java deleted file mode 100644 index a454936..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/pz2utils/ListenerFieldIds.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.indexdata.pz2utils4jsf.pz2utils; - -import java.io.Serializable; - -import javax.enterprise.context.ApplicationScoped; -import javax.inject.Named; - -@Named("pz2watch") -@ApplicationScoped -public class ListenerFieldIds implements Serializable { - - private static final long serialVersionUID = -57079241763914538L; - - public String getHistory () { - return ":pz2watch:stateForm:windowlocationhash"; - } - - public String getActiveclients () { - return ":pz2watch:activeclientsForm:activeclientsField"; - } - - public String getActiveclientsRecord () { - return ":pz2watch:activeclientsForm:activeclientsFieldRecord"; - } - - public String getErrorMessages () { - return ":pz2watch:activeclientsForm:errorMessages"; - } - -} diff --git a/src/main/java/com/indexdata/pz2utils4jsf/utils/Utils.java b/src/main/java/com/indexdata/pz2utils4jsf/utils/Utils.java deleted file mode 100644 index 5273134..0000000 --- a/src/main/java/com/indexdata/pz2utils4jsf/utils/Utils.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.indexdata.pz2utils4jsf.utils; - -public class Utils { - - public static String nl = System.getProperty("line.separator"); - - public static String objectId(Object o) { - int lastdot = o.toString().lastIndexOf('.'); - if (lastdot>-1 && lastdot+1