d9f89fc136484e5f1abffbd9805b2d3461193cef
[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.ByteArrayOutputStream;\r
6 import java.io.File;\r
7 import java.io.IOException;\r
8 import java.util.ArrayList;\r
9 import java.util.HashMap;\r
10 import java.util.List;\r
11 import java.util.Map;\r
12 \r
13 import javax.enterprise.context.SessionScoped;\r
14 import javax.inject.Named;\r
15 \r
16 import org.apache.http.HttpEntity;\r
17 import org.apache.http.HttpResponse;\r
18 import org.apache.http.StatusLine;\r
19 import org.apache.http.client.ClientProtocolException;\r
20 import org.apache.http.client.HttpClient;\r
21 import org.apache.http.client.ResponseHandler;\r
22 import org.apache.http.client.methods.HttpGet;\r
23 import org.apache.http.client.methods.HttpPost;\r
24 import org.apache.http.conn.ClientConnectionManager;\r
25 import org.apache.http.conn.scheme.PlainSocketFactory;\r
26 import org.apache.http.conn.scheme.Scheme;\r
27 import org.apache.http.conn.scheme.SchemeRegistry;\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.CommandParameter;\r
40 import com.indexdata.pz2utils4jsf.pazpar2.CommandResponse;\r
41 import com.indexdata.pz2utils4jsf.pazpar2.Pazpar2Command;\r
42 import com.indexdata.pz2utils4jsf.pazpar2.SearchClient;\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 @Named @SessionScoped \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   \r
58   ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler();\r
59   private HttpClient client;\r
60   private ServiceProxyUser user;\r
61 \r
62   public ServiceProxyClient () {\r
63     SchemeRegistry schemeRegistry = new SchemeRegistry();\r
64     schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));\r
65     ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);\r
66     client = new DefaultHttpClient(cm);    \r
67   }\r
68     \r
69   @Override\r
70   public void configure (ConfigurationReader configReader) {\r
71     logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
72     try {\r
73       Configuration config = configReader.getConfiguration(this);      \r
74       serviceUrl = config.getMandatory(SERVICE_PROXY_URL);  \r
75       this.initDocPaths = getMultiProperty(config.get(SP_INIT_DOC_PATHS));            \r
76     } catch (ConfigurationException c) {\r
77       c.printStackTrace();\r
78     } catch (MissingMandatoryParameterException mmp) {\r
79       mmp.printStackTrace();\r
80     }    \r
81   }\r
82   \r
83   private String[] getMultiProperty(String prop) {    \r
84     if (prop != null) {\r
85       return prop.split(",");\r
86     } else {\r
87       return null;\r
88     }\r
89   }\r
90   \r
91   public boolean authenticate (AuthenticationEntity user) {\r
92     try {      \r
93       logger.info("Authenticating [" + user.getProperty("name") + "]");\r
94       this.user = (ServiceProxyUser) user;\r
95       Pazpar2Command auth = new Pazpar2Command("auth");\r
96       auth.setParameter(new CommandParameter("action","=","login"));\r
97       auth.setParameter(new CommandParameter("username","=",user.getProperty("name")));\r
98       auth.setParameter(new CommandParameter("password","=",user.getProperty("password")));\r
99       byte[] response = send(auth);\r
100       String responseStr = new String(response,"UTF-8");\r
101       logger.info(responseStr);      \r
102       if (responseStr.contains("FAIL")) {\r
103         return false;\r
104       } else {\r
105         return true;\r
106       }      \r
107     } catch (ClientProtocolException e) {\r
108       // TODO Auto-generated catch block\r
109       e.printStackTrace();\r
110       return false;\r
111     } catch (IOException e) {\r
112       // TODO Auto-generated catch block\r
113       e.printStackTrace();\r
114       return false;\r
115     }        \r
116   }\r
117   \r
118   public boolean checkAuthentication () {\r
119     try {\r
120       Pazpar2Command check = new Pazpar2Command("auth");\r
121       check.setParameter(new CommandParameter("action","=","check"));\r
122       byte[] response = send(check);\r
123       logger.info(new String(response,"UTF-8"));\r
124     } catch (ClientProtocolException e) {\r
125       // TODO Auto-generated catch block\r
126       e.printStackTrace();\r
127       return false;\r
128     } catch (IOException e) {\r
129       // TODO Auto-generated catch block\r
130       e.printStackTrace();\r
131       return false;\r
132     }    \r
133     return true;\r
134     \r
135   }\r
136   \r
137   public boolean isAuthenticatingClient () {\r
138     return true;\r
139   }\r
140   \r
141   public boolean isAuthenticated () {\r
142     if (user.getProperty("name") != null && user.getProperty("password") != null) {\r
143       return checkAuthentication();\r
144     } else {\r
145       return false;\r
146     }\r
147   }\r
148   \r
149   /**\r
150    * Makes the request\r
151    * @param request\r
152    * @return HTTP response as a String\r
153    * @throws ClientProtocolException\r
154    * @throws IOException\r
155    */\r
156   private byte[] send(Pazpar2Command command) throws ClientProtocolException, IOException {\r
157     String url = serviceUrl + "?" + command.getEncodedQueryString(); \r
158     logger.info("Sending request "+url);    \r
159     HttpGet httpget = new HttpGet(url);     \r
160     byte[] response = client.execute(httpget, handler);    \r
161     return response;\r
162   }\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     post.setEntity(new FileEntity(initDoc));\r
237     byte[] response = client.execute(post, handler);\r
238     logger.info("Response on POST was: " + new String(response,"UTF-8"));\r
239     return response;\r
240   }\r
241   \r
242   public String[] getInitDocPaths () {\r
243     logger.info("Get init doc paths ");\r
244     logger.info("length: " + initDocPaths.length);\r
245     return initDocPaths;\r
246   }\r
247   \r
248   public void setServiceProxyUrl (String url) {\r
249     serviceUrl = url;\r
250   }\r
251   \r
252   public String getServiceProxyUrl () {\r
253     return serviceUrl;\r
254   }\r
255 \r
256 }\r