e6e96bca338856b3012be052aacc058c99f7b5a0
[mkjsf-moved-to-github.git] / src / main / java / com / indexdata / pz2utils4jsf / pazpar2 / ProxyPz2Client.java
1 package com.indexdata.pz2utils4jsf.pazpar2;\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.IOException;\r
7 import java.util.ArrayList;\r
8 import java.util.HashMap;\r
9 import java.util.List;\r
10 import java.util.Map;\r
11 \r
12 import javax.enterprise.context.SessionScoped;\r
13 import javax.inject.Named;\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.conn.ClientConnectionManager;\r
23 import org.apache.http.conn.scheme.PlainSocketFactory;\r
24 import org.apache.http.conn.scheme.Scheme;\r
25 import org.apache.http.conn.scheme.SchemeRegistry;\r
26 import org.apache.http.impl.client.DefaultHttpClient;\r
27 import org.apache.http.impl.conn.PoolingClientConnectionManager;\r
28 import org.apache.http.util.EntityUtils;\r
29 import org.apache.log4j.Logger;\r
30 \r
31 import com.indexdata.masterkey.config.MissingMandatoryParameterException;\r
32 import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException;\r
33 import com.indexdata.pz2utils4jsf.config.Configuration;\r
34 import com.indexdata.pz2utils4jsf.config.ConfigurationReader;\r
35 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;\r
36 import com.indexdata.pz2utils4jsf.pazpar2.sp.auth.AuthenticationEntity;\r
37 import com.indexdata.pz2utils4jsf.pazpar2.sp.auth.ServiceProxyUser;\r
38 import com.indexdata.pz2utils4jsf.utils.Utils;\r
39 \r
40 @Named @SessionScoped \r
41 public class ProxyPz2Client implements SearchClient {\r
42     \r
43   private static final long serialVersionUID = -4031644009579840277L;\r
44   private static Logger logger = Logger.getLogger(ProxyPz2Client.class);\r
45   public static final String MODULENAME = "proxyclient";\r
46   private String serviceUrl = "undefined";\r
47   \r
48   ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler();\r
49   private HttpClient client;\r
50   private ServiceProxyUser user;\r
51 \r
52   public ProxyPz2Client () {\r
53     SchemeRegistry schemeRegistry = new SchemeRegistry();\r
54     schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));\r
55     ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);\r
56     client = new DefaultHttpClient(cm);    \r
57   }\r
58     \r
59   @Override\r
60   public void configure (ConfigurationReader configReader) {\r
61     logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
62     try {\r
63       Configuration config = configReader.getConfiguration(this);      \r
64       serviceUrl = config.getMandatory("SERVICE_PROXY_URL");      \r
65     } catch (ConfigurationException c) {\r
66       c.printStackTrace();\r
67     } catch (MissingMandatoryParameterException mmp) {\r
68       mmp.printStackTrace();\r
69     }    \r
70   }\r
71   \r
72   public boolean authenticate (AuthenticationEntity user) {\r
73     try {      \r
74       logger.info("Authenticating [" + user.getProperty("name") + "]");\r
75       this.user = (ServiceProxyUser) user;\r
76       Pazpar2Command auth = new Pazpar2Command("auth");\r
77       auth.setParameter(new CommandParameter("action","=","login"));\r
78       auth.setParameter(new CommandParameter("username","=",user.getProperty("name")));\r
79       auth.setParameter(new CommandParameter("password","=",user.getProperty("password")));\r
80       byte[] response = send(auth);\r
81       String responseStr = new String(response,"UTF-8");\r
82       logger.info(responseStr);      \r
83       if (responseStr.contains("FAIL")) {\r
84         return false;\r
85       } else {\r
86         return true;\r
87       }      \r
88     } catch (ClientProtocolException e) {\r
89       // TODO Auto-generated catch block\r
90       e.printStackTrace();\r
91       return false;\r
92     } catch (IOException e) {\r
93       // TODO Auto-generated catch block\r
94       e.printStackTrace();\r
95       return false;\r
96     }        \r
97   }\r
98   \r
99   public boolean checkAuthentication () {\r
100     try {\r
101       Pazpar2Command check = new Pazpar2Command("auth");\r
102       check.setParameter(new CommandParameter("action","=","check"));\r
103       byte[] response = send(check);\r
104       logger.info(new String(response,"UTF-8"));\r
105     } catch (ClientProtocolException e) {\r
106       // TODO Auto-generated catch block\r
107       e.printStackTrace();\r
108       return false;\r
109     } catch (IOException e) {\r
110       // TODO Auto-generated catch block\r
111       e.printStackTrace();\r
112       return false;\r
113     }    \r
114     return true;\r
115     \r
116   }\r
117   \r
118   public boolean isAuthenticatingClient () {\r
119     return true;\r
120   }\r
121   \r
122   public boolean isAuthenticated () {\r
123     if (user.getProperty("name") != null && user.getProperty("password") != null) {\r
124       return checkAuthentication();\r
125     } else {\r
126       return false;\r
127     }\r
128   }\r
129   \r
130   /**\r
131    * Makes the request\r
132    * @param request\r
133    * @return HTTP response as a String\r
134    * @throws ClientProtocolException\r
135    * @throws IOException\r
136    */\r
137   private byte[] send(Pazpar2Command command) throws ClientProtocolException, IOException {\r
138     String url = serviceUrl + "?" + command.getEncodedQueryString(); \r
139     logger.info("Sending request "+url);    \r
140     HttpGet httpget = new HttpGet(url);     \r
141     byte[] response = client.execute(httpget, handler);    \r
142     return response;\r
143   }\r
144 \r
145   \r
146   public class ProxyPz2ResponseHandler implements ResponseHandler<byte[]> {\r
147     private StatusLine statusLine = null;\r
148     public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {\r
149       byte[] resp = null;\r
150       HttpEntity entity = response.getEntity();      \r
151       statusLine = response.getStatusLine();\r
152       if (entity != null) {        \r
153         resp = EntityUtils.toByteArray(entity);        \r
154       } \r
155       EntityUtils.consume(entity);\r
156       return resp;\r
157     }\r
158     public int getStatusCode() {\r
159       return statusLine.getStatusCode();\r
160     }    \r
161     public String getReasonPhrase() {\r
162       return statusLine.getReasonPhrase();\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   @Override\r
175   public void setSearchCommand(Pazpar2Command command) {\r
176     // Do nothing, Service Proxy is handling this    \r
177   }\r
178 \r
179   @Override\r
180   public CommandResponse executeCommand(Pazpar2Command command,\r
181       ByteArrayOutputStream baos) throws Pazpar2ErrorException, IOException {\r
182     byte[] response = send(command);\r
183     baos.write(response);\r
184     return new ProxyPz2ClientCommandResponse(getStatusCode(), new String(response,"UTF-8"));    \r
185   }\r
186 \r
187   public ProxyPz2Client cloneMe() {\r
188     logger.debug("Cloning StraightPz2Client");\r
189     ProxyPz2Client clone = new ProxyPz2Client();\r
190     clone.client = this.client;\r
191     clone.serviceUrl = this.serviceUrl;\r
192     return clone;\r
193   }\r
194 \r
195   @Override\r
196   public Map<String, String> getDefaults() {    \r
197     return new HashMap<String,String>();\r
198   }\r
199 \r
200   @Override\r
201   public String getModuleName() {\r
202     return MODULENAME;\r
203   }\r
204   \r
205   @Override\r
206   public List<String> documentConfiguration () {\r
207     List<String> doc = new ArrayList<String>();\r
208     doc.add(nl+ MODULENAME + " was configured to access the Pazpar2 service proxy at: " + serviceUrl);\r
209     return null;\r
210   }\r
211 \r
212 }\r