KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > rdql > parser > Q_Query


1 /*
2  * (c) Copyright 2001, 2002, 2003, 2004, 2005 Hewlett-Packard Development Company, LP
3  * [See end of file]
4  */

5
6 /* Generated By:JJTree: Do not edit this line. Q_Query.java */
7
8 package com.hp.hpl.jena.rdql.parser;
9
10
11 import com.hp.hpl.jena.datatypes.xsd.*;
12 import com.hp.hpl.jena.rdql.*;
13
14 import java.util.* ;
15
16 /** Concrete result of parsing a query.
17  * This is the top node inth eabstract syntax tree generated by the jjtree/javacc grammar.
18  * After being created this class builds a Query suitable for execution. After that,
19  * this is not used, although many of the syntax tree nodes are used as they implement
20  * the interfaces needed by the abstarct query model.
21  */

22
23 public class Q_Query extends SimpleNode
24 {
25     
26     public Q_Query(int id) { super(id); }
27
28     public Q_Query(RDQLParser p, int id) { super(p, id); }
29
30     private Query query = null ;
31
32     // --------------------------------------------------------------------
33

34     boolean selectAllVars = false ;
35
36     // Post parsing fixups.
37
// This is to rearrange the parse tree (pull up the structural nodes
38
// and remove the need for later casting).
39
// It separates the parse tree from the query processor.
40
// By the end, the only classes of relevance should be:
41
// Var
42
// Expr
43
// Value
44
// TriplePattern
45
// all nicely inserted into the Query object.
46

47     // This code could live in the parser object itself but then it is stored in the
48
// .jjt file, making development harder.
49

50     public void phase2(Query q)
51     {
52         query = q ;
53         try {
54             int numQueryChildren = jjtGetNumChildren() ;
55             // Firstly , fix up URIs and qnames.
56
// Do this always because of default prefixes.
57

58             for ( int j = 0 ; j < numQueryChildren ; j++ )
59             {
60                 Node n = jjtGetChild(j) ;
61                 if ( n instanceof Q_PrefixesClause )
62                 {
63                     extractPrefixes(q, (Q_PrefixesClause)n) ;
64                 }
65             }
66             this.postParse(q) ;
67             
68             int i = 0 ;
69             // Select
70
if ( jjtGetChild(i) instanceof Q_SelectClause )
71             {
72                 extractVarList(q, jjtGetChild(i)) ;
73                 i++ ;
74             }
75             else
76                 throw new RDQL_InternalErrorException("Parser didn't catch absense of select clause") ;
77
78             // Source
79
if ( jjtGetChild(i) instanceof Q_SourceClause )
80             {
81                 // SourceClause -> SourceSelector -> URL
82
int numSources = jjtGetChild(i).jjtGetNumChildren() ;
83                 if ( numSources > 1 )
84                 {
85                     throw new QueryException("Error: Multiple sources in FROM clause") ;
86                 }
87                 
88                 // This coide is waiting to be fixed for multiple sources
89
// That requires an interface change to Query
90
for ( int j = 0 ; j < numSources ; j++ )
91                 {
92                     Node n = jjtGetChild(i).jjtGetChild(j).jjtGetChild(0) ;
93                     String JavaDoc source = ((Q_URL)n).urlString ;
94                     // Just the first
95
if ( j == 0 )
96                         q.setSourceURL(source) ;
97                 }
98                 i++ ;
99             }
100
101             // Triple patterns
102

103             if ( jjtGetChild(i) instanceof Q_TriplePatternClause )
104             {
105                 // Convert to graph-level query.
106
extractTriplePatternsFP(q, jjtGetChild(i)) ;
107                 i++ ;
108             }
109             else
110                 throw new RDQL_InternalErrorException("Parser didn't catch absense of triple patterns") ;
111
112             // Constraints
113

114             if ( i < numQueryChildren )
115             {
116                 if ( jjtGetChild(i) instanceof Q_ConstraintClause )
117                 {
118                     extractConstraints(q, jjtGetChild(i)) ;
119                     i++ ;
120                 }
121             }
122         }
123         catch (RDQL_InternalErrorException e) { throw e ; }
124         catch (QueryException qEx) { throw qEx; }
125         catch (ClassCastException JavaDoc e) { throw new RDQL_InternalErrorException("Parser generated illegal parse tree: "+e) ; }
126         catch (Exception JavaDoc e)
127         {
128             e.printStackTrace(System.err) ;
129             throw new RDQL_InternalErrorException("Unknown exception: "+e) ;
130         }
131     }
132
133
134     /** Formats the query from phase 2 in a style that is acceptable to the
135      * parser. Note this is NOT guaranteed to be the same as the original string
136      * because we may have done optimizations or other rearranging.
137      * It should give the same answers on the same dataset.
138      */

139
140     public String JavaDoc toString()
141     {
142         throw new UnsupportedOperationException JavaDoc ("Q_Query.toString()") ;
143         /*
144         StringBuff sbuff = new StringBuffer(1024) ;
145         sbuff.append(RDQLParserConstants.tokenImage[RDQLParserConstants.SELECT]) ;
146         for ( for i = 0 ; i < query.resultVars.size() ; i++ )
147             sbuff.append(" ?").append(((Var)query.resultVars.get(i)).getVarName()) ;
148
149         sbuff.append(" ").append(RDQLParserConstants.tokenImage[RDQLParserConstants.WHERE]) ;
150         for ( for i = 0 ; i < query.constraints ; i++ )
151         {
152             TriplePattern tp = (TriplePattern)query.constraints.get(i) ;
153             sbuff.append(tp.toString()) ;
154         }
155         */

156     }
157
158     private void extractVarList(Query q, Node node)
159     {
160         int n = node.jjtGetNumChildren() ;
161         selectAllVars = ( n == 0 ) ;
162
163         for ( int i = 0 ; i < n ; i++ )
164         {
165             Node c = node.jjtGetChild(i) ;
166             if ( ! (c instanceof Q_Var) )
167                 throw new RDQL_InternalErrorException("Internal error: parser created '"+c.getClass().getName()+"' when Q_Var expected") ;
168             Q_Var v = (Q_Var)c ;
169             q.addResultVar(v.varName) ;
170         }
171     }
172
173     // Like the above but for Graph objects, not Model objects.
174

175     private void extractTriplePatternsFP(Query q, Node node)
176     {
177         Q_TriplePatternClause tpc = (Q_TriplePatternClause)node ;
178         List patternVars = q.getBoundVars() ;
179         int n = tpc.jjtGetNumChildren() ;
180         for ( int j = 0 ; j < n ; j++ )
181         {
182             Q_TriplePattern tp = (Q_TriplePattern)tpc.jjtGetChild(j) ;
183             if ( tp.jjtGetNumChildren() != 3 )
184                 throw new RDQL_InternalErrorException("Triple pattern has "+tp.jjtGetNumChildren()+" children") ;
185
186             com.hp.hpl.jena.graph.Node nodeSubj = convertToGraphNode(tp.jjtGetChild(0), q) ;
187             com.hp.hpl.jena.graph.Node nodePred = convertToGraphNode(tp.jjtGetChild(1), q) ;
188             com.hp.hpl.jena.graph.Node nodeObj = convertToGraphNode(tp.jjtGetChild(2), q) ;
189             q.addTriplePattern(nodeSubj, nodePred, nodeObj) ;
190         }
191         
192         if ( selectAllVars )
193         {
194             for ( Iterator iter = patternVars.iterator() ; iter.hasNext() ; )
195             {
196                 String JavaDoc varName = (String JavaDoc)iter.next() ;
197                 q.addResultVar(varName) ;
198             }
199         }
200         
201         
202     }
203
204     // This operation puts all the thing to graph node conversion code in
205
// one place.
206

207     
208     static private com.hp.hpl.jena.graph.Node convertToGraphNode(Node n, Query q)
209     {
210         if ( n instanceof Var )
211         {
212             String JavaDoc varName = ((Var)n).getVarName() ;
213             q.addBoundVar(varName) ;
214             return com.hp.hpl.jena.graph.Node.createVariable(((Var)n).getVarName()) ;
215         }
216         if ( n instanceof ParsedLiteral)
217         {
218             ParsedLiteral v = (ParsedLiteral)n ;
219             
220             if ( v.isNode() )
221                 return v.getNode() ;
222
223             if ( v.isURI() )
224                 return com.hp.hpl.jena.graph.Node.createURI(v.getURI()) ;
225                 
226             if ( v.isString() )
227                 return com.hp.hpl.jena.graph.Node.createLiteral(v.getString(), null, null) ;
228             if ( v.isBoolean())
229                 return com.hp.hpl.jena.graph.Node.createLiteral(v.asUnquotedString(), null,null) ;
230             
231 //
232
if ( v.isInt() )
233                 return com.hp.hpl.jena.graph.Node.createLiteral(
234                         v.asUnquotedString(), null, XSDDatatype.XSDinteger) ;
235             if ( v.isDouble())
236                 return com.hp.hpl.jena.graph.Node.createLiteral(
237                     v.asUnquotedString(), null, XSDDatatype.XSDdouble) ;
238
239             String JavaDoc s = v.getString() ;
240             System.err.println("BUG: "+s) ;
241                 
242 //
243
//
244
// //if ( v.isNumber())
245

246         }
247         throw new RDQL_InternalErrorException("convertToGraphNode encountered strange type: "+n.getClass().getName()) ;
248                                                                 
249     }
250
251     private void extractConstraints(Query q, Node node)
252     {
253         Q_ConstraintClause qcc = (Q_ConstraintClause)node ;
254         int n = qcc.jjtGetNumChildren() ;
255         for ( int j = 0 ; j < n ; j++ )
256         {
257             Object JavaDoc obj = qcc.jjtGetChild(j) ;
258             if ( ! ( obj instanceof Constraint ) )
259                 throw new RDQL_InternalErrorException("Parse node in AND clause isn't a Constraint") ;
260             //q.addConstraint(new ConstraintExpr(expr)) ;
261
q.addConstraint((Constraint)obj) ;
262         }
263     }
264
265     private void extractPrefixes(Query q, Q_PrefixesClause qns)
266     {
267         if ( qns == null )
268             return ;
269     
270         int n = qns.jjtGetNumChildren() ;
271         for ( int j = 0 ; j < n ; j++ )
272         {
273             Q_PrefixDecl qnsd = (Q_PrefixDecl)qns.jjtGetChild(j) ;
274             // They should appear in pairs: an identifier and a URI
275
for ( int k = 0 ; k < qnsd.jjtGetNumChildren() ; k+=2 )
276             {
277                 Q_Identifier id = (Q_Identifier)qnsd.jjtGetChild(k) ;
278                 //Object tmp = qnsd.jjtGetChild(k+1) ; // Temp debug
279
Q_URI uri = (Q_URI)qnsd.jjtGetChild(k+1) ;
280                 query.setPrefix(id.toString(), uri.toString()) ;
281             }
282         }
283     }
284 }
285
286 /*
287  * (c) Copyright 2001, 2002, 2003, 2004, 2005 Hewlett-Packard Development Company, LP
288  * All rights reserved.
289  *
290  * Redistribution and use in source and binary forms, with or without
291  * modification, are permitted provided that the following conditions
292  * are met:
293  * 1. Redistributions of source code must retain the above copyright
294  * notice, this list of conditions and the following disclaimer.
295  * 2. Redistributions in binary form must reproduce the above copyright
296  * notice, this list of conditions and the following disclaimer in the
297  * documentation and/or other materials provided with the distribution.
298  * 3. The name of the author may not be used to endorse or promote products
299  * derived from this software without specific prior written permission.
300  *
301  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
302  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
303  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
304  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
305  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
306  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
307  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
308  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
309  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
310  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
311  */

312
Popular Tags