KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > batik > svggen > SVGAccuracyTest


1 /*
2
3    Copyright 2001,2003 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.svggen;
19
20 import org.apache.batik.svggen.SVGGeneratorContext.GraphicContextDefaults;
21
22 import java.awt.Dimension JavaDoc;
23 import java.awt.Font JavaDoc;
24
25 import java.net.URL JavaDoc;
26
27 import java.io.BufferedInputStream JavaDoc;
28 import java.io.BufferedReader JavaDoc;
29 import java.io.InputStreamReader JavaDoc;
30 import java.io.File JavaDoc;
31 import java.io.FileOutputStream JavaDoc;
32 import java.io.InputStream JavaDoc;
33 import java.io.IOException JavaDoc;
34 import java.io.ByteArrayInputStream JavaDoc;
35 import java.io.ByteArrayOutputStream JavaDoc;
36 import java.io.OutputStreamWriter JavaDoc;
37 import java.io.StringWriter JavaDoc;
38 import java.io.PrintWriter JavaDoc;
39
40 import org.apache.batik.util.SVGConstants;
41 import org.apache.batik.test.AbstractTest;
42 import org.apache.batik.test.DefaultTestReport;
43 import org.apache.batik.test.TestReport;
44
45 import org.apache.batik.svggen.SVGGraphics2D;
46 import org.apache.batik.dom.GenericDOMImplementation;
47 import org.w3c.dom.Document JavaDoc;
48 import org.w3c.dom.DOMImplementation JavaDoc;
49
50 /**
51  * This test validates that a given rendering sequence, modeled
52  * by a <tt>Painter</tt> is properly converted to an SVG document
53  * by comparing the generated SVG document to a know, valid
54  * SVG reference.
55  *
56  * @author <a HREF="mailto:vhardy@apache.org">Vincent Hardy</a>
57  * @version $Id: SVGAccuracyTest.java,v 1.14 2004/08/18 07:16:45 vhardy Exp $
58  */

