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