From 624e99924920a462fba11c993daf9813c994ae07 Mon Sep 17 00:00:00 2001 From: "Niels Erik G. Nielsen" Date: Wed, 8 May 2013 15:45:34 -0400 Subject: [PATCH] Adds support for chosing pz2 or sp service run-time The client type as well as the service url can thus be changed dynamically. Defining service type deploy time is now done by a config parameter - rather than -- as it used to be -- by setting an injection instruction in beans.xml. --- .../java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java | 204 +++++++++++-- .../com/indexdata/mkjsf/pazpar2/Pz2Client.java | 33 ++- .../com/indexdata/mkjsf/pazpar2/Pz2Interface.java | 11 +- .../com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java | 149 ---------- .../com/indexdata/mkjsf/pazpar2/SearchClient.java | 3 + .../mkjsf/pazpar2/ServiceProxyExtensions.java | 111 +++++++ .../mkjsf/pazpar2/commands/sp/InitDocUpload.java | 13 +- .../mkjsf/pazpar2/sp/ServiceProxyClient.java | 304 -------------------- .../mkjsf/pazpar2/sp/ServiceProxyInterface.java | 17 -- 9 files changed, 345 insertions(+), 500 deletions(-) delete mode 100644 src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java create mode 100644 src/main/java/com/indexdata/mkjsf/pazpar2/ServiceProxyExtensions.java delete mode 100644 src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java delete mode 100644 src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java index f0cfa7d..490cee6 100644 --- a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Bean.java @@ -2,17 +2,21 @@ package com.indexdata.mkjsf.pazpar2; 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 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.Configurable; +import com.indexdata.mkjsf.config.Configuration; import com.indexdata.mkjsf.config.ConfigurationReader; import com.indexdata.mkjsf.controls.ResultsPager; import com.indexdata.mkjsf.errors.ConfigurationError; @@ -25,27 +29,40 @@ 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.sp.auth.ServiceProxyUser; 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 { +@Named("pz2") @SessionScoped +public class Pz2Bean implements Pz2Interface, StateListener, Configurable, Serializable { + + private static final String MODULE_NAME = "service"; + private static String SERVICE_TYPE_TBD = "TBD", SERVICE_TYPE_PZ2 = "PZ2", SERVICE_TYPE_SP = "SP"; + private static final List serviceTypes = + Arrays.asList(SERVICE_TYPE_PZ2,SERVICE_TYPE_SP,SERVICE_TYPE_TBD); + private String serviceType = SERVICE_TYPE_TBD; + private List serviceProxyUrls = new ArrayList(); + public static final String SERVICE_PROXY_URL_LIST = "SERVICE_PROXY_URL_LIST"; + private List pazpar2Urls = new ArrayList(); + public static final String PAZPAR2_URL_LIST = "PAZPAR2_URL_LIST"; + 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; - + private static Logger responseLogger = Logger.getLogger("com.indexdata.mkjsf.pazpar2.responses"); + protected Pz2Client pz2Client = null; + protected ServiceProxyClient spClient = null; + protected SearchClient searchClient = null; + @Inject ConfigurationReader configurator; @Inject StateManager stateMgr; @Inject Pazpar2Commands pzreq; @Inject Pazpar2Responses pzresp; @Inject ErrorCentral errors; + @Inject ServiceProxyUser user; protected ResultsPager pager = null; - protected ErrorHelper errorHelper = null; @@ -55,19 +72,25 @@ public class Pz2Bean implements Pz2Interface, StateListener, Serializable { @PostConstruct public void postConstruct() { - logger.debug("in start of Pz2Bean post-construct configurator is " + configurator); + logger.debug("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); + pz2Client = new Pz2Client(); + configureClient(pz2Client,configurator); + spClient = new ServiceProxyClient(); + configureClient(spClient,configurator); + try { + this.configure(configurator); + } catch (ConfigurationException e) { + logger.error("There was a problem configuring the Pz2Bean (\"pz2\")"); + e.printStackTrace(); + } stateMgr.addStateListener(this); } - public void configureClient(SearchClient searchClient, ConfigurationReader configReader) { + public void configureClient(SearchClient client, ConfigurationReader configReader) { logger.debug(Utils.objectId(this) + " will configure search client for the session"); try { - searchClient.configure(configReader); + client.configure(configReader); } catch (ConfigurationException e) { logger.debug("Pz2Bean adding configuration error"); errors.addConfigurationError(new ConfigurationError("Search Client","Configuration",e.getMessage())); @@ -75,6 +98,12 @@ public class Pz2Bean implements Pz2Interface, StateListener, Serializable { logger.info(configReader.document()); pzresp.reset(); } + + public void resetSearchAndResults () { + pzreq.getRecord().removeParametersInState(); + pzreq.getSearch().removeParametersInState(); + pzresp.reset(); + } public void doSearch(String query) { @@ -264,9 +293,81 @@ public class Pz2Bean implements Pz2Interface, StateListener, Serializable { } } + public void setServiceProxyUrl(String url) { + searchClient = spClient; + setServiceUrl(url); + } + + public String getServiceProxyUrl () { + return spClient.getServiceUrl(); + } + + public void setPazpar2Url(String url) { + searchClient = pz2Client; + setServiceUrl(url); + } + + public String getPazpar2Url() { + return pz2Client.getServiceUrl(); + } + + + @Override + public void setServiceUrl(String url) { + if (url!=null && searchClient != null && !url.equals(searchClient.getServiceUrl())) { + pzreq.getRecord().removeParametersInState(); + pzreq.getSearch().removeParametersInState(); + pzresp.reset(); + user.clear(); + searchClient.setServiceUrl(url); + } + } + + public String getServiceUrl() { + return (searchClient!=null ? searchClient.getServiceUrl() : ""); + } + + public boolean getServiceUrlIsDefined() { + return (searchClient != null && searchClient.hasServiceUrl()); + } + + public List getServiceProxyUrls() { + List urls = new ArrayList(); + urls.add(""); + urls.addAll(serviceProxyUrls); + return urls; + } + + public List getPazpar2Urls () { + List urls = new ArrayList(); + urls.add(""); + urls.addAll(pazpar2Urls); + return urls; + } + + public String getServiceType () { + return serviceType; + } + + public boolean isPazpar2Service () { + return serviceType.equals(SERVICE_TYPE_PZ2); + } + + public boolean isServiceProxyService() { + return serviceType.equals(SERVICE_TYPE_SP); + } + + public boolean serviceIsToBeDecided () { + return serviceType.equals(SERVICE_TYPE_TBD); + } + + public ServiceProxyClient getSpClient () { + return spClient; + } + @Override public boolean getAuthenticationRequired () { - return searchClient.isAuthenticatingClient(); + return spClient.isAuthenticatingClient(); } @Override @@ -283,5 +384,76 @@ public class Pz2Bean implements Pz2Interface, StateListener, Serializable { public String getWatchActiveclientsRecord () { return ":pz2watch:activeclientsForm:activeclientsFieldRecord"; } + + @Override + public void configure(ConfigurationReader reader) + throws ConfigurationException { + Configuration config = reader.getConfiguration(this); + if (config == null) { + serviceType = SERVICE_TYPE_TBD; + } else { + String service = config.get("TYPE"); + if (service == null || service.length()==0) { + serviceType = SERVICE_TYPE_TBD; + } else if (serviceTypes.contains(service.toUpperCase())) { + setServiceType(service.toUpperCase()); + } else { + logger.error("Unknown serviceType type in configuration [" + service + "], can be one of " + serviceTypes); + serviceType = SERVICE_TYPE_TBD; + } + serviceProxyUrls = config.getMultiProperty(SERVICE_PROXY_URL_LIST,","); + pazpar2Urls = config.getMultiProperty(PAZPAR2_URL_LIST, ","); + } + logger.info("Service Type is configured to " + serviceType); + + } + + @Override + public Map getDefaults() { + return new HashMap(); + } + + @Override + public String getModuleName() { + return MODULE_NAME; + } + + @Override + public List documentConfiguration() { + return new ArrayList(); + } + + @Override + public void setServiceTypePZ2() { + setServiceType(SERVICE_TYPE_PZ2); + } + + @Override + public void setServiceTypeSP() { + setServiceType(SERVICE_TYPE_SP); + } + + @Override + public void setServiceTypeTBD() { + setServiceType(SERVICE_TYPE_TBD); + } + + private void setServiceType(String type) { + if (!serviceType.equals(type) && + !serviceType.equals(SERVICE_TYPE_TBD)) { + resetSearchAndResults(); + } + serviceType = type; + if (serviceType.equals(SERVICE_TYPE_PZ2)) { + searchClient = pz2Client; + logger.info("Setting a Pazpar2 client to serve requests."); + } else if (serviceType.equals(SERVICE_TYPE_SP)) { + searchClient = spClient; + logger.info("Setting a Service Proxy client to serve requests."); + } else { + logger.info("Clearing search client. No client defined to serve requests at this point."); + searchClient = null; + } + } } diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Client.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Client.java index a68e67f..2bfb52b 100644 --- a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Client.java +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Client.java @@ -35,9 +35,10 @@ public class Pz2Client implements SearchClient { private Pazpar2ClientConfiguration cfg = null; public static final String MODULENAME = "pz2client"; public static Map DEFAULTS = new HashMap(); - Configuration config = null; + Configuration config = null; static { + DEFAULTS.put("PAZPAR2_URL", ""); DEFAULTS.put("PROXY_MODE","1"); DEFAULTS.put("SERIALIZE_REQUESTS", "false"); DEFAULTS.put("STREAMBUFF_SIZE", "4096"); @@ -50,7 +51,7 @@ public class Pz2Client implements SearchClient { 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); + config = configReader.getConfiguration(this); cfg = new Pazpar2ClientConfiguration(new ConfigurationGetter(config)); } catch (ProxyErrorException pe) { logger.error("Could not configure Pazpar2 client: " + pe.getMessage()); @@ -89,7 +90,7 @@ public class Pz2Client implements SearchClient { @Override public CommandResponse executeCommand(Pazpar2Command command) { - Pz2CommandResponse commandResponse = null; + ClientCommandResponse commandResponse = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ClientCommand clientCommand = new ClientCommand(command.getCommandName(), command.getEncodedQueryString()); Pazpar2HttpResponse pz2HttpResponse = null; @@ -97,25 +98,25 @@ public class Pz2Client implements SearchClient { try { pz2HttpResponse = client.executeCommand(clientCommand, baos); if (pz2HttpResponse.getStatusCode()==200) { - commandResponse = new Pz2CommandResponse(pz2HttpResponse,baos); + commandResponse = new ClientCommandResponse(pz2HttpResponse,baos); } else if (pz2HttpResponse.getStatusCode()==417) { logger.error("Pazpar2 status code 417: " + baos.toString("UTF-8")); - commandResponse = new Pz2CommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2: Expectation failed (417)", baos.toString("UTF-8")),"text/xml"); + commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2: Expectation failed (417)", baos.toString("UTF-8")),"text/xml"); } else { String resp = baos.toString("UTF-8"); logger.error("Pazpar2 status code was " + pz2HttpResponse.getStatusCode() + ": " + resp); - commandResponse = new Pz2CommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2 error occurred", baos.toString("UTF-8")),"text/xml"); + commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Pazpar2 error occurred", baos.toString("UTF-8")),"text/xml"); throw new Pazpar2ErrorException(resp,pz2HttpResponse.getStatusCode(),resp,null); } } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); - commandResponse = new Pz2CommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml"); + commandResponse = new ClientCommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml"); } catch (Pazpar2ErrorException e) { logger.error(e.getMessage()); e.printStackTrace(); logger.error("Creating error XML"); - commandResponse = new Pz2CommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml"); + commandResponse = new ClientCommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), "io", e.getMessage()),"text/xml"); } long end = System.currentTimeMillis(); logger.debug("Executed " + command.getCommandName() + " in " + (end-start) + " ms." ); @@ -175,4 +176,20 @@ public class Pz2Client implements SearchClient { return config; } + @Override + public String getServiceUrl() { + return cfg.PAZPAR2_URL; + } + + @Override + public boolean hasServiceUrl() { + return cfg.PAZPAR2_URL != null && cfg.PAZPAR2_URL.length()>0; + } + + @Override + public void setServiceUrl (String serviceUrl) { + cfg.PAZPAR2_URL = serviceUrl; + + } + } diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Interface.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Interface.java index bf8aa40..7b0b863 100644 --- a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Interface.java +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2Interface.java @@ -101,5 +101,14 @@ public interface Pz2Interface extends Serializable { public String getCheckHistory (); public String getWatchActiveclients (); public String getWatchActiveclientsRecord (); - + + public void setServiceTypePZ2 (); + public void setServiceTypeSP (); + public void setServiceTypeTBD (); + public void setServiceUrl(String url); + public String getServiceUrl(); + public String getServiceType(); + public boolean isPazpar2Service (); + public boolean isServiceProxyService(); + public boolean serviceIsToBeDecided (); } diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java b/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java deleted file mode 100644 index 7bc0145..0000000 --- a/src/main/java/com/indexdata/mkjsf/pazpar2/Pz2ProxyBean.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.indexdata.mkjsf.pazpar2; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -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.ServiceProxyCommandResponse; -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 = ""; - - @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."); - } - } - - public void login(String un, String pw) { - if (user.isAuthenticated() && user.getName().equals(un) && ((ServiceProxyClient) searchClient).checkAuthentication(user)) { - logger.info("Repeat request from UI to authenticate user. Auth verified for given user name so skipping log-in."); - } else { - logger.info("doing un/pw login"); - user.setName(un); - user.setPassword(pw); - login("dummy"); - } - } - - @Override - public String login(String navigateTo) { - logger.info("doing login"); - ((ServiceProxyClient)searchClient).authenticate(user); - pzreq.getRecord().removeParametersInState(); - pzreq.getSearch().removeParametersInState(); - pzresp.reset(); - return navigateTo; - } - - public void ipAuthenticate (ServiceProxyUser user) { - if (!user.isIpAuthenticated()) { - if (user.isAuthenticated()) { - user.clear(); - } - pzreq.getRecord().removeParametersInState(); - pzreq.getSearch().removeParametersInState(); - pzresp.reset(); - ((ServiceProxyClient)searchClient).ipAuthenticate(user); - } - } - - @Override - public void setServiceProxyUrl(String url) { - logger.info("Setting Service Proxy url: " + url); - if (url!=null & !url.equals(((ServiceProxyClient)searchClient).getServiceProxyUrl())) { - pzreq.getRecord().removeParametersInState(); - pzreq.getSearch().removeParametersInState(); - pzresp.reset(); - user.clear(); - ((ServiceProxyClient)searchClient).setServiceProxyUrl(url); - } - } - - public String getServiceProxyUrl() { - return ((ServiceProxyClient)searchClient).getServiceProxyUrl(); - } - - public boolean getServiceProxyUrlIsDefined() { - return ((ServiceProxyClient)searchClient).getServiceProxyUrl().length()>0; - } - - public List getServiceProxyUrls() { - List urls = new ArrayList(); - urls.add(""); - urls.addAll(((ServiceProxyClient)searchClient).getServiceProxyUrls()); - return urls; - } - - 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 ServiceProxyCommandResponse postInit() throws UnsupportedEncodingException, IOException { - String initDocPath = ((ServiceProxyClient)searchClient).getInitDocPaths().get(0); - logger.info("Paths: " + ((ServiceProxyClient)searchClient).getInitDocPaths()); - logger.info("Path: " + initDocPath); - pzresp.reset(); - ServiceProxyCommandResponse response = ((ServiceProxyClient)searchClient).postInitDoc(initDocPath + getInitFileName()); - return response; - } - - @Override - public ServiceProxyCommandResponse postInit(byte[] initDoc, boolean includeDebug) throws UnsupportedEncodingException, IOException { - pzresp.reset(); - ServiceProxyCommandResponse response = ((ServiceProxyClient)searchClient).postInitDoc(initDoc,includeDebug); - return response; - } - - @Override - public String getInitResponse() { - return initDocResponse; - } - -} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/SearchClient.java b/src/main/java/com/indexdata/mkjsf/pazpar2/SearchClient.java index c7ec2c5..745a6b6 100644 --- a/src/main/java/com/indexdata/mkjsf/pazpar2/SearchClient.java +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/SearchClient.java @@ -20,4 +20,7 @@ public interface SearchClient extends Configurable, Serializable { public boolean isAuthenticatingClient(); public Configuration getConfiguration(); + public String getServiceUrl(); + public void setServiceUrl(String url); + public boolean hasServiceUrl(); } diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/ServiceProxyExtensions.java b/src/main/java/com/indexdata/mkjsf/pazpar2/ServiceProxyExtensions.java new file mode 100644 index 0000000..04343c3 --- /dev/null +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/ServiceProxyExtensions.java @@ -0,0 +1,111 @@ +package com.indexdata.mkjsf.pazpar2; + +import java.io.IOException; +import java.io.Serializable; +import java.io.UnsupportedEncodingException; + +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.commands.Pazpar2Commands; +import com.indexdata.mkjsf.pazpar2.commands.sp.InitDocUpload; +import com.indexdata.mkjsf.pazpar2.data.Pazpar2Responses; +import com.indexdata.mkjsf.pazpar2.sp.auth.ServiceProxyUser; + +@Named("pz2x") @SessionScoped +public class ServiceProxyExtensions implements ServiceProxyInterface, Serializable { + + private static final long serialVersionUID = 4221824985678758225L; + private static Logger logger = Logger.getLogger(ServiceProxyExtensions.class); + private String initDocFileName = ""; + private String initDocResponse = ""; + private InitDocUpload initDocUpload; + + @Inject ConfigurationReader configurator; + @Inject ServiceProxyUser user; + @Inject Pz2Bean pz2; + @Inject Pazpar2Commands pzreq; + @Inject Pazpar2Responses pzresp; + + + public ServiceProxyExtensions() { + this.initDocUpload = new InitDocUpload(this); + // TODO: + //stateMgr.addStateListener(this); + } + + public void login(String un, String pw) { + if (user.isAuthenticated() && user.getName().equals(un) && pz2.spClient.checkAuthentication(user)) { + logger.info("Repeat request from UI to authenticate user. Auth verified for given user name so skipping log-in."); + } else { + logger.info("doing un/pw login"); + user.setName(un); + user.setPassword(pw); + login("dummy"); + } + } + + @Override + public String login(String navigateTo) { + logger.info("doing login by " + user + " using " + pz2 + " and client " + pz2.getSpClient()); + pz2.getSpClient().authenticate(user); + pz2.resetSearchAndResults(); + return navigateTo; + } + + public void ipAuthenticate (ServiceProxyUser user) { + if (!user.isIpAuthenticated()) { + if (user.isAuthenticated()) { + user.clear(); + } + pz2.resetSearchAndResults(); + pz2.getSpClient().ipAuthenticate(user); + } + } + + public String getInitDocPath () { + return pz2.getSpClient().getConfiguration().get("INIT_DOC_PATH"); + } + + @Override + public void setInitFileName(String fileName) { + this.initDocFileName = fileName; + + } + + @Override + public String getInitFileName() { + return initDocFileName; + } + + @Override + public ClientCommandResponse postInit() throws UnsupportedEncodingException, IOException { + String initDocPath = pz2.getSpClient().getInitDocPaths().get(0); + logger.info("Paths: " + pz2.getSpClient().getInitDocPaths()); + logger.info("Path: " + initDocPath); + pz2.resetSearchAndResults(); + ClientCommandResponse response = pz2.getSpClient().postInitDoc(initDocPath + getInitFileName()); + return response; + } + + @Override + public ClientCommandResponse postInit(byte[] initDoc, boolean includeDebug) throws UnsupportedEncodingException, IOException { + pz2.resetSearchAndResults(); + ClientCommandResponse response = pz2.getSpClient().postInitDoc(initDoc,includeDebug); + return response; + } + + @Override + public String getInitResponse() { + return initDocResponse; + } + + public InitDocUpload getInitDocUpload () { + return initDocUpload; + } + +} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/sp/InitDocUpload.java b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/sp/InitDocUpload.java index 02b4c37..7a2fb46 100644 --- a/src/main/java/com/indexdata/mkjsf/pazpar2/commands/sp/InitDocUpload.java +++ b/src/main/java/com/indexdata/mkjsf/pazpar2/commands/sp/InitDocUpload.java @@ -3,12 +3,11 @@ package com.indexdata.mkjsf.pazpar2.commands.sp; import java.io.IOException; import javax.enterprise.context.SessionScoped; -import javax.inject.Inject; import javax.inject.Named; import org.apache.log4j.Logger; -import com.indexdata.mkjsf.pazpar2.Pz2ProxyBean; +import com.indexdata.mkjsf.pazpar2.ServiceProxyExtensions; import com.indexdata.mkjsf.utils.FileUpload; import com.indexdata.mkjsf.utils.Utils; @@ -17,10 +16,14 @@ import com.indexdata.mkjsf.utils.Utils; public class InitDocUpload extends FileUpload { private static Logger logger = Logger.getLogger(InitDocUpload.class); - private static final long serialVersionUID = 1846749236304941323L; - @Inject Pz2ProxyBean spBean; + private static final long serialVersionUID = 1846749236304941323L; private boolean includeDebug = false; - + private ServiceProxyExtensions spBean; + + public InitDocUpload(ServiceProxyExtensions spBean) { + this.spBean = spBean; + } + public String submit() throws IOException { logger.info(Utils.objectId(this) + " submitting"); //String fileName = FilenameUtils.getName(uploadedFile.getName()); diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java deleted file mode 100644 index e52e797..0000000 --- a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyClient.java +++ /dev/null @@ -1,304 +0,0 @@ -package com.indexdata.mkjsf.pazpar2.sp; - -import static com.indexdata.mkjsf.utils.Utils.nl; - -import java.io.BufferedReader; -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 java.util.StringTokenizer; - -import org.apache.http.Header; -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.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.commands.sp.AuthCommand; -import com.indexdata.mkjsf.pazpar2.data.CommandError; -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 selectedServiceUrl = ""; - private List serviceUrls = new ArrayList(); - private List initDocPaths = null; - private Configuration config = null; - - ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler(); - private transient HttpClient client; - private Pazpar2Command checkAuth = null; - private Pazpar2Command ipAuth = null; - - 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); - serviceUrls = getMultiProperty(config.get(SERVICE_PROXY_URL),","); - if (serviceUrls.size()==1) { - selectedServiceUrl = serviceUrls.get(0); - } - this.initDocPaths = getMultiProperty(config.get(SP_INIT_DOC_PATHS),","); - checkAuth = new AuthCommand(null); - checkAuth.setParameterInState(new CommandParameter("action","=","check")); - ipAuth = new AuthCommand(null); - ipAuth.setParameterInState(new CommandParameter("action","=","ipauth")); - } catch (ConfigurationException c) { - // TODO: - c.printStackTrace(); - } - } - - private List getMultiProperty(String prop, String separator) { - List props = new ArrayList(); - if (prop != null) { - StringTokenizer tokenizer = new StringTokenizer(prop,separator); - while (tokenizer.hasMoreElements()) { - props.add(tokenizer.nextToken()); - } - } - return props; - } - - public boolean authenticate (ServiceProxyUser user) { - logger.info("Authenticating [" + user.getProperty("name") + "]"); - Pazpar2Command auth = new AuthCommand(null); - auth.setParametersInState(new CommandParameter("action","=","login"), - new CommandParameter("username","=",user.getProperty("name")), - new CommandParameter("password","=",user.getProperty("password"))); - ServiceProxyCommandResponse commandResponse = send(auth); - String responseStr = commandResponse.getResponseString(); - logger.info(responseStr); - if (responseStr.contains("FAIL")) { - user.credentialsAuthenticationSucceeded(false); - return false; - } else { - user.credentialsAuthenticationSucceeded(true); - return true; - } - } - - public boolean checkAuthentication (ServiceProxyUser user) { - ServiceProxyCommandResponse commandResponse = send(checkAuth); - String responseStr = commandResponse.getResponseString(); - logger.info(responseStr); - if (responseStr.contains("FAIL")) { - user.authenticationCheckFailed(); - return false; - } else { - return true; - } - } - - public boolean ipAuthenticate (ServiceProxyUser user) { - ServiceProxyCommandResponse commandResponse = send(ipAuth); - String responseStr = commandResponse.getResponseString(); - logger.info(responseStr); - if (responseStr.contains("FAIL")) { - user.ipAuthenticationSucceeded(false); - return false; - } else { - user.ipAuthenticationSucceeded(true); - return true; - } - } - - public boolean isAuthenticatingClient () { - return true; - } - - public boolean isAuthenticated (ServiceProxyUser user) { - if (user.getProperty("name") != null && user.getProperty("password") != null) { - return checkAuthentication(user); - } else { - return false; - } - } - - /** - * Makes the request - * @param request - * @return HTTP response as a String - * @throws ClientProtocolException - * @throws IOException - */ - private ServiceProxyCommandResponse send(Pazpar2Command command) { - ServiceProxyCommandResponse commandResponse = null; - String url = selectedServiceUrl + "?" + command.getEncodedQueryString(); - logger.info("Sending request "+url); - HttpGet httpget = new HttpGet(url); - byte[] response = null; - try { - response = client.execute(httpget, handler); - if (handler.getStatusCode()==200) { - commandResponse = new ServiceProxyCommandResponse(handler.getStatusCode(),response,handler.getContentType()); - } else { - logger.error("Service Proxy status code: " + handler.getStatusCode()); - commandResponse = new ServiceProxyCommandResponse(handler.getStatusCode(),CommandError.insertPazpar2ErrorXml(command.getCommandName(), "Service Proxy error occurred", new String(response,"UTF-8")),"text/xml"); - } - } catch (Exception e) { - e.printStackTrace(); - commandResponse = new ServiceProxyCommandResponse(-1,CommandError.createErrorXml(command.getCommandName(), e.getClass().getSimpleName(), (e.getMessage()!= null ? e.getMessage() : "") + (e.getCause()!=null ? e.getCause().getMessage() : "")),"text/xml"); - } - return commandResponse; - } - - public class ProxyPz2ResponseHandler implements ResponseHandler { - private StatusLine statusLine = null; - private Header contentType = 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); - contentType = response.getEntity().getContentType(); - } - EntityUtils.consume(entity); - return resp; - } - public int getStatusCode() { - return statusLine.getStatusCode(); - } - public String getReasonPhrase() { - return statusLine.getReasonPhrase(); - } - public String getContentType () { - return (contentType != null ? contentType.getValue() : "Content-Type not known"); - } - } - - 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) { - return send(command); - } - - public ServiceProxyClient cloneMe() { - logger.debug("Cloning Pz2Client"); - ServiceProxyClient clone = new ServiceProxyClient(); - clone.client = this.client; - clone.serviceUrls = this.serviceUrls; - clone.selectedServiceUrl = this.selectedServiceUrl; - 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: " + (selectedServiceUrl.length()>0 ? selectedServiceUrl : "[not defined yet]")); - return null; - } - - public ServiceProxyCommandResponse postInitDoc (String filePath) throws IOException { - logger.info("Looking to post the file in : [" + filePath +"]"); - HttpPost post = new HttpPost(selectedServiceUrl+"?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 new ServiceProxyCommandResponse(handler.getStatusCode(),response,handler.getContentType()); - } - - public List getInitDocPaths () { - logger.debug("Get init doc paths "); - logger.debug("length: " + initDocPaths.size()); - return initDocPaths; - } - - public ServiceProxyCommandResponse postInitDoc(byte[] initDoc, boolean includeDebug) throws IOException { - HttpPost post = new HttpPost(selectedServiceUrl+"?command=init" + (includeDebug? "&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 new ServiceProxyCommandResponse(handler.getStatusCode(),response,handler.getContentType()); - } - - public void setServiceProxyUrl (String url) { - selectedServiceUrl = url; - } - - public String getServiceProxyUrl () { - return selectedServiceUrl; - } - - public List getServiceProxyUrls () { - return serviceUrls; - } - - public Configuration getConfiguration () { - return config; - } - -} diff --git a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java b/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java deleted file mode 100644 index 74d5f75..0000000 --- a/src/main/java/com/indexdata/mkjsf/pazpar2/sp/ServiceProxyInterface.java +++ /dev/null @@ -1,17 +0,0 @@ -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 ServiceProxyCommandResponse postInit() throws UnsupportedEncodingException, IOException; - public ServiceProxyCommandResponse postInit(byte[] initDoc, boolean includeDebug) throws UnsupportedEncodingException, IOException; - public String getInitResponse(); - public void setServiceProxyUrl(String url); - public String getServiceProxyUrl(); -} -- 1.7.10.4