KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > joseki > rdfqueryremote


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

5
6 package joseki;
7
8 import java.util.* ;
9 import java.io.* ;
10 import java.net.* ;
11
12 import jena.cmdline.*;
13
14 import com.hp.hpl.jena.joseki.* ;
15
16 import com.hp.hpl.jena.rdf.model.* ;
17 //import com.hp.hpl.jena.rdf.model.impl.* ;
18
//import com.hp.hpl.jena.vocabulary.* ;
19
import com.hp.hpl.jena.rdql.* ;
20
21 /** Command line application to issue queries against a remote model.
22  *
23  * @author Andy Seaborne
24  * @version $Id: rdfqueryremote.java,v 1.7 2004/04/30 14:13:14 andy_seaborne Exp $
25  */

26
27
28 public class rdfqueryremote
29 {
30     public static final String JavaDoc defaultURL = "http://localhost:2020/rdfserver/rdf" ;
31     public static URL targetURL = null ;
32     public static String JavaDoc modelURLStr = null ;
33     
34     public static final String JavaDoc FormatArg = "format" ;
35     public static final String JavaDoc QueryFile = "query" ;
36     public static final String JavaDoc ModelURLArg = "model" ;
37     public static final String JavaDoc ModelURLArgAlt = "url" ;
38     
39     public static boolean VERBOSE = false ;
40     public static boolean DEBUG = false ;
41     
42     static final int FMT_NONE = -1 ;
43     static final int FMT_TUPLES = 0 ;
44     static final int FMT_TEXT = 1 ;
45     static final int FMT_HTML = 2 ;
46     static final int FMT_DUMP = 3 ;
47
48     static public int outputFormat = FMT_TEXT ;
49     
50     
51     public static void main (String JavaDoc args[])
52     {
53         try {
54             String JavaDoc usageMessage = rdfqueryremote.class.getName()+
55                                     " [--verbose] [--format fmt] "+
56                                     "[--"+ModelURLArg+" modelURL] {--query file | queryString}" ;
57
58             CommandLine cmd = new CommandLine() ;
59             cmd.setUsage(usageMessage) ;
60
61             ArgDecl verboseDecl = new ArgDecl(false, "-v", "--verbose") ;
62             ArgDecl modelDecl = new ArgDecl(true, ModelURLArg, ModelURLArgAlt) ;
63             
64             cmd.add(verboseDecl) ;
65             cmd.add(modelDecl) ;
66             
67             cmd.add("--format", true) ;
68
69             cmd.add("--debug", false) ;
70             cmd.add(QueryFile, true) ;
71
72             // Addition argument, after the flags, is a query
73
cmd.process(args) ;
74
75             if ( cmd.contains("--debug") )
76                 DEBUG = true ;
77
78             if ( cmd.contains("--help") )
79             {
80                 System.err.println(usageMessage) ;
81                 System.exit(0) ;
82             }
83
84             if ( cmd.contains(verboseDecl) )
85                 VERBOSE = true ;
86
87             if ( ! cmd.contains(QueryFile) && cmd.args().size() == 0 )
88             {
89                 //System.err.println("Need either a query string or a query in a file") ;
90
System.err.println(usageMessage) ;
91                 System.exit(0) ;
92             }
93
94             if ( cmd.contains(modelDecl) )
95                 modelURLStr = cmd.getArg(modelDecl).getValue() ;
96            
97             for (Iterator iter = cmd.args().iterator(); iter.hasNext();)
98             {
99                 Arg arg = (Arg) iter.next();
100
101                 if (arg.getName().equals(FormatArg))
102                 {
103                     String JavaDoc argValue = arg.getValue();
104                     if (argValue.equalsIgnoreCase("none"))
105                         outputFormat = FMT_NONE;
106                     else if (argValue.equalsIgnoreCase("tuples"))
107                         outputFormat = FMT_TUPLES;
108                     else if (argValue.equalsIgnoreCase("tuple"))
109                         outputFormat = FMT_TUPLES;
110                     else if (argValue.equalsIgnoreCase("text"))
111                         outputFormat = FMT_TEXT;
112                     else if (argValue.equalsIgnoreCase("html"))
113                         outputFormat = FMT_HTML;
114                     else if (argValue.equalsIgnoreCase("dump"))
115                         outputFormat = FMT_DUMP;
116                     else
117                     {
118                         System.err.println("Unrecognized output format: " + argValue);
119                         System.exit(1);
120                     }
121                     continue;
122                 }
123             }
124
125             List queries = new ArrayList() ;
126
127             if ( cmd.contains(QueryFile) )
128             {
129                 try {
130                     String JavaDoc qs = com.hp.hpl.jena.util.FileUtils.readWholeFileAsUTF8(cmd.getArg(QueryFile).getValue()) ;
131                     // Goes first
132
queries.add(qs) ;
133                 } catch (IOException ioEx)
134                 {
135                     System.err.println("Failed to read file: "+cmd.getArg(QueryFile).getValue()) ;
136                     ioEx.printStackTrace(System.err) ;
137                     System.exit(1) ;
138                 }
139             }
140
141             for ( Iterator iter = cmd.items().iterator() ; iter.hasNext() ; )
142                 queries.add(iter.next()) ;
143
144             if ( queries.size() > 0 )
145             {
146                 for ( Iterator iter = queries.iterator() ; iter.hasNext(); )
147                 {
148                     String JavaDoc queryString = (String JavaDoc)iter.next() ;
149                     doOneQuery(queryString, modelURLStr) ;
150                 }
151             }
152             else
153             {
154                 // No query - do a plain GET
155
doPlainGet(modelURLStr) ;
156             }
157         }
158         catch (Exception JavaDoc e)
159         {
160             System.err.println(e.getMessage()) ;
161             //e.printStackTrace(System.err) ;
162
System.exit(9) ;
163         }
164     }
165     
166     
167     static void doOneQuery(String JavaDoc queryString, String JavaDoc modelURLstr)
168     {
169         try
170         {
171             boolean doBlank = false;
172             Query q = new Query(queryString);
173             String JavaDoc u = modelURLStr;
174
175             if (u == null)
176                 u = q.getSourceURL();
177
178             if (u == null)
179             {
180                 System.err.println("No target model for query");
181                 System.exit(1);
182             }
183
184             QueryEngineHTTP qHTTP = new QueryEngineHTTP(q, u);
185             QueryExecution qe = qHTTP;
186             
187             if ( VERBOSE )
188                 System.out.println(qHTTP.getHttpQuery().toString()) ;
189             
190             QueryResults results = qe.exec();
191
192             if (results == null)
193             {
194                 System.err.println("doOneQuery: Null results iterator");
195                 return;
196             }
197
198             QueryResultsFormatter fmt = new QueryResultsFormatter(results);
199             PrintWriter pw = new PrintWriter(System.out);
200
201             if (outputFormat == FMT_NONE)
202                 fmt.consume();
203             else
204             {
205                 if (doBlank)
206                     System.out.println();
207                 switch (outputFormat)
208                 {
209                     case FMT_TEXT :
210                         fmt.printAll(pw);
211                         break;
212                     case FMT_HTML :
213                         fmt.printHTML(pw);
214                         break;
215                     case FMT_TUPLES :
216                         fmt.dump(pw, true);
217                         break;
218                     case FMT_DUMP :
219                         fmt.dump(pw, false);
220                         break;
221                 }
222                 pw.flush();
223                 doBlank = true;
224             }
225             
226             if ( VERBOSE )
227                 ((QueryEngineHTTP)qe).getResultModel().write(System.out,"N3") ;
228             fmt.close() ;
229             results.close() ;
230             qe.close() ;
231         }
232         catch (QueryException qEx)
233         {
234             System.err.println("rdfqueryremote: "+qEx.getMessage()) ;
235             return ;
236         }
237         catch (HttpException httpEx)
238         {
239             if ( httpEx.getResponseCode() == HttpException.NoServer )
240                 System.err.println("rdfqueryremote: Failed to contact the server") ;
241             else
242                 System.err.println("Error: "+httpEx.getResponseCode()+" : "+httpEx.getResponseMessage()) ;
243             return ;
244         }
245         catch (JosekiException ex)
246         {
247             System.err.println("Exception: "+modelURLStr+" :: "+ex) ;
248             System.exit(2) ;
249         }
250     }
251     
252     static private void doPlainGet(String JavaDoc urlStr) throws MalformedURLException
253     {
254         try
255         {
256             HttpQuery q = new HttpQuery(urlStr, null);
257             Model resultModel = q.exec();
258
259             PrintWriter pw = new PrintWriter(System.out);
260             resultModel.write(pw, "N3");
261             pw.flush();
262             return;
263         }
264         catch (JosekiException jEx)
265         {
266             System.err.println("Exception for " + urlStr);
267             return;
268         }
269         catch (RDFException rdfEx)
270         {
271             System.err.println("Unexception rdf exception: " + rdfEx);
272             return;
273         }
274     }
275 }
276
277 /*
278  * (c) Copyright 2003, 2004 Hewlett-Packard Development Company, LP
279  * All rights reserved.
280  *
281  * Redistribution and use in source and binary forms, with or without
282  * modification, are permitted provided that the following conditions
283  * are met:
284  * 1. Redistributions of source code must retain the above copyright
285  * notice, this list of conditions and the following disclaimer.
286  * 2. Redistributions in binary form must reproduce the above copyright
287  * notice, this list of conditions and the following disclaimer in the
288  * documentation and/or other materials provided with the distribution.
289  * 3. The name of the author may not be used to endorse or promote products
290  * derived from this software without specific prior written permission.
291  *
292  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
293  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
294  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
295  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
296  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
297  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
298  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
299  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
300  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
301  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
302  */

303
Popular Tags