Service proxy client and configuration schemes
[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.enterprise.inject.Alternative;\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.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.impl.client.DefaultHttpClient;\r
28 import org.apache.http.impl.conn.PoolingClientConnectionManager;\r
29 import org.apache.http.util.EntityUtils;\r
30 import org.apache.log4j.Logger;\r
31 \r
32 import com.indexdata.masterkey.config.MissingMandatoryParameterException;\r
33 import com.indexdata.masterkey.pazpar2.client.exceptions.Pazpar2ErrorException;\r
34 import com.indexdata.pz2utils4jsf.config.Configuration;\r
35 import com.indexdata.pz2utils4jsf.config.ConfigurationReader;\r
36 import com.indexdata.pz2utils4jsf.errors.ConfigurationException;\r
37 import com.indexdata.pz2utils4jsf.utils.Utils;\r
38 \r
39 @Named @SessionScoped @Alternative\r
40 public class ProxyPz2Client implements SearchClient {\r
41 \r
42   private static final long serialVersionUID = -4031644009579840277L;\r
43   private static Logger logger = Logger.getLogger(ProxyPz2Client.class);\r
44   public static final String MODULENAME = "proxyclient";\r
45   private String serviceUrl = "undefined";\r
46   \r
47   ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler();\r
48   private HttpClient client;\r
49 \r
50   public ProxyPz2Client () {\r
51     SchemeRegistry schemeRegistry = new SchemeRegistry();\r
52     schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));\r
53     ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);\r
54     client = new DefaultHttpClient(cm);\r
55   }\r
56     \r
57   @Override\r
58   public void configure (ConfigurationReader configReader) {\r
59     logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));\r
60     try {\r
61       Configuration config = configReader.getConfiguration(this);      \r
62       serviceUrl = config.getMandatory("SERVICE_PROXY_URL");\r
63       authenticate();\r
64     } catch (ConfigurationException c) {\r
65       // TODO Auto-generated catch block\r
66       c.printStackTrace();\r
67     } catch (MissingMandatoryParameterException mmp) {\r
68       mmp.printStackTrace();\r
69     }\r
70   }\r
71   \r
72   public void authenticate () {\r
73     try {\r
74       Pazpar2Command auth = new Pazpar2Command("auth");\r
75       auth.setParameter(new CommandParameter("action","=","login"));\r
76       auth.setParameter(new CommandParameter("username","=","demo"));\r
77       auth.setParameter(new CommandParameter("password","=","demo"));\r
78       send(auth);\r
79     } catch (ClientProtocolException e) {\r
80       // TODO Auto-generated catch block\r
81       e.printStackTrace();\r
82     } catch (IOException e) {\r
83       // TODO Auto-generated catch block\r
84       e.printStackTrace();\r
85     }\r
86     \r
87   }\r
88   \r
89   /**\r
90    * Makes the request\r
91    * @param request\r
92    * @return HTTP response as a String\r
93    * @throws ClientProtocolException\r
94    * @throws IOException\r
95    */\r
96   private String send(Pazpar2Command command) throws ClientProtocolException, IOException {\r
97     String url = serviceUrl + "?" + command.getEncodedQueryString(); \r
98     logger.info("Sending request "+url);    \r
99     HttpGet httpget = new HttpGet(url);     \r
100     byte[] response = client.execute(httpget, handler);    \r
101     return new String(response);\r
102   }\r
103 \r
104   \r
105   public class ProxyPz2ResponseHandler implements ResponseHandler<byte[]> {\r
106     private StatusLine statusLine = null;\r
107     public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {\r
108       byte[] resp = null;\r
109       HttpEntity entity = response.getEntity();      \r
110       statusLine = response.getStatusLine();\r
111       if (entity != null) {        \r
112         resp = EntityUtils.toByteArray(entity);        \r
113       } \r
114       EntityUtils.consume(entity);\r
115       return resp;\r
116     }\r
117     public int getStatusCode() {\r
118       return statusLine.getStatusCode();\r
119     }    \r
120     public String getReasonPhrase() {\r
121       return statusLine.getReasonPhrase();\r
122     }\r
123   }\r
124 \r
125   public int getStatusCode () {\r
126     return handler.getStatusCode();\r
127   }\r
128   \r
129   public String getReasonPhrase() {\r
130     return handler.getReasonPhrase();\r
131   }\r
132 \r
133   @Override\r
134   public void setSearchCommand(Pazpar2Command command) {\r
135     // Do nothing, Service Proxy is handling this    \r
136   }\r
137 \r
138   @Override\r
139   public CommandResponse executeCommand(Pazpar2Command command,\r
140       ByteArrayOutputStream baos) throws Pazpar2ErrorException, IOException {\r
141     String response = send(command);\r
142     return new ProxyPz2ClientCommandResponse(getStatusCode(), response);    \r
143   }\r
144 \r
145   public ProxyPz2Client cloneMe() {\r
146     logger.debug("Cloning StraightPz2Client");\r
147     ProxyPz2Client clone = new ProxyPz2Client();\r
148     clone.client = this.client;\r
149     clone.serviceUrl = this.serviceUrl;\r
150     return clone;\r
151   }\r
152 \r
153   @Override\r
154   public Map<String, String> getDefaults() {    \r
155     return new HashMap<String,String>();\r
156   }\r
157 \r
158   @Override\r
159   public String getModuleName() {\r
160     return MODULENAME;\r
161   }\r
162   \r
163   @Override\r
164   public List<String> documentConfiguration () {\r
165     List<String> doc = new ArrayList<String>();\r
166     doc.add(nl+ MODULENAME + " was configured to access the Pazpar2 service proxy at: " + serviceUrl);\r
167     return null;\r
168   }\r
169 \r
170 }\r