KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xml > internal > security > utils > resolver > implementations > ResolverDirectHTTP


1
2 /*
3  * Copyright 1999-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18 package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
19
20
21
22 import java.io.ByteArrayOutputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.net.MalformedURLException JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.net.URLConnection JavaDoc;
28
29 import com.sun.org.apache.xml.internal.utils.URI;
30 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
31 import com.sun.org.apache.xml.internal.security.utils.Base64;
32 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
33 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
34 import org.w3c.dom.Attr JavaDoc;
35
36
37 /**
38  * A simple ResourceResolver for HTTP requests. This class handles only 'pure'
39  * HTTP URIs which means without a fragment. The Fragment handling is done by the
40  * {@link ResolverFragment} class.
41  * <BR>
42  * If the user has a corporate HTTP proxy which is to be used, the usage can be
43  * switched on by setting properties for the resolver:
44  * <PRE>
45  * resourceResolver.setProperty("http.proxy.host", "proxy.company.com");
46  * resourceResolver.setProperty("http.proxy.port", "8080");
47  *
48  * // if we need a password for the proxy
49  * resourceResolver.setProperty("http.proxy.username", "proxyuser3");
50  * resourceResolver.setProperty("http.proxy.password", "secretca");
51  * </PRE>
52  *
53  *
54  * @author $Author: mullan $
55  * @see <A HREF="http://www.javaworld.com/javaworld/javatips/jw-javatip42_p.html">Java Tip 42: Write Java apps that work with proxy-based firewalls</A>
56  * @see <A HREF="http://java.sun.com/j2se/1.4/docs/guide/net/properties.html">SUN J2SE docs for network properties</A>
57  * @see <A HREF="http://metalab.unc.edu/javafaq/javafaq.html#proxy">The JAVA FAQ Question 9.5: How do I make Java work with a proxy server?</A>
58  * $todo$ the proxy behaviour seems not to work; if a on-existing proxy is set, it works ?!?
59  */

