KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > joseki > HttpExecute


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

5
6 package com.hp.hpl.jena.joseki;
7
8 import org.apache.commons.logging.* ;
9 import java.net.* ;
10 import java.io.* ;
11
12 import com.hp.hpl.jena.rdf.model.*;
13 import org.joseki.*;
14
15 /** Common code for performing an HTTP operation (not query) on a remote model.
16  *
17  * @see HttpAdd
18  * @see HttpRemove
19  * @see HttpPing
20  * @see HttpOptions
21  * @see HttpQuery
22  * @author Andy Seaborne
23  * @version $Id: HttpExecute.java,v 1.7 2004/04/30 14:13:13 andy_seaborne Exp $
24  */

25
26 public class HttpExecute
27 {
28     private static Log log = LogFactory.getLog(HttpExecute.class.getName()) ;
29
30     private URL url = null ;
31
32     private String JavaDoc requestMethod = null ;
33     private boolean doOutput = true ;
34     private boolean hasExecuted = false ;
35
36     static final String JavaDoc ENC_UTF8 = "UTF-8" ;
37
38     /** Usual way to contruct the request
39      * @param target
40      * @param opName
41      * @throws MalformedURLException
42      */

43
44     protected HttpExecute(String JavaDoc target, String JavaDoc opName) throws MalformedURLException
45     { init(target, opName) ; }
46     
47     /** Allow 2 stage constructor because subclasses may wish to
48      * compute before setting the URL (@see setURL)
49      */

50     protected HttpExecute() { }
51     
52     protected void init(String JavaDoc target, String JavaDoc opName)
53         throws MalformedURLException
54     {
55         url = new URL(target+"?op="+opName) ;
56     }
57     
58     // Special: allow the HTTP verb to be changed.
59
protected void setRequestMethod(String JavaDoc rMethod, boolean _doOutput)
60     {
61         requestMethod = rMethod ;
62         doOutput = _doOutput ;
63     }
64     
65     // Special: allow the URL to be directly set.
66
protected void setURL(String JavaDoc urlStr) throws MalformedURLException
67     {
68         url = new URL(urlStr) ;
69     }
70     
71     public Model exec() throws HttpException
72     {
73         HttpURLConnection conn = null ;
74         try
75         {
76             conn = (HttpURLConnection) url.openConnection();
77             conn.setRequestProperty("Accept", Joseki.contentTypeRDFXML+", "+
78                                               Joseki.contentTypeN3) ;
79             conn.setRequestProperty("Accept-Charset", ENC_UTF8) ;
80             
81             if ( requestMethod != null )
82                 conn.setRequestMethod(requestMethod) ;
83             conn.setDoInput(true);
84             
85             if ( doOutput )
86             {
87                 conn.setRequestProperty("Content-Type", //Joseki.clientContentType);
88
Joseki.clientContentType+ "; charset="+ENC_UTF8) ;
89                 // Maybe we should set the charset.
90
// At the moment, we leave it to the onSend operation to
91
// do the right thing.
92
conn.setDoOutput(true);
93                 onSend(Joseki.clientContentType, conn.getOutputStream());
94                 conn.getOutputStream().flush() ;
95             }
96             conn.connect();
97         }
98         catch (java.net.ConnectException JavaDoc connEx)
99         {
100             throw new HttpException(-1, "Failed to connect to remote server");
101         }
102
103         catch (IOException ioEx)
104         {
105             throw new HttpException(ioEx);
106         }
107         catch (RDFException rdfEx)
108         {
109             throw new HttpException(rdfEx) ;
110         }
111
112         try {
113             int responseCode = conn.getResponseCode() ;
114             String JavaDoc responseMessage = conn.getResponseMessage() ;
115             
116             // 1xx: Informational
117
// 2xx: Success
118
// 3xx: Redirection
119
// 4xx: Client Error
120
// 5xx: Server Error
121

122             if ( 300 <= responseCode && responseCode < 400 )
123             {
124                 throw new HttpException(responseCode, responseMessage) ;
125             }
126             
127             // Other 400 and 500 - errors
128

129             if ( responseCode >= 400 )
130             {
131                 throw new HttpException(responseCode, responseMessage) ;
132             }
133   
134             // Request suceeded
135
// Result coming back is a model
136
Model resultModel = onResult(conn.getContentType(), conn.getInputStream()) ;
137             return resultModel ;
138         }
139         catch (IOException ioEx)
140         {
141             log.info("IOException after connect: "+ioEx) ;
142             throw new HttpException(ioEx) ;
143         }
144         catch (RDFException rdfEx)
145         {
146             log.info("RDFException(result): "+rdfEx) ;
147             throw new HttpException(rdfEx) ;
148         }
149     }
150
151     /** Called when output to the POST is needed.
152      * Content should be written with UTF-8.
153      * @param mediaType
154      * @param out
155      */

156     
157     protected void onSend(String JavaDoc mediaType, OutputStream out) { return ; }
158     
159     protected Model onResult(String JavaDoc mediaType, InputStream in)
160     {
161         // Normal result is a model.
162
Model resultModel = ModelFactory.createDefaultModel() ;
163         String JavaDoc rType = Joseki.getWriterType(mediaType) ;
164         
165         if ( false )
166         {
167             try
168             {
169                 log.trace("Reader type: "+rType) ;
170
171                 byte b[] = new byte[1024] ;
172                 ByteArrayOutputStream bout = new ByteArrayOutputStream() ;
173                 while(true)
174                 {
175                     int len = in.read(b) ;
176                     if ( len == -1 )
177                         break ;
178                     bout.write(b, 0, len) ;
179                 }
180                 // Crude.
181
log.trace("\n"+bout.toString()) ;
182                 
183                 // reset to reread
184
in = new ByteArrayInputStream(bout.toByteArray()) ;
185             }
186             catch (IOException ioEx) { System.err.println("IOException: "+ioEx) ; return null ; }
187         }
188         resultModel.read(in, "http://somewhere/", Joseki.getWriterType(mediaType)) ;
189         hasExecuted = true ;
190         return resultModel ;
191     }
192 }
193
194
195 /*
196  * (c) Copyright 2003, 2004 Hewlett-Packard Development Company, LP
197  * All rights reserved.
198  *
199  * Redistribution and use in source and binary forms, with or without
200  * modification, are permitted provided that the following conditions
201  * are met:
202  * 1. Redistributions of source code must retain the above copyright
203  * notice, this list of conditions and the following disclaimer.
204  * 2. Redistributions in binary form must reproduce the above copyright
205  * notice, this list of conditions and the following disclaimer in the
206  * documentation and/or other materials provided with the distribution.
207  * 3. The name of the author may not be used to endorse or promote products
208  * derived from this software without specific prior written permission.
209  *
210  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
211  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
212  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
213  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
214  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
215  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
216  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
217  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
218  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
219  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
220  */

221
222
Popular Tags