KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xml > internal > serializer > utils > SystemIDResolver


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

16 /*
17  * $Id: SystemIDResolver.java,v 1.1.4.1 2005/09/08 11:03:20 suresh_emailid Exp $
18  */

19 package com.sun.org.apache.xml.internal.serializer.utils;
20
21 import java.io.File JavaDoc;
22
23 import javax.xml.transform.TransformerException JavaDoc;
24
25 import com.sun.org.apache.xml.internal.serializer.utils.URI.MalformedURIException;
26
27 /**
28  * This class is used to resolve relative URIs and SystemID
29  * strings into absolute URIs.
30  *
31  * <p>This is a generic utility for resolving URIs, other than the
32  * fact that it's declared to throw TransformerException. Please
33  * see code comments for details on how resolution is performed.</p>
34  *
35  * This class is a copy of the one in com.sun.org.apache.xml.internal.utils.
36  * It exists to cut the serializers dependancy on that package.
37  *
38  * This class is not a public API, it is only public because it is
39  * used in com.sun.org.apache.xml.internal.serializer.
40  *
41  * @xsl.usage internal
42  */

43 public final class SystemIDResolver
44 {
45
46   /**
47    * Get an absolute URI from a given relative URI (local path).
48    *
49    * <p>The relative URI is a local filesystem path. The path can be
50    * absolute or relative. If it is a relative path, it is resolved relative
51    * to the system property "user.dir" if it is available; if not (i.e. in an
52    * Applet perhaps which throws SecurityException) then we just return the
53    * relative path. The space and backslash characters are also replaced to
54    * generate a good absolute URI.</p>
55    *
56    * @param localPath The relative URI to resolve
57    *
58    * @return Resolved absolute URI
59    */

60   public static String JavaDoc getAbsoluteURIFromRelative(String JavaDoc localPath)
61   {
62     if (localPath == null || localPath.length() == 0)
63       return "";
64       
65     // If the local path is a relative path, then it is resolved against
66
// the "user.dir" system property.
67
String JavaDoc absolutePath = localPath;
68     if (!isAbsolutePath(localPath))
69     {
70       try
71       {
72         absolutePath = getAbsolutePathFromRelativePath(localPath);
73       }
74       // user.dir not accessible from applet
75
catch (SecurityException JavaDoc se)
76       {
77         return "file:" + localPath;
78       }
79     }
80
81     String JavaDoc urlString;
82     if (null != absolutePath)
83     {
84       if (absolutePath.startsWith(File.separator))
85         urlString = "file://" + absolutePath;
86       else
87         urlString = "file:///" + absolutePath;
88     }
89     else
90       urlString = "file:" + localPath;
91     
92     return replaceChars(urlString);
93   }
94   
95   /**
96    * Return an absolute path from a relative path.
97    *
98    * @param relativePath A relative path
99    * @return The absolute path
100    */

101   private static String JavaDoc getAbsolutePathFromRelativePath(String JavaDoc relativePath)
102   {
103     return new File JavaDoc(relativePath).getAbsolutePath();
104   }
105   
106   /**
107    * Return true if the systemId denotes an absolute URI .
108    *
109    * @param systemId The systemId string
110    * @return true if the systemId is an an absolute URI
111    */

112   public static boolean isAbsoluteURI(String JavaDoc systemId)
113   {
114      /** http://www.ietf.org/rfc/rfc2396.txt
115       * Authors should be aware that a path segment which contains a colon
116       * character cannot be used as the first segment of a relative URI path
117       * (e.g., "this:that"), because it would be mistaken for a scheme name.
118      **/

119      /**
120       * %REVIEW% Can we assume here that systemId is a valid URI?
121       * It looks like we cannot ( See discussion of this common problem in
122       * Bugzilla Bug 22777 ).
123      **/

124      //"fix" for Bugzilla Bug 22777
125
if(isWindowsAbsolutePath(systemId)){
126         return false;
127      }
128     
129     final int fragmentIndex = systemId.indexOf('#');
130     final int queryIndex = systemId.indexOf('?');
131     final int slashIndex = systemId.indexOf('/');
132     final int colonIndex = systemId.indexOf(':');
133     
134     //finding substring before '#', '?', and '/'
135
int index = systemId.length() -1;
136     if(fragmentIndex > 0)
137         index = fragmentIndex;
138     if((queryIndex > 0) && (queryIndex <index))
139         index = queryIndex;
140     if((slashIndex > 0) && (slashIndex <index))
141         index = slashIndex;
142     // return true if there is ':' before '#', '?', and '/'
143
return ((colonIndex >0) && (colonIndex<index));
144     
145   }
146   
147   /**
148    * Return true if the local path is an absolute path.
149    *
150    * @param systemId The path string
151    * @return true if the path is absolute
152    */

153   public static boolean isAbsolutePath(String JavaDoc systemId)
154   {
155     if(systemId == null)
156         return false;
157     final File JavaDoc file = new File JavaDoc(systemId);
158     return file.isAbsolute();
159     
160   }
161   
162    /**
163    * Return true if the local path is a Windows absolute path.
164    *
165    * @param systemId The path string
166    * @return true if the path is a Windows absolute path
167    */

168     private static boolean isWindowsAbsolutePath(String JavaDoc systemId)
169   {
170     if(!isAbsolutePath(systemId))
171       return false;
172     // On Windows, an absolute path starts with "[drive_letter]:\".
173
if (systemId.length() > 2
174         && systemId.charAt(1) == ':'
175         && Character.isLetter(systemId.charAt(0))
176         && (systemId.charAt(2) == '\\' || systemId.charAt(2) == '/'))
177       return true;
178     else
179       return false;
180   }
181   
182   /**
183    * Replace spaces with "%20" and backslashes with forward slashes in
184    * the input string to generate a well-formed URI string.
185    *
186    * @param str The input string
187    * @return The string after conversion
188    */

189   private static String JavaDoc replaceChars(String JavaDoc str)
190   {
191     StringBuffer JavaDoc buf = new StringBuffer JavaDoc(str);
192     int length = buf.length();
193     for (int i = 0; i < length; i++)
194     {
195       char currentChar = buf.charAt(i);
196       // Replace space with "%20"
197
if (currentChar == ' ')
198       {
199         buf.setCharAt(i, '%');
200         buf.insert(i+1, "20");
201         length = length + 2;
202         i = i + 2;
203       }
204       // Replace backslash with forward slash
205
else if (currentChar == '\\')
206       {
207         buf.setCharAt(i, '/');
208       }
209     }
210     
211     return buf.toString();
212   }
213   
214   /**
215    * Take a SystemID string and try to turn it into a good absolute URI.
216    *
217    * @param systemId A URI string, which may be absolute or relative.
218    *
219    * @return The resolved absolute URI
220    */

221   public static String JavaDoc getAbsoluteURI(String JavaDoc systemId)
222   {
223     String JavaDoc absoluteURI = systemId;
224     if (isAbsoluteURI(systemId))
225     {
226       // Only process the systemId if it starts with "file:".
227
if (systemId.startsWith("file:"))
228       {
229         String JavaDoc str = systemId.substring(5);
230         
231         // Resolve the absolute path if the systemId starts with "file:///"
232
// or "file:/". Don't do anything if it only starts with "file://".
233
if (str != null && str.startsWith("/"))
234         {
235           if (str.startsWith("///") || !str.startsWith("//"))
236           {
237             // A Windows path containing a drive letter can be relative.
238
// A Unix path starting with "file:/" is always absolute.
239
int secondColonIndex = systemId.indexOf(':', 5);
240             if (secondColonIndex > 0)
241             {
242               String JavaDoc localPath = systemId.substring(secondColonIndex-1);
243               try {
244                 if (!isAbsolutePath(localPath))
245                   absoluteURI = systemId.substring(0, secondColonIndex-1) +
246                                 getAbsolutePathFromRelativePath(localPath);
247               }
248               catch (SecurityException JavaDoc se) {
249                 return systemId;
250               }
251             }
252           }
253         }
254         else
255         {
256           return getAbsoluteURIFromRelative(systemId.substring(5));
257         }
258                 
259         return replaceChars(absoluteURI);
260       }
261       else
262         return systemId;
263     }
264     else
265       return getAbsoluteURIFromRelative(systemId);
266     
267   }
268
269
270   /**
271    * Take a SystemID string and try to turn it into a good absolute URI.
272    *
273    * @param urlString SystemID string
274    * @param base The URI string used as the base for resolving the systemID
275    *
276    * @return The resolved absolute URI
277    * @throws TransformerException thrown if the string can't be turned into a URI.
278    */

279   public static String JavaDoc getAbsoluteURI(String JavaDoc urlString, String JavaDoc base)
280           throws TransformerException JavaDoc
281   {
282     if (base == null)
283       return getAbsoluteURI(urlString);
284     
285     String JavaDoc absoluteBase = getAbsoluteURI(base);
286     URI uri = null;
287     try
288     {
289       URI baseURI = new URI(absoluteBase);
290       uri = new URI(baseURI, urlString);
291     }
292     catch (MalformedURIException mue)
293     {
294       throw new TransformerException JavaDoc(mue);
295     }
296     
297     return replaceChars(uri.toString());
298   }
299   
300 }
301
Popular Tags