KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exoplatform > services > xml > querying > impl > xtas > Query


1 package org.exoplatform.services.xml.querying.impl.xtas;
2
3 import java.io.IOException JavaDoc;
4 import java.io.InputStream JavaDoc;
5 import java.util.ArrayList JavaDoc;
6 import java.io.ByteArrayInputStream JavaDoc;
7
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
10 import org.exoplatform.services.xml.querying.InvalidDestinationException;
11 import org.exoplatform.services.xml.querying.InvalidSourceException;
12 import org.exoplatform.services.xml.querying.InvalidStatementException;
13 import org.exoplatform.services.xml.querying.QueryRunTimeException;
14 import org.exoplatform.services.xml.querying.Statement;
15 import org.exoplatform.services.xml.querying.UniFormTransformationException;
16 import org.exoplatform.services.xml.querying.XMLData;
17 import org.exoplatform.services.xml.querying.XMLQuery;
18 import org.exoplatform.services.xml.querying.impl.xtas.resource.Resource;
19 import org.exoplatform.services.xml.querying.impl.xtas.resource.ResourceResolver;
20
21 /**
22  * Encapsulates XTAS Query
23  * Life Cycle of Query:
24  * 1. Create (constructor)
25  * 2. setInputStream() (optional if not in the Content)
26  * 3. execute()
27  * 4. serialize() or getResult()
28  * For the time only one instruction will be executed
29  * @version $Id: Query.java 566 2005-01-25 12:50:49Z kravchuk $
30  *
31  */

