KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > batik > test > svg > SVGOnLoadExceptionTest


1 /*
2
3    Copyright 2002-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 org.apache.batik.test.svg;
19
20 import java.io.File JavaDoc;
21 import java.net.MalformedURLException JavaDoc;
22 import java.net.URL JavaDoc;
23
24 import org.w3c.dom.Document JavaDoc;
25 import org.w3c.dom.Element JavaDoc;
26
27 import org.apache.batik.bridge.BaseScriptingEnvironment;
28 import org.apache.batik.bridge.BridgeContext;
29 import org.apache.batik.bridge.BridgeException;
30 import org.apache.batik.bridge.DefaultExternalResourceSecurity;
31 import org.apache.batik.bridge.DefaultScriptSecurity;
32 import org.apache.batik.bridge.EmbededExternalResourceSecurity;
33 import org.apache.batik.bridge.EmbededScriptSecurity;
34 import org.apache.batik.bridge.ExternalResourceSecurity;
35 import org.apache.batik.bridge.GVTBuilder;
36 import org.apache.batik.bridge.NoLoadExternalResourceSecurity;
37 import org.apache.batik.bridge.NoLoadScriptSecurity;
38 import org.apache.batik.bridge.RelaxedExternalResourceSecurity;
39 import org.apache.batik.bridge.RelaxedScriptSecurity;
40 import org.apache.batik.bridge.ScriptSecurity;
41 import org.apache.batik.bridge.UserAgent;
42 import org.apache.batik.bridge.UserAgentAdapter;
43 import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
44 import org.apache.batik.test.AbstractTest;
45 import org.apache.batik.test.TestReport;
46 import org.apache.batik.util.ParsedURL;
47 import org.apache.batik.util.XMLResourceDescriptor;
48 import org.apache.batik.util.ApplicationSecurityEnforcer;
49
50 import java.security.AccessController JavaDoc;
51 import java.security.AccessControlContext JavaDoc;
52 import java.security.CodeSource JavaDoc;
53 import java.security.PrivilegedExceptionAction JavaDoc;
54 import java.security.PrivilegedActionException JavaDoc;
55 import java.security.ProtectionDomain JavaDoc;
56 import java.security.Permission JavaDoc;
57 import java.security.PermissionCollection JavaDoc;
58 import java.security.Permissions JavaDoc;
59 import java.security.Policy JavaDoc;
60
61 import java.io.FilePermission JavaDoc;
62
63 import java.util.Enumeration JavaDoc;
64
65 /**
66  * This test takes an SVG file as an input. It processes the input SVG
67  * (meaning it turns it into a GVT tree) and then dispatches the 'onload'
68  * event.
69  *
70  * In that process, the test checks for the occurence of a specific
71  * exception type and, for BridgeExceptions, for a given error code.
72  *
73  * If an exception of the given type (and, optionally, code) happens,
74  * then the test passes. If an exception of an unexpected type
75  * (or code, for BridgeExceptions) happens, or if no exception happens,
76  * the test fails.
77  *
78  * The following properties control the test's operation:
79  * - Scripts: list of allowed script types (e.g., "application/java-archive")
80  * - ScriptOrigin: "ANY", "DOCUMENT", "EMBEDED", "NONE"
81  * - ResourceOrigin: "ANY", "DOCUMENT", "EMBEDED", "NONE"
82  * - ExpectedExceptionClass (e.g., "java.lang.SecurityException")
83  * - ExpectedErrorCode (e.g., "err.uri.unsecure")
84  * - Validate (e.g., "true")
85  *
86  * @author <a HREF="mailto:vhardy@apache.org">Vincent Hardy</a>
87  * @version $Id: SVGOnLoadExceptionTest.java,v 1.8 2005/03/29 10:48:04 deweese Exp $
88  */