59 public class SVGAccuracyTest extends AbstractTest
60     implements SVGConstants{
61     /**
62      * Error when an error occurs while generating SVG
63      * with the <tt>SVGGraphics2D</tt>
64      * {0} = painter class name if painter not null. Null otherwise
65      * {1} = exception class name
66      * {2} = exception message
67      * {3} = exception stack trace.
68      */

69     public static final String JavaDoc ERROR_CANNOT_GENERATE_SVG
70         = "SVGAccuracyTest.error.cannot.generate.svg";
71
72     /**
73      * Error when the reference SVG file cannot be opened
74      * {0} = URI of the reference image
75      * {1} = IOException message
76      */

77     public static final String JavaDoc ERROR_CANNOT_OPEN_REFERENCE_SVG_FILE
78         = "SVGAccuracyTest.error.cannot.open.reference.svg.file";
79
80     /**
81      * Error when there is an IOException while comparing the
82      * reference SVG file with the newly generated SVG content
83      * {0} = URI of the reference image
84      * {1} = IOException message.
85      */

86     public static final String JavaDoc ERROR_ERROR_WHILE_COMPARING_FILES
87         = "SVGAccuracyTest.error.while.comparing.files";
88
89     /**
90      * Error when the generated SVG is inaccurate
91      */

92     public static final String JavaDoc ERROR_GENERATED_SVG_INACCURATE
93         = "SVGAccuracyTest.error.generated.svg.inaccurate";
94
95     public static final String JavaDoc ENTRY_KEY_ERROR_DESCRIPTION
96         = "SVGAccuracyTest.entry.key.error.description";
97
98     public static final String JavaDoc ENTRY_KEY_LINE_NUMBER
99         = "SVGAccuracyTest.entry.key.line.number";
100
101     public static final String JavaDoc ENTRY_KEY_COLUMN_NUMBER
102         = "SVGAccuracyTest.entry.key.column.number";
103
104     public static final String JavaDoc ENTRY_KEY_COLUMN_EXPECTED_VALUE
105         = "SVGAccuracyTest.entry.key.column.expected.value";
106
107     public static final String JavaDoc ENTRY_KEY_COLUMN_FOUND_VALUE
108         = "SVGAccuracyTest.entry.key.column.found.value";
109
110     public static final String JavaDoc ENTRY_KEY_REFERENCE_LINE
111         = "SVGAccuracyTest.entry.key.reference.line";
112
113     public static final String JavaDoc ENTRY_KEY_NEW_LINE
114         = "SVGAccuracyTest.entry.key.new.line";
115
116     /**
117      * Canvas size for all tests
118      */

119     public static final Dimension JavaDoc CANVAS_SIZE
120         = new Dimension JavaDoc(300, 400);
121
122     /**
123      * Painter which performs an arbitrary rendering
124      * sequence.
125      */

126     private Painter painter;
127
128     /**
129      * Reference SVG URL
130      */

131     private URL JavaDoc refURL;
132
133     /**
134      * File where the generated SVG might be saved
135      */

136     private File JavaDoc saveSVG;
137
138     /**
139      * Constructor
140      * @param painter the <tt>Painter</tt> object which will
141      * perform an arbitrary rendering sequence.
142      * @param refURL the location of a reference SVG which
143      * should be exactly identical to that generated
144      * by the painter.
145      */

146     public SVGAccuracyTest(Painter painter,
147                            URL JavaDoc refURL){
148         this.painter = painter;
149         this.refURL = refURL;
150     }
151
152     public File JavaDoc getSaveSVG(){
153         return saveSVG;
154     }
155
156     public void setSaveSVG(File JavaDoc saveSVG){
157         this.saveSVG = saveSVG;
158     }
159
160     /**
161      * This method will only throw exceptions if some aspect
162      * of the test's internal operation fails.
163      */

164     public TestReport runImpl() throws Exception JavaDoc {
165         DefaultTestReport report
166             = new DefaultTestReport(this);
167
168         SVGGraphics2D g2d = buildSVGGraphics2D();
169         g2d.setSVGCanvasSize(CANVAS_SIZE);
170
171         //
172
// Generate SVG content
173
//
174
ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
175         OutputStreamWriter JavaDoc osw = new OutputStreamWriter JavaDoc(bos, "UTF-8");
176         try{
177             painter.paint(g2d);
178             configureSVGGraphics2D(g2d);
179             g2d.stream(osw);
180             osw.flush();
181             bos.flush();
182             bos.close();
183         }catch(Exception JavaDoc e){
184             StringWriter JavaDoc trace = new StringWriter JavaDoc();
185             e.printStackTrace(new PrintWriter JavaDoc(trace));
186             report.setErrorCode(ERROR_CANNOT_GENERATE_SVG);
187             report.setDescription(new TestReport.Entry[]{
188                 new TestReport.Entry(Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
189                                      Messages.formatMessage(ERROR_CANNOT_GENERATE_SVG,
190                                                             new String JavaDoc[]{painter == null? "null" : painter.getClass().getName(),
191                                                                          e.getClass().getName(),
192                                                                          e.getMessage(),
193                                                                          trace.toString() })) });
194             report.setPassed(false);
195             return report;
196         }
197
198         //
199
// Compare with reference SVG
200
//
201
InputStream JavaDoc refStream = null;
202         try {
203             refStream =
204                 new BufferedInputStream JavaDoc(refURL.openStream());
205         }catch(Exception JavaDoc e){
206             report.setErrorCode(ERROR_CANNOT_OPEN_REFERENCE_SVG_FILE);
207             report.setDescription( new TestReport.Entry[]{
208                 new TestReport.Entry(Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
209                           Messages.formatMessage(ERROR_CANNOT_OPEN_REFERENCE_SVG_FILE,
210                                                  new Object JavaDoc[]{refURL != null? refURL.toExternalForm() : "null",
211                                                               e.getMessage()})) });
212             report.setPassed(false);
213             save(bos.toByteArray());
214             return report;
215         }
216
217         InputStream JavaDoc newStream = new ByteArrayInputStream JavaDoc(bos.toByteArray());
218
219         boolean accurate = true;
220         String JavaDoc refLine = null;
221         String JavaDoc newLine = null;
222         int ln = 1;
223
224         try{
225             // accurate = compare(refStream, newStream);
226
BufferedReader JavaDoc refReader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(refStream));
227             BufferedReader JavaDoc newReader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(newStream));
228             while((refLine = refReader.readLine()) != null){
229                 newLine = newReader.readLine();
230                 if(newLine == null || !refLine.equals(newLine)){
231                     accurate = false;
232                     break;
233                 }
234                 ln++;
235             }
236
237             if(accurate){
238                 // need to make sure newLine is null as well
239
newLine = newReader.readLine();
240                 if(newLine != null){
241                     accurate = false;
242                 }
243             }
244
245         } catch(IOException JavaDoc e) {
246             report.setErrorCode(ERROR_ERROR_WHILE_COMPARING_FILES);
247             report.setDescription(new TestReport.Entry[]{
248                 new TestReport.Entry(Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
249                                      Messages.formatMessage(ERROR_ERROR_WHILE_COMPARING_FILES,
250                                                             new Object JavaDoc[]{refURL.toExternalForm(),
251                                                                          e.getMessage()}))});
252             report.setPassed(false);
253             save(bos.toByteArray());
254             return report;
255         }
256
257         if(!accurate){
258             save(bos.toByteArray());
259             int cn = computeColumnNumber(refLine, newLine);
260             String JavaDoc expectedChar = "eol";
261             if(cn >= 0 && refLine != null && refLine.length() > cn){
262                 expectedChar = (new Character JavaDoc(refLine.charAt(cn))).toString();
263             }
264             String JavaDoc foundChar = "null";
265             if(cn >=0 && newLine != null && newLine.length() > cn){
266                 foundChar = (new Character JavaDoc(newLine.charAt(cn))).toString();
267             }
268
269             if(expectedChar.equals(" ")){
270                 expectedChar = "' '";
271             }
272             if(foundChar.equals(" ")){
273                 foundChar = "' '";
274             }
275
276             report.setErrorCode(ERROR_GENERATED_SVG_INACCURATE);
277             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_LINE_NUMBER,null), new Integer JavaDoc(ln));
278             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_COLUMN_NUMBER,null), new Integer JavaDoc(cn));
279             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_COLUMN_EXPECTED_VALUE,null), expectedChar);
280             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_COLUMN_FOUND_VALUE,null), foundChar);
281             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_REFERENCE_LINE,null), refLine);
282             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_NEW_LINE,null), newLine);
283             report.setPassed(false);
284         }
285         else{
286             report.setPassed(true);
287         }
288
289         return report;
290     }
291     
292     public int computeColumnNumber(String JavaDoc aStr, String JavaDoc bStr){
293         if(aStr == null || bStr == null){
294             return -1;
295         }
296
297         int n = aStr.length();
298         int i = -1;
299         for(i=0; i<n; i++){
300             char a = aStr.charAt(i);
301             if(i < bStr.length()){
302                 char b = bStr.charAt(i);
303                 if(a != b){
304                     break;
305                 }
306             }
307             else {
308                 break;
309             }
310         }
311
312         return i;
313     }
314
315     /**
316      * Saves the byte array in the "saveSVG" file
317      * if that file's parent directory exists.
318      */

