1 package com.indexdata.mkjsf.pazpar2;
\r
3 import static com.indexdata.mkjsf.utils.Utils.nl;
\r
5 import java.io.BufferedReader;
\r
7 import java.io.FileReader;
\r
8 import java.io.IOException;
\r
9 import java.util.ArrayList;
\r
10 import java.util.HashMap;
\r
11 import java.util.List;
\r
12 import java.util.Map;
\r
14 import org.apache.http.Header;
\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.client.methods.HttpPost;
\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.entity.ByteArrayEntity;
\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
34 import com.indexdata.mkjsf.config.Configuration;
\r
35 import com.indexdata.mkjsf.config.ConfigurationReader;
\r
36 import com.indexdata.mkjsf.errors.ConfigurationException;
\r
37 import com.indexdata.mkjsf.pazpar2.commands.CommandParameter;
\r
38 import com.indexdata.mkjsf.pazpar2.commands.Pazpar2Command;
\r
39 import com.indexdata.mkjsf.pazpar2.commands.sp.AuthCommand;
\r
40 import com.indexdata.mkjsf.pazpar2.data.CommandError;
\r
41 import com.indexdata.mkjsf.utils.Utils;
\r
43 public class ServiceProxyClient implements SearchClient {
\r
45 private static final long serialVersionUID = -4031644009579840277L;
\r
46 private static Logger logger = Logger.getLogger(ServiceProxyClient.class);
\r
47 public static final String MODULENAME = "proxyclient";
\r
49 public static final String SP_INIT_DOC_PATHS = "SP_INIT_DOC_PATHS";
\r
50 private String serviceUrl = "";
\r
52 private List<String> initDocPaths = null;
\r
53 private Configuration config = null;
\r
55 ProxyPz2ResponseHandler handler = new ProxyPz2ResponseHandler();
\r
56 private transient HttpClient client;
\r
57 private Pazpar2Command checkAuth = null;
\r
58 private Pazpar2Command ipAuth = null;
\r
60 public ServiceProxyClient () {
\r
61 SchemeRegistry schemeRegistry = new SchemeRegistry();
\r
62 schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
\r
63 ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
\r
64 client = new DefaultHttpClient(cm);
\r
68 public void configure (ConfigurationReader configReader) {
\r
69 logger.info(Utils.objectId(this) + " is configuring using the provided " + Utils.objectId(configReader));
\r
71 config = configReader.getConfiguration(this);
\r
72 serviceUrl = config.get("SERVICE_PROXY_URL");
\r
73 this.initDocPaths = config.getMultiProperty(SP_INIT_DOC_PATHS,",");
\r
74 checkAuth = new AuthCommand();
\r
75 checkAuth.setParameterInState(new CommandParameter("action","=","check"));
\r
76 ipAuth = new AuthCommand();
\r
77 ipAuth.setParameterInState(new CommandParameter("action","=","ipauth"));
\r
78 } catch (ConfigurationException c) {
\r
80 c.printStackTrace();
\r
84 public boolean isAuthenticatingClient () {
\r
91 * @return HTTP response as a String
\r
92 * @throws ClientProtocolException
\r
93 * @throws IOException
\r
95 public ClientCommandResponse send(Pazpar2Command command) {
\r
96 ClientCommandResponse commandResponse = null;
\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 = null;
\r
102 response = client.execute(httpget, handler);
\r
103 if (handler.getStatusCode()==200 && (handler.getContentType().contains("xml") || handler.getContentType().contains("octet-stream"))) {
\r
104 logger.trace("Creating command response holding content of type " + handler.getContentType());
\r
105 commandResponse = new ClientCommandResponse(handler.getStatusCode(),response,handler.getContentType());
\r
107 logger.error("Service Proxy status code: " + handler.getStatusCode());
\r
108 String errorXml = "";
\r
109 if (handler.getContentType().contains("xml")) {
\r
110 errorXml = CommandError.insertErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), "Service Proxy error: "+handler.getStatusCode(), new String(response,"UTF-8"));
\r
112 if (handler.getContentType().contains("html")) {
\r
113 String htmlStrippedOfTags = (new String(response,"UTF-8")).replaceAll("\\<[^>]*>","");
\r
114 if (htmlStrippedOfTags.toLowerCase().contains("domain")) {
\r
115 errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), "Unexpected response type from Service Proxy", "Expected XML from SP but got HTML. It contains the word domain suggesting that the service address was not found.", htmlStrippedOfTags);
\r
117 errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), "Unexpected response type from Service Proxy", "Expected XML from SP but got HTML", htmlStrippedOfTags);
\r
120 errorXml = CommandError.createErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), "Unexpected response type from Service Proxy: "+handler.getContentType(), "Could not process non-XML response from Service Proxy", new String(response,"UTF-8"));
\r
123 commandResponse = new ClientCommandResponse(handler.getStatusCode(),errorXml,handler.getContentType());
\r
125 } catch (Exception e) {
\r
126 e.printStackTrace();
\r
127 commandResponse = new ClientCommandResponse(handler.getStatusCode(),CommandError.createErrorXml(command.getCommandName(), String.valueOf(handler.getStatusCode()), e.getClass().getSimpleName(), (e.getMessage()!= null ? e.getMessage() : "") + (e.getCause()!=null ? e.getCause().getMessage() : ""), e.getStackTrace().toString()),handler.getContentType());
\r
129 return commandResponse;
\r
132 public class ProxyPz2ResponseHandler implements ResponseHandler<byte[]> {
\r
133 private StatusLine statusLine = null;
\r
134 private Header contentType = null;
\r
135 public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
\r
136 byte[] resp = null;
\r
137 HttpEntity entity = response.getEntity();
\r
138 statusLine = response.getStatusLine();
\r
139 if (entity != null) {
\r
140 resp = EntityUtils.toByteArray(entity);
\r
141 contentType = response.getEntity().getContentType();
\r
143 EntityUtils.consume(entity);
\r
146 public int getStatusCode() {
\r
147 return statusLine.getStatusCode();
\r
149 public String getReasonPhrase() {
\r
150 return statusLine.getReasonPhrase();
\r
152 public String getContentType () {
\r
153 return (contentType != null ? contentType.getValue() : "Content-Type not known");
\r
157 public int getStatusCode () {
\r
158 return handler.getStatusCode();
\r
161 public String getReasonPhrase() {
\r
162 return handler.getReasonPhrase();
\r
166 public void setSearchCommand(Pazpar2Command command) {
\r
167 // Do nothing, Service Proxy is handling this
\r
171 public HttpResponseWrapper executeCommand(Pazpar2Command command) {
\r
172 return send(command);
\r
175 public ServiceProxyClient cloneMe() {
\r
176 logger.debug("Cloning Pz2Client");
\r
177 ServiceProxyClient clone = new ServiceProxyClient();
\r
178 clone.client = this.client;
\r
179 clone.serviceUrl = this.serviceUrl;
\r
180 clone.initDocPaths = this.initDocPaths;
\r
185 public Map<String, String> getDefaults() {
\r
186 return new HashMap<String,String>();
\r
190 public String getModuleName() {
\r
195 public List<String> documentConfiguration () {
\r
196 List<String> doc = new ArrayList<String>();
\r
197 doc.add(nl+ MODULENAME + " was configured to access the Pazpar2 service proxy at: " + (serviceUrl.length()>0 ? serviceUrl : "[not defined yet]"));
\r
201 public ClientCommandResponse postInitDoc (String filePath) throws IOException {
\r
202 logger.info("Looking to post the file in : [" + filePath +"]");
\r
203 HttpPost post = new HttpPost(serviceUrl+"?command=init&includeDebug=yes");
\r
204 File initDoc = new File(filePath);
\r
205 logger.info("Posting to SP: ");
\r
206 if (logger.isDebugEnabled()) {
\r
207 BufferedReader reader = new BufferedReader(new FileReader(initDoc));
\r
209 while ( (line = reader.readLine()) != null) {
\r
210 System.out.println(line);
\r
214 post.setEntity(new FileEntity(initDoc));
\r
215 byte[] response = client.execute(post, handler);
\r
216 logger.debug("Response on POST was: " + new String(response,"UTF-8"));
\r
217 return new ClientCommandResponse(handler.getStatusCode(),response,handler.getContentType());
\r
220 public List<String> getInitDocPaths () {
\r
221 logger.debug("Get init doc paths ");
\r
222 logger.debug("length: " + initDocPaths.size());
\r
223 return initDocPaths;
\r
226 public HttpResponseWrapper postInitDoc(byte[] initDoc, boolean includeDebug) {
\r
227 HttpPost post = new HttpPost(serviceUrl+"?command=init" + (includeDebug? "&includeDebug=yes" : ""));
\r
228 post.setEntity(new ByteArrayEntity(initDoc));
\r
229 ClientCommandResponse commandResponse = null;
\r
232 response = client.execute(post, handler);
\r
233 if (handler.getStatusCode()==200) {
\r
234 commandResponse = new ClientCommandResponse(handler.getStatusCode(),response,handler.getContentType());
\r
236 logger.error("Service Proxy status code: " + handler.getStatusCode());
\r
237 commandResponse = new ClientCommandResponse(handler.getStatusCode(),CommandError.insertErrorXml("init", String.valueOf(handler.getStatusCode()), "Service Proxy error: "+handler.getStatusCode(), new String(response,"UTF-8")),"text/xml");
\r
239 } catch (ClientProtocolException e) {
\r
240 logger.error(e.getMessage());
\r
241 e.printStackTrace();
\r
242 commandResponse = new ClientCommandResponse(-1,CommandError.createErrorXml("init", String.valueOf(handler.getStatusCode()), "Client protocol exception", e.getMessage(), e.getStackTrace().toString()),"text/xml");
\r
243 } catch (IOException e) {
\r
244 logger.error(e.getMessage());
\r
245 e.printStackTrace();
\r
246 commandResponse = new ClientCommandResponse(-1,CommandError.createErrorXml("init", String.valueOf(handler.getStatusCode()), "IO exception", e.getMessage(),e.getStackTrace().toString()),"text/xml");
\r
248 return commandResponse;
\r
251 public void setServiceUrl (String url) {
\r
255 public Configuration getConfiguration () {
\r
260 public String getServiceUrl() {
\r
265 public boolean hasServiceUrl() {
\r
266 return serviceUrl != null && serviceUrl.length()>0;
\r