Additional downgrade details (1.7 to 1.6)
[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.ByteArrayEntity;\r
29 import org.apache.http.entity.FileEntity;\r
30 import org.apache.http.impl.client.DefaultHttpClient;\r
31 import org.apache.http.impl.conn.PoolingClientConnectionManager;\r
32 import org.apache.http.util.EntityUtils;\r
33 import org.apache.log4j.Logger;\r
34 \r
35 import com.indexdata.masterkey.config.MissingMandatoryParameterException;\r
36 import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException;\r
37 import com.indexdata.pz2utils4jsf.config.Configuration;\r
38 import com.indexdata.pz2utils4jsf.config.ConfigurationReader;\r
39 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;\r
40 import com.indexdata.pz2utils4jsf.pazpar2.CommandParameter;\r
41 import com.indexdata.pz2utils4jsf.pazpar2.CommandResponse;\r
42 import com.indexdata.pz2utils4jsf.pazpar2.Pazpar2Command;\r
43 import com.indexdata.pz2utils4jsf.pazpar2.SearchClient;\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 @Named @SessionScoped \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");\r
98       auth.setParameter(new CommandParameter("action","=","login"));\r
99       auth.setParameter(new CommandParameter("username","=",user.getProperty("name")));\r
100       auth.setParameter(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");\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(Pazpar2Command 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(Pazpar2Command command) {\r
196     // Do nothing, Service Proxy is handling this    \r
197   }\r
198 \r
199   @Override\r
200   public CommandResponse executeCommand(Pazpar2Command 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     //Path path = Paths.get(filePath);\r
239     /*\r
240     if (logger.isDebugEnabled()) {\r
241       try (Scanner scanner =  new Scanner(path, "UTF-8")){\r
242         while (scanner.hasNextLine()){\r
243           System.out.println(scanner.nextLine());\r
244         }      \r
245       }     \r
246     }\r
247     */\r
248     post.setEntity(new FileEntity(initDoc));\r
249     byte[] response = client.execute(post, handler);\r
250     logger.info("Response on POST was: " + new String(response,"UTF-8"));    \r
251     return response;\r
252   }\r
253   \r
254   public String[] getInitDocPaths () {\r
255     logger.info("Get init doc paths ");\r
256     logger.info("length: " + initDocPaths.length);\r
257     return initDocPaths;\r
258   }\r
259   \r
260   public byte[] postInitDoc(byte[] initDoc) throws IOException {\r
261     HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes");\r
262     post.setEntity(new ByteArrayEntity(initDoc));\r
263     byte[] response = client.execute(post, handler);\r
264     logger.info("Response on POST was: " + new String(response,"UTF-8"));    \r
265     return response;\r
266   }\r
267   \r
268   public void setServiceProxyUrl (String url) {\r
269     serviceUrl = url;\r
270   }\r
271   \r
272   public String getServiceProxyUrl () {\r
273     return serviceUrl;\r
274   }\r
275   \r
276   public Configuration getConfiguration () {\r
277     return config;\r
278   }\r
279   \r
280 }\r