32 public class Query implements XMLQuery {
33
34     private static Log _log = LogFactory.getLog(Query.class);
35
36     private BaseStatement statement;
37     private Object JavaDoc resourceContext;
38
39     private UniFormTree input;
40     private UniFormTree result = null;
41
42 // private Resource destination;
43
private boolean validate=false;
44
45     private Instruction executedInstruction;
46
47     /** @link dependency
48      * @stereotype use*/

49     /*# QueryType lnkQueryType; */
50
51     /** @link dependency
52      * @stereotype use*/

53     /*# ResourceResolver lnkResourceResolver; */
54
55     public Query()
56     {
57     }
58
59     /**
60      * The main Constructor.
61      * <code>content</code> must be with source - attribute
62      */

63     public Query(Statement statement) throws InvalidSourceException
64     {
65        prepare ( statement );
66     }
67
68     /**
69      * Constructor for external source (inputStream)
70      * NOTE: stream must contain the well-formed XML!
71      */

72     public Query(Statement statement, InputStream JavaDoc inputStream) throws InvalidSourceException
73     {
74          this(statement);
75          setInputStream(inputStream);
76     }
77
78     /**
79      * Executes this query
80      * For the time only one instruction will executed
81      */

82     public void execute() throws InvalidSourceException, QueryRunTimeException
83     {
84
85        if( this.statement == null)
86            throw new QueryRunTimeException("Query execution Error: XTAS Statement Can Not be NULL. Call prepare() first !");
87
88        Instruction curInstruction = null;
89
90        int count = statement.getInstructions().length;
91        if( count == 0)
92            throw new QueryRunTimeException("Query execution Error: XTAS Statement has not instructions to execute !");
93
94        if( count > 1)
95            throw new QueryRunTimeException("TEMPORARY Query execution Error: XTAS Statement does not support more than 1 instructions!");
96
97
98        for(int i=0; i<count; i++) {
99
100           try {
101
102                 curInstruction = statement.pickNextInstruction();
103
104                 curInstruction.compile();
105
106                 curInstruction.setContext(resourceContext);
107
108                 result = curInstruction.execute(input);
109
110            } catch (InvalidStatementException e) {
111
112                throw new QueryRunTimeException(e.toString());
113
114            } catch (ForbiddenOperationException e) {
115
116                throw new QueryRunTimeException(e.toString());
117
118            }
119
120            executedInstruction = curInstruction;
121        }
122
123     }
124
125     /**
126      * Serializes (stores) querie's result into <destination>
127      */

128     public void serialize() throws IOException JavaDoc, InvalidDestinationException
129     {
130
131        Resource destination;
132        if( result == null ) // DO NOTHING!
133
return;
134
135         String JavaDoc destId = statement.getDestinationId();
136
137
138         if( destId != null ) {
139            try {
140
141                destination = ResourceResolver.getInstance().getResource( destId );
142
143            } catch (Exception JavaDoc e) {
144
145                 throw new InvalidDestinationException("Query.serialize() Can not prepare query's destination. Reason: " + e);
146
147            }
148
149         } else {
150                 throw new InvalidDestinationException("Query.serialize() Can not prepare query's destination. Destination ID is NULL ");
151         }
152     
153        if( destination != null ) {
154            try {
155
156               destination.setContext(resourceContext);
157               WellFormedUniFormTree _xml = UniFormConverter.toWellForm(this.result);
158
159               _xml.setOmitXmlDeclaration(false);
160               _xml.setIndentOutput(true);
161
162               String JavaDoc sysId = null;
163               String JavaDoc pubId = null;
164               if( input != null ) {
165
166                   WellFormedUniFormTree _inxml = UniFormConverter.toWellForm(this.input);
167                   sysId = _inxml.getValidationHandler().getSystemId();
168                   pubId = _inxml.getValidationHandler().getPublicId();
169
170               }
171
172               if( sysId != null )
173                   _xml.setDTDSystemId(sysId);
174               if( pubId != null )
175                   _xml.setDTDPublicId(pubId);
176
177               if( sysId != null || pubId != null )
178                   _xml.setValidate( true );
179               else
180                   _xml.setValidate( false );
181
182               if(result != null) //DROP returns null
183
destination.save( _xml );
184
185            } catch (UniFormTransformationException e) {
186
187                throw new InvalidDestinationException("Can not save the query result Reason: " + e);
188
189            } catch (IOException JavaDoc e) {
190
191                throw new IOException JavaDoc("Query Serialization I/O error: "+ e);
192            } catch (Exception JavaDoc e) {
193
194                throw new IOException JavaDoc("Query Serialization error: "+ e);
195            } finally {
196                destination.close();
197            }
198
199
200        } else
201            throw new InvalidDestinationException("XTAS Destination not described!");
202
203     }
204     /**
205      * Prepares this query
206      */

207     public void prepare( Statement statement ) throws InvalidSourceException
208     {
209        prepare( statement, null );
210     }
211
212     /**
213      * Prepares this query
214      */

215     public void prepare( Statement statement, Object JavaDoc resourceContext ) throws InvalidSourceException
216     {
217
218         String JavaDoc srcId = statement.getSourceId();
219       
220         _log.debug("Prepare query: "+statement.toString()+" Context: "+resourceContext);
221
222 // System.out.println("Prepare query: "+statement.toString()+" Context: "+resourceContext);
223

224         Resource source = null;
225
226         try {
227
228            if( srcId != null ) {
229
230               source = ResourceResolver.getInstance().getResource( srcId );
231               source.setContext(resourceContext);
232               loadSource(source);
233            }
234
235         } catch (Exception JavaDoc e) {
236              throw new InvalidSourceException("Can not prepare query's source. Source: "+srcId+" Reason: " + e);
237
238         } finally {
239
240            if( source != null )
241               source.close();
242         }
243
244         this.statement = (BaseStatement)statement;
245         this.resourceContext = resourceContext;
246
247     }
248
249     /**
250      * Prepares this query
251      * Statement's source ID will be ignored
252      * Input for the query is result of previous execution.
253      */

254
255     public void prepareNext( Statement statement ) throws InvalidSourceException
256     {
257
258         if(result == null)
259              throw new InvalidSourceException("Query.prepareNext("+statement+") Query's result is NULL!");
260         this.input = this.result;
261         this.statement = (BaseStatement)statement;
262
263     }
264
265    public void setInputStream(InputStream JavaDoc inputStream) throws InvalidSourceException
266     {
267         if (inputStream == null)
268             throw new InvalidSourceException("Can not init query inputStream with NULL value!");
269
270         // It is not necessary to be Well formed here
271
try {
272
273             this.input = new UniFormTreeFragment ();
274             ((UniFormTreeFragment)this.input).init( inputStream );
275
276         } catch (UniFormTransformationException e) {
277
278             throw new InvalidSourceException("Can not init query's inputStream. Reason: " + e);
279
280         }
281     }
282
283     /**
284      * Laizy loader for the XML source load in run-time
285      */

286     public void loadSource(Resource source) throws InvalidSourceException
287     {
288
289          // From here the input MUST be Well Formed!
290
try {
291
292              this.input = (UniFormTree)source.load();
293
294          } catch (UniFormTransformationException e) {
295
296              throw new InvalidSourceException("Can not Load the source for the Query. Reason: " + e);
297
298          } catch (IOException JavaDoc e) {
299
300                throw new InvalidSourceException("Query Source I/O error: "+ e);
301          }
302     }
303
304    public XMLData getInput()
305    {
306         return input;
307    }
308
309    public void setInput(XMLData input)
310     {
311         this.input = (UniFormTree)input;
312     }
313
314     public XMLData getResult()
315     {
316         return result;
317     }
318
319    public void setResult(XMLData result)
320     {
321         this.result = (UniFormTree)result;
322     }
323
324     /**
325      * For debugging only!
326      */

327     public Instruction getExecutedInstruction() throws ForbiddenOperationException
328     {
329         if (executedInstruction != null)
330
331            return executedInstruction;/*.toString();*/
332         else
333
334            return null;
335     }
336
337     public void setDestination(String JavaDoc destinationId)
338     {
339         this.statement.setDestinationId(destinationId);
340     }
341
342     /**
343      * Constructor For chain of queries
344      * Applicable only for well-formed result !!!!
345      * @deprecated Use prepareNext instead.
346      */

347     public Query createNext(Statement statement)
348     {
349         Query q = null;
350
351         try {
352
353             q = new Query( statement );
354             q.setInput( UniFormConverter.toFragment( result ) );
355
356         // Impossible situation!
357
} catch (Exception JavaDoc e) {
358             _log.fatal("Query.createNext STRANGE Exception!", e);
359         }
360         return q;
361
362     }
363
364 }
365
Popular Tags