60 public class ResolverDirectHTTP extends ResourceResolverSpi {
61
62    /** {@link java.util.logging} logging facility */
63     static java.util.logging.Logger JavaDoc log =
64         java.util.logging.Logger.getLogger(
65                             ResolverDirectHTTP.class.getName());
66
67    /** Field properties[] */
68    static final String JavaDoc properties[] = { "http.proxy.host", "http.proxy.port",
69                                         "http.proxy.username",
70                                         "http.proxy.password",
71                                         "http.basic.username",
72                                         "http.basic.password" };
73
74    /** Field HttpProxyHost */
75    private static final int HttpProxyHost = 0;
76
77    /** Field HttpProxyPort */
78    private static final int HttpProxyPort = 1;
79
80    /** Field HttpProxyUser */
81    private static final int HttpProxyUser = 2;
82
83    /** Field HttpProxyPass */
84    private static final int HttpProxyPass = 3;
85
86    /** Field HttpProxyUser */
87    private static final int HttpBasicUser = 4;
88
89    /** Field HttpProxyPass */
90    private static final int HttpBasicPass = 5;
91
92    /**
93     * Method resolve
94     *
95     * @param uri
96     * @param BaseURI
97     *
98     * @throws ResourceResolverException
99     * @return
100     * $todo$ calculate the correct URI from the attribute and the BaseURI
101     */

102    public XMLSignatureInput engineResolve(Attr JavaDoc uri, String JavaDoc BaseURI)
103            throws ResourceResolverException {
104
105       try {
106          boolean useProxy = false;
107          String JavaDoc proxyHost =
108             engineGetProperty(ResolverDirectHTTP
109                .properties[ResolverDirectHTTP.HttpProxyHost]);
110          String JavaDoc proxyPort =
111             engineGetProperty(ResolverDirectHTTP
112                .properties[ResolverDirectHTTP.HttpProxyPort]);
113
114          if ((proxyHost != null) && (proxyPort != null)) {
115             useProxy = true;
116          }
117
118          String JavaDoc oldProxySet =
119             (String JavaDoc) System.getProperties().get("http.proxySet");
120          String JavaDoc oldProxyHost =
121             (String JavaDoc) System.getProperties().get("http.proxyHost");
122          String JavaDoc oldProxyPort =
123             (String JavaDoc) System.getProperties().get("http.proxyPort");
124          boolean switchBackProxy = ((oldProxySet != null)
125                                     && (oldProxyHost != null)
126                                     && (oldProxyPort != null));
127
128          // switch on proxy usage
129
if (useProxy) {
130             if (true)
131                 if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Use of HTTP proxy enabled: " + proxyHost + ":"
132                       + proxyPort);
133             System.getProperties().put("http.proxySet", "true");
134             System.getProperties().put("http.proxyHost", proxyHost);
135             System.getProperties().put("http.proxyPort", proxyPort);
136          }
137
138          // calculate new URI
139
URI uriNew = getNewURI(uri.getNodeValue(), BaseURI);
140
141          // if the URI contains a fragment, ignore it
142
URI uriNewNoFrag = new URI(uriNew);
143
144          uriNewNoFrag.setFragment(null);
145
146          URL JavaDoc url = new URL JavaDoc(uriNewNoFrag.toString());
147          URLConnection JavaDoc urlConnection = url.openConnection();
148
149          {
150
151             // set proxy pass
152
String JavaDoc proxyUser =
153                engineGetProperty(ResolverDirectHTTP
154                   .properties[ResolverDirectHTTP.HttpProxyUser]);
155             String JavaDoc proxyPass =
156                engineGetProperty(ResolverDirectHTTP
157                   .properties[ResolverDirectHTTP.HttpProxyPass]);
158
159             if ((proxyUser != null) && (proxyPass != null)) {
160                String JavaDoc password = proxyUser + ":" + proxyPass;
161                String JavaDoc encodedPassword = Base64.encode(password.getBytes());
162
163                // or was it Proxy-Authenticate ?
164
urlConnection.setRequestProperty("Proxy-Authorization",
165                                                 encodedPassword);
166             }
167          }
168
169          {
170
171             // check if Basic authentication is required
172
String JavaDoc auth = urlConnection.getHeaderField("WWW-Authenticate");
173
174             if (auth != null) {
175
176                // do http basic authentication
177
if (auth.startsWith("Basic")) {
178                   String JavaDoc user =
179                      engineGetProperty(ResolverDirectHTTP
180                         .properties[ResolverDirectHTTP.HttpBasicUser]);
181                   String JavaDoc pass =
182                      engineGetProperty(ResolverDirectHTTP
183                         .properties[ResolverDirectHTTP.HttpBasicPass]);
184
185                   if ((user != null) && (pass != null)) {
186                      urlConnection = url.openConnection();
187
188                      String JavaDoc password = user + ":" + pass;
189                      String JavaDoc encodedPassword =
190                         Base64.encode(password.getBytes());
191
192                      // set authentication property in the http header
193
urlConnection.setRequestProperty("Authorization",
194                                                       "Basic "
195                                                       + encodedPassword);
196                   }
197                }
198             }
199          }
200
201          String JavaDoc mimeType = urlConnection.getHeaderField("Content-Type");
202          InputStream JavaDoc inputStream = urlConnection.getInputStream();
203          ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
204          byte buf[] = new byte[4096];
205          int read = 0;
206          int summarized = 0;
207
208          while ((read = inputStream.read(buf)) >= 0) {
209             baos.write(buf, 0, read);
210
211             summarized += read;
212          }
213
214          if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI "
215                    + uriNew.toString());
216
217          XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());
218
219          // XMLSignatureInput result = new XMLSignatureInput(inputStream);
220
result.setSourceURI(uriNew.toString());
221          result.setMIMEType(mimeType);
222
223          // switch off proxy usage
224
if (switchBackProxy) {
225             System.getProperties().put("http.proxySet", oldProxySet);
226             System.getProperties().put("http.proxyHost", oldProxyHost);
227             System.getProperties().put("http.proxyPort", oldProxyPort);
228          }
229
230          return result;
231       } catch (MalformedURLException JavaDoc ex) {
232          throw new ResourceResolverException("generic.EmptyMessage", ex, uri,
233                                              BaseURI);
234       } catch (IOException JavaDoc ex) {
235          throw new ResourceResolverException("generic.EmptyMessage", ex, uri,
236                                              BaseURI);
237       }
238    }
239
240    /**
241     * We resolve http URIs <I>without</I> fragment...
242     *
243     * @param uri
244     * @param BaseURI
245     * @return true if can be resolved
246     */

247    public boolean engineCanResolve(Attr JavaDoc uri, String JavaDoc BaseURI) {
248       if (uri == null) {
249          if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "quick fail, uri == null");
250
251          return false;
252       }
253
254       String JavaDoc uriNodeValue = uri.getNodeValue();
255
256       if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#')) {
257          if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones");
258
259          return false;
260       }
261
262       if (true)
263         if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue);
264
265       if ( uriNodeValue.startsWith("http:") ||
266                  BaseURI.startsWith("http:")) {
267          if (true)
268             if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue);
269
270          return true;
271       }
272
273       if (true)
274         if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + uriNodeValue);
275
276       return false;
277    }
278
279    /**
280     * @inheritDoc
281     */

282    public String JavaDoc[] engineGetPropertyKeys() {
283       return (String JavaDoc[]) ResolverDirectHTTP.properties.clone();
284    }
285
286    private URI getNewURI(String JavaDoc uri, String JavaDoc BaseURI)
287            throws URI.MalformedURIException {
288
289       if ((BaseURI == null) || "".equals(BaseURI)) {
290          return new URI(uri);
291       }
292       return new URI(new URI(BaseURI), uri);
293    }
294 }
295
Popular Tags