e.g. Calendar Search Help
You must enter a value before pressing Search
batik

Class: org.apache.batik.svggen.SVGAccuracyTest   ©

 OK to copy?
001 /*
002 
003  ============================================================================
004                    The Apache Software License, Version 1.1
005  ============================================================================
006 
007  Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
008 
009  Redistribution and use in source and binary forms, with or without modifica-
010  tion, are permitted provided that the following conditions are met:
011 
012  1. Redistributions of  source code must  retain the above copyright  notice,
013     this list of conditions and the following disclaimer.
014 
015  2. Redistributions in binary form must reproduce the above copyright notice,
016     this list of conditions and the following disclaimer in the documentation
017     and/or other materials provided with the distribution.
018 
019  3. The end-user documentation included with the redistribution, if any, must
020     include  the following  acknowledgment:  "This product includes  software
021     developed  by the  Apache Software Foundation  (http://www.apache.org/)."
022     Alternately, this  acknowledgment may  appear in the software itself,  if
023     and wherever such third-party acknowledgments normally appear.
024 
025  4. The names "Batik" and  "Apache Software Foundation" must  not  be
026     used to  endorse or promote  products derived from  this software without
027     prior written permission. For written permission, please contact
028     apache@apache.org.
029 
030  5. Products  derived from this software may not  be called "Apache", nor may
031     "Apache" appear  in their name,  without prior written permission  of the
032     Apache Software Foundation.
033 
034  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
035  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
036  FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
037  APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
038  INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
039  DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
040  OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
041  ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
042  (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
043  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
044 
045  This software  consists of voluntary contributions made  by many individuals
046  on  behalf of the Apache Software  Foundation. For more  information on the
047  Apache Software Foundation, please see <http://www.apache.org/>.
048 
049 */
050 
051 package org.apache.batik.svggen;
052 
053 import org.apache.batik.svggen.SVGGeneratorContext.GraphicContextDefaults;
054 
055 import java.awt.Dimension;
056 import java.awt.Font;
057 
058 import java.net.URL;
059 
060 import java.io.BufferedInputStream;
061 import java.io.BufferedReader;
062 import java.io.InputStreamReader;
063 import java.io.File;
064 import java.io.FileOutputStream;
065 import java.io.InputStream;
066 import java.io.IOException;
067 import java.io.ByteArrayInputStream;
068 import java.io.ByteArrayOutputStream;
069 import java.io.OutputStreamWriter;
070 import java.io.StringWriter;
071 import java.io.PrintWriter;
072 
073 import org.apache.batik.util.SVGConstants;
074 import org.apache.batik.test.AbstractTest;
075 import org.apache.batik.test.DefaultTestReport;
076 import org.apache.batik.test.TestReport;
077 
078 import org.apache.batik.svggen.SVGGraphics2D;
079 import org.apache.batik.dom.GenericDOMImplementation;
080 import org.w3c.dom.Document;
081 import org.w3c.dom.DOMImplementation;
082 
083 /**
084  * This test validates that a given rendering sequence, modeled
085  * by a <tt>Painter</tt> is properly converted to an SVG document
086  * by comparing the generated SVG document to a know, valid
087  * SVG reference.
088  *
089  * @author <a href="mailto:vhardy@apache.org">Vincent Hardy</a>
090  * @version $Id: SVGAccuracyTest.java,v 1.13 2003/08/08 11:39:38 vhardy Exp $
091  */
092 public class SVGAccuracyTest extends AbstractTest
093     implements SVGConstants{
094     /**
095      * Error when an error occurs while generating SVG
096      * with the <tt>SVGGraphics2D</tt>
097      * {0} = painter class name if painter not null. Null otherwise
098      * {1} = exception class name
099      * {2} = exception message
100      * {3} = exception stack trace.
101      */
102     public static final String ERROR_CANNOT_GENERATE_SVG
103         = "SVGAccuracyTest.error.cannot.generate.svg";
104 
105     /**
106      * Error when the reference SVG file cannot be opened
107      * {0} = URI of the reference image
108      * {1} = IOException message
109      */
110     public static final String ERROR_CANNOT_OPEN_REFERENCE_SVG_FILE
111         = "SVGAccuracyTest.error.cannot.open.reference.svg.file";
112 
113     /**
114      * Error when there is an IOException while comparing the
115      * reference SVG file with the newly generated SVG content
116      * {0} = URI of the reference image
117      * {1} = IOException message.
118      */
119     public static final String ERROR_ERROR_WHILE_COMPARING_FILES
120         = "SVGAccuracyTest.error.while.comparing.files";
121 
122     /**
123      * Error when the generated SVG is inaccurate
124      */
125     public static final String ERROR_GENERATED_SVG_INACCURATE
126         = "SVGAccuracyTest.error.generated.svg.inaccurate";
127 
128     public static final String ENTRY_KEY_ERROR_DESCRIPTION
129         = "SVGAccuracyTest.entry.key.error.description";
130 
131     public static final String ENTRY_KEY_LINE_NUMBER
132         = "SVGAccuracyTest.entry.key.line.number";
133 
134     public static final String ENTRY_KEY_COLUMN_NUMBER
135         = "SVGAccuracyTest.entry.key.column.number";
136 
137     public static final String ENTRY_KEY_COLUMN_EXPECTED_VALUE
138         = "SVGAccuracyTest.entry.key.column.expected.value";
139 
140     public static final String ENTRY_KEY_COLUMN_FOUND_VALUE
141         = "SVGAccuracyTest.entry.key.column.found.value";
142 
143     public static final String ENTRY_KEY_REFERENCE_LINE
144         = "SVGAccuracyTest.entry.key.reference.line";
145 
146     public static final String ENTRY_KEY_NEW_LINE
147         = "SVGAccuracyTest.entry.key.new.line";
148 
149     /**
150      * Canvas size for all tests
151      */
152     public static final Dimension CANVAS_SIZE
153         = new Dimension(300, 400);
154 
155     /**
156      * Painter which performs an arbitrary rendering
157      * sequence.
158      */
159     private Painter painter;
160 
161     /**
162      * Reference SVG URL
163      */
164     private URL refURL;
165 
166     /**
167      * File where the generated SVG might be saved
168      */
169     private File saveSVG;
170 
171     /**
172      * Constructor
173      * @param painter the <tt>Painter</tt> object which will
174      *        perform an arbitrary rendering sequence.
175      * @param refURL the location of a reference SVG which
176      *        should be exactly identical to that generated
177      *        by the painter.
178      */
179     public SVGAccuracyTest(Painter painter,
180                            URL refURL){
181         this.painter = painter;
182         this.refURL  = refURL;
183     }
184 
185     public File getSaveSVG(){
186         return saveSVG;
187     }
188 
189     public void setSaveSVG(File saveSVG){
190         this.saveSVG = saveSVG;
191     }
192 
193     /**
194      * This method will only throw exceptions if some aspect
195      * of the test's internal operation fails.
196      */
197     public TestReport runImpl() throws Exception {
198         DefaultTestReport report
199             = new DefaultTestReport(this);
200 
201         SVGGraphics2D g2d = buildSVGGraphics2D();
202         g2d.setSVGCanvasSize(CANVAS_SIZE);
203 
204         //
205         // Generate SVG content
206         //
207         ByteArrayOutputStream bos = new ByteArrayOutputStream();
208         OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8");
209         try{
210             painter.paint(g2d);
211             configureSVGGraphics2D(g2d);
212             g2d.stream(osw);
213             osw.flush();
214             bos.flush();
215             bos.close();
216         }catch(Exception e){
217             StringWriter trace = new StringWriter();
218             e.printStackTrace(new PrintWriter(trace));
219             report.setErrorCode(ERROR_CANNOT_GENERATE_SVG);
220             report.setDescription(new TestReport.Entry[]{
221                 new TestReport.Entry(Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
222                                      Messages.formatMessage(ERROR_CANNOT_GENERATE_SVG,
223                                                             new String[]{painter == null? "null" : painter.getClass().getName(),
224                                                                          e.getClass().getName(),
225                                                                          e.getMessage(),
226                                                                          trace.toString() })) });
227             report.setPassed(false);
228             return report;
229         }
230 
231         //
232         // Compare with reference SVG
233         //
234         InputStream refStream = null;
235         try {
236             refStream =
237                 new BufferedInputStream(refURL.openStream());
238         }catch(Exception e){
239             report.setErrorCode(ERROR_CANNOT_OPEN_REFERENCE_SVG_FILE);
Rate240             report.setDescription( new TestReport.Entry[]{
241                 new TestReport.Entry(Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
242                           Messages.formatMessage(ERROR_CANNOT_OPEN_REFERENCE_SVG_FILE,
243                                                  new Object[]{refURL != null? refURL.toExternalForm() : "null",
244                                                               e.getMessage()})) });
245             report.setPassed(false);
246             save(bos.toByteArray());
247             return report;
248         }
249 
250         InputStream newStream = new ByteArrayInputStream(bos.toByteArray());
251 
252         boolean accurate = true;
253         String refLine = null;
254         String newLine = null;
255         int ln = 1;
256 
257         try{
258             // accurate = compare(refStream, newStream);
259             BufferedReader refReader = new BufferedReader(new InputStreamReader(refStream));
260             BufferedReader newReader = new BufferedReader(new InputStreamReader(newStream));
261             while((refLine = refReader.readLine()) != null){
262                 newLine = newReader.readLine();
263                 if(newLine == null || !refLine.equals(newLine)){
264                     accurate = false;
265                     break;
266                 }
267                 ln++;
268             }
269 
270             if(accurate){
271                 // need to make sure newLine is null as well
272                 newLine = newReader.readLine();
273                 if(newLine != null){
274                     accurate = false;
275                 }
276             }
277 
278         } catch(IOException e) {
279             report.setErrorCode(ERROR_ERROR_WHILE_COMPARING_FILES);
Rate280             report.setDescription(new TestReport.Entry[]{
281                 new TestReport.Entry(Messages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
282                                      Messages.formatMessage(ERROR_ERROR_WHILE_COMPARING_FILES,
283                                                             new Object[]{refURL.toExternalForm(),
284                                                                          e.getMessage()}))});
285             report.setPassed(false);
286             save(bos.toByteArray());
287             return report;
288         }
289 
290         if(!accurate){
291             save(bos.toByteArray());
292             int cn = computeColumnNumber(refLine, newLine);
293             String expectedChar = "eol";
294             if(cn >= 0 && refLine != null && refLine.length() > cn){
295                 expectedChar = (new Character(refLine.charAt(cn))).toString();
296             }
297             String foundChar = "null";
298             if(cn >=0 && newLine != null && newLine.length() > cn){
299                 foundChar = (new Character(newLine.charAt(cn))).toString();
300             }
301 
302             if(expectedChar.equals(" ")){
303                 expectedChar = "' '";
304             }
305             if(foundChar.equals(" ")){
306                 foundChar = "' '";
307             }
308 
309             report.setErrorCode(ERROR_GENERATED_SVG_INACCURATE);
310             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_LINE_NUMBER,null), new Integer(ln));
311             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_COLUMN_NUMBER,null), new Integer(cn));
312             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_COLUMN_EXPECTED_VALUE,null), expectedChar);
313             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_COLUMN_FOUND_VALUE,null), foundChar);
314             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_REFERENCE_LINE,null), refLine);
315             report.addDescriptionEntry(Messages.formatMessage(ENTRY_KEY_NEW_LINE,null), newLine);
316             report.setPassed(false);
317         }
318         else{
319             report.setPassed(true);
320         }
321 
322         return report;
323     }
324     
325     public int computeColumnNumber(String aStr, String bStr){
326         if(aStr == null || bStr == null){
327             return -1;
328         }
329 
330         int n = aStr.length();
331         int i = -1;
332         for(i=0; i<n; i++){
333             char a = aStr.charAt(i);
334             if(i < bStr.length()){
335                 char b = bStr.charAt(i);
336                 if(a != b){
337                     break;
338                 }
339             }
340             else {
341                 break;
342             }
343         }
344 
345         return i;
346     }
347 
348     /**
349      * Saves the byte array in the "saveSVG" file
350      * if that file's parent directory exists.
351      */
352     protected void save(byte[] data) throws IOException{
353         if(saveSVG == null){
354             return;
355         }
356 
357         FileOutputStream os = new FileOutputStream(saveSVG);
358         os.write(data);
359         os.close();
360     }
361 
362     /**
363      * Compare the two input streams
364      */
365     protected boolean byteCompare(InputStream refStream,
366                                   InputStream newStream)
367         throws IOException{
368         int b = 0;
369         int nb = 0;
370         do {
371             if (b == nb || nb != 13)
372                 b = refStream.read();
373             nb = newStream.read();
374         } while (b != -1 && nb != -1 && (b == nb || nb == 13));
375         refStream.close();
376         newStream.close();
377         return (b == nb || nb == 13);
378     }
379 
380     /**
381      * Builds an <tt>SVGGraphics2D</tt> with a default
382      * configuration.
383      */
384     protected SVGGraphics2D buildSVGGraphics2D() {
385         // CSSDocumentHandler.setParserClassName(CSS_PARSER_CLASS_NAME);
386         DOMImplementation impl = GenericDOMImplementation.getDOMImplementation();
387         String namespaceURI = SVGConstants.SVG_NAMESPACE_URI;
388         Document domFactory = impl.createDocument(namespaceURI, SVG_SVG_TAG, null);
389         SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(domFactory);
390         GraphicContextDefaults defaults 
391             = new GraphicContextDefaults();
392         defaults.font = new Font("Arial", Font.PLAIN, 12);
393         ctx.setGraphicContextDefaults(defaults);
394         ctx.setPrecision(12);
395         return new SVGGraphics2D(ctx, false);
396     }
397 
398 
399     /**
400      * Eventually configure the <tt>SVGGraphics2D</tt> after dumping in it and just
401      * before serializing the DOM Tree.
402      */
403     protected void configureSVGGraphics2D(SVGGraphics2D g2d) {}
404 }

            
All Examples in File:
Example
Line
Rating (found
useful by...)
240 0% of 0
280 0% of 0