89 public class SVGOnLoadExceptionTest extends AbstractTest {
90     /**
91      * Value for the script having successfully run.
92      */

93     public static final String JavaDoc RAN = "ran";
94
95     /**
96      * Error when the expected exception did not occur
97      */

98     public static final String JavaDoc ERROR_EXCEPTION_DID_NOT_OCCUR
99         = "SVGOnLoadExceptionTest.error.exception.did.not.occur";
100
101     /**
102      * Error when an exception occured, but not of the expected
103      * class
104      */

105     public static final String JavaDoc ERROR_UNEXPECTED_EXCEPTION
106         = "SVGOnLoadExceptionTest.error.unexpected.exception";
107
108     /**
109      * Error when a BridgeException occured, as expected, but
110      * with an unexpected error code
111      */

112     public static final String JavaDoc ERROR_UNEXPECTED_ERROR_CODE
113         = "SVGOnLoadExceptionTest.error.unexpected.error.code";
114
115     /**
116      * Error when the script does not run as expected.
117      */

118     public static final String JavaDoc ERROR_SCRIPT_DID_NOT_RUN
119         = "SVGOnLoadExceptionTest.error.script.did.not.run";
120
121     /**
122      * Entry describing the unexpected exception
123      */

124     public static final String JavaDoc ENTRY_KEY_UNEXPECTED_EXCEPTION
125         = "SVGOnLoadExceptionTest.entry.key.unexpected.exception";
126
127     /**
128      * Entry describing the unexpected error code
129      */

130     public static final String JavaDoc ENTRY_KEY_UNEXPECTED_ERROR_CODE
131         = "SVGOnLoadExceptionTest.entry.key.unexpected.error.code";
132
133     /**
134      * Entry describign the expected error code
135      */

136     public static final String JavaDoc ENTRY_KEY_EXPECTED_ERROR_CODE
137         = "SVGOnLoadExceptionTest.entry.key.expected.error.code";
138
139     /**
140      * Entry describing the expected exception
141      */

142     public static final String JavaDoc ENTRY_KEY_EXPECTED_EXCEPTION
143         = "SVGOnLoadExceptionTest.entry.key.expected.exception";
144
145     /**
146      * Entry describing the unexpected exception
147      */

148     public static final String JavaDoc ENTRY_KEY_UNEXPECTED_RESULT
149         = "SVGOnLoadExceptionTest.entry.key.unexpected.result";
150
151     /**
152      * Value used to disable error code check on BridgeExceptions
153      */

154     public static final String JavaDoc ERROR_CODE_NO_CHECK
155         = "noCheck";
156
157     /**
158      * Test Namespace
159      */

160     public static final String JavaDoc testNS = "http://xml.apache.org/batik/test";
161
162     /**
163      * The URL for the input SVG document to be tested
164      */

165     protected String JavaDoc svgURL;
166
167     /**
168      * The allowed script types
169      */

170     protected String JavaDoc scripts = "text/ecmascript, application/java-archive";
171     
172     /**
173      * Name of the expected exception class
174      */

175     protected String JavaDoc expectedExceptionClass = "org.apache.batik.bridge.Exception";
176
177     /**
178      * Expected error code (for BridgeExceptions)
179      */

180     protected String JavaDoc expectedErrorCode = "none";
181
182     /**
183      * The allowed script origin
184      */

185     protected String JavaDoc scriptOrigin = "ANY";
186
187     /**
188      * The allowed external resource origin
189      */

190     protected String JavaDoc resourceOrigin = "ANY";
191
192     /**
193      * True if the scripts are run securely (i.e., with a security manager)
194      */

195     protected boolean secure = false;
196
197     /**
198      * Controls whether or not the input SVG document should be validated
199      */

200     protected Boolean JavaDoc validate = new Boolean JavaDoc(false);
201
202     /**
203      * The name of the test file
204      */

205     protected String JavaDoc fileName;
206
207     /**
208      * Controls whether on not the document should be processed from
209      * a 'restricted' context, one with no createClassLoader permission.
210      */

211     protected boolean restricted = false;
212
213     public boolean getRestricted() {
214         return restricted;
215     }
216
217     public void setRestricted(boolean restricted) {
218         this.restricted = restricted;
219     }
220
221     public void setScripts(String JavaDoc scripts){
222         this.scripts = scripts;
223     }
224
225     public String JavaDoc getScripts(){
226         return scripts;
227     }
228
229     public void setScriptOrigin(String JavaDoc scriptOrigin){
230         this.scriptOrigin = scriptOrigin;
231     }
232
233     public String JavaDoc getScriptOrigin(){
234         return this.scriptOrigin;
235     }
236
237     public void setResourceOrigin(String JavaDoc resourceOrigin){
238         this.resourceOrigin = resourceOrigin;
239     }
240
241     public String JavaDoc getResourceOrigin(){
242         return this.resourceOrigin;
243     }
244
245     public void setSecure(boolean secure){
246         this.secure = secure;
247     }
248
249     public boolean getSecure(){
250         return secure;
251     }
252
253     public void setExpectedExceptionClass(String JavaDoc expectedExceptionClass){
254         this.expectedExceptionClass = expectedExceptionClass;
255     }
256
257     public String JavaDoc getExpectedExceptionClass(){
258         return this.expectedExceptionClass;
259     }
260
261     public void setExpectedErrorCode(String JavaDoc expectedErrorCode){
262         this.expectedErrorCode = expectedErrorCode;
263     }
264
265     public String JavaDoc getExpectedErrorCode(){
266         return this.expectedErrorCode;
267     }
268
269     public Boolean JavaDoc getValidate() {
270         return validate;
271     }
272
273     public void setValidate(Boolean JavaDoc validate) {
274         this.validate = validate;
275         if (this.validate == null) {
276             this.validate = new Boolean JavaDoc(false);
277         }
278     }
279     
280     /**
281      * Default constructor
282      */

283     public SVGOnLoadExceptionTest(){
284     }
285
286     public void setId(String JavaDoc id){
287         super.setId(id);
288
289         if (id != null) {
290             int i = id.indexOf("(");
291             if (i != -1) {
292                 id = id.substring(0, i);
293             }
294             fileName = "test-resources/org/apache/batik/" + id + ".svg";
295             svgURL = resolveURL(fileName);
296         }
297     }
298
299     /**
300      * Resolves the input string as follows.
301      * + First, the string is interpreted as a file description.
302      * If the file exists, then the file name is turned into
303      * a URL.
304      * + Otherwise, the string is supposed to be a URL. If it
305      * is an invalid URL, an IllegalArgumentException is thrown.
306      */

307     protected String JavaDoc resolveURL(String JavaDoc url){
308         // Is url a file?
309
File JavaDoc f = (new File JavaDoc(url)).getAbsoluteFile();
310         if(f.getParentFile().exists()){
311             try{
312                 return f.toURL().toString();
313             }catch(MalformedURLException JavaDoc e){
314                 throw new IllegalArgumentException JavaDoc();
315             }
316         }
317         
318         // url is not a file. It must be a regular URL...
319
try{
320             return (new URL JavaDoc(url)).toString();
321         }catch(MalformedURLException JavaDoc e){
322             throw new IllegalArgumentException JavaDoc(url);
323         }
324     }
325
326
327     /**
328      * Run this test and produce a report.
329      * The test goes through the following steps: <ul>
330      * <li>load the input SVG into a Document</li>
331      * <li>build the GVT tree corresponding to the
332      * Document and dispatch the 'onload' event</li>
333      * </ul>
334      *
335      */

336     public TestReport runImpl() throws Exception JavaDoc{
337         ApplicationSecurityEnforcer ase
338             = new ApplicationSecurityEnforcer(this.getClass(),
339                                               "org/apache/batik/apps/svgbrowser/resources/svgbrowser.policy");
340
341         if (secure) {
342             ase.enforceSecurity(true);
343         }
344
345         try {
346             if (!restricted) {
347                 return testImpl();
348             } else {
349                 // Emulate calling from restricted code. We create a
350
// calling context with only the permission to read
351
// the file.
352
Policy JavaDoc policy = Policy.getPolicy();
353                 URL JavaDoc classesURL = (new File JavaDoc("classes")).toURL();
354                 CodeSource JavaDoc cs = new CodeSource JavaDoc(classesURL, null);
355                 PermissionCollection JavaDoc permissionsOrig
356                     = policy.getPermissions(cs);
357                 Permissions JavaDoc permissions = new Permissions JavaDoc();
358                 Enumeration JavaDoc iter = permissionsOrig.elements();
359                 while (iter.hasMoreElements()) {
360                     Permission JavaDoc p = (Permission JavaDoc)iter.nextElement();
361                     if (!(p instanceof RuntimePermission JavaDoc)) {
362                         if (!(p instanceof java.security.AllPermission JavaDoc)) {
363                             permissions.add(p);
364                         }
365                     } else {
366                         if (!"createClassLoader".equals(p.getName())) {
367                             permissions.add(p);
368                         }
369                     }
370                 }
371
372                 permissions.add(new FilePermission JavaDoc(fileName, "read"));
373                 permissions.add(new RuntimePermission JavaDoc("accessDeclaredMembers"));
374
375                 ProtectionDomain JavaDoc domain;
376                 AccessControlContext JavaDoc ctx;
377                 domain = new ProtectionDomain JavaDoc(null, permissions);
378                 ctx = new AccessControlContext JavaDoc(new ProtectionDomain JavaDoc[]{domain});
379
380                 try {
381                     return (TestReport)AccessController.doPrivileged
382                         (new PrivilegedExceptionAction JavaDoc() {
383                                 public Object JavaDoc run() throws Exception JavaDoc {
384                                     return testImpl();
385                                 }
386                             }, ctx);
387                 } catch (PrivilegedActionException JavaDoc pae) {
388                     throw pae.getException();
389                 }
390             }
391         } finally {
392             ase.enforceSecurity(false);
393         }
394     }
395
396     /**
397      * Implementation helper
398      */

399     protected TestReport testImpl() {
400         //
401
// First step:
402
//
403
// Load the input SVG into a Document object
404
//
405
String JavaDoc parserClassName = XMLResourceDescriptor.getXMLParserClassName();
406         SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parserClassName);
407         f.setValidating(validate.booleanValue());
408         Document JavaDoc doc = null;
409         
410         try {
411             doc = f.createDocument(svgURL);
412         } catch(Exception JavaDoc e){
413             e.printStackTrace();
414             return handleException(e);
415         }
416         
417         //
418
// Second step:
419
//
420
// Now that the SVG file has been loaded, build
421
// a GVT Tree from it
422
//
423
TestUserAgent userAgent = buildUserAgent();
424         GVTBuilder builder = new GVTBuilder();
425         BridgeContext ctx = new BridgeContext(userAgent);
426         ctx.setDynamic(true);
427         Exception JavaDoc e = null;
428         try {
429             builder.build(ctx, doc);
430             BaseScriptingEnvironment scriptEnvironment
431                 = new BaseScriptingEnvironment(ctx);
432             scriptEnvironment.loadScripts();
433             scriptEnvironment.dispatchSVGLoadEvent();
434         } catch (Exception JavaDoc ex){
435             e = ex;
436         } finally {
437             if (e == null && userAgent.e != null) {
438                 e = userAgent.e;
439             }
440             
441             if (e != null) {
442                 return handleException(e);
443             }
444         }
445         
446         //
447
// If we got here, it means that an exception did not
448
// happen. Check if this is expected.
449
TestReport report = null;
450         if (expectedExceptionClass == null) {
451             // No error was expected then check that the script ran.
452
Element JavaDoc elem = doc.getElementById("testResult");
453             String JavaDoc s = elem.getAttributeNS(null, "result");
454             if (RAN.equals(s)) {
455                 report = reportSuccess();
456             } else {
457                 report = reportError(ERROR_SCRIPT_DID_NOT_RUN);
458                 report.addDescriptionEntry(ENTRY_KEY_UNEXPECTED_RESULT,
459                                            s);
460             }
461         }
462         if (report == null) {
463             report = reportError(ERROR_EXCEPTION_DID_NOT_OCCUR);
464             report.addDescriptionEntry(ENTRY_KEY_EXPECTED_EXCEPTION,
465                                        expectedExceptionClass);
466         }
467         return report;
468     }
469
470     /**
471      * Compares the input exception with the expected exception
472      * If they match, then the test passes. Otherwise, the test fails
473      */

