Documents configuration schemes in more detail
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / Pz2Client.java
1 package com.indexdata.mkjsf.pazpar2;\r
2 \r
3 import static com.indexdata.mkjsf.utils.Utils.nl;\r
4 \r
5 import java.io.ByteArrayOutputStream;\r
6 import java.io.IOException;\r
7 import java.util.ArrayList;\r
8 import java.util.HashMap;\r
9 import java.util.List;\r
10 import java.util.Map;\r
11 \r
12 import org.apache.log4j.Logger;\r
13 \r
14 import com.indexdata.masterkey.config.MissingMandatoryParameterException;\r
15 import com.indexdata.masterkey.config.ModuleConfigurationGetter;\r
16 import com.indexdata.masterkey.pazpar2.client.ClientCommand;\r
17 import com.indexdata.masterkey.pazpar2.client.Pazpar2Client;\r
18 import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientConfiguration;\r
19 import com.indexdata.masterkey.pazpar2.client.Pazpar2ClientGeneric;\r
20 import com.indexdata.masterkey.pazpar2.client.Pazpar2HttpResponse;\r
21 import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException;\r
22 import com.indexdata.masterkey.pazpar2.client.exceptions.ProxyErrorException;\r
23 import com.indexdata.mkjsf.config.Configuration;\r
24 import com.indexdata.mkjsf.config.ConfigurationReader;\r
25 import com.indexdata.mkjsf.errors.ConfigurationException;\r
26 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;\r
27 import com.indexdata.mkjsf.pazpar2.data.CommandError;\r
28 import com.indexdata.mkjsf.utils.Utils;\r
29 \r
30 /**\r
31  * Search client handling straight Pazpar2 requests. \r
32  * \r
33  * <p>Although it is described here as straight Pazpar2, the client itself \r
34  * actually represents a layer between Pazpar2 and the JSF application because it \r
35  * uses the Pazpar2 client from the library masterkey-common.</p>\r
36  * That client, which is the one also used by the Service Proxy, does perform certain \r
37  * types of session handling, bootstraps lost sessions, avoids repeating already \r
38  * executed queries etc, so it is -- in other words -- still a mediated interaction \r
39  * with Pazpar2 that takes place. At least for now.</p>  \r
40  * \r
41  * <h3>Configuration</h3>\r
42  *\r
43  * Configuration name: pz2client.\r
44  *  \r
45  * <p>When configuring the client using the Mk2Config scheme, this is the prefix to\r
46  * use in the .properties file. When using web.xml context parameters for configuration\r
47  * the configuration name has no effect.</p> \r
48  * \r
49  * <p>Pz2Client will acknowledge following configuration parameters:\r
50  * \r
51  * <ul>\r
52  *  <li>(pz2client.)PAZPAR2_URL</li>\r
53  *  <li>(pz2client.)SERVICE_ID</li>\r
54  * </ul> \r
55  *  \r
56  * @author Niels Erik\r
57  *\r
58  */\r
59 public class Pz2Client implements SearchClient {\r
60 \r
61   private static final long serialVersionUID = 5414266730169982028L;\r
62   private static Logger logger = Logger.getLogger(Pz2Client.class);\r
63   private transient Pazpar2Client client = null;\r
64   private Pazpar2ClientConfiguration cfg = null;\r
65   public static final String MODULENAME = "pz2client";\r
66   \r
67   /**\r
68    * PAZPAR2_URL=none, PROXY_MODE=1, SERIALIZE_REQUESTS=false, STREAMBUFF_SIZE=4096, PARSE_RESPONSES=true\r
69    */\r
70   public static Map<String,String> DEFAULTS = new HashMap<String,String>();\r
71   Configuration config = null;  \r
72   \r
73   static {    \r
74     DEFAULTS.put("PAZPAR2_URL", "");\r
75     DEFAULTS.put("PROXY_MODE","1");\r
76     DEFAULTS.put("SERIALIZE_REQUESTS", "false");\r
77     DEFAULTS.put("STREAMBUFF_SIZE", "4096");\r
78     DEFAULTS.put("PARSE_RESPONSES", "true");    \r
79   }\r
80   \r
81   public Pz2Client() {}\r
82   \r
83   @Override\r
84   public void configure(ConfigurationReader configReader) throws ConfigurationException {    \r
85     logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
86     try {\r
87       config = configReader.getConfiguration(this);      \r
88       cfg = new Pazpar2ClientConfiguration(new ConfigurationGetter(config));\r
89     } catch (ProxyErrorException pe) {\r
90       logger.error("Could not configure Pazpar2 client: " + pe.getMessage());\r
91       throw new ConfigurationException("Could not configure Pz2Client:  "+ pe.getMessage(),pe);\r
92     } \r
93     if (cfg != null) {\r
94       try {\r
95         client = new Pazpar2ClientGeneric(cfg);        \r
96       } catch (ProxyErrorException pe) {\r
97         logger.error("Could not configure Pazpar2 client: " + pe.getMessage());\r
98         throw new ConfigurationException("Could not configure Pz2Client:  "+ pe.getMessage(),pe);\r
99       }\r
100     } else {\r
101       logger.error("There was a problem creating Pz2Client. Client is null after configuration.");\r
102       throw new ConfigurationException("Pazpar2Client is null after configuration");\r
103     } \r
104   }\r
105   \r
106   public boolean isAuthenticatingClient () {\r
107     return false;\r
108   }\r
109   \r
110   public boolean isAuthenticated() {\r
111     return false;\r
112   }\r
113   \r
114   public boolean authenticate() {\r
115     throw new UnsupportedOperationException("No authentication mechanism for straight pazpar2 client");\r
116   }\r
117   \r
118   @Override\r
119   public void setSearchCommand(Pazpar2Command command) {\r
120     ClientCommand clientCommand = new ClientCommand(command.getCommandName(), command.getEncodedQueryString());\r
121     client.setSearchCommand(clientCommand);    \r
122   }\r
123 \r
124   /**\r
125    * Runs the give Pazpar2 command and returns a response wrapper with either the received response or \r
126    * with some form of error message. \r
127    * \r
128    * It is intended that this method never throws an exception. All events are supposed to be captured and\r
129    * returned in some form of response. \r
130    */\r
131   @Override\r
132   public HttpResponseWrapper executeCommand(Pazpar2Command command) {\r
133     ClientCommandResponse commandResponse = null;\r
134     ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
135     ClientCommand clientCommand = new ClientCommand(command.getCommandName(), command.getEncodedQueryString());\r
136     Pazpar2HttpResponse pz2HttpResponse = null;\r
137     long start = System.currentTimeMillis();\r
138     try {\r
139       pz2HttpResponse = client.executeCommand(clientCommand, baos);\r
140       if (pz2HttpResponse.getStatusCode()==200 && pz2HttpResponse.getContentType().contains("xml")) {\r
141         commandResponse = new ClientCommandResponse(pz2HttpResponse,baos);\r
142       } else if (pz2HttpResponse.getStatusCode()==200 && pz2HttpResponse.getContentType().contains("octet-stream")) {\r
143         commandResponse = new ClientCommandResponse(pz2HttpResponse,baos);\r
144         logger.info("Content type: " + commandResponse.getContentType() + ". isBinary?: " + commandResponse.isBinary());\r
145       } else if (pz2HttpResponse.getStatusCode()==417) {\r
146         logger.error("Pazpar2 status code 417: " + baos.toString("UTF-8"));\r
147         commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()) ,"Pazpar2: Expectation failed (417)", baos.toString("UTF-8")),"text/xml");                       \r
148       } else if (pz2HttpResponse.getContentType().contains("html")) {\r
149         String resp = baos.toString("UTF-8");\r
150         logger.error("HTML response where XML was expected. Status code was " + pz2HttpResponse.getStatusCode() + ": " + resp);\r
151         String htmlStrippedOfTags = resp.replaceAll("\\<[^>]*>","");\r
152         String errorXml = "";\r
153         if (htmlStrippedOfTags.toLowerCase().contains("domain")) {\r
154           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
155         } else {  \r
156           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
157         } \r
158         commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),errorXml,pz2HttpResponse.getContentType());        \r
159       } else {\r
160         String resp = baos.toString("UTF-8");\r
161         logger.error("Pazpar2 status code was " + pz2HttpResponse.getStatusCode() + ": " + resp);\r
162         commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.insertErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "Pazpar2 error occurred", baos.toString("UTF-8")),"text/xml");        \r
163       }       \r
164     } catch (IOException e) {\r
165       logger.error(e.getMessage());\r
166       e.printStackTrace();\r
167       commandResponse = new ClientCommandResponse(pz2HttpResponse.getStatusCode(),CommandError.createErrorXml(command.getCommandName(), String.valueOf(pz2HttpResponse.getStatusCode()), "IO exception", e.getMessage(), ""),"text/xml");      \r
168     } catch (Pazpar2ErrorException e) {\r
169       logger.error(e.getMessage());\r
170       e.printStackTrace();\r
171       logger.error("Creating error XML");\r
172       commandResponse = new ClientCommandResponse(0,CommandError.createErrorXml(command.getCommandName(), "", "ServiceError", e.getMessage(),""),"text/xml");\r
173     }\r
174     long end = System.currentTimeMillis();      \r
175     logger.info("Executed " + command.getCommandName() + " in " + (end-start) + " ms." );\r
176     return commandResponse;\r
177   }\r
178 \r
179   public Pz2Client cloneMe() {\r
180     logger.debug("Cloning Pz2Client");\r
181     Pz2Client clone = new Pz2Client();\r
182     clone.client = this.client;\r
183     clone.cfg = this.cfg;\r
184     return clone;\r
185   }\r
186 \r
187   /**\r
188    * Returns default configuration parameters for the client.\r
189    */\r
190   @Override\r
191   public Map<String, String> getDefaults() {\r
192     return DEFAULTS;\r
193   }\r
194 \r
195   /**\r
196    * Returns the configuration name of the client\r
197    */\r
198   @Override\r
199   public String getModuleName() {\r
200     return MODULENAME;\r
201   }\r
202   \r
203   class ConfigurationGetter implements ModuleConfigurationGetter {\r
204     Configuration config = null;\r
205     ConfigurationGetter(Configuration configuration) {\r
206       config = configuration;\r
207     }\r
208     @Override\r
209     public String get(String value) {\r
210       return config.get(value);\r
211     }\r
212     @Override\r
213     public String get(String value, String defaultValue) {\r
214       return config.get(value,defaultValue);\r
215     }\r
216     @Override\r
217     public String getMandatory(String name)\r
218         throws MissingMandatoryParameterException {\r
219       return config.getMandatory(name);\r
220     }\r
221     @Override\r
222     public String getConfigFilePath() {\r
223       return config.getConfigFilePath();\r
224     }\r
225   }\r
226 \r
227   /**\r
228    * Provides configuration documentation -- mostly for diagnosing problems   \r
229    */\r
230   @Override\r
231   public List<String> documentConfiguration() {\r
232     List<String> doc = new ArrayList<String>();\r
233     doc.add(nl+ MODULENAME + " was configured to access Pazpar2 at : " + cfg.PAZPAR2_URL);    \r
234     return new ArrayList<String>();\r
235   }\r
236   \r
237   public Configuration getConfiguration () {\r
238     return config;\r
239   }\r
240 \r
241   /**\r
242    * Returns the currently configured Papzar2 URL.\r
243    */\r
244   @Override\r
245   public String getServiceUrl() {\r
246     return cfg.PAZPAR2_URL;    \r
247   }\r
248 \r
249   /**\r
250    * Returns true if a Papzar2 URL was defined yet. \r
251    */\r
252   @Override\r
253   public boolean hasServiceUrl() {\r
254     return cfg.PAZPAR2_URL != null && cfg.PAZPAR2_URL.length()>0;\r
255   }\r
256   \r
257   /**\r
258    * Sets the Pazpar2 URL to use for requests. \r
259    */\r
260   @Override \r
261   public void setServiceUrl (String serviceUrl) {    \r
262     cfg.PAZPAR2_URL = serviceUrl;    \r
263   }\r
264   \r
265   /**\r
266    * Returns the Pazpar2 Service ID \r
267    */\r
268   public String getServiceId () {\r
269     return cfg.PAZPAR2_SERVICE_ID;\r
270   }\r
271   \r
272   /**\r
273    * Sets the service ID that Pazpar2 should use when servicing requests\r
274    * @param serviceId\r
275    */\r
276   public void setServiceId(String serviceId) {\r
277     cfg.PAZPAR2_SERVICE_ID = serviceId;\r
278     try {\r
279       client = new Pazpar2ClientGeneric(cfg);  \r
280     } catch (ProxyErrorException pe) {\r
281       logger.error("Could not configure Pazpar2 client: " + pe.getMessage());      \r
282     }\r
283   }\r
284 \r
285 }\r