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