474     protected TestReport handleException(Exception JavaDoc e) {
475         if (!isMatch(e.getClass(), expectedExceptionClass)) {
476             TestReport report = reportError(ERROR_UNEXPECTED_EXCEPTION);
477             report.addDescriptionEntry(ENTRY_KEY_UNEXPECTED_EXCEPTION,
478                                        e.getClass().getName());
479             report.addDescriptionEntry(ENTRY_KEY_EXPECTED_EXCEPTION,
480                                        expectedExceptionClass);
481             return report;
482         } else {
483             if (!ERROR_CODE_NO_CHECK.equals(expectedErrorCode)
484                 && e instanceof BridgeException) {
485                 if ( !expectedErrorCode.equals(((BridgeException)e).getCode()) ) {
486                     TestReport report = reportError(ERROR_UNEXPECTED_ERROR_CODE);
487                     report.addDescriptionEntry(ENTRY_KEY_UNEXPECTED_ERROR_CODE,
488                                                ((BridgeException)e).getCode());
489                     report.addDescriptionEntry(ENTRY_KEY_EXPECTED_ERROR_CODE,
490                                                expectedErrorCode);
491                     return report;
492                 }
493             }
494             return reportSuccess();
495         }
496     }
497
498     /**
499      * Check if the input class' name (or one of its base classes) matches
500      * the input name.
501      */

