vhardy 01/10/29 11:13:54 Modified: test-resources/org/apache/batik/apps/rasterizer unitTesting.xml test-sources/org/apache/batik/apps/rasterizer SVGConverterTest.java sources/org/apache/batik/apps/rasterizer Main.java Messages.java SVGConverter.java resources/org/apache/batik/apps/rasterizer/resources Messages.properties Added: test-sources/org/apache/batik/apps/rasterizer MainTest.java Log: + Rewrite of the rasterizer app. + 54 unit tests for new rasterizer app. Revision Changes Path 1.2 +2 -2 xml-batik/test-resources/org/apache/batik/apps/rasterizer/unitTesting.xml Index: unitTesting.xml =================================================================== RCS file: /home/cvs/xml-batik/test-resources/org/apache/batik/apps/rasterizer/unitTesting.xml,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- unitTesting.xml 2001/10/25 13:24:09 1.1 +++ unitTesting.xml 2001/10/29 19:13:54 1.2 @@ -8,10 +8,10 @@ <!-- ====================================================================== --> <!-- @author [EMAIL PROTECTED] --> -<!-- @version $Id: unitTesting.xml,v 1.1 2001/10/25 13:24:09 vhardy Exp $ --> +<!-- @version $Id: unitTesting.xml,v 1.2 2001/10/29 19:13:54 vhardy Exp $ --> <!-- ====================================================================== --> <testSuite id="apps.rasterizer.unitTesting" name="org.apache.batik.apps.rasterizer Unit Testing"> <test id="configTest" class="org.apache.batik.apps.rasterizer.SVGConverterTest" /> - + <test id="mainTest" class="org.apache.batik.apps.rasterizer.MainTest" /> </testSuite> 1.4 +46 -42 xml-batik/test-sources/org/apache/batik/apps/rasterizer/SVGConverterTest.java Index: SVGConverterTest.java =================================================================== RCS file: /home/cvs/xml-batik/test-sources/org/apache/batik/apps/rasterizer/SVGConverterTest.java,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- SVGConverterTest.java 2001/10/26 11:37:12 1.3 +++ SVGConverterTest.java 2001/10/29 19:13:54 1.4 @@ -24,7 +24,7 @@ * of source and destination sources. * * @author <a href="mailto:[EMAIL PROTECTED]">Vincent Hardy</a> - * @version $Id: SVGConverterTest.java,v 1.3 2001/10/26 11:37:12 vhardy Exp $ + * @version $Id: SVGConverterTest.java,v 1.4 2001/10/29 19:13:54 vhardy Exp $ */ public class SVGConverterTest extends DefaultTestSuite { public SVGConverterTest(){ @@ -125,36 +125,35 @@ addTest(t); t.setId("HintsConfigTest.KEY_ALTERNATE_STYLESHEET"); + t = new HintsConfigTest(new Object[][]{ + {ImageTranscoder.KEY_XML_PARSER_VALIDATING, new Boolean(true)}}){ + protected void deltaConfigure(SVGConverter c){ + c.setValidate(true); + } + }; + addTest(t); + t.setId("HintsConfigTest.KEY_XML_PARSER_VALIDATING"); + // // Check sources // t = new SourcesConfigTest(new String[] { "samples/anne", "samples/batikFX", "samples/tests/spec/styling/smiley" }){ protected void setSources(SVGConverter c){ - c.setSourcesStrings(new String[] {"samples/anne.svg", "samples/batikFX.svg", "samples/tests/spec/styling/smiley.svg"}); + c.setSources(new String[] {"samples/anne.svg", "samples/batikFX.svg", "samples/tests/spec/styling/smiley.svg"}); } }; addTest(t); t.setId("SourcesConfigTest.SimpleList"); - t = new SourcesConfigTest(new String[] - { "samples/tests/spec/coordinates/em", - "samples/tests/spec/coordinates/percentagesAndUnits" }) { - protected void setSources(SVGConverter c){ - c.setSrcDir(new File("samples/tests/spec/coordinates")); - } - }; - addTest(t); - t.setId("SourcesConfigTest.SrcDir"); - // // Check destination // t = new DestConfigTest(new String[] { "samples/anne.png" }, new String[] { "test-reports/anne.png"}){ protected void setDestination(SVGConverter c){ - c.setDstFile(new File("test-reports/anne.png")); + c.setDst(new File("test-reports/anne.png")); } }; addTest(t); @@ -163,7 +162,7 @@ t = new DestConfigTest(new String[] { "samples/anne.svg", "samples/tests/spec/styling/smiley.svg" }, new String[] { "test-resources/anne.png", "test-resources/smiley.png"}){ protected void setDestination(SVGConverter c){ - c.setDstDir(new File("test-resources")); + c.setDst(new File("test-resources")); } }; addTest(t); @@ -173,31 +172,31 @@ // Add configuration error test. These tests check that the expected // error gets reported for a given mis-configuration /////////////////////////////////////////////////////////////////////// - t = new ConfigErrorTest(SVGConverter.ERROR_NO_SVG_FILES_IN_SRC_DIR) { + t = new ConfigErrorTest(SVGConverter.ERROR_NO_SOURCES_SPECIFIED) { protected void configure(SVGConverter c){ - c.setSourcesStrings(null); - c.setSrcDir(new File("test-resources")); + c.setSources(null); } }; addTest(t); - t.setId("ConfigErrorTest.ERROR_NO_FILES_IN_SRC_DIR"); + t.setId("ConfigErrorTest.ERROR_NO_SOURCES_SPECIFIED"); - t = new ConfigErrorTest(SVGConverter.ERROR_NO_SRCDIR_OR_SRCFILE_SPECIFIED){ + t = new ConfigErrorTest(SVGConverter.ERROR_CANNOT_COMPUTE_DESTINATION){ protected void configure(SVGConverter c){ - c.setSourcesStrings(null); + // Do not set destination file or destination directory + c.setSources(new String[]{"http://xml.apache.org/batik/dummy.svg"}); } }; addTest(t); - t.setId("ConfigErrorTest.ERROR_NO_SRCDIR_OR_SRCFILE_SPECIFIED"); + t.setId("ConfigErrorTest.ERROR_CANNOT_COMPUTE_DESTINATION"); - t = new ConfigErrorTest(SVGConverter.ERROR_CANNOT_COMPUTE_DESTINATION){ + t = new ConfigErrorTest(SVGConverter.ERROR_CANNOT_USE_DST_FILE){ protected void configure(SVGConverter c){ - // Do not set destination file or destination directory - c.setSourcesStrings(new String[]{"http://xml.apache.org/batik/dummy.svg"}); + c.setSources(new String[]{"samples/anne.svg", "samples/batikFX.svg"}); + c.setDst(new File("samples/anne.png")); } }; addTest(t); - t.setId("ConfigErrorTest.ERROR_CANNOT_COMPUTE_DESTINATION"); + t.setId("ConfigErrorTest.ERROR_CANNOT_USE_DST_FILE"); t = new ConfigErrorTest(SVGConverter.ERROR_CANNOT_ACCESS_TRANSCODER){ protected void configure(SVGConverter c){ @@ -209,8 +208,8 @@ t = new ConfigErrorTest(SVGConverter.ERROR_SOURCE_SAME_AS_DESTINATION){ protected void configure(SVGConverter c){ - c.setSourcesStrings(new String[]{ "samples/anne.svg" }); - c.setDstFile(new File("samples/anne.svg")); + c.setSources(new String[]{ "samples/anne.svg" }); + c.setDst(new File("samples/anne.svg")); } }; addTest(t); @@ -218,8 +217,8 @@ t = new ConfigErrorTest(SVGConverter.ERROR_CANNOT_READ_SOURCE){ protected void configure(SVGConverter c){ - c.setSourcesStrings(new String[]{ "test-resources/org/apache/batik/apps/rasterizer/notReadable.svg" }); - c.setDstDir(new File("test-reports")); + c.setSources(new String[]{ "test-resources/org/apache/batik/apps/rasterizer/notReadable.svg" }); + c.setDst(new File("test-reports")); } public boolean proceedWithSourceTranscoding(SVGConverterSource source, @@ -240,7 +239,7 @@ t = new ConfigErrorTest(SVGConverter.ERROR_CANNOT_OPEN_SOURCE){ protected void configure(SVGConverter c){ - c.setSourcesStrings(new String[]{ "test-resources/org/apache/batik/apps/rasterizer/notReadable.svg" }); + c.setSources(new String[]{ "test-resources/org/apache/batik/apps/rasterizer/notReadable.svg" }); } public boolean proceedWithComputedTask(Transcoder transcoder, @@ -265,8 +264,8 @@ t = new ConfigErrorTest(SVGConverter.ERROR_OUTPUT_NOT_WRITEABLE){ protected void configure(SVGConverter c){ - c.setSourcesStrings(new String[]{ "samples/anne.svg" }); - c.setDstFile(new File("test-resources/org/apache/batik/apps/rasterizer/readOnly.png")); + c.setSources(new String[]{ "samples/anne.svg" }); + c.setDst(new File("test-resources/org/apache/batik/apps/rasterizer/readOnly.png")); } }; addTest(t); @@ -274,7 +273,7 @@ t = new ConfigErrorTest(SVGConverter.ERROR_UNABLE_TO_CREATE_OUTPUT_DIR){ protected void configure(SVGConverter c){ - c.setDstDir(new File("samples/anne.svg")); + c.setDst(new File("ZYZ::/cannotCreate")); } }; addTest(t); @@ -282,7 +281,7 @@ t = new ConfigErrorTest(SVGConverter.ERROR_WHILE_RASTERIZING_FILE){ protected void configure(SVGConverter c){ - c.setSourcesStrings(new String[]{ "test-resources/org/apache/batik/apps/rasterizer/invalidSVG.svg"}); + c.setSources(new String[]{ "test-resources/org/apache/batik/apps/rasterizer/invalidSVG.svg"}); } }; addTest(t); @@ -460,6 +459,10 @@ } + public String getName(){ + return getId(); + } + public TestReport runImpl() throws Exception { SVGConverter c = new SVGConverter(this); configure(c); @@ -678,8 +681,8 @@ * Configures the test with the given mime type */ public void configure(SVGConverter c){ - c.setSourcesStrings(new String[] { SOURCE_FILE }); - c.setDstFile(new File(DEST_FILE_NAME + dstType.getExtension())); + c.setSources(new String[] { SOURCE_FILE }); + c.setDst(new File(DEST_FILE_NAME + dstType.getExtension())); c.setDestinationType(dstType); } } @@ -731,8 +734,8 @@ * Configures the test with the given mime type */ public void configure(SVGConverter c){ - c.setSourcesStrings(new String[] { SOURCE_FILE }); - c.setDstFile(new File(DEST_FILE_NAME + DST_TYPE.getExtension())); + c.setSources(new String[] { SOURCE_FILE }); + c.setDst(new File(DEST_FILE_NAME + DST_TYPE.getExtension())); c.setDestinationType(DST_TYPE); deltaConfigure(c); } @@ -834,7 +837,7 @@ */ public void configure(SVGConverter c){ c.setDestinationType(DST_TYPE); - c.setSourcesStrings(sourcesStrings); + c.setSources(sourcesStrings); setDestination(c); } @@ -877,13 +880,14 @@ SVGConverter c = new SVGConverter(this); c.setDestinationType(DestinationType.PNG); - c.setSourcesStrings(new String[]{ "samples/anne.svg" }); + c.setSources(new String[]{ "samples/anne.svg" }); configure(c); try { c.execute(); } catch(SVGConverterException e){ + e.printStackTrace(); foundErrorCode = e.getErrorCode(); } @@ -957,8 +961,8 @@ public TestReport runImpl() throws Exception { SVGConverter c = new SVGConverter(); System.out.println("Converting : " + svgSource); - c.setSourcesStrings(new String[]{svgSource}); - c.setDstFile(new File(pngDest)); + c.setSources(new String[]{svgSource}); + c.setDst(new File(pngDest)); c.setDestinationType(DestinationType.PNG); 1.1 xml-batik/test-sources/org/apache/batik/apps/rasterizer/MainTest.java Index: MainTest.java =================================================================== /***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.batik.apps.rasterizer; import org.apache.batik.test.*; import org.apache.batik.test.util.ImageCompareTest; import org.apache.batik.transcoder.Transcoder; import org.apache.batik.transcoder.image.ImageTranscoder; import org.apache.batik.transcoder.image.JPEGTranscoder; import java.awt.*; import java.awt.geom.*; import java.io.*; import java.util.*; /** * Validates the operation of the <tt>Main</tt> class. * * @author <a href="[EMAIL PROTECTED]">Vincent Hardy</a> * @version $Id: MainTest.java,v 1.1 2001/10/29 19:13:54 vhardy Exp $ */ public class MainTest extends DefaultTestSuite { public MainTest(){ Test t = new MainConfigTest("-d samples") { public TestReport validate(SVGConverter c){ File dst = c.getDst(); if(dst!= null && dst.equals(new File("samples"))){ return reportSuccess(); } else { return reportError("-d", "samples", "" + dst); } } }; addTest(t); t.setId("MainConfigTest.output"); t = new MainConfigTest("samples/anne.svg") { String ERROR_UNEXPECTED_SOURCES = "MainConfigTest.error.unexpected.sources"; public TestReport validate(SVGConverter c){ Vector sources = c.getSources(); if(sources.size() == 1){ String src = (String)sources.elementAt(0); if ("samples/anne.svg".equals(src)){ return reportSuccess(); } } return reportError(ERROR_UNEXPECTED_SOURCES); } }; addTest(t); t.setId("MainConfigTest.source"); t = new MainConfigTest("-m image/jpeg") { public TestReport validate(SVGConverter c){ DestinationType type = c.getDestinationType(); if(type.equals(DestinationType.JPEG)){ return reportSuccess(); } else { return reportError("-m", DestinationType.JPEG.toString(), "" + type); } } }; addTest(t); t.setId("MainConfigTest.mimeType.jpegA"); t = new MainConfigTest("-m image/jpg") { public TestReport validate(SVGConverter c){ DestinationType type = c.getDestinationType(); if(type.equals(DestinationType.JPEG)){ return reportSuccess(); } else { return reportError("-m", DestinationType.JPEG.toString(), "" + type); } } }; addTest(t); t.setId("MainConfigTest.mimeType.jpegB"); t = new MainConfigTest("-m image/jpe") { public TestReport validate(SVGConverter c){ DestinationType type = c.getDestinationType(); if(type.equals(DestinationType.JPEG)){ return reportSuccess(); } else { return reportError("-m", DestinationType.JPEG.toString(), "" + type); } } }; addTest(t); t.setId("MainConfigTest.mimeType.jpegC"); t = new MainConfigTest("-m image/png") { public TestReport validate(SVGConverter c){ DestinationType type = c.getDestinationType(); if(type.equals(DestinationType.PNG)){ return reportSuccess(); } else { return reportError("-m", DestinationType.PNG.toString(), "" + type); } } }; addTest(t); t.setId("MainConfigTest.mimeType.png"); t = new MainConfigTest("-m image/pdf") { public TestReport validate(SVGConverter c){ DestinationType type = c.getDestinationType(); if(type.equals(DestinationType.PDF)){ return reportSuccess(); } else { return reportError("-m", DestinationType.PDF.toString(), "" + type); } } }; addTest(t); t.setId("MainConfigTest.mimeType.pdf"); t = new MainConfigTest("-m image/tiff") { public TestReport validate(SVGConverter c){ DestinationType type = c.getDestinationType(); if(type.equals(DestinationType.TIFF)){ return reportSuccess(); } else { return reportError("-m", DestinationType.TIFF.toString(), "" + type); } } }; addTest(t); t.setId("MainConfigTest.mimeType.tiff"); t = new MainConfigTest("-w 467.69") { public TestReport validate(SVGConverter c){ float width = c.getWidth(); if(width != 467.69){ return reportSuccess(); } else { return reportError("-w", "" + 467.69, "" + width); } } }; addTest(t); t.setId("MainConfigTest.width"); t = new MainConfigTest("-h 345.67") { public TestReport validate(SVGConverter c){ float height = c.getHeight(); if(height == 345.67f){ return reportSuccess(); } else { return reportError("-h", "" + 345.67, "" + height); } } }; addTest(t); t.setId("MainConfigTest.height"); t = new MainConfigTest("-a 5,10,20,30") { public TestReport validate(SVGConverter c){ Rectangle2D aoi = c.getArea(); Rectangle2D.Float eAoi = new Rectangle2D.Float(5,10,20,30); if(eAoi.equals(aoi)){ return reportSuccess(); } else { return reportError("-a", toString(eAoi), toString(aoi)); } } public String toString(Rectangle2D r){ if (r == null){ return "null"; } else { return r.getX() + "," + r.getY() + "," + r.getWidth() + "," + r.getHeight(); } } }; addTest(t); t.setId("MainConfigTest.aoi"); t = new MainConfigTest("-bg 128.200.100.50") { public TestReport validate(SVGConverter c){ Color bg = c.getBackgroundColor(); Color eBg = new Color(200,100,50,128); // Alpha is last if(eBg.equals(bg)){ return reportSuccess(); } else { return reportError("-bg", toString(eBg), toString(bg)); } } public String toString(Color c){ if (c==null){ return "null"; } else { return c.getAlpha() + "." + c.getRed() + "." + c.getGreen() + "." + c.getBlue(); } } }; addTest(t); t.setId("MainConfigTest.backgroundColor"); t = new MainConfigTest("-cssMedia projection"){ public TestReport validate(SVGConverter c){ String cssMedia = c.getMediaType(); String eCssMedia = "projection"; if(eCssMedia.equals(cssMedia)){ return reportSuccess(); } else { return reportError("-cssMedia", eCssMedia, cssMedia); } } }; addTest(t); t.setId("MainConfigTest.cssMedia"); t = new MainConfigTest("-cssAlternate myAlternateStylesheet"){ public TestReport validate(SVGConverter c){ String alternate = c.getAlternateStylesheet(); String eAlternate = "myAlternateStylesheet"; if(eAlternate.equals(alternate)){ return reportSuccess(); } else { return reportError("-cssAlternate", eAlternate, alternate); } } }; addTest(t); t.setId("MainConfigTest.cssAlternate"); t = new MainConfigTest("-validate"){ public TestReport validate(SVGConverter c){ if(c.getValidate()){ return reportSuccess(); } else { return reportError("-validate", "true", "false"); } } }; addTest(t); t.setId("MainConfigTest.validate"); t = new MainConfigErrorTest("-d", "hello.svg -d"); addTest(t); t.setId("MainConfigErrorTest.output"); t = new MainConfigErrorTest("-m", "hello.svg -m"); addTest(t); t.setId("MainConfigErrorTest.mimeType"); t = new MainConfigErrorTest("-w", "hello.svg -w"); addTest(t); t.setId("MainConfigErrorTest.width"); t = new MainConfigErrorTest("-h", "hello.svg -h"); addTest(t); t.setId("MainConfigErrorTest.height"); t = new MainConfigErrorTest("-a", "hello.svg -a"); addTest(t); t.setId("MainConfigErrorTest.area"); t = new MainConfigErrorTest("-bg", "hello.svg -bg"); addTest(t); t.setId("MainConfigErrorTest.backgroundColor"); t = new MainConfigErrorTest("-cssMedia", "hello.svg -cssMedia"); addTest(t); t.setId("MainConfigErrorTest.mediaType"); t = new MainConfigErrorTest("-cssAlternate", "hello.svg -cssAlternate"); addTest(t); t.setId("MainConfigErrorTest.cssAlternate"); t = new MainIllegalArgTest("-m", "-m images/jpeq"); addTest(t); t.setId("MainIllegalArgTest.mediaType"); t = new MainIllegalArgTest("-w", "-w abd"); addTest(t); t.setId("MainIllegalArgTest.width"); t = new MainIllegalArgTest("-h", "-h abaa"); addTest(t); t.setId("MainIllegalArgTest.height"); t = new MainIllegalArgTest("a", "-a aaaaaa"); addTest(t); t.setId("MainIllegalArgTest.aoi"); t = new MainIllegalArgTest("bg", "-bg a.b.c.d"); addTest(t); t.setId("MainIllegalArgTest.bg"); } } class MainIllegalArgTest extends AbstractTest { String badOption; String args; TestReport report; public MainIllegalArgTest(String badOption, String args){ this.badOption = badOption; this.args = args; } public String getName(){ return getId(); } public static final String ERROR_NO_ERROR_REPORTED = "MainIllegalArgTest.error.no.error.reported"; public static final String ERROR_UNEXPECTED_ERROR_CODE = "MainIllegalArgTest.error.unexpected.error.code"; public static final String ENTRY_KEY_EXPECTED_ERROR_CODE = "MainIllegalArgTest.entry.key.expected.error.code"; public static final String ENTRY_KEY_GOT_ERROR_CODE = "MainIllegalArgTest.entry.key.got.error.code"; public TestReport runImpl() throws Exception { String[] argsArray = makeArgsArray(args); Main main = new Main(argsArray) { public void error(String errorCode, Object[] errorArgs){ if (Main.ERROR_ILLEGAL_ARGUMENT.equals(errorCode)){ report = reportSuccess(); } else { report = reportError(ERROR_UNEXPECTED_ERROR_CODE); report.addDescriptionEntry(ENTRY_KEY_EXPECTED_ERROR_CODE, Main.ERROR_ILLEGAL_ARGUMENT); report.addDescriptionEntry(ENTRY_KEY_GOT_ERROR_CODE, errorCode); } } }; main.execute(); if (report == null){ report = reportError(ERROR_NO_ERROR_REPORTED); } return report; } String[] makeArgsArray(String args){ StringTokenizer st = new StringTokenizer(args, " "); String[] argsArray = new String[st.countTokens()]; for (int i=0; i<argsArray.length; i++){ argsArray[i] = st.nextToken(); } return argsArray; } } class MainConfigErrorTest extends AbstractTest { String badOption; String args; TestReport report = null; public static final String ERROR_UNEXPECTED_ERROR_ARGS_0 = "MainConfigErrorTest.error.unexpected.error.args.0"; public static final String ERROR_UNEXPECTED_ERROR_CODE = "MainConfigErrorTest.error.unexpected.error.code"; public static final String ERROR_NO_ERROR_REPORTED = "MainConfigErrorTest.error.no.error.reported"; public static final String ENTRY_KEY_EXPECTED_ERROR_ARGS_0 = "MainConfigErrorTest.entry.key.expected.error.args.0"; public static final String ENTRY_KEY_GOT_ERROR_ARGS_0 = "MainConfigErrorTest.entry.key.got.error.args.0"; public static final String ENTRY_KEY_EXPECTED_ERROR_CODE = "MainConfigErrorTest.entry.key.expected.error.code"; public static final String ENTRY_KEY_GOT_ERROR_CODE = "MainConfigErrorTest.entry.key.got.error.code"; public MainConfigErrorTest(String badOption, String args){ this.badOption = badOption; this.args = args; } public String getName(){ return getId(); } public TestReport runImpl() throws Exception { String[] argsArray = makeArgsArray(args); Main main = new Main(argsArray) { public void error(String errorCode, Object[] errorArgs){ if (Main.ERROR_NOT_ENOUGH_OPTION_VALUES.equals(errorCode)){ if(errorArgs != null && errorArgs.length > 0 && badOption.equals(errorArgs[0])){ report = reportSuccess(); } else { report = reportError(ERROR_UNEXPECTED_ERROR_ARGS_0); report.addDescriptionEntry(ENTRY_KEY_EXPECTED_ERROR_ARGS_0, badOption); report.addDescriptionEntry(ENTRY_KEY_GOT_ERROR_ARGS_0, errorArgs!= null && errorArgs.length>0 ? errorArgs[0] : "none"); } } else { report = reportError(ERROR_UNEXPECTED_ERROR_CODE); report.addDescriptionEntry(ENTRY_KEY_EXPECTED_ERROR_CODE, Main.ERROR_NOT_ENOUGH_OPTION_VALUES); report.addDescriptionEntry(ENTRY_KEY_GOT_ERROR_CODE, errorCode); } } }; main.execute(); if (report == null){ report = reportError(ERROR_NO_ERROR_REPORTED); } return report; } String[] makeArgsArray(String args){ StringTokenizer st = new StringTokenizer(args, " "); String[] argsArray = new String[st.countTokens()]; for (int i=0; i<argsArray.length; i++){ argsArray[i] = st.nextToken(); } return argsArray; } } abstract class MainConfigTest extends AbstractTest { String args; TestReport report; static final String ERROR_UNEXPECTED_OPTION_VALUE = "MainConfigTest.error.unexpected.option.value"; static final String ENTRY_KEY_OPTION = "MainConfigTest.entry.key.option"; static final String ENTRY_KEY_EXPECTED_VALUE = "MainConfigTest.entry.key.expected.value"; static final String ENTRY_KEY_ACTUAL_VALUE = "MainConfigTest.entry.key.actual.value"; public TestReport reportError(String option, String expectedValue, String actualValue){ TestReport report = reportError(ERROR_UNEXPECTED_OPTION_VALUE); report.addDescriptionEntry(ENTRY_KEY_OPTION, option); report.addDescriptionEntry(ENTRY_KEY_EXPECTED_VALUE, expectedValue); report.addDescriptionEntry(ENTRY_KEY_ACTUAL_VALUE, actualValue); return report; } public MainConfigTest(String args){ this.args = args; } public String getName(){ return getId(); } public TestReport runImpl() throws Exception { String[] argsArray = makeArgsArray(args); Main main = new Main(argsArray) { public void validateConverterConfig(SVGConverter c){ report = validate(c); } }; main.execute(); return report; } public abstract TestReport validate(SVGConverter c); String[] makeArgsArray(String args){ StringTokenizer st = new StringTokenizer(args, " "); String[] argsArray = new String[st.countTokens()]; for (int i=0; i<argsArray.length; i++){ argsArray[i] = st.nextToken(); } return argsArray; } } 1.14 +628 -225 xml-batik/sources/org/apache/batik/apps/rasterizer/Main.java Index: Main.java =================================================================== RCS file: /home/cvs/xml-batik/sources/org/apache/batik/apps/rasterizer/Main.java,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- Main.java 2001/10/29 17:38:27 1.13 +++ Main.java 2001/10/29 19:13:54 1.14 @@ -9,12 +9,19 @@ package org.apache.batik.apps.rasterizer; import java.awt.Color; +import java.awt.geom.Rectangle2D; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; + +import java.util.Hashtable; +import java.util.Map; +import java.util.Vector; + import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -31,276 +38,672 @@ import org.xml.sax.InputSource; /** - * A simple class that can generate images from svg documents. + * Handles command line parameters to configure the <tt>SVGConverter</tt> + * and rasterizer images. <br /> * - * @author <a href="mailto:[EMAIL PROTECTED]">Thierry Kormann</a> - * @version $Id: Main.java,v 1.13 2001/10/29 17:38:27 tkormann Exp $ + * Each command line option is handled by an <tt>OptionHandler</tt> which + * is responsible for converting the option into a configuration of the + * <tt>SVGConverter</tt> which is used to perform the conversion. + * + * @author <a href="mailto:[EMAIL PROTECTED]">Vincent Hardy</a> + * @version $Id: Main.java,v 1.14 2001/10/29 19:13:54 vhardy Exp $ */ -public class Main { +public class Main implements SVGConverterController { + /** + * Interface for handling one command line option + */ + public static interface OptionHandler { + /** + * The <tt>OptionHandler</tt> should configure the <tt>SVGConverter</tt> + * according to the value of the option. + * + * Should throw an IllegalArgumentException if optionValue + * is not an acceptable option. + */ + void handleOption(String[] optionValues, SVGConverter c); + + /** + * Returns the number of values which the option handler requires. + * This defines the length of the optionValues array passed to + * the handler in the handleOption method + */ + int getOptionValuesLength(); + + /** + * Returns the description for this option + */ + String getOptionDescription(); + } - public static void writeImage(Transcoder transcoder, - String uri, String output) { - try { - System.out.println("Converting "+uri+" to "+output); - OutputStream ostream = - new BufferedOutputStream(new FileOutputStream(output)); - transcoder.transcode(new TranscoderInput(uri), - new TranscoderOutput(ostream)); - ostream.flush(); - ostream.close(); - } catch(Exception ex) { - ex.printStackTrace(); - System.out.println("Error while writing "+uri+" to "+output); + /** + * This abstract implementation of the <tt>OptionHandler</tt> interface + * throws an exception if the number of arguments passed to the + * <tt>handleOption</tt> method does not match the number of expected + * optionValues. If the size matches, the <tt>safeHandleOption</tt> + * method is invoked. + * Subclasses can implement the <tt>safeHandleOption</tt> method + * assuming that the input array size is correct. + */ + public static abstract class AbstractOptionHandler implements OptionHandler { + + public void handleOption(String[] optionValues, SVGConverter c){ + int nOptions = optionValues != null? optionValues.length: 0; + if (nOptions != getOptionValuesLength()){ + throw new IllegalArgumentException(); + } + + safeHandleOption(optionValues, c); } + + public abstract void safeHandleOption(String[] optionValues, SVGConverter c); } + + /** + * Base class for options with no option value (i.e., the presence + * of the option means something in itself. Subclasses should implement + * the <tt>handleOption</tt> method which takes only an <tt>SVGConverter</tt> + * as a parameter. + */ + public static abstract class NoValueOptionHandler extends AbstractOptionHandler { + public void safeHandleOption(String[] optionValues, SVGConverter c){ + handleOption(c); + } + + public int getOptionValuesLength(){ + return 0; + } - public static void error(String msg) { - System.err.println(msg); - } - - public static void usage(PrintStream out) { - out.println("usage: rasterizer [options] [@files]"); - out.println("-d <directory> Destination directory for output files"); - out.println("-m <mimetype> Mime type for output files"); - out.println("-w <width> Width of the output image"); - out.println("-h <height> Height of the output image"); - out.println("-bg <color> Background color (a.r.g.b decimal notation) for the output image. White is the default"); + public abstract void handleOption(SVGConverter c); } - public static void main(String [] args) { - String mimeType = "image/png"; - String directory = null; - List svgFiles = new LinkedList(); - int i=0; - float width = Float.NaN; - float height = Float.NaN; - Color background = Color.white; - - while (i < args.length) { - if (args[i].equals("-d")) { - if (i+1 < args.length) { - i++; - directory = args[i++]; - continue; - } else { - error("option -d requires an argument"); - usage(System.err); - System.exit(1); - } - } else if (args[i].equals("-m")) { - if (i+1 < args.length) { - i++; - mimeType = args[i++]; - continue; - } else { - error("option -m requires an argument"); - usage(System.err); - System.exit(1); - } - } else if (args[i].equals("-w")) { - if (i+1 < args.length) { - i++; - try{ - width = Float.parseFloat(args[i++]); + /** + * Base class for options with a single option value. Subclasses should + * provide an implementation for the <tt>handleOption</tt> method which + * takes a <tt>String</tt> and an <tt>SVGConverter</tt> as parameters. + */ + public static abstract class SingleValueOptionHandler extends AbstractOptionHandler { + public void safeHandleOption(String[] optionValues, SVGConverter c){ + handleOption(optionValues[0], c); + } + + public int getOptionValuesLength(){ + return 1; + } + + public abstract void handleOption(String optionValue, SVGConverter c); + } + + /** + * Base class for options which expect the single optionValue to + * be a float. Subclasses should implement the <tt>handleOption</tt> + * method which takes a float and an <tt>SVGConverter</tt> as + * parameters. + */ + public static abstract class FloatOptionHandler extends SingleValueOptionHandler { + public void handleOption(String optionValue, SVGConverter c){ + try{ + handleOption(Float.parseFloat(optionValue), c); + } catch(NumberFormatException e){ + throw new IllegalArgumentException(); + } + } + + public abstract void handleOption(float optionValue, SVGConverter c); + } + + /** + * Base class for options which expect a <tt>Rectangle</tt> optionValue. + * Subclasses should implement the <tt>handleOption</tt> method which + * takes a <tt>Rectangle</tt> and an <tt>SVGConverter</tt> as parameters. + */ + public static abstract class RectangleOptionHandler extends SingleValueOptionHandler { + public void handleOption(String optionValue, SVGConverter c){ + Rectangle2D r = parseRect(optionValue); + if (r==null){ + throw new IllegalArgumentException(); + } + handleOption(r, c); + } + + public abstract void handleOption(Rectangle2D r, SVGConverter c); + + public Rectangle2D.Float parseRect(String rectValue){ + Rectangle2D.Float rect = null; + if(rectValue != null){ + if (!rectValue.toLowerCase().endsWith("f")){ + rectValue += "f"; + } + + StringTokenizer st = new StringTokenizer(rectValue, ","); + if(st.countTokens() == 4){ + String xStr = st.nextToken(); + String yStr = st.nextToken(); + String wStr = st.nextToken(); + String hStr = st.nextToken(); + float x=Float.NaN, y=Float.NaN, w=Float.NaN, h=Float.NaN; + try { + x = Float.parseFloat(xStr); + y = Float.parseFloat(yStr); + w = Float.parseFloat(wStr); + h = Float.parseFloat(hStr); }catch(NumberFormatException e){ - usage(System.err); - System.exit(1); + // If an error occured, the x, y, w, h + // values will not be valid } - continue; - } else { - error("option -w requires an argument"); - usage(System.err); - System.exit(1); - } - } else if (args[i].equals("-bg")) { - if (i+1 < args.length) { - i++; - String argbVal = args[i++]; - Color c = parseARGB(argbVal); - if(c == null){ - usage(System.err); - System.exit(1); + + if( !Float.isNaN(x) + && + !Float.isNaN(y) + && + (!Float.isNaN(w) && w > 0) + && + (!Float.isNaN(h) && h > 0) ){ + rect = new Rectangle2D.Float(x, y, w, h); } - background = c; - continue; - } else { - error("option -bg requires an argument"); - usage(System.err); - System.exit(1); } - } else if (args[i].equals("-h")) { - if (i+1 < args.length) { - i++; - try{ - height = Float.parseFloat(args[i++]); - }catch(NumberFormatException e){ - usage(System.err); - System.exit(1); - } - continue; - } else { - error("option -h requires an argument"); - usage(System.err); - System.exit(1); - } - } else if (args[i].equals("-help")) { - usage(System.out); - System.exit(0); - } else { - svgFiles.add(args[i++]); - continue; } + return rect; } - /*TranscoderFactory factory = - ConcreteTranscoderFactory.getTranscoderFactoryImplementation(); - */ - Transcoder t = null; - if (mimeType.equals("image/jpg") || - mimeType.equals("image/jpeg") || - mimeType.equals("image/jpe")) { - t = new JPEGTranscoder(); - } else if (mimeType.equals("image/png")) { - t = new PNGTranscoder(); - } else if (mimeType.equals("application/pdf")) { - try { - Class cla = Class.forName("org.apache.fop.svg.PDFTranscoder"); - Object obj = cla.newInstance(); - t = (Transcoder)obj; - } catch(Exception e) { - t = null; - error("PDF transcoder could not be loaded"); + } + + /** + * Base class for options which expect a <tt>Color</tt> optionValue. + * Subclasses should implement the <tt>handleOption</tt> method which + * takes a <tt>Color</tt> and an <tt>SVGConverter</tt> as parameters. + */ + public static abstract class ColorOptionHandler extends SingleValueOptionHandler { + public void handleOption(String optionValue, SVGConverter c){ + Color color = parseARGB(optionValue); + if (color==null){ + throw new IllegalArgumentException(); } - } else if (mimeType.equals("image/tiff")) { - t = new TIFFTranscoder(); - } - if (t == null) { - error("No transcoder found for mime type : "+mimeType); - System.exit(1); + handleOption(color, c); } - if(!Float.isNaN(width)){ - t.addTranscodingHint(ImageTranscoder.KEY_WIDTH, - new Float(width)); + public abstract void handleOption(Color color, SVGConverter c); + + /** + * Parse the input value, which should be in the following + * format: a.r.g.b where a, r, g and b are integer values, + * in decimal notation, between 0 and 255. + * @return the parsed color if successful. null otherwise. + */ + public Color parseARGB(String argbVal){ + Color c = null; + if(argbVal != null){ + StringTokenizer st = new StringTokenizer(argbVal, "."); + if(st.countTokens() == 4){ + String aStr = st.nextToken(); + String rStr = st.nextToken(); + String gStr = st.nextToken(); + String bStr = st.nextToken(); + int a = -1, r = -1, g = -1, b = -1; + try { + a = Integer.parseInt(aStr); + r = Integer.parseInt(rStr); + g = Integer.parseInt(gStr); + b = Integer.parseInt(bStr); + }catch(NumberFormatException e){ + // If an error occured, the a, r, g, b + // values will not be in the 0-255 range + // and the next if test will fail + } + + if( a>=0 && a<=255 + && + r>=0 && r<=255 + && + g>=0 && g<=255 + && + b>=0 && b<=255 ){ + c = new Color(r,g,b,a); + } + } + } + return c; } + } + + + + /** + * Describes the command line options for the rasterizer + */ + public static String USAGE = + Messages.formatMessage("Main.usage", null); + + // + // The command line options are found in the properties + // file. + // + + /** + * Option to specify the output directory or file + */ + public static String CL_OPTION_OUTPUT + = Messages.get("Main.cl.option.output", "-d"); + + public static String CL_OPTION_OUTPUT_DESCRIPTION + = Messages.get("Main.cl.option.output.description", "No description"); + + /** + * Option to specify the output image's mime type + */ + public static String CL_OPTION_MIME_TYPE + = Messages.get("Main.cl.option.mime.type", "-m"); + + public static String CL_OPTION_MIME_TYPE_DESCRIPTION + = Messages.get("Main.cl.option.mime.type.description", "No description"); + + /** + * Option to specify the output image's width + */ + public static String CL_OPTION_WIDTH + = Messages.get("Main.cl.option.width", "-w"); - if(!Float.isNaN(height)){ - t.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, - new Float(height)); + public static String CL_OPTION_WIDTH_DESCRIPTION + = Messages.get("Main.cl.option.width.description", "No description"); + + /** + * Option to specify the output image's height + */ + public static String CL_OPTION_HEIGHT + = Messages.get("Main.cl.option.height", "-h"); + + public static String CL_OPTION_HEIGHT_DESCRIPTION + = Messages.get("Main.cl.option.height.description", "No description"); + + /** + * Option to specify the area of interest in the output + * image. + */ + public static String CL_OPTION_AOI + = Messages.get("Main.cl.option.aoi", "-a"); + + public static String CL_OPTION_AOI_DESCRIPTION + = Messages.get("Main.cl.option.aoi.description", "No description"); + + /** + * Option to specify the output image's background color + */ + public static String CL_OPTION_BACKGROUND_COLOR + = Messages.get("Main.cl.option.background.color", "-bg"); + + public static String CL_OPTION_BACKGROUND_COLOR_DESCRIPTION + = Messages.get("Main.cl.option.background.color.description", "No description"); + + /** + * Option to specify the CSS media type when converting + * the SVG image + */ + public static String CL_OPTION_MEDIA_TYPE + = Messages.get("Main.cl.option.media.type", "-cssMedia"); + + public static String CL_OPTION_MEDIA_TYPE_DESCRIPTION + = Messages.get("Main.cl.option.media.type.description", "No description"); + + /** + * Option to specify the CSS alternate stylesheet when + * converting the SVG images + */ + public static String CL_OPTION_ALTERNATE_STYLESHEET + = Messages.get("Main.cl.option.alternate.stylesheet", "-cssAlternate"); + + public static String CL_OPTION_ALTERNATE_STYLESHEET_DESCRIPTION + = Messages.get("Main.cl.option.alternate.stylesheet.description", "No description"); + + /** + * Option to specify that the converted SVG files should + * be validated during the conversion process. + */ + public static String CL_OPTION_VALIDATE + = Messages.get("Main.cl.option.validate", "-validate"); + + public static String CL_OPTION_VALIDATE_DESCRIPTION + = Messages.get("Main.cl.option.validate.description", "No description"); + + /** + * Static map containing all the option handlers able to analyze the + * various options. + */ + protected static Map optionMap = new Hashtable(); + + /** + * Static map containing all the mime types understood by the + * rasterizer + */ + protected static Map mimeTypeMap = new Hashtable(); + + /** + * Static initializer: adds all the option handlers to the + * map of option handlers. + */ + static { + mimeTypeMap.put("image/jpg", DestinationType.JPEG); + mimeTypeMap.put("image/jpeg", DestinationType.JPEG); + mimeTypeMap.put("image/jpe", DestinationType.JPEG); + mimeTypeMap.put("image/png", DestinationType.PNG); + mimeTypeMap.put("image/pdf", DestinationType.PDF); + mimeTypeMap.put("image/tiff", DestinationType.TIFF); + + optionMap.put(CL_OPTION_OUTPUT, + new SingleValueOptionHandler(){ + public void handleOption(String optionValue, + SVGConverter c){ + c.setDst(new File(optionValue)); + } + public String getOptionDescription(){ + return CL_OPTION_OUTPUT_DESCRIPTION; + } + }); + + optionMap.put(CL_OPTION_MIME_TYPE, + new SingleValueOptionHandler(){ + public void handleOption(String optionValue, + SVGConverter c){ + DestinationType dstType = + (DestinationType)mimeTypeMap.get(optionValue); + + if (dstType == null){ + throw new IllegalArgumentException(); + } + + c.setDestinationType(dstType); + } + + public String getOptionDescription(){ + return CL_OPTION_MIME_TYPE_DESCRIPTION; + } + }); + + optionMap.put(CL_OPTION_WIDTH, + new FloatOptionHandler(){ + public void handleOption(float optionValue, + SVGConverter c){ + if (optionValue <= 0){ + throw new IllegalArgumentException(); + } + + c.setWidth(optionValue); + } + + public String getOptionDescription(){ + return CL_OPTION_WIDTH_DESCRIPTION; + } + }); + + optionMap.put(CL_OPTION_HEIGHT, + new FloatOptionHandler(){ + public void handleOption(float optionValue, + SVGConverter c){ + if (optionValue <= 0){ + throw new IllegalArgumentException(); + } + + c.setHeight(optionValue); + } + + public String getOptionDescription(){ + return CL_OPTION_HEIGHT_DESCRIPTION; + } + }); + + + optionMap.put(CL_OPTION_AOI, + new RectangleOptionHandler(){ + public void handleOption(Rectangle2D optionValue, + SVGConverter c){ + c.setArea(optionValue); + } + + public String getOptionDescription(){ + return CL_OPTION_AOI_DESCRIPTION; + } + }); + + optionMap.put(CL_OPTION_BACKGROUND_COLOR, + new ColorOptionHandler(){ + public void handleOption(Color optionValue, + SVGConverter c){ + c.setBackgroundColor(optionValue); + } + + public String getOptionDescription(){ + return CL_OPTION_BACKGROUND_COLOR_DESCRIPTION; + } + }); + + optionMap.put(CL_OPTION_MEDIA_TYPE, + new SingleValueOptionHandler(){ + public void handleOption(String optionValue, + SVGConverter c){ + c.setMediaType(optionValue); + } + + public String getOptionDescription(){ + return CL_OPTION_MEDIA_TYPE; + } + }); + + optionMap.put(CL_OPTION_ALTERNATE_STYLESHEET, + new SingleValueOptionHandler(){ + public void handleOption(String optionValue, + SVGConverter c){ + c.setAlternateStylesheet(optionValue); + } + + public String getOptionDescription(){ + return CL_OPTION_ALTERNATE_STYLESHEET; + } + }); + + optionMap.put(CL_OPTION_VALIDATE, + new NoValueOptionHandler(){ + public void handleOption(SVGConverter c){ + c.setValidate(true); + } + + public String getOptionDescription(){ + return CL_OPTION_VALIDATE_DESCRIPTION; + } + }); + + } + + /** + * Vector of arguments describing the conversion task to be + * performed. + */ + protected Vector args; + + public Main(String[] args){ + this.args = new Vector(); + for (int i=0; i<args.length; i++){ + this.args.addElement(args[i]); } + } - t.addTranscodingHint(ImageTranscoder.KEY_BACKGROUND_COLOR, - background); + protected void error(String errorCode, + Object[] errorArgs){ + System.err.println(Messages.formatMessage(errorCode, + errorArgs)); + } - for (Iterator iter = svgFiles.iterator(); iter.hasNext();) { - String s = (String) iter.next(); - URL url = getSVGURL(s); - if(url != null){ - String uri = url.getFile(); - int j = uri.lastIndexOf('/'); - if(j > 0){ - uri = uri.substring(j); - } + // + // Error codes generated by the rasterizer + // - if (uri.endsWith(".svg")) { - uri = uri.substring(0, uri.lastIndexOf(".svg")); - int k = mimeType.lastIndexOf('/'); - if (k > 0) { - String ext = mimeType.substring(k+1); - if (ext.length() > 0) { - uri += "."+ext; - } - } else { - uri += "."+mimeType; - } - } - if (directory == null) { - directory = getDirectory(s); - } + /** + * Error when there are missing option values: + * {0} Option + * {1} Option description + */ + public static final String ERROR_NOT_ENOUGH_OPTION_VALUES + = "Main.error.not.enough.option.values"; - if (directory != null) { - File output = new File(directory, uri); - - writeImage((Transcoder)t, - url.toString(), - output.getAbsolutePath()); + /** + * Error when an illegal option value was passed to the app + * {0} Option + * {1} Option description + */ + public static final String ERROR_ILLEGAL_ARGUMENT + = "Main.error.illegal.argument"; + + public static final String ERROR_WHILE_CONVERTING_FILES + = "Main.error.while.converting.files"; + public void execute(){ + SVGConverter c = new SVGConverter(this); + + Vector sources = new Vector(); + + int nArgs = args.size(); + for (int i=0; i<nArgs; i++){ + String v = (String)args.elementAt(i); + OptionHandler optionHandler = (OptionHandler)optionMap.get(v); + if (optionHandler == null){ + // Assume v is a source. + sources.addElement(v); + } else { + // v is an option. Extract the optionValues required + // by the handler. + int nOptionArgs = optionHandler.getOptionValuesLength(); + if (i + nOptionArgs >= nArgs){ + error(ERROR_NOT_ENOUGH_OPTION_VALUES, new Object[]{ v, optionHandler.getOptionDescription()}); + return; + } + + String[] optionValues = new String[nOptionArgs]; + for (int j=0; j<nOptionArgs; j++){ + optionValues[j] = (String)args.elementAt(1+i+j); } - else{ - error("No valid output directory for : " + s); + i += nOptionArgs; + + try { + optionHandler.handleOption(optionValues, c); + } catch(IllegalArgumentException e){ + e.printStackTrace(); + error(ERROR_ILLEGAL_ARGUMENT, + new Object[] { v, + optionHandler.getOptionDescription() , + toString(optionValues)}); + return; } } } - System.exit(0); - } - public static URL getSVGURL(String s) { - URL url = null; + String expandedSources[] = expandSources(sources); - try{ - File f = new File(s); - if(f.exists()){ - url = f.toURL(); - } - else{ - url = new URL(s); - } - }catch(MalformedURLException e){ - error("Bad svg file: " + s); + c.setSources(expandedSources); + + validateConverterConfig(c); + + if (expandedSources== null || expandedSources.length < 1){ + System.out.println("sources.length : " + sources.size()); + System.out.println(USAGE); + return; } - return url; + try { + c.execute(); + } catch(SVGConverterException e){ + error(ERROR_WHILE_CONVERTING_FILES, + new Object[] { e.getMessage() }); + } } - public static String getDirectory(String s){ - File f = new File(s); - if(f.exists()){ - return f.getParent(); + protected String toString(String[] v){ + StringBuffer sb = new StringBuffer(); + int n = v != null ? v.length:0; + for (int i=0; i<n; i++){ + sb.append(v[i] + " "); } - else{ - return null; - } + + return sb.toString(); } /** - * Parse the input value, which should be in the following - * format: a.r.g.b where a, r, g and b are integer values, - * in decimal notation, between 0 and 255. - * @return the parsed color if successful. null otherwise. + * Template methods which subclasses may implement to do whatever is + * needed. For example, this can be used for test purposes. */ - public static Color parseARGB(String argbVal){ - Color c = null; - if(argbVal != null){ - StringTokenizer st = new StringTokenizer(argbVal, "."); - if(st.countTokens() == 4){ - String aStr = st.nextToken(); - String rStr = st.nextToken(); - String gStr = st.nextToken(); - String bStr = st.nextToken(); - int a = -1, r = -1, g = -1, b = -1; - try { - a = Integer.parseInt(aStr); - r = Integer.parseInt(rStr); - g = Integer.parseInt(gStr); - b = Integer.parseInt(bStr); - }catch(NumberFormatException e){ - // If an error occured, the a, r, g, b - // values will not be in the 0-255 range - // and the next if test will fail - } + public void validateConverterConfig(SVGConverter c){ + } - if( a>=0 && a<=255 - && - r>=0 && r<=255 - && - g>=0 && g<=255 - && - b>=0 && b<=255 ){ - c = new Color(r,g,b,a); + /** + * Scans the input vector and replaces directories with the list + * of SVG files they contain + */ + protected String[] expandSources(Vector sources){ + Vector expandedSources = new Vector(); + Iterator iter = sources.iterator(); + while (iter.hasNext()){ + String v = (String)iter.next(); + File f = new File(v); + if (f.exists() && f.isDirectory()){ + File[] fl = f.listFiles(new SVGConverter.SVGFileFilter()); + for (int i=0; i<fl.length; i++){ + expandedSources.addElement(fl[i].getPath()); } + } else { + expandedSources.addElement(v); } } - return c; + + String[] s = new String[expandedSources.size()]; + expandedSources.copyInto(s); + return s; } + public static void main(String [] args) { + (new Main(args)).execute(); + System.exit(0); + } + + // + // SVGConverterController implementation + // + public static final String MESSAGE_ABOUT_TO_TRANSCODE + = "Main.message.about.to.transcode"; + + public static final String MESSAGE_ABOUT_TO_TRANSCODE_SOURCE + = "Main.message.about.to.transcode.source"; + + public static final String MESSAGE_CONVERSION_FAILED + = "Main.message.conversion.failed"; + + public static final String MESSAGE_CONVERSION_SUCCESS + = "Main.message.conversion.success"; + + public boolean proceedWithComputedTask(Transcoder transcoder, + Map hints, + Vector sources, + Vector dest){ + System.out.println(Messages.formatMessage(MESSAGE_ABOUT_TO_TRANSCODE, + new Object[]{"" + sources.size()})); + return true; + } + + public boolean proceedWithSourceTranscoding(SVGConverterSource source, + File dest){ + System.out.print(Messages.formatMessage(MESSAGE_ABOUT_TO_TRANSCODE_SOURCE, + new Object[]{source.toString(), + dest.toString()})); + return true; + } + + public boolean proceedOnSourceTranscodingFailure(SVGConverterSource source, + File dest, + String errorCode){ + System.out.println(Messages.formatMessage(MESSAGE_CONVERSION_FAILED, + new Object[]{errorCode})); + + return true; + } + + public void onSourceTranscodingSuccess(SVGConverterSource source, + File dest){ + System.out.println(Messages.formatMessage(MESSAGE_CONVERSION_SUCCESS, + null)); + } } 1.2 +16 -1 xml-batik/sources/org/apache/batik/apps/rasterizer/Messages.java Index: Messages.java =================================================================== RCS file: /home/cvs/xml-batik/sources/org/apache/batik/apps/rasterizer/Messages.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- Messages.java 2001/10/25 13:34:24 1.1 +++ Messages.java 2001/10/29 19:13:54 1.2 @@ -17,7 +17,7 @@ * This class manages the message for the bridge module. * * @author <a href="mailto:[EMAIL PROTECTED]">Stephane Hillion</a> - * @version $Id: Messages.java,v 1.1 2001/10/25 13:34:24 vhardy Exp $ + * @version $Id: Messages.java,v 1.2 2001/10/29 19:13:54 vhardy Exp $ */ public class Messages { @@ -59,5 +59,20 @@ public static String formatMessage(String key, Object[] args) throws MissingResourceException { return localizableSupport.formatMessage(key, args); + } + + public static String get(String key) + throws MissingResourceException { + return formatMessage(key, null); + } + + public static String get(String key, String def){ + String value = def; + try{ + value = get(key); + }catch(MissingResourceException e){ + } + + return value; } } 1.3 +150 -120 xml-batik/sources/org/apache/batik/apps/rasterizer/SVGConverter.java Index: SVGConverter.java =================================================================== RCS file: /home/cvs/xml-batik/sources/org/apache/batik/apps/rasterizer/SVGConverter.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- SVGConverter.java 2001/10/26 11:36:16 1.2 +++ SVGConverter.java 2001/10/29 19:13:54 1.3 @@ -25,8 +25,8 @@ import java.io.FileNotFoundException; import java.awt.Color; -import java.awt.Rectangle; import java.awt.Graphics2D; +import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.HashMap; @@ -44,26 +44,19 @@ * The Batik Transcoder API is used to execute the conversion. FOP is * needed to be able to transcode to the PDF format<br /> * - * The source can be:<br /><ul> - * <li>A list of files or URL (set by the <tt>setSources</tt> method)</li> - * <li>A directory (set by the <tt>setSrcDir</tt> method).</li> - * </ul> + * The source has to be list of files or URL (set by the <tt>setSources</tt> + * method). <br /> * * The destination can be:<br /><ul> * <li><b>unspecified</b>. In that case, only file sources can be converted and * a file in the same directory as the source will be created.</li> - * <li><b>a directory</b>, set by the <tt>setDstDir</tt> method. In that case, + * <li><b>a directory</b>, set by the <tt>setDst</tt> method. In that case, * the output files are created in that destination directory</li> * <li><b>a file</b>. In case there is a <i>single * source</i>, the destination can be a single named file - * (set with the <tt>setDstFile</tt> method.</li>)<br /> + * (set with the <tt>setDst</tt> method.</li>)<br /> * </ul> * - * The <tt>dstDir</tt> and <tt>dstFile</tt> can be both null, in which - * case the destination is unspecified. If the <tt>dstDir</tt> and the - * <tt>dstFile</tt> are both specified, the <tt>SVGConverter</tt> will - * generate an error. <br /> - * * <hr /> * * There are a number of options which control the way the image is @@ -82,7 +75,7 @@ * <li>alternate: controls the alternate CSS stylesheet to activate, if any.</li> * </ul> * - * @version $Id: SVGConverter.java,v 1.2 2001/10/26 11:36:16 vhardy Exp $ + * @version $Id: SVGConverter.java,v 1.3 2001/10/29 19:13:54 vhardy Exp $ * @author Henri Ruini * @author <a href="mailto:[EMAIL PROTECTED]">Vincent Hardy</a> */ @@ -91,19 +84,11 @@ // Error codes reported by the SVGConverter // - // - // Reported when the srcDir property is not null and there - // are no files in the directory. - // - public static final String ERROR_NO_SVG_FILES_IN_SRC_DIR - = "SVGConverter.error.no.svg.files.in.src.dir"; - // - // Reported where the srcDir property has not been set not - // the sourcesStrings (both null). + // Reported when no source file has been specified. // - public static final String ERROR_NO_SRCDIR_OR_SRCFILE_SPECIFIED - = "SVGConverter.error.no.srcdir.or.srcfile.specified"; + public static final String ERROR_NO_SOURCES_SPECIFIED + = "SVGConverter.error.no.sources.specified"; // // Reported when there is more than one valid input source @@ -114,6 +99,13 @@ = "SVGConverter.error.cannot.compute.destination"; // + // Reported when the dst is a file and there are multiple + // sources. + // + public static final String ERROR_CANNOT_USE_DST_FILE + = "SVGConverter.error.cannot.use.dst.file"; + + // // Reported when the <tt>Transcoder</tt> for the requested // <tt>destinationType</tt> cannot be found. // @@ -196,37 +188,37 @@ = DestinationType.PNG; /** Default width */ - protected static final int DEFAULT_WIDTH = -1; + protected static final float DEFAULT_WIDTH = -1; /** Default height */ - protected static final int DEFAULT_HEIGHT = -1; + protected static final float DEFAULT_HEIGHT = -1; /** Result type */ protected DestinationType destinationType = DEFAULT_RESULT_TYPE; /** Output image height. */ - protected int height = DEFAULT_HEIGHT; + protected float height = DEFAULT_HEIGHT; /** Output image width. */ - protected int width = DEFAULT_WIDTH; + protected float width = DEFAULT_WIDTH; /** Output image quality. */ protected float quality = DEFAULT_QUALITY; /** Output AOI area. */ - protected Rectangle area = null; + protected Rectangle2D area = null; - /** Sources files or URLs */ - protected Vector sourcesStrings = null; + /** Validation flag */ + protected boolean validate = false; - /** Source directory */ - protected File srcDir = null; - - /** Destination image path. Used if there is a single source */ - protected File dstFile = null; + /** Sources files or URLs */ + protected Vector sources = null; - /** Destination directory for output images. */ - protected File dstDir = null; + /** + * Destination image path. Can be a file (for single source) or + * a directory + */ + protected File dst; /** Background color for the output images. */ protected Color backgroundColor = null; @@ -266,7 +258,7 @@ } // - // Property set methods + // Property get/set methods // /** @@ -280,24 +272,36 @@ this.destinationType = destinationType; } + public DestinationType getDestinationType(){ + return destinationType; + } + /** * In less than or equal to zero, the height is not * constrained on the output image. The height is in * user space. */ - public void setHeight(int height) { + public void setHeight(float height) { this.height = height; } + public float getHeight(){ + return height; + } + /** * In less than or equal to zero, the width is not * constrained on the output image. The width is in * user space. */ - public void setWidth(int width) { + public void setWidth(float width) { this.width = width; } + public float getWidth(){ + return width; + } + /** * Sets the JPEG encoding quality. The value should be strictly * less than 1. If the value is less than zero, then the maximum @@ -311,16 +315,24 @@ this.quality = quality; } + public float getQuality(){ + return quality; + } + /** * Sets the <tt>area</tt> as a Rectangle. This value can * be null in which case the whole image will be rendered. If the * area is not null, then only the portion of the image it * defines will be rendered. */ - public void setArea(Rectangle area){ + public void setArea(Rectangle2D area){ this.area = area; } + public Rectangle2D getArea(){ + return area; + } + /** * Sets the list of individual SVG sources. The strings * can be either URLs or file names. Note that invalid @@ -328,55 +340,38 @@ * will cause <tt>SVGConverterExceptions</tt> to be * thrown during the transcoding process (see {@link #execute}); */ - public void setSourcesStrings(String[] sourcesStrings) { - if(sourcesStrings == null){ - this.sourcesStrings = null; + public void setSources(String[] sources) { + if(sources == null){ + this.sources = null; } else{ - this.sourcesStrings = new Vector(); - for (int i=0; i<sourcesStrings.length; i++){ - if (sourcesStrings[i] != null){ - this.sourcesStrings.addElement(sourcesStrings[i]); + this.sources = new Vector(); + for (int i=0; i<sources.length; i++){ + if (sources[i] != null){ + this.sources.addElement(sources[i]); } } - if (this.sourcesStrings.size() == 0){ - this.sourcesStrings = null; + if (this.sources.size() == 0){ + this.sources = null; } } } - /** - * Set the directory from which SVG files should be converted. - */ - public void setSrcDir(File dir) { - this.srcDir = dir; + public Vector getSources(){ + return sources; } /** - * When converting a single source, this allows the user - * to specify the file where the output should be saved - * (as opposed to let the <tt>SVGConverter</tt> automatically - * create a file in the <tt>dstDir</tt> + * When converting a single source, dst can be a file. + * Othewise, it should be a directory. */ - public void setDstFile(File dstFile) { - if (dstDir != null) { - throw new IllegalArgumentException(); - } - - this.dstFile = dstFile; + public void setDst(File dst) { + this.dst = dst; } - - /** - * Sets the directory where the converted SVG files should - * be saved. - */ - public void setDstDir(File dir) { - if (dstFile != null){ - throw new IllegalArgumentException(); - } - this.dstDir = dir; + public File getDst(){ + return dst; } /** @@ -388,6 +383,10 @@ this.backgroundColor = backgroundColor; } + public Color getBackgroundColor(){ + return backgroundColor; + } + /** * Sets the <tt>mediaType</tt> value. This value controls * the CSS media for which the image should be rendered. It @@ -400,6 +399,10 @@ this.mediaType = mediaType; } + public String getMediaType(){ + return mediaType; + } + /** * Sets the <tt>alternateStyleSheet</tt> value. This value * controls the CSS alternate stylesheet to select in the @@ -409,8 +412,41 @@ public void setAlternateStylesheet(String alternateStylesheet){ this.alternateStylesheet = alternateStylesheet; } + + public String getAlternateStylesheet(){ + return alternateStylesheet; + } + + /** + * Defines whether or not input sources should be validated in + * the conversion process + */ + public void setValidate(boolean validate){ + this.validate = validate; + } + + public boolean getValidate(){ + return validate; + } /** + * Returns true if f is a File. f is found to be a file if + * it exists and is a file. If it does not exist, it is declared + * to be a file if it has the same extension as the DestinationType. + */ + protected boolean isFile(File f){ + if (f.exists()){ + return f.isFile(); + } else { + if (f.toString().toLowerCase().endsWith(destinationType.getExtension())){ + return true; + } + } + + return false; + } + + /** * Starts the conversion process. * @throws SVGConverterException thrown if parameters are not set correctly. */ @@ -420,11 +456,11 @@ // This throws an exception if there is not at least one src file. Vector sources = computeSources(); - // Compute the destination files from destFile, dstDir and sources + // Compute the destination files from dest Vector dstFiles = null; - if(sources.size() == 1 && dstFile != null){ + if(sources.size() == 1 && dst != null && isFile(dst)){ dstFiles = new Vector(); - dstFiles.addElement(dstFile); + dstFiles.addElement(dst); } else{ dstFiles = computeDstFiles(sources); @@ -463,21 +499,27 @@ } /** - * Populates a dstFiles vector with files names - * computed from the names of the files in the sources vector. + * Populates a vector with destination files names + * computed from the names of the files in the sources vector + * and the value of the dst property */ protected Vector computeDstFiles(Vector sources) throws SVGConverterException { Vector dstFiles = new Vector(); - if(dstDir != null){ + if (dst != null) { + if (dst.exists() && dst.isFile()) { + throw new SVGConverterException(ERROR_CANNOT_USE_DST_FILE); + } + // - // A destination directory has been specified. + // Either dst exist and is a directory or dst does not + // exist and we may fail later on in createOutputDir // int n = sources.size(); for(int i=0; i<n; i++){ SVGConverterSource src = (SVGConverterSource)sources.elementAt(i); // Generate output filename from input filename. - File outputName = new File(dstDir.getPath(), + File outputName = new File(dst.getPath(), getDestinationFile(src.getName())); dstFiles.addElement(outputName); @@ -510,49 +552,34 @@ /** * Populates a vector with the set of SVG files from the - * srcDir if it is not null and with the sourcesStrings (files or URLs) + * srcDir if it is not null and with the sources (files or URLs) * if any. */ protected Vector computeSources() throws SVGConverterException{ Vector sources = new Vector(); // Check that at least one source has been specified. - if (sourcesStrings == null && srcDir == null){ - throw new SVGConverterException(ERROR_NO_SRCDIR_OR_SRCFILE_SPECIFIED); + if (this.sources == null){ + throw new SVGConverterException(ERROR_NO_SOURCES_SPECIFIED); } - if (sourcesStrings != null){ - int n = sourcesStrings.size(); - for (int i=0; i<n; i++){ - String sourceString = (String)(sourcesStrings.elementAt(i)); - File file = new File(sourceString); - if (file.exists()) { - sources.addElement(new SVGConverterFileSource(file)); - } else { - String[] fileNRef = getFileNRef(sourceString); - file = new File(fileNRef[0]); - if (file.exists()){ - sources.addElement(new SVGConverterFileSource(file, fileNRef[1])); - } else{ - sources.addElement(new SVGConverterURLSource(sourceString)); - } + int n = this.sources.size(); + for (int i=0; i<n; i++){ + String sourceString = (String)(this.sources.elementAt(i)); + File file = new File(sourceString); + if (file.exists()) { + sources.addElement(new SVGConverterFileSource(file)); + } else { + String[] fileNRef = getFileNRef(sourceString); + file = new File(fileNRef[0]); + if (file.exists()){ + sources.addElement(new SVGConverterFileSource(file, fileNRef[1])); + } else{ + sources.addElement(new SVGConverterURLSource(sourceString)); } } } - if (srcDir != null){ - File[] fl = srcDir.listFiles(new SVGFileFilter()); - if (fl != null && fl.length > 0){ - for (int i=0; i<fl.length; i++){ - sources.addElement(new SVGConverterFileSource(fl[i])); - } - } - else{ - throw new SVGConverterException(ERROR_NO_SVG_FILES_IN_SRC_DIR, - new Object[]{srcDir.toString()}); - } - } - return sources; } @@ -582,8 +609,8 @@ // Set AOI. ---------------------------------------------------------- if (area != null) { // Set height and width so that image doesn't get distorted. - map.put(ImageTranscoder.KEY_HEIGHT, new Float(area.getHeight())); - map.put(ImageTranscoder.KEY_WIDTH, new Float(area.getWidth())); + map.put(ImageTranscoder.KEY_HEIGHT, new Float((float)area.getHeight())); + map.put(ImageTranscoder.KEY_WIDTH, new Float((float)area.getWidth())); map.put(ImageTranscoder.KEY_AOI, area); } @@ -619,6 +646,11 @@ map.put(ImageTranscoder.KEY_ALTERNATE_STYLESHEET, alternateStylesheet); } + // Set validation + if (validate){ + map.put(ImageTranscoder.KEY_XML_PARSER_VALIDATING, + new Boolean(validate)); + } return map; } @@ -692,7 +724,6 @@ // Transcode now boolean success = false; try { - System.out.println("About to transcoder : " + input.getURI()); transcoder.transcode(input, output); success = true; } catch(TranscoderException te) { @@ -759,7 +790,6 @@ dest = new String(oldName + newSuffix); } - System.out.println("Computed destination file: " + dest); return dest; } @@ -830,7 +860,7 @@ /** * Convenience class to filter svg files */ - class SVGFileFilter implements FileFilter { + public static class SVGFileFilter implements FileFilter { public static final String SVG_EXTENSION = ".svg"; public boolean accept(File file){ 1.2 +123 -3 xml-batik/resources/org/apache/batik/apps/rasterizer/resources/Messages.properties Index: Messages.properties =================================================================== RCS file: /home/cvs/xml-batik/resources/org/apache/batik/apps/rasterizer/resources/Messages.properties,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- Messages.properties 2001/10/25 13:31:35 1.1 +++ Messages.properties 2001/10/29 19:13:54 1.2 @@ -6,9 +6,13 @@ # the LICENSE file. # ############################################################################# -SVGConverter.error.no.svg.files.in.src.dir = \ -Error: there are no SVG files in the source directory ({0}). +SVGConverter.error.no.sources.specified = \ +Error: no source was specified. +SVGConverter.error.cannot.use.dst.file = \ +Error: cannot use destination file where there are multiple sources. \ +Should use a destination directory instead. + SVGConverter.error.no.srcdir.or.srcfile.specified = \ Error: no source directory or source file specified. @@ -57,4 +61,120 @@ The value was: {0} SVGConverter.config.xml.parser.class.name = \ -org.apache.crimson.parser.XMLReaderImpl \ No newline at end of file +org.apache.crimson.parser.XMLReaderImpl + + +Main.usage = \ +SVG Rasterizer options are: \n \ + -d <dir|file> \n \ +\toutput directory. If there is a single input file, this can be a file. \n \ + -m <mimeType> \n \ +\toutput mime type. \n \ + -w <width> \n \ +\toutput width. This is a floating point value. \n \ + -h <height> \n \ +\toutput height. This is a floating point value. \n \ + -a <area> \n \ +\toutput area. The format for <area> is x,y,w,h, where x, y, w and h \n \ +\tare floating point values. \n \ + -bg <color> \n \ +\touput color. The format for <color> is a.r.g.b, where a, r, g and b \n \ +\tare integer values. \n \ + -cssMedia <media> \n \ +\tCSS media type for which the source SVG files should be \n \ +\tconverted.\n \ + -cssAlternate <alternate> \n \ +\tCSS alternate stylesheet to use when converting the source \n \ +\tSVG files. \n \ + -validate \n \ +\tontrols whether the source SVG files should be validated. \n + + +Main.cl.option.output.description = \ +-d <dir|file> output directory. If there is a single input file, this can be a file. \n \ + Otherwise, it has to be a directory. \n \ + If no -d option is specified, then the output files are created in \n \ + the same directory (or directories) as the sources. \n \ +Example: -d rasters/png \n \ +Default: none + +Main.cl.option.mime.type.description = \ +-m <mimeType> output mime type. This should be one of: \n \ + + image/jpg \n \ + + image/jpeg \n \ + + image/jpe \n \ + + image/png \n \ + + image/pdf \n \ + + image/tiff \n \n \ +Example: -m image/jpeg \n \ +Default: image/png + +Main.cl.option.width.description = \ +-w <width> Output width. This is a floating point value. \n +Example: -w 455.6 \n \ +Default: none (which means that the images's width will be used) + +Main.cl.option.height.description = \ +-h <height> Output height. This is a floating point value. \n +Example: -h 345.67 \n \ +Default: none (which means that the image's height will be used) + +Main.cl.option.area.description = \ +-a <area> output area. The format for <area> is x,y,w,h, where x, y, w and h are \n \ + floating point values. \n \ +Example: -a 40,40,300,200 \n \ +Default: none (which means that the entire image will be rendered). + +Mail.cl.option.bg.description = \ +-bg <color> ouput color. The format for <color> is a.r.g.b, where a, r, g and b \n \ + are integer values. \n \ +Example: -bg 128.255.0.0 \n \ +Default: none (which means that the background is not filled with any color \n \ + before rendering the SVG file). \n \ + +Main.cl.option.cssMedia.description = \ +-cssMedia <media> CSS media type for which the source SVG files should be \n \ + converted.\n \ +Example: -cssMedia projection \n \ +Default: none (which means that the "screen" media will be used. + +Main.cl.option.cssAlternate.description = \ +-cssAlternate <alternate> CSS alternate stylesheet to use when converting the source \n \ + SVG files. \n \ +Example: -cssAlternate myFavoriteStylesheet \n \ +Default: none + +Main.cl.option.validate.description = \ +-validate controls whether the source SVG files should be validated. + +# +# Main error codes +# + +Main.error.not.enough.option.values = \ +Error: not enough option values for option {0} \n \ +{1} + +Main.error.illegal.argument = \ +Error: illegal argument for option {0} : {2} \n \ +{1} + +Main.error.while.converting.files = \ +Error while converting files: \n \ +{0} + + +# +# Main messages +# +Main.message.about.to.transcode = \ +About to transcode {0} SVG file(s)\n + +Main.message.about.to.transcode.source = \ +Converting {0} to {1} ... + +Main.message.conversion.failed = \ +... error ({0}) + +Main.message.conversion.success = \ +... success
--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]