319     protected void save(byte[] data) throws IOException JavaDoc{
320         if(saveSVG == null){
321             return;
322         }
323
324         FileOutputStream JavaDoc os = new FileOutputStream JavaDoc(saveSVG);
325         os.write(data);
326         os.close();
327     }
328
329     /**
330      * Compare the two input streams
331      */

332     protected boolean byteCompare(InputStream JavaDoc refStream,
333                                   InputStream JavaDoc newStream)
334         throws IOException JavaDoc{
335         int b = 0;
336         int nb = 0;
337         do {
338             if (b == nb || nb != 13)
339                 b = refStream.read();
340             nb = newStream.read();
341         } while (b != -1 && nb != -1 && (b == nb || nb == 13));
342         refStream.close();
343         newStream.close();
344         return (b == nb || nb == 13);
345     }
346
347     /**
348      * Builds an <tt>SVGGraphics2D</tt> with a default
349      * configuration.
350      */

351     protected SVGGraphics2D buildSVGGraphics2D() {
352         // CSSDocumentHandler.setParserClassName(CSS_PARSER_CLASS_NAME);
353
DOMImplementation impl = GenericDOMImplementation.getDOMImplementation();
354         String JavaDoc namespaceURI = SVGConstants.SVG_NAMESPACE_URI;
355         Document JavaDoc domFactory = impl.createDocument(namespaceURI, SVG_SVG_TAG, null);
356         SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(domFactory);
357         GraphicContextDefaults defaults
358             = new GraphicContextDefaults();
359         defaults.font = new Font JavaDoc("Arial", Font.PLAIN, 12);
360         ctx.setGraphicContextDefaults(defaults);
361         ctx.setPrecision(12);
362         return new SVGGraphics2D(ctx, false);
363     }
364
365
366     /**
367      * Eventually configure the <tt>SVGGraphics2D</tt> after dumping in it and just
368      * before serializing the DOM Tree.
369      */

370     protected void configureSVGGraphics2D(SVGGraphics2D g2d) {}
371 }
372
Popular Tags