Merge branch 'master' of ssh://git.indexdata.com/home/git/private/mkjsf.git into...
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / Pz2Client.java
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 (file)
index 0000000..3417a47
--- /dev/null
@@ -0,0 +1,266 @@
+package com.indexdata.mkjsf.pazpar2;\r
+\r
+import static com.indexdata.mkjsf.utils.Utils.nl;\r
+\r
+import java.io.ByteArrayOutputStream;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import org.apache.log4j.Logger;\r
+\r
+import com.indexdata.masterkey.config.MissingMandatoryParameterException;\r
+import com.indexdata.masterkey.config.ModuleConfigurationGetter;\r
+import com.indexdata.masterkey.pazpar2.client.ClientCommand;\r
+import com.indexdata.masterkey.pazpar2.client.Pazpar2Client;\r
+import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientConfiguration;\r
+import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientGeneric;\r
+import com.indexdata.masterkey.pazpar2.client.Pazpar2HttpResponse;\r
+import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException;\r
+import com.indexdata.masterkey.pazpar2.client.exceptions.ProxyErrorException;\r
+import com.indexdata.mkjsf.config.Configuration;\r
+import com.indexdata.mkjsf.config.ConfigurationReader;\r
+import com.indexdata.mkjsf.errors.ConfigurationException;\r
+import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;\r
+import com.indexdata.mkjsf.pazpar2.data.CommandError;\r
+import com.indexdata.mkjsf.utils.Utils;\r
+\r
+/**\r
+ * Search client handling straight Pazpar2 requests. \r
+ * \r
+ * <p>Although it is described here as straight Pazpar2, the client itself \r
+ * actually represents a layer between Pazpar2 and the JSF application because it \r
+ * uses the Pazpar2 client from the library masterkey-common.</p>\r
+ * That client, which is the one also used by the Service Proxy, does perform certain \r
+ * types of session handling, bootstraps lost sessions, avoids repeating already \r
+ * executed queries etc, so it is -- in other words -- still a mediated interaction \r
+ * with Pazpar2 that takes place. At least for now.</p>  \r
+ *  \r
+ * @author Niels Erik\r
+ *\r
+ */\r
+public class Pz2Client implements SearchClient {\r
+\r
+  private static final long serialVersionUID = 5414266730169982028L;\r
+  private static Logger logger = Logger.getLogger(Pz2Client.class);\r
+  private transient Pazpar2Client client = null;\r
+  private Pazpar2ClientConfiguration cfg = null;\r
+  public static final String MODULENAME = "pz2client";\r
+  public static Map<String,String> DEFAULTS = new HashMap<String,String>();\r
+  Configuration config = null;  \r
+  \r
+  static {    \r
+    DEFAULTS.put("PAZPAR2_URL", "");\r
+    DEFAULTS.put("PROXY_MODE","1");\r
+    DEFAULTS.put("SERIALIZE_REQUESTS", "false");\r
+    DEFAULTS.put("STREAMBUFF_SIZE", "4096");\r
+    DEFAULTS.put("PARSE_RESPONSES", "true");    \r
+  }\r
+  \r
+  public Pz2Client() {}\r
+  \r
+  @Override\r
+  public void configure(ConfigurationReader configReader) throws ConfigurationException {    \r
+    logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
+    try {\r
+      config = configReader.getConfiguration(this);      \r
+      cfg = new Pazpar2ClientConfiguration(new ConfigurationGetter(config));\r
+    } catch (ProxyErrorException pe) {\r
+      logger.error("Could not configure Pazpar2 client: " + pe.getMessage());\r
+      throw new ConfigurationException("Could not configure Pz2Client:  "+ pe.getMessage(),pe);\r
+    } \r
+    if (cfg != null) {\r
+      try {\r
+        client = new Pazpar2ClientGeneric(cfg);        \r
+      } catch (ProxyErrorException pe) {\r
+        logger.error("Could not configure Pazpar2 client: " + pe.getMessage());\r
+        throw new ConfigurationException("Could not configure Pz2Client:  "+ pe.getMessage(),pe);\r
+      }\r
+    } else {\r
+      logger.error("There was a problem creating Pz2Client. Client is null after configuration.");\r
+      throw new ConfigurationException("Pazpar2Client is null after configuration");\r
+    } \r
+  }\r
+  \r
+  public boolean isAuthenticatingClient () {\r
+    return false;\r
+  }\r
+  \r
+  public boolean isAuthenticated() {\r
+    return false;\r
+  }\r
+  \r
+  public boolean authenticate() {\r
+    throw new UnsupportedOperationException("No authentication mechanism for straight pazpar2 client");\r
+  }\r
+  \r
+  @Override\r
+  public void setSearchCommand(Pazpar2Command command) {\r
+    ClientCommand clientCommand = new ClientCommand(command.getCommandName(), command.getEncodedQueryString());\r
+    client.setSearchCommand(clientCommand);    \r
+  }\r
+\r
+  /**\r
+   * Runs the give Pazpar2 command and returns a response wrapper with either the received response or \r
+   * with some form of error message. \r
+   * \r
+   * It is intended that this method never throws an exception. All events are supposed to be captured and\r
+   * returned in some form of response. \r
+   */\r
+  @Override\r
+  public HttpResponseWrapper executeCommand(Pazpar2Command command) {\r
+    ClientCommandResponse commandResponse = null;\r
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
+    ClientCommand clientCommand = new ClientCommand(command.getCommandName(), command.getEncodedQueryString());\r
+    Pazpar2HttpResponse pz2HttpResponse = null;\r
+    long start = System.currentTimeMillis();\r
+    try {\r
+      pz2HttpResponse = client.executeCommand(clientCommand, baos);\r
+      if (pz2HttpResponse.getStatusCode()==200 && pz2HttpResponse.getContentType().contains("xml")) {\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse,baos);\r
+      } else if (pz2HttpResponse.getStatusCode()==200 && pz2HttpResponse.getContentType().contains("octet-stream")) {\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse,baos);\r
+        logger.info("Content type: " + commandResponse.getContentType() + ". isBinary?: " + commandResponse.isBinary());\r
+      } else if (pz2HttpResponse.getStatusCode()==417) {\r
+        logger.error("Pazpar2 status code 417: " + baos.toString("UTF-8"));\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()) ,"Pazpar2: Expectation failed (417)", baos.toString("UTF-8")),"text/xml");                       \r
+      } else if (pz2HttpResponse.getContentType().contains("html")) {\r
+        String resp = baos.toString("UTF-8");\r
+        logger.error("HTML response where XML was expected. Status code was " + pz2HttpResponse.getStatusCode() + ": " + resp);\r
+        String htmlStrippedOfTags = resp.replaceAll("\\<[^>]*>","");\r
+        String errorXml = "";\r
+        if (htmlStrippedOfTags.toLowerCase().contains("domain")) {\r
+          errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "Unexpected response type from Pazpar2", "Error: Expected XML response from Pazpar2 but got HTML. The HTML contains the word domain suggesting that the Pazpar2 address was not found.", htmlStrippedOfTags);\r
+        } else {  \r
+          errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "Unexpected response type from Pazpar2: " + pz2HttpResponse.getContentType(),"Expected XML response from Pazpar2, got HTML", htmlStrippedOfTags);\r
+        } \r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),errorXml,pz2HttpResponse.getContentType());        \r
+      } else {\r
+        String resp = baos.toString("UTF-8");\r
+        logger.error("Pazpar2 status code was " + pz2HttpResponse.getStatusCode() + ": " + resp);\r
+        commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "Pazpar2 error occurred", baos.toString("UTF-8")),"text/xml");        \r
+      }       \r
+    } catch (IOException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+      commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.createErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "IO exception", e.getMessage(), ""),"text/xml");      \r
+    } catch (Pazpar2ErrorException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+      logger.error("Creating error XML");\r
+      commandResponse = new ClientCommandResponse(0,CommandError.createErrorXml(command.getCommandName(), "", "ServiceError", e.getMessage(),""),"text/xml");\r
+    }\r
+    long end = System.currentTimeMillis();      \r
+    logger.info("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );\r
+    return commandResponse;\r
+  }\r
+\r
+  public Pz2Client cloneMe() {\r
+    logger.debug("Cloning Pz2Client");\r
+    Pz2Client clone = new Pz2Client();\r
+    clone.client = this.client;\r
+    clone.cfg = this.cfg;\r
+    return clone;\r
+  }\r
+\r
+  /**\r
+   * Returns default configuration parameters for the client.\r
+   */\r
+  @Override\r
+  public Map<String, String> getDefaults() {\r
+    return DEFAULTS;\r
+  }\r
+\r
+  /**\r
+   * Returns the configuration name of the client\r
+   */\r
+  @Override\r
+  public String getModuleName() {\r
+    return MODULENAME;\r
+  }\r
+  \r
+  class ConfigurationGetter implements ModuleConfigurationGetter {\r
+    Configuration config = null;\r
+    ConfigurationGetter(Configuration configuration) {\r
+      config = configuration;\r
+    }\r
+    @Override\r
+    public String get(String value) {\r
+      return config.get(value);\r
+    }\r
+    @Override\r
+    public String get(String value, String defaultValue) {\r
+      return config.get(value,defaultValue);\r
+    }\r
+    @Override\r
+    public String getMandatory(String name)\r
+        throws MissingMandatoryParameterException {\r
+      return config.getMandatory(name);\r
+    }\r
+    @Override\r
+    public String getConfigFilePath() {\r
+      return config.getConfigFilePath();\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Provides configuration documentation -- mostly for diagnosing problems   \r
+   */\r
+  @Override\r
+  public List<String> documentConfiguration() {\r
+    List<String> doc = new ArrayList<String>();\r
+    doc.add(nl+ MODULENAME + " was configured to access Pazpar2 at : " + cfg.PAZPAR2_URL);    \r
+    return new ArrayList<String>();\r
+  }\r
+  \r
+  public Configuration getConfiguration () {\r
+    return config;\r
+  }\r
+\r
+  /**\r
+   * Returns the currently configured Papzar2 URL.\r
+   */\r
+  @Override\r
+  public String getServiceUrl() {\r
+    return cfg.PAZPAR2_URL;    \r
+  }\r
+\r
+  /**\r
+   * Returns true if a Papzar2 URL was defined yet. \r
+   */\r
+  @Override\r
+  public boolean hasServiceUrl() {\r
+    return cfg.PAZPAR2_URL != null && cfg.PAZPAR2_URL.length()>0;\r
+  }\r
+  \r
+  /**\r
+   * Sets the Pazpar2 URL to use for requests. \r
+   */\r
+  @Override \r
+  public void setServiceUrl (String serviceUrl) {    \r
+    cfg.PAZPAR2_URL = serviceUrl;    \r
+  }\r
+  \r
+  /**\r
+   * Returns the Pazpar2 Service ID \r
+   */\r
+  public String getServiceId () {\r
+    return cfg.PAZPAR2_SERVICE_ID;\r
+  }\r
+  \r
+  /**\r
+   * Sets the service ID that Pazpar2 should use when servicing requests\r
+   * @param serviceId\r
+   */\r
+  public void setServiceId(String serviceId) {\r
+    cfg.PAZPAR2_SERVICE_ID = serviceId;\r
+    try {\r
+      client = new Pazpar2ClientGeneric(cfg);  \r
+    } catch (ProxyErrorException pe) {\r
+      logger.error("Could not configure Pazpar2 client: " + pe.getMessage());      \r
+    }\r
+  }\r
+\r
+}\r