502     protected boolean isMatch(final Class JavaDoc cl, final String JavaDoc name) {
503         if (cl == null) {
504             return false;
505         } else if (cl.getName().equals(name)) {
506             return true;
507         } else {
508             return isMatch(cl.getSuperclass(), name);
509         }
510     }
511
512     /**
513      * Give subclasses a chance to build their own UserAgent
514      */

515     protected TestUserAgent buildUserAgent(){
516         return new TestUserAgent();
517     }
518
519     class TestUserAgent extends UserAgentAdapter {
520         Exception JavaDoc e;
521
522         public ExternalResourceSecurity
523             getExternalResourceSecurity(ParsedURL resourceURL,
524                                         ParsedURL docURL) {
525             if ("ANY".equals(resourceOrigin)) {
526                 return new RelaxedExternalResourceSecurity(resourceURL,
527                                                            docURL);
528             } else if ("DOCUMENT".equals(resourceOrigin)) {
529                 return new DefaultExternalResourceSecurity(resourceURL,
530                                                            docURL);
531             } else if ("EMBEDED".equals(resourceOrigin)) {
532                 return new EmbededExternalResourceSecurity(resourceURL);
533             } else {
534                 return new NoLoadExternalResourceSecurity();
535             }
536         }
537
538         public ScriptSecurity
539             getScriptSecurity(String JavaDoc scriptType,
540                               ParsedURL scriptURL,
541                               ParsedURL docURL) {
542             ScriptSecurity result = null;
543             if (scripts.indexOf(scriptType) == -1) {
544                 result = new NoLoadScriptSecurity(scriptType);
545             } else {
546                 if ("ANY".equals(scriptOrigin)) {
547                     result = new RelaxedScriptSecurity(scriptType,
548                                                      scriptURL,
549                                                      docURL);
550                 } else if ("DOCUMENT".equals(scriptOrigin)) {
551                     result = new DefaultScriptSecurity(scriptType,
552                                                      scriptURL,
553                                                      docURL);
554                 } else if ("EMBEDED".equals(scriptOrigin)) {
555                     result = new EmbededScriptSecurity(scriptType,
556                                                      scriptURL,
557                                                      docURL);
558                 } else {
559                     result = new NoLoadScriptSecurity(scriptType);
560                 }
561             }
562             return result;
563         }
564
565         public void displayError(Exception JavaDoc e) {
566             this.e = e;
567         }
568     }
569
570 }
571
Popular Tags