View Javadoc

1   /*
2    * $Id: QueryDBService.java,v 1.7 2004/12/18 18:30:16 jdt Exp $
3    */
4   package org.astrogrid.xmldb.eXist.server;
5   
6   import org.astrogrid.config.Config;
7   
8   import java.io.IOException;
9   import java.io.UnsupportedEncodingException;
10  import javax.xml.parsers.ParserConfigurationException;
11  import org.xml.sax.SAXException;
12  import java.net.MalformedURLException;
13  
14  import java.net.URL;
15  import java.net.HttpURLConnection;
16  import java.net.URLEncoder;
17  import org.astrogrid.util.DomHelper;
18  import org.apache.axis.AxisFault;
19  
20  import java.io.DataOutputStream;
21  
22  import org.apache.commons.logging.Log;
23  import org.apache.commons.logging.LogFactory;
24  
25  import org.w3c.dom.Document;
26  import org.w3c.dom.NodeList;
27  import org.w3c.dom.Element;
28  import org.w3c.dom.Node;
29  
30  import javax.xml.namespace.QName;
31  
32  import org.apache.commons.httpclient.HttpClient;
33  import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
34  import org.apache.commons.httpclient.methods.PostMethod;
35  import org.apache.commons.httpclient.UsernamePasswordCredentials;
36  
37  
38  
39  public class QueryDBService {
40  
41     private static final Log log = LogFactory.getLog(QueryDBService.class);
42  
43     public static Config conf = null;
44     private static String existLocation = null;
45  
46     static {
47        if(conf == null) {
48           conf = org.astrogrid.config.SimpleConfig.getSingleton();
49           existLocation = conf.getString("exist.db.url");
50        }
51     }
52  
53  
54     public Document query(String collectionName, String xql) throws AxisFault {
55        log.debug("start query");
56  
57        try {
58           return runQuery(collectionName,xql);
59        }catch(MalformedURLException mue) {
60           log.error(mue);
61           throw new AxisFault("URL incorrect", mue);
62        }catch(ParserConfigurationException pce) {
63           log.error(pce);
64           throw new AxisFault("XML Parser Configuration error", pce);
65        }catch(IOException ioe) {
66           log.error(ioe);
67           throw new AxisFault("IO Excepiton error", ioe);
68        }catch(SAXException se) {
69           log.error(se);
70           throw new AxisFault("SAX Exception - could not parse the result into xml", se);
71        }finally {
72           log.debug("end query");
73        }
74     }
75  
76     private String getQueryUrl(String collectionName) throws MalformedURLException, UnsupportedEncodingException
77     {
78        log.debug("start getQueryUrl");
79        String location = existLocation;
80        if(collectionName == null || collectionName.trim().length() == 0) {
81           collectionName = "";
82        }
83        location += "/servlet/db/" + collectionName;
84        log.debug("end getQueryUrl");
85        return location;
86        //return new URL(location);
87     }
88     
89     public Document getCollection(String collectionName)
90     throws MalformedURLException, ParserConfigurationException,
91     IOException, UnsupportedEncodingException, SAXException {
92         return DomHelper.newDocument(new URL(getQueryUrl(collectionName)));
93     }
94  
95  
96     public Document getResource(String collectionName,String resource)
97         throws MalformedURLException, ParserConfigurationException,
98         IOException, UnsupportedEncodingException, SAXException
99     {
100 
101        String resourceUniqueName = resource.replaceAll("[^//w*]","_");
102        return DomHelper.newDocument(new URL(getQueryUrl(collectionName + "/" + resourceUniqueName + ".xml")));
103    }
104 
105 
106    public Document runQuery(String collectionName, String xql)
107               throws MalformedURLException, ParserConfigurationException,
108                      IOException, UnsupportedEncodingException, SAXException {
109       log.debug("start runQuery");
110       Document queryDoc = null;
111       int numberOfResourcesReturned = conf.getInt("exist.query.returncount", 25);
112       log.info("max number of resources to be returned = " + numberOfResourcesReturned);
113 
114       String query = "<query xmlns=\"http://exist.sourceforge.net/NS/exist\"" +
115          " start=\"1\" max=\"" + numberOfResourcesReturned + "\">" +
116          "<text><![CDATA[" + xql + "]]></text></query>";
117       queryDoc = DomHelper.newDocument(query);
118       //System.out.println("the exist query to be posted = " + query);
119       log.info("query to be posted = " + query);
120       long beginQ = System.currentTimeMillis();
121       log.info("Query begin time: " + beginQ);
122       
123       HttpClient httpclient = new HttpClient();
124       /*
125       httpclient.getState().setCredentials(
126               new AuthScope("www.verisign.com", 443, "realm"),
127               new UsernamePasswordCredentials("username", "password")
128           );
129       */
130       //httpclient.getState().setCredentials(null,existLocation,new UsernamePasswordCredentials("kevindd", "testkevindd"));
131       //System.out.println("now trying nullwrealm");
132       //httpclient.getState().setCredentials("realm",null,new UsernamePasswordCredentials("kevindd", "testkevindd"));
133 
134       
135       
136       //URL postURL = getQueryUrl(collectionName);
137       String queryURL = getQueryUrl(collectionName);
138       PostMethod post = new PostMethod(queryURL);
139       //post.setDoAuthentication(true);
140 
141       /*
142       HttpURLConnection huc = (HttpURLConnection)postURL.openConnection();
143       huc.setRequestProperty("Content-Type", "text/xml");
144       huc.setDoOutput(true);
145       huc.setDoInput(true);
146       huc.connect();
147       DataOutputStream dos = new DataOutputStream(huc.getOutputStream());
148       DomHelper.DocumentToStream(queryDoc,dos);      
149       dos.flush();
150       dos.close();
151       */
152       String xml = DomHelper.DocumentToString(queryDoc);
153       post.setRequestBody(xml);
154       if (xml.length() < Integer.MAX_VALUE) {
155           post.setRequestContentLength((int)xml.length());
156       } else {
157           post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
158       }
159 //    Specify content type and encoding
160       // If content encoding is not explicitly specified
161       // ISO-8859-1 is assumed
162       post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
163 //    Get HTTP client
164       
165       // Execute request
166       int result = httpclient.executeMethod(post);
167       log.info("result of status code of query = " + result);
168       if(result != 200) {
169           String error = post.getResponseBodyAsString();
170           log.error("Seems to be a problem with query = " + error);
171           throw new IOException(error);          
172       }
173       //Document resultDoc = DomHelper.newDocument(post.getResponseBodyAsString());
174       Document resultDoc = DomHelper.newDocument(post.getResponseBodyAsStream());
175       // Release current connection to the connection pool once you are done
176       post.releaseConnection();
177 
178       //Document resultDoc = DomHelper.newDocument(huc.getInputStream());
179       //System.out.println("the resultDoc in QueryDbservice = " + DomHelper.DocumentToString(resultDoc));
180       long endQ = System.currentTimeMillis();
181       log.info("Query end time: " + endQ);
182       log.info("Query total time: " + (endQ - beginQ));
183       log.debug("end runQuery");
184       return resultDoc;
185    }
186 }
187 
188 /*
189 $Log: QueryDBService.java,v $
190 Revision 1.7  2004/12/18 18:30:16  jdt
191 KMB's merges:
192 		Reg_KMB_728 astrogrid/registry
193           o Reg_KMB_728 astrogrid/workflow
194           o Reg_KMB_728 astrogrid/community
195 
196           o Exist_KMB_613 astrogrid/exist
197           o Reg_KMB_605 astrogrid/auto-integration -- only r
198 
199 Revision 1.6.10.3  2004/12/13 21:20:15  KevinBenson
200 added a default on the maven xml, changed where it logs and throws an exception on something that is not a 200 status code returned
201 
202 Revision 1.6.10.2  2004/12/02 23:22:24  KevinBenson
203 added a getCollection to it
204 
205 Revision 1.6.10.1  2004/11/26 22:00:16  KevinBenson
206 new changes to apache commons http
207 
208 Revision 1.6  2004/11/03 00:05:00  mch
209 Fix for returncount default
210 
211  */
212