source: MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/model/Query.java @ 879

Last change on this file since 879 was 879, checked in by gaba, 14 years ago
File size: 10.1 KB
Line 
1package eu.clarin.cmdi.mdservice.model;
2
3/**
4 * The main model class, carrying users_query
5 * able to parse and transform the user-string
6 * and execute the query, ie issue appropriate request on the MDRepository
7 * getting the url-wording right from MDRepositoryProxy
8 *   
9 * At the moment just responsible for querying MDRepository
10 * perhaps unify approach for other proxies - subtyping this Class 
11 */
12
13import java.io.IOException;
14import java.net.MalformedURLException;
15import java.net.URL;
16
17import javax.xml.parsers.DocumentBuilder;
18import javax.xml.parsers.DocumentBuilderFactory;
19
20import org.w3c.dom.Document;
21import org.z3950.zing.cql.CQLNode;
22import org.z3950.zing.cql.CQLParseException;
23import org.z3950.zing.cql.CQLParser;
24
25import eu.clarin.cmdi.mdservice.action.Admin;
26import eu.clarin.cmdi.mdservice.action.MDTransformer;
27
28public class Query {   
29        public static String COLLECTIONS = "collections";
30        public static String COLUMNS = "columns";
31        public static String MODEL = "model";
32        public static String RECORDSET = "recordset";
33        public static String RECORD = "record";
34       
35        public static String PARSED = "parsed";
36        public static String PARSEERROR = "parseerror";
37       
38        private String type;
39        /**
40         * meant a target url/service, allowing querying different services on per query basis
41         * not used yet
42         */
43        private String target; 
44       
45        private URL targetRequest;
46        private String syntax = "cql";  /* cql, cmdIndex, xpath */
47        private String squery_string;
48        private String query_string;
49        private String full_query_string;
50        private CQLNode query_cql;
51        private String msg;
52        /**
53         * temporary default;
54         */
55        private String collection="";
56        private String columns="Id,name";
57        private String startRecord = "1";
58        private String maximumRecords = "50";
59        private String squery = null;
60        private int maxdepth=1;
61       
62        /**
63         * reference to the result-object
64         */
65        private Result result = new Result(this);
66
67       
68        public Query(String squeryString, String queryString) {         
69                this(squeryString, queryString, MODEL);
70        }
71
72        /**     
73         * main constructor, with user's querystring and type of the query, and context-collection (at the moment just one)
74         * @param queryString
75         * @param type
76         * @param collection
77         */
78
79        public Query(String squeryString,String queryString, String type, String collection, String columns) {
80                this.type =type;
81                setFullQueryString(squeryString, queryString);
82                setCollection(collection);
83                setColumns(columns);
84        }
85       
86        /**     
87         * main constructor, with user's querystring and type of the query, and context-collection (at the moment just one)
88         * @param queryString
89         * @param type
90         * @param collection
91         */
92
93        public Query(String squeryString, String queryString, String type, String collection) {
94                this.type =type;
95                setFullQueryString(squeryString, queryString);
96                setCollection(collection);
97        }
98
99        /**     
100         * another constructor, with user's querystring and type of the query;
101         * problematic not setting the collection! 
102         * @param queryString
103         * @param type
104         */
105
106        public Query(String squeryString, String queryString, String type) {
107                this.type =type;
108                if (squeryString == null)squeryString =""; 
109                setFullQueryString(squeryString, queryString);
110        }
111
112        public Boolean isStatus(String qstatus) {
113                return (qstatus.equals(getStatus()));
114        }
115       
116        public String getStatus() {
117                if (type.equals(Query.RECORDSET) && query_cql== null && (full_query_string != "")) {
118                        return Query.PARSEERROR;
119                } else {
120                        return Query.PARSED;
121                }
122               
123        }
124       
125        public String getType() {
126                return type;
127        }
128
129        public void setType(String type) {
130                this.type = type;
131        }
132
133        public String getQueryString() {
134                return query_string;
135        }
136
137        public void setFullQueryString(String squeryString, String queryString) {
138               
139                query_string=queryString;
140               
141                if (squeryString.trim().length() == 0){
142                        squeryString = null;
143                }
144                if (queryString.trim().length() == 0){
145                        queryString = null;
146                }
147               
148                String squery = createsqueryString(squeryString);
149                if (squery != null && queryString != null){
150                        full_query_string = "(" + squery + " ) and (" + queryString + ")";
151                } else if (squery != null) {
152                        full_query_string = squery;
153                } else if (queryString != null){
154                        full_query_string = queryString;
155                } else {
156                        full_query_string = "";
157                }
158                Admin.notifyUser("QUERY.FULLQUERYSTRING:" + full_query_string);
159                if (type.equals(RECORDSET) && (full_query_string.length() > 0)) {       
160                        parse();
161                        //preprocess();
162                }
163                       
164        }
165       
166        public String getFullQueryString() {
167                return full_query_string;
168        }
169
170       
171        public void setCollection(String collection) {
172                if (collection!=null) {
173                        this.collection = collection;
174                }
175        }
176       
177        public String getCollection() {
178                return collection;
179        }
180       
181        public String getColumns() {
182                return columns;
183        }
184       
185        public void setColumns(String columns) {
186                if (columns!=null) {
187                        this.columns = columns;
188                }
189        }
190
191        public String getSQuery() {
192                return this.squery;
193        }
194       
195        public void setSQuery(String squery) {
196                if (squery!=null) {
197                        this.squery = squery;
198                }
199        }
200       
201        public String getStartRecord() {
202                return startRecord;
203        }
204       
205        public void setStartRecord(String startRecord) {
206                if (startRecord!=null) {
207                        this.startRecord = startRecord;
208                }
209        }
210       
211        public String getMaximumRecords() {
212                return maximumRecords;
213        }
214       
215        public void setMaximumRecords(String maximumRecords) {
216                if (maximumRecords!=null) {
217                        this.maximumRecords = maximumRecords;
218                }
219        }
220        public void setMaxdepth(int maxdepth) {
221                if (maxdepth > 0) {
222                        this.maxdepth = maxdepth;
223                }
224        }
225
226        public int getMaxdepth() {
227                return maxdepth;
228        }
229
230        public void setResult(Result result) {
231                this.result = result;
232        }
233
234
235        public Result getResult() {
236                return result;
237        }
238       
239        public String getMsg() {
240                return msg;
241        }
242
243        public void setMsg(String msg) {
244                this.msg = msg;
245        }
246
247        // apply rules form squery
248        public String createsqueryString (String _squery){
249                String sq = null;
250               
251                if (_squery !=null){
252                        sq = "* any " + _squery;
253                }
254
255                return sq;
256        }
257        public static String getSimpleQueryString(String querystring) {
258                String[] arr_and = querystring.split(" and ");
259                String simple_form = "";
260                String simple_form_all = "";
261                String rel = "";
262               
263                for( int i=0;i<arr_and.length;i++){
264                        arr_and[i] = arr_and[i].trim();
265                        String[] arr_or = arr_and[i].split(" or ");
266                        simple_form = "";
267                        for( int j=0;j<arr_or.length;j++){
268                                arr_or[j] = arr_or[j].trim();
269                                while (arr_or[j].substring(0,1).equals("(") ) {
270                                        arr_or[j] = arr_or[j].substring(1,arr_or[j].length());
271                                        arr_or[j] = arr_or[j].trim();
272                                }
273                                while ( arr_or[j].substring(arr_or[j].length()-1,arr_or[j].length()).equals(")")){
274                                        arr_or[j] = arr_or[j].substring(0,arr_or[j].length()-1);
275                                        arr_or[j] = arr_or[j].trim();
276                                }
277                                if (j > 0) { 
278                                        rel = " or ";
279                                } else {
280                                        rel = "";
281                                }
282                                simple_form = simple_form + rel + arr_or[j];
283                        }
284                        //Admin.notifyUser(simple_form);
285                        if (arr_or.length > 1){
286                                simple_form = "(" + simple_form + ") ";
287                        }
288                        if (i > 0) { 
289                                rel = " and  ";
290                        } else {
291                                rel = "";
292                        }
293                        simple_form_all = simple_form_all + rel + simple_form;
294                       
295                }
296               
297                return simple_form_all;
298        }
299        /**
300         * construct the URL-Param
301         * @return
302         * @throws MalformedURLException
303         * TODO url-encode (especially the query-param) !
304         */
305        public String toURLParam() throws MalformedURLException {
306               
307                String targetRequest;
308               
309                if (type.equals(MODEL)) {
310                        targetRequest = toCMDIndex() + "&maxdepth=" + getMaxdepth()  ; /* + "&maxdepth=" + getMaxdepth() );  "&collection=" + getCollection() + */
311                } else if (type.equals(RECORD)) {
312                        //  2010-07-11 this is just a hack, because url-encoding the handle acted strange
313                        //String corrid = getQueryString().replace('_', '/');
314                        String corrid = getQueryString();
315                        targetRequest = "//MdSelfLink[.='" + corrid + "']";                     
316                } else { 
317                        if (query_cql == null){
318                                targetRequest =  "//*" + "&collection=" + getCollection();
319                        } else {
320                                targetRequest = toXPath() + "&collection=" + getCollection();   
321                        }
322                        if ((startRecord != null) && (maximumRecords != null)) {
323                                targetRequest = targetRequest +  "&startRecord=" + getStartRecord() + "&iend=" + getMaximumRecords();
324                        }
325                }
326               
327                return targetRequest;
328               
329        }
330       
331        /**
332         * tries to parse the full_query_string according the CQL-syntax
333         * if successful returns the root-node of the parse-tree
334         */
335        public CQLNode parse() {
336                 
337          try {
338                CQLParser parser = new CQLParser();             
339                query_cql = parser.parse(full_query_string);
340          }
341                catch (CQLParseException e) {
342                        // TODO better handling of failed parse 
343                        setMsg("Query.ParseError-"+ e.getClass() + ": " + e.getMessage());
344                } catch (IOException e) {
345                        // TODO Auto-generated catch block
346                        e.printStackTrace();
347                }
348               
349       
350                return query_cql;
351        }
352       
353        /**
354         */
355        public void  preprocess() {
356                 
357          try { 
358                Admin.notifyUser(toXCQL());
359                       
360               
361                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
362                DocumentBuilder builder = factory.newDocumentBuilder();
363                Document doc = builder.parse(new org.xml.sax.InputSource(new java.io.StringReader(toXCQL())));
364                       
365                //Admin.notifyUser("document created");
366                SearchClauses searchclauses = new SearchClauses(doc);
367                //do the processing
368                searchclauses.process();
369                String xml_s = searchclauses.toXML();
370               
371                //Admin.notifyUser("AAAA2:" + xml_s);
372          }
373                catch (Exception e) {
374                        e.printStackTrace();
375                }
376                return;
377        }
378       
379       
380        /**
381         * provides a xml-version of the query (if parsed successfully)
382         * according to the XCQL-schema defined in the SRU/CQL standard
383         * @return
384         */
385        public String toXCQL() {       
386                 return query_cql.toXCQL(0);
387        }
388
389        /**
390         * provides a xpath version of the query, based on the XCQL-version,
391         * applying a stylesheet on the XCQL-version 
392         * @return XPath-query
393         */
394        public String toXPath() {       
395                MDTransformer.getMDTransformer().setParams(MDTransformer.createParamsMap("XCQL2XPATH"));
396                return MDTransformer.getMDTransformer().transformXML(toXCQL());
397        }
398
399        /**
400         * if the query is just a path-like structure
401         * "transforms" to cmdIndex-format, means replace('.', '/') ;)
402         * @return
403         */
404        public String toCMDIndex() {   
405                 return query_string.replace('.', '/'); 
406        }
407
408        /**
409         * OBSOLETED! MDRepoProxyAction executes the request, Query only provides itself encoded
410         * runs the query! by opening the stream on the targetService/URL
411         * setting it as inputStream of the Result
412         * @throws Exception
413         */
414/*      public void execute() throws Exception {
415                       
416                result.setInputStream(getTargetRequest().openStream());
417       
418        }
419*/
420       
421       
422}
Note: See TracBrowser for help on using the repository browser.