Renames class, removes obsolete, javadoc
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / mkjsf / pazpar2 / ServiceProxyClient.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.BufferedReader;\r
6 import java.io.File;\r
7 import java.io.FileReader;\r
8 import java.io.IOException;\r
9 import java.util.ArrayList;\r
10 import java.util.HashMap;\r
11 import java.util.List;\r
12 import java.util.Map;\r
13 \r
14 import org.apache.http.Header;\r
15 import org.apache.http.HttpEntity;\r
16 import org.apache.http.HttpResponse;\r
17 import org.apache.http.StatusLine;\r
18 import org.apache.http.client.ClientProtocolException;\r
19 import org.apache.http.client.HttpClient;\r
20 import org.apache.http.client.ResponseHandler;\r
21 import org.apache.http.client.methods.HttpGet;\r
22 import org.apache.http.client.methods.HttpPost;\r
23 import org.apache.http.conn.ClientConnectionManager;\r
24 import org.apache.http.conn.scheme.PlainSocketFactory;\r
25 import org.apache.http.conn.scheme.Scheme;\r
26 import org.apache.http.conn.scheme.SchemeRegistry;\r
27 import org.apache.http.entity.ByteArrayEntity;\r
28 import org.apache.http.entity.FileEntity;\r
29 import org.apache.http.impl.client.DefaultHttpClient;\r
30 import org.apache.http.impl.conn.PoolingClientConnectionManager;\r
31 import org.apache.http.util.EntityUtils;\r
32 import org.apache.log4j.Logger;\r
33 \r
34 import com.indexdata.mkjsf.config.Configuration;\r
35 import com.indexdata.mkjsf.config.ConfigurationReader;\r
36 import com.indexdata.mkjsf.errors.ConfigurationException;\r
37 import com.indexdata.mkjsf.errors.MissingConfigurationContextException;\r
38 import com.indexdata.mkjsf.pazpar2.commands.CommandParameter;\r
39 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;\r
40 import com.indexdata.mkjsf.pazpar2.commands.sp.AuthCommand;\r
41 import com.indexdata.mkjsf.pazpar2.data.CommandError;\r
42 import com.indexdata.mkjsf.utils.Utils;\r
43 \r
44 /**\r
45  * Search client handling Service Proxy requests. \r
46  *   \r
47  * @author Niels Erik\r
48  *\r
49  */\r
50 public class ServiceProxyClient implements SearchClient {\r
51     \r
52   private static final long serialVersionUID = -4031644009579840277L;\r
53   private static Logger logger = Logger.getLogger(ServiceProxyClient.class);\r
54   public static final String MODULENAME = "proxyclient";\r
55   \r
56   public static final String SP_INIT_DOC_PATHS = "SP_INIT_DOC_PATHS";\r
57   private String serviceUrl = "";\r
58   \r
59   private List<String> initDocPaths = null;\r
60   private Configuration config = null;\r
61   \r
62   ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler();\r
63   private transient HttpClient client;  \r
64   private Pazpar2Command checkAuth = null;\r
65   private Pazpar2Command ipAuth = null;\r
66 \r
67   public ServiceProxyClient () {\r
68     SchemeRegistry schemeRegistry = new SchemeRegistry();\r
69     schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));\r
70     ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);\r
71     client = new DefaultHttpClient(cm);\r
72   }\r
73     \r
74   @Override\r
75   public void configure (ConfigurationReader configReader) throws MissingConfigurationContextException {\r
76     logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
77     try {\r
78       config = configReader.getConfiguration(this);      \r
79       serviceUrl = config.get("SERVICE_PROXY_URL");\r
80       this.initDocPaths = config.getMultiProperty(SP_INIT_DOC_PATHS,",");\r
81       checkAuth = new AuthCommand();\r
82       checkAuth.setParameterInState(new CommandParameter("action","=","check"));\r
83       ipAuth = new AuthCommand();\r
84       ipAuth.setParameterInState(new CommandParameter("action","=","ipauth"));\r
85     } catch (MissingConfigurationContextException mcce) {\r
86       throw mcce;\r
87     } catch (ConfigurationException ce) {\r
88       logger.error("Failed to configure Service Proxy client");\r
89       ce.printStackTrace();\r
90     }\r
91   }\r
92     \r
93   public boolean isAuthenticatingClient () {\r
94     return true;\r
95   }\r
96     \r
97   /**\r
98    * Makes the request\r
99    * @param request\r
100    * @return HTTP response as a String\r
101    * @throws ClientProtocolException\r
102    * @throws IOException\r
103    */\r
104   public ClientCommandResponse send(Pazpar2Command command) {\r
105     ClientCommandResponse commandResponse = null;\r
106     String url = serviceUrl + "?" + command.getEncodedQueryString(); \r
107     logger.info("Sending request "+url);    \r
108     HttpGet httpget = new HttpGet(url);     \r
109     byte[] response = null;\r
110     try {\r
111       response = client.execute(httpget, handler);\r
112       if (handler.getStatusCode()==200 && (handler.getContentType().contains("xml") || handler.getContentType().contains("octet-stream"))) {\r
113         logger.trace("Creating command response holding content of type " + handler.getContentType());\r
114         commandResponse = new ClientCommandResponse(handler.getStatusCode(),response,handler.getContentType());\r
115       } else {\r
116         logger.error("Service Proxy status code: " + handler.getStatusCode());\r
117         String errorXml = "";\r
118         if (handler.getContentType().contains("xml")) {\r
119           errorXml = CommandError.insertErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), "Service Proxy error: "+handler.getStatusCode(), new String(response,"UTF-8"));        \r
120         } else {\r
121           if (handler.getContentType().contains("html")) {\r
122             String htmlStrippedOfTags = (new String(response,"UTF-8")).replaceAll("\\<[^>]*>","");\r
123             if (htmlStrippedOfTags.toLowerCase().contains("domain")) {\r
124               errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), "Unexpected response type from Service Proxy", "Expected XML from SP but got HTML. It contains the word domain suggesting that the service address was not found.", htmlStrippedOfTags);              \r
125             } else {\r
126               errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), "Unexpected response type from Service Proxy", "Expected XML from SP but got HTML", htmlStrippedOfTags);              \r
127             }\r
128           } else {\r
129             errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), "Unexpected response type from Service Proxy: "+handler.getContentType(), "Could not process non-XML response from Service Proxy", new String(response,"UTF-8"));\r
130           }          \r
131         }\r
132         commandResponse = new ClientCommandResponse(handler.getStatusCode(),errorXml,handler.getContentType());\r
133       }       \r
134     } catch (Exception e) {\r
135       e.printStackTrace();\r
136       commandResponse = new ClientCommandResponse(handler.getStatusCode(),CommandError.createErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), e.getClass().getSimpleName(), (e.getMessage()!= null ? e.getMessage() : "") + (e.getCause()!=null ? e.getCause().getMessage() : ""), e.getStackTrace().toString()),handler.getContentType());\r
137     }\r
138     return commandResponse; \r
139   }\r
140   \r
141   public class ProxyPz2ResponseHandler implements ResponseHandler<byte[]> {\r
142     private StatusLine statusLine = null;\r
143     private Header contentType = null;\r
144     public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {\r
145       byte[] resp = null;\r
146       HttpEntity entity = response.getEntity();      \r
147       statusLine = response.getStatusLine();\r
148       if (entity != null) {        \r
149         resp = EntityUtils.toByteArray(entity);        \r
150         contentType = response.getEntity().getContentType();        \r
151       }       \r
152       EntityUtils.consume(entity);      \r
153       return resp;\r
154     }\r
155     public int getStatusCode() {\r
156       return statusLine.getStatusCode();\r
157     }    \r
158     public String getReasonPhrase() {\r
159       return statusLine.getReasonPhrase();\r
160     }\r
161     public String getContentType () {\r
162       return (contentType != null ? contentType.getValue() : "Content-Type not known"); \r
163     }\r
164   }\r
165 \r
166   public int getStatusCode () {\r
167     return handler.getStatusCode();\r
168   }\r
169   \r
170   public String getReasonPhrase() {\r
171     return handler.getReasonPhrase();\r
172   }\r
173 \r
174   /**\r
175    * Does nothing in Service Proxy context\r
176    */\r
177   @Override\r
178   public void setSearchCommand(Pazpar2Command command) {\r
179     // Do nothing, Service Proxy is handling this    \r
180   }\r
181 \r
182   @Override\r
183   public HttpResponseWrapper executeCommand(Pazpar2Command command) {\r
184     return send(command);\r
185   }\r
186 \r
187   public ServiceProxyClient cloneMe() {\r
188     logger.debug("Cloning Pz2Client");\r
189     ServiceProxyClient clone = new ServiceProxyClient();\r
190     clone.client = this.client;\r
191     clone.serviceUrl = this.serviceUrl;\r
192     clone.initDocPaths = this.initDocPaths;\r
193     return clone;\r
194   }\r
195 \r
196   /**\r
197    * Returns default configuration parameters for the client.\r
198    */\r
199   @Override\r
200   public Map<String, String> getDefaults() {    \r
201     return new HashMap<String,String>();\r
202   }\r
203 \r
204   /**\r
205    * Returns the configuration name of the client\r
206    */\r
207   @Override\r
208   public String getModuleName() {\r
209     return MODULENAME;\r
210   }\r
211   \r
212   @Override\r
213   public List<String> documentConfiguration () {\r
214     List<String> doc = new ArrayList<String>();\r
215     doc.add(nl+ MODULENAME + " was configured to access the Pazpar2 service proxy at: " + (serviceUrl.length()>0 ? serviceUrl : "[not defined yet]"));\r
216     return null;\r
217   }\r
218   \r
219   public ClientCommandResponse postInitDoc (String filePath) throws IOException {\r
220     logger.info("Looking to post the file in : [" + filePath +"]");\r
221     HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes");\r
222     File initDoc = new File(filePath);\r
223     logger.info("Posting to SP: ");\r
224     if (logger.isDebugEnabled()) {\r
225       BufferedReader reader = new BufferedReader(new FileReader(initDoc));\r
226       String line;\r
227       while ( (line = reader.readLine()) != null) {\r
228         System.out.println(line);\r
229       }\r
230       reader.close();\r
231     }\r
232     post.setEntity(new FileEntity(initDoc));\r
233     byte[] response = client.execute(post, handler);\r
234     logger.debug("Response on POST was: " + new String(response,"UTF-8"));    \r
235     return new ClientCommandResponse(handler.getStatusCode(),response,handler.getContentType());    \r
236   }\r
237   \r
238   public List<String> getInitDocPaths () {\r
239     logger.debug("Get init doc paths ");\r
240     logger.debug("length: " + initDocPaths.size());\r
241     return initDocPaths;\r
242   }\r
243   \r
244   public HttpResponseWrapper postInitDoc(byte[] initDoc, boolean includeDebug) {\r
245     HttpPost post = new HttpPost(serviceUrl+"?command=init" + (includeDebug? "&includeDebug=yes" : ""));\r
246     post.setEntity(new ByteArrayEntity(initDoc));\r
247     ClientCommandResponse commandResponse = null;\r
248     byte[] response;\r
249     try {\r
250       response = client.execute(post, handler);\r
251       if (handler.getStatusCode()==200) {\r
252         commandResponse = new ClientCommandResponse(handler.getStatusCode(),response,handler.getContentType());\r
253       } else {\r
254         logger.error("Service Proxy status code: " + handler.getStatusCode());\r
255         commandResponse = new ClientCommandResponse(handler.getStatusCode(),CommandError.insertErrorXml("init", String.valueOf(handler.getStatusCode()), "Service Proxy error: "+handler.getStatusCode(), new String(response,"UTF-8")),"text/xml");                               \r
256       }\r
257     } catch (ClientProtocolException e) {\r
258       logger.error(e.getMessage());\r
259       e.printStackTrace();\r
260       commandResponse = new ClientCommandResponse(-1,CommandError.createErrorXml("init", String.valueOf(handler.getStatusCode()), "Client protocol exception", e.getMessage(), e.getStackTrace().toString()),"text/xml");      \r
261     } catch (IOException e) {\r
262       logger.error(e.getMessage());\r
263       e.printStackTrace();\r
264       commandResponse = new ClientCommandResponse(-1,CommandError.createErrorXml("init", String.valueOf(handler.getStatusCode()), "IO exception", e.getMessage(),e.getStackTrace().toString()),"text/xml");      \r
265     }\r
266     return commandResponse;    \r
267   }\r
268   \r
269   /**\r
270    * Sets the URL of the Service Proxy that should service requests. \r
271    */\r
272   public void setServiceUrl (String url) {    \r
273     serviceUrl = url;\r
274   }\r
275           \r
276   public Configuration getConfiguration () {\r
277     return config;\r
278   }\r
279 \r
280   @Override\r
281   public String getServiceUrl() {    \r
282     return serviceUrl;\r
283   }\r
284 \r
285   /**\r
286    * Returns true if a Service Proxy URL was defined yet.\r
287    */\r
288   @Override\r
289   public boolean hasServiceUrl() {\r
290     return serviceUrl != null && serviceUrl.length()>0;\r
291   }\r
292   \r
293 }\r