Moves response objects from pz2 bean to dedicated bean
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / pz2utils4jsf / pazpar2 / sp / ServiceProxyClient.java
1 package com.indexdata.pz2utils4jsf.pazpar2.sp;\r
2 \r
3 import static com.indexdata.pz2utils4jsf.utils.Utils.nl;\r
4 \r
5 import java.io.BufferedReader;\r
6 import java.io.ByteArrayOutputStream;\r
7 import java.io.File;\r
8 import java.io.FileReader;\r
9 import java.io.IOException;\r
10 import java.util.ArrayList;\r
11 import java.util.HashMap;\r
12 import java.util.List;\r
13 import java.util.Map;\r
14 \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.masterkey.config.MissingMandatoryParameterException;\r
35 import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException;\r
36 import com.indexdata.pz2utils4jsf.config.Configuration;\r
37 import com.indexdata.pz2utils4jsf.config.ConfigurationReader;\r
38 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;\r
39 import com.indexdata.pz2utils4jsf.pazpar2.CommandResponse;\r
40 import com.indexdata.pz2utils4jsf.pazpar2.SearchClient;\r
41 import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandParameter;\r
42 import com.indexdata.pz2utils4jsf.pazpar2.commands.CommandReadOnly;\r
43 import com.indexdata.pz2utils4jsf.pazpar2.commands.Pazpar2Command;\r
44 import com.indexdata.pz2utils4jsf.pazpar2.sp.auth.AuthenticationEntity;\r
45 import com.indexdata.pz2utils4jsf.pazpar2.sp.auth.ServiceProxyUser;\r
46 import com.indexdata.pz2utils4jsf.utils.Utils;\r
47 \r
48 \r
49 public class ServiceProxyClient implements SearchClient {\r
50     \r
51   private static final long serialVersionUID = -4031644009579840277L;\r
52   private static Logger logger = Logger.getLogger(ServiceProxyClient.class);\r
53   public static final String MODULENAME = "proxyclient";\r
54   public static final String SERVICE_PROXY_URL = "SERVICE_PROXY_URL";\r
55   public static final String SP_INIT_DOC_PATHS = "SP_INIT_DOC_PATHS";\r
56   private String serviceUrl = "undefined";\r
57   private String[] initDocPaths = null;\r
58   private Configuration config = null;\r
59   \r
60   ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler();\r
61   private HttpClient client;\r
62   private ServiceProxyUser user;\r
63 \r
64   public ServiceProxyClient () {\r
65     SchemeRegistry schemeRegistry = new SchemeRegistry();\r
66     schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));\r
67     ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);\r
68     client = new DefaultHttpClient(cm);    \r
69   }\r
70     \r
71   @Override\r
72   public void configure (ConfigurationReader configReader) {\r
73     logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
74     try {\r
75       config = configReader.getConfiguration(this);      \r
76       serviceUrl = config.getMandatory(SERVICE_PROXY_URL);  \r
77       this.initDocPaths = getMultiProperty(config.get(SP_INIT_DOC_PATHS));            \r
78     } catch (ConfigurationException c) {\r
79       c.printStackTrace();\r
80     } catch (MissingMandatoryParameterException mmp) {\r
81       mmp.printStackTrace();\r
82     }    \r
83   }\r
84   \r
85   private String[] getMultiProperty(String prop) {    \r
86     if (prop != null) {\r
87       return prop.split(",");\r
88     } else {\r
89       return null;\r
90     }\r
91   }\r
92   \r
93   public boolean authenticate (AuthenticationEntity user) {\r
94     try {      \r
95       logger.info("Authenticating [" + user.getProperty("name") + "]");\r
96       this.user = (ServiceProxyUser) user;\r
97       Pazpar2Command auth = new Pazpar2Command("auth",null);\r
98       auth.setParameters(new CommandParameter("action","=","login"), \r
99                          new CommandParameter("username","=",user.getProperty("name")), \r
100                          new CommandParameter("password","=",user.getProperty("password")));\r
101       byte[] response = send(auth);\r
102       String responseStr = new String(response,"UTF-8");\r
103       logger.info(responseStr);      \r
104       if (responseStr.contains("FAIL")) {\r
105         return false;\r
106       } else {\r
107         return true;\r
108       }      \r
109     } catch (ClientProtocolException e) {\r
110       // TODO Auto-generated catch block\r
111       e.printStackTrace();\r
112       return false;\r
113     } catch (IOException e) {\r
114       // TODO Auto-generated catch block\r
115       e.printStackTrace();\r
116       return false;\r
117     }        \r
118   }\r
119   \r
120   public boolean checkAuthentication () {\r
121     try {\r
122       Pazpar2Command check = new Pazpar2Command("auth",null);\r
123       check.setParameter(new CommandParameter("action","=","check"));\r
124       byte[] response = send(check);\r
125       logger.info(new String(response,"UTF-8"));\r
126     } catch (ClientProtocolException e) {\r
127       // TODO Auto-generated catch block\r
128       e.printStackTrace();\r
129       return false;\r
130     } catch (IOException e) {\r
131       // TODO Auto-generated catch block\r
132       e.printStackTrace();\r
133       return false;\r
134     }    \r
135     return true;\r
136     \r
137   }\r
138   \r
139   public boolean isAuthenticatingClient () {\r
140     return true;\r
141   }\r
142   \r
143   public boolean isAuthenticated () {\r
144     if (user.getProperty("name") != null && user.getProperty("password") != null) {\r
145       return checkAuthentication();\r
146     } else {\r
147       return false;\r
148     }\r
149   }\r
150   \r
151   /**\r
152    * Makes the request\r
153    * @param request\r
154    * @return HTTP response as a String\r
155    * @throws ClientProtocolException\r
156    * @throws IOException\r
157    */\r
158   private byte[] send(CommandReadOnly command) throws ClientProtocolException, IOException {\r
159     String url = serviceUrl + "?" + command.getEncodedQueryString(); \r
160     logger.info("Sending request "+url);    \r
161     HttpGet httpget = new HttpGet(url);     \r
162     byte[] response = client.execute(httpget, handler);    \r
163     return response;\r
164   }\r
165   \r
166   public class ProxyPz2ResponseHandler implements ResponseHandler<byte[]> {\r
167     private StatusLine statusLine = null;\r
168     public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {\r
169       byte[] resp = null;\r
170       HttpEntity entity = response.getEntity();      \r
171       statusLine = response.getStatusLine();\r
172       if (entity != null) {        \r
173         resp = EntityUtils.toByteArray(entity);        \r
174       } \r
175       EntityUtils.consume(entity);\r
176       return resp;\r
177     }\r
178     public int getStatusCode() {\r
179       return statusLine.getStatusCode();\r
180     }    \r
181     public String getReasonPhrase() {\r
182       return statusLine.getReasonPhrase();\r
183     }\r
184   }\r
185 \r
186   public int getStatusCode () {\r
187     return handler.getStatusCode();\r
188   }\r
189   \r
190   public String getReasonPhrase() {\r
191     return handler.getReasonPhrase();\r
192   }\r
193 \r
194   @Override\r
195   public void setSearchCommand(CommandReadOnly command) {\r
196     // Do nothing, Service Proxy is handling this    \r
197   }\r
198 \r
199   @Override\r
200   public CommandResponse executeCommand(CommandReadOnly command,\r
201       ByteArrayOutputStream baos) throws Pazpar2ErrorException, IOException {\r
202     byte[] response = send(command);\r
203     baos.write(response);\r
204     return new ServiceProxyClientCommandResponse(getStatusCode(), new String(response,"UTF-8"));    \r
205   }\r
206 \r
207   public ServiceProxyClient cloneMe() {\r
208     logger.debug("Cloning Pz2Client");\r
209     ServiceProxyClient clone = new ServiceProxyClient();\r
210     clone.client = this.client;\r
211     clone.serviceUrl = this.serviceUrl;\r
212     clone.initDocPaths = this.initDocPaths;\r
213     return clone;\r
214   }\r
215 \r
216   @Override\r
217   public Map<String, String> getDefaults() {    \r
218     return new HashMap<String,String>();\r
219   }\r
220 \r
221   @Override\r
222   public String getModuleName() {\r
223     return MODULENAME;\r
224   }\r
225   \r
226   @Override\r
227   public List<String> documentConfiguration () {\r
228     List<String> doc = new ArrayList<String>();\r
229     doc.add(nl+ MODULENAME + " was configured to access the Pazpar2 service proxy at: " + serviceUrl);\r
230     return null;\r
231   }\r
232   \r
233   public byte[] postInitDoc (String filePath) throws IOException {\r
234     logger.info("Looking to post the file in : [" + filePath +"]");\r
235     HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes");\r
236     File initDoc = new File(filePath);\r
237     logger.info("Posting to SP: ");\r
238     if (logger.isDebugEnabled()) {\r
239       BufferedReader reader = new BufferedReader(new FileReader(initDoc));\r
240       String line;\r
241       while ( (line = reader.readLine()) != null) {\r
242         System.out.println(line);\r
243       }\r
244       reader.close();\r
245     }\r
246     post.setEntity(new FileEntity(initDoc));\r
247     byte[] response = client.execute(post, handler);\r
248     logger.debug("Response on POST was: " + new String(response,"UTF-8"));    \r
249     return response;\r
250   }\r
251   \r
252   public String[] getInitDocPaths () {\r
253     logger.debug("Get init doc paths ");\r
254     logger.debug("length: " + initDocPaths.length);\r
255     return initDocPaths;\r
256   }\r
257   \r
258   public byte[] postInitDoc(byte[] initDoc) throws IOException {\r
259     HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes");\r
260     post.setEntity(new ByteArrayEntity(initDoc));\r
261     byte[] response = client.execute(post, handler);\r
262     logger.debug("Response on POST was: " + new String(response,"UTF-8"));    \r
263     return response;\r
264   }\r
265   \r
266   public void setServiceProxyUrl (String url) {\r
267     serviceUrl = url;\r
268   }\r
269   \r
270   public String getServiceProxyUrl () {\r
271     return serviceUrl;\r
272   }\r
273   \r
274   public Configuration getConfiguration () {\r
275     return config;\r
276   }\r
277   \r
278 }\r