KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdesktop > jdnc > markup > RealizationUtils


1 /*
2  * $Id: RealizationUtils.java,v 1.2 2004/07/28 00:51:43 davidson1 Exp $
3  *
4  * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
5  * Santa Clara, California 95054, U.S.A. All rights reserved.
6  */

7
8 package org.jdesktop.jdnc.markup;
9
10 import java.beans.Expression JavaDoc;
11
12 import java.io.File JavaDoc;
13 import java.io.IOException JavaDoc;
14
15 import java.net.MalformedURLException JavaDoc;
16 import java.net.Socket JavaDoc;
17 import java.net.UnknownHostException JavaDoc;
18 import java.net.URL JavaDoc;
19 import java.net.URLConnection JavaDoc;
20
21 import java.util.logging.Level JavaDoc;
22
23 import net.openmarkup.Error;
24 import net.openmarkup.Glitch;
25 import net.openmarkup.Warning;
26 import net.openmarkup.ApplierError;
27 import net.openmarkup.ApplierException;
28 import net.openmarkup.ApplierWarning;
29 import net.openmarkup.ObjectRealizer;
30 import net.openmarkup.Realizable;
31 import net.openmarkup.Scribe;
32
33 import org.w3c.dom.Element JavaDoc;
34 import org.w3c.dom.Document JavaDoc;
35
36 /**
37  * A utility class to handle some redundant chores for object realiztion. Mostly,
38  * this class encapsulates a lot of reflective hacks and discrepancies between
39  * object realizer implementations.
40  *
41  * @author Mark Davidson
42  */

43 public class RealizationUtils {
44
45     /**
46      * This method insulates the ObjectRealizer implementation to get the Realized Object
47      * from the Element that has been referenced by the attributeValue.
48      */

49     public static Object JavaDoc getReferencedObject(Realizable target, String JavaDoc attributeValue) {
50         Document JavaDoc doc = target.getOwnerDocument();
51         if (doc instanceof net.openmarkup.Document) {
52             return ( (net.openmarkup.Document) doc).getElement(attributeValue).
53                 getObject();
54         }
55
56         try {
57             // Reflectively try the Sun ObjectRealizer
58
ObjectRealizer or = target.getObjectRealizer();
59             Expression JavaDoc exp = new Expression JavaDoc(or, "getElementById",
60                                             new Object JavaDoc[] {target,
61                                             attributeValue});
62             Element JavaDoc element = (Element JavaDoc) exp.getValue();
63             Realizable realizable = RealizationUtils.getRealizable(element);
64             if (realizable == null) {
65                 return null;
66             }
67             return realizable.getObject();
68         }
69         catch (Exception JavaDoc ex) {
70             throw new RuntimeException JavaDoc("Error processing " + attributeValue, ex);
71         }
72     }
73
74     public static Element JavaDoc getReferencedElement(Realizable target,
75                                                String JavaDoc attributeValue) {
76         Document JavaDoc doc = target.getOwnerDocument();
77         if (doc instanceof net.openmarkup.Document) {
78             return ( (net.openmarkup.Document) doc).getElement(attributeValue);
79         }
80         try {
81             // Reflectively try the Sun ObjectRealizer
82
ObjectRealizer or = target.getObjectRealizer();
83             Expression JavaDoc exp = new Expression JavaDoc(or, "getElementById",
84                                             new Object JavaDoc[] {target,
85                                             attributeValue});
86             return (Element JavaDoc) exp.getValue();
87
88         }
89         catch (Exception JavaDoc ex) {
90             throw new RuntimeException JavaDoc("Error processing " + attributeValue, ex);
91         }
92     }
93
94     /**
95      * Checks the url to determine if it is valid. Will throw an Error if invalid.
96      *
97      * @param url the URL to be checked in a string form
98      */

99     public static boolean validateURL(String JavaDoc url) throws ApplierException {
100     return validateURL(url, true);
101     }
102
103     /**
104      * Checks the url to determine if it is valid. Will throw an exception if invalid.
105      * The type of exception is determined by the value of the severe flag.
106      *
107      * @param url the URL to be checked in a string form
108      * @param severe if true then an invalid url will be an Error; otherwise
109      * it will be a Warning.
110      * @return true if url is valid
111      * @throws ApplierException if the url is not valid
112      */

113     public static boolean validateURL(String JavaDoc url, boolean severe) throws ApplierException {
114     try {
115         return validateURL(new URL JavaDoc(url), severe);
116     } catch (MalformedURLException JavaDoc ex) {
117         String JavaDoc message = "Malformed URL: " + url;
118         if (severe) {
119         throw new ApplierError(message, ex);
120         } else {
121         throw new ApplierWarning(message, ex);
122         }
123     }
124     }
125
126     /**
127      * Checks the url to determine if it is valid. Will throw an exception if invalid.
128      * The type of exception is determined by the value of the severe flag.
129      *
130      * @param url the URL to be checked
131      */

132     public static boolean validateURL(URL JavaDoc url) throws ApplierException {
133     return validateURL(url, true);
134     }
135
136     /**
137      * Checks the url to determine if it is valid. Will throw an exception if invalid.
138      * The type of exception is determined by the value of the severe flag.
139      *
140      * @param url the URL to be checked
141      * @param severe if true then an invalid url will be an Error; otherwise
142      * it will be a Warning.
143      * @return true if url is valid
144      * @throws ApplierException if the url is not valid
145      */

146     public static boolean validateURL(URL JavaDoc url, boolean severe) throws ApplierException {
147     if (url != null) {
148         String JavaDoc protocol = url.getProtocol();
149         if ("file".equals(protocol)) {
150         return validateFileURL(url, severe);
151         } else if ("http".equals(protocol) || "https".equals(protocol)) {
152         return validateHttpURL(url, severe);
153         }
154     }
155     return false;
156     }
157
158     private static boolean validateFileURL(URL JavaDoc url, boolean severe) throws ApplierException {
159     try {
160         File JavaDoc file = new File JavaDoc(url.getFile());
161         return file.canRead();
162     } catch (Exception JavaDoc ex) {
163         String JavaDoc message = "Cannot read file: " + url.toExternalForm();
164         if (severe) {
165         throw new ApplierError(message, ex);
166         } else {
167         throw new ApplierWarning(message, ex);
168         }
169     }
170     }
171
172     private static boolean validateHttpURL(URL JavaDoc url, boolean severe) throws ApplierException {
173     Socket JavaDoc connection = null;
174     try {
175         int port = url.getPort();
176         if (port == -1) {
177         port = url.getDefaultPort();
178         }
179         connection = new Socket JavaDoc(url.getHost(), port);
180     } catch (UnknownHostException JavaDoc ex0) {
181         String JavaDoc message = "Cannot find host for: " + url.toExternalForm();
182         if (severe) {
183         throw new ApplierError(message, ex0);
184         } else {
185         throw new ApplierWarning(message, ex0);
186         }
187     } catch (IOException JavaDoc ex) {
188         String JavaDoc message = "Cannot open connection to: " + url.toExternalForm();
189         if (severe) {
190         throw new ApplierError(message, ex);
191         } else {
192         throw new ApplierWarning(message, ex);
193         }
194     }
195     finally {
196         if (connection != null) {
197         try {
198             connection.close();
199         } catch (IOException JavaDoc ex) {
200             throw new ApplierException("Error closing Socket for URL: " +
201                            url.toExternalForm(), ex);
202         }
203         }
204     }
205     return true;
206     }
207
208     public static Realizable getRealizable(Element JavaDoc element) {
209         // In XOR, native element implementations and the corresponding Realizable
210
// are one and the same, but it stores the Realizable for plug-in element
211
// implementations in the dom element's user data (or user object).
212

213         Object JavaDoc userObject = null;
214
215         // For Crimson:
216
//userObject = ((org.apache.crimson.tree.ElementNode) element).getUserObject();
217

218         // For Xerces:
219
try {
220         Class JavaDoc clz = Class.forName("org.apache.xerces.dom.NodeImpl");
221         if (element.getClass() == clz) {
222         userObject = (new Expression JavaDoc(element, "getUserData", new Object JavaDoc[0])).getValue();
223         }
224     } catch (ClassNotFoundException JavaDoc ex) {
225         // NodeImpl not found. Ignore.
226
} catch (Exception JavaDoc ex) {
227         // Any other exception is worth noting.
228
throw new RuntimeException JavaDoc("Error invoking getUserData for " + element.toString(), ex);
229     }
230
231     if (!(userObject instanceof Realizable)) {
232         // For Sun Object Realizer:
233
ObjectRealizer or = getObjectRealizer();
234
235         try {
236         userObject = (Realizable)(new Expression JavaDoc(or, "getRealizable",
237                              new Object JavaDoc[] { element })).getValue();
238         } catch (Exception JavaDoc ex) {
239         String JavaDoc message = "Error getting Realizable from " + element.toString();
240         throw new RuntimeException JavaDoc(message, ex);
241         }
242     }
243     return (Realizable) (userObject == null ? element : userObject);
244     }
245
246     /**
247      * Logs the exception. If the exception represents a {@link net.openmarkup.Error }
248      * then it will be rethrown. The logging Level will be determined based on the
249      * type of exception. For a Glich, an INFO message will be sent, Error -> SEVERE,
250      * Warning -> WARNING
251      *
252      * @param messgae Message to send to logger
253      * @param ex the exception to log
254      * @throws RuntimeException if the exception represents an Error
255      * @see net.openmarkup.Error
256      * @see net.openmarkup.Glich
257      * @see net.openmarkup.Warning
258      */

259     public static void logException(String JavaDoc message, Exception JavaDoc ex) {
260     Level JavaDoc level = Level.INFO;
261
262     if (ex instanceof Error JavaDoc) {
263         level = Level.SEVERE;
264     }
265     else if (ex instanceof Glitch) {
266         level = Level.INFO;
267     }
268     else if (ex instanceof Warning) {
269         level = Level.WARNING;
270     }
271     else {
272         // Any other exception is a severe
273
level = Level.SEVERE;
274     }
275     Scribe.getLogger().log(level, message, ex);
276
277     if (ex instanceof Error JavaDoc) {
278         // If this represents a serious error then this shudl bubble up
279
throw new RuntimeException JavaDoc(ex);
280     }
281     }
282
283     /**
284      * Serious hack. Use reflection to get the Sun OR singleton.
285      * yes. I'm a sick puppy.
286      * This should be consolidated with runner.Application.getObjectRealizer
287      */

288     public static ObjectRealizer getObjectRealizer() {
289     String JavaDoc realizerImplName = null;
290     try {
291         // The OR implementation should be looked up in System.properties.
292
realizerImplName = System.getProperty("openmarkup.realizer.impl");
293         if (realizerImplName == null) {
294         // This should be an Env property.
295
realizerImplName = "org.jdesktop.openmarkup.ri.ObjectRealizerImpl";
296         }
297     } catch (SecurityException JavaDoc ex) {
298         // Access to properties are not allowed. For example, in sandboxed
299
// applications.
300
realizerImplName = "org.jdesktop.openmarkup.ri.ObjectRealizerImpl";
301     }
302
303     ObjectRealizer realizer = null;
304     try {
305         Class JavaDoc clz = Class.forName(realizerImplName);
306         Object JavaDoc or = clz.newInstance();
307
308         // XXX this is a big hack since the Sun ObjectRealizer doesn't
309
// use net.openmarkup.Document.
310
try {
311         realizer = (ObjectRealizer)(new Expression JavaDoc(or, "getInstance",
312                                new Object JavaDoc[0])).getValue();
313         } catch (Exception JavaDoc ex) {
314         // error
315
}
316
317         if (realizer == null) {
318         realizer = (ObjectRealizer)or;
319         }
320     } catch (Exception JavaDoc ex) {
321         throw new RuntimeException JavaDoc("Cannot find ObjectRealizer: " + realizerImplName, ex);
322     }
323     return realizer;
324     }
325
326     /**
327      * Returns a url based on which is resolved according to the precedence
328      * rules in
329      * http://www.w3c.org/TR/xmlbase
330      * http://www.ietf.org/rfc/rfc2396.txt section 5.1
331      *
332      * @see net.openmarkup.Realizable#getResolvedURL
333      */

334      public static URL JavaDoc getResolvedURL(Realizable realizable, String JavaDoc uri) {
335     URL JavaDoc url = null;
336
337     // using the xml:base attribute
338
Document JavaDoc doc = realizable.getOwnerDocument();
339     Element JavaDoc docElement = doc.getDocumentElement();
340     String JavaDoc base = docElement.getAttributeNS("http://www.w3.org/XML/1998/namespace", "base");
341     if (base != null && !base.equals("")) {
342         try {
343         url = new URL JavaDoc(new URL JavaDoc(base), uri);
344         } catch (MalformedURLException JavaDoc ex) {
345         //
346
}
347     }
348     if (url == null) {
349         try {
350         url = new URL JavaDoc(getObjectRealizer().getDefaultBaseURL(), uri);
351         // Test the url
352
} catch (MalformedURLException JavaDoc ex) {
353         url = realizable.getClass().getResource(uri);
354         }
355         // Scribe.getLogger().info("getResolvedURL("+ uri + ") -> " + url);
356
}
357         return url;
358
359     }
360 }
361
Popular Tags