You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FopFactoryConfigurator.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. 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. /* $Id$ */
  18. package org.apache.fop.apps;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.net.MalformedURLException;
  22. import java.net.URI;
  23. import java.net.URISyntaxException;
  24. import java.util.HashMap;
  25. import java.util.Map;
  26. import org.xml.sax.SAXException;
  27. import org.apache.avalon.framework.configuration.Configuration;
  28. import org.apache.avalon.framework.configuration.ConfigurationException;
  29. import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
  30. import org.apache.commons.logging.Log;
  31. import org.apache.commons.logging.LogFactory;
  32. import org.apache.xmlgraphics.image.GraphicsConstants;
  33. import org.apache.xmlgraphics.image.loader.spi.ImageImplRegistry;
  34. import org.apache.xmlgraphics.image.loader.util.Penalty;
  35. import org.apache.fop.fonts.FontManagerConfigurator;
  36. import org.apache.fop.hyphenation.HyphenationTreeCache;
  37. import org.apache.fop.util.LogUtil;
  38. /**
  39. * FopFactory configurator
  40. */
  41. public class FopFactoryConfigurator {
  42. /** Defines if FOP should use an alternative rule to determine text indents */
  43. public static final boolean DEFAULT_BREAK_INDENT_INHERITANCE = false;
  44. /** Defines if FOP should validate the user config strictly */
  45. public static final boolean DEFAULT_STRICT_USERCONFIG_VALIDATION = true;
  46. /** Defines if FOP should use strict validation for FO and user config */
  47. public static final boolean DEFAULT_STRICT_FO_VALIDATION = true;
  48. /** Defines the default page-width */
  49. public static final String DEFAULT_PAGE_WIDTH = "8.26in";
  50. /** Defines the default page-height */
  51. public static final String DEFAULT_PAGE_HEIGHT = "11in";
  52. /** Defines the default source resolution (72dpi) for FOP */
  53. public static final float DEFAULT_SOURCE_RESOLUTION = GraphicsConstants.DEFAULT_DPI; //dpi
  54. /** Defines the default target resolution (72dpi) for FOP */
  55. public static final float DEFAULT_TARGET_RESOLUTION = GraphicsConstants.DEFAULT_DPI; //dpi
  56. /** Defines the default complex script support */
  57. public static final boolean DEFAULT_COMPLEX_SCRIPT_FEATURES = true;
  58. private static final String PREFER_RENDERER = "prefer-renderer";
  59. /** logger instance */
  60. private final Log log = LogFactory.getLog(FopFactoryConfigurator.class);
  61. /** Fop factory */
  62. private FopFactory factory = null;
  63. /** Fop factory configuration */
  64. private Configuration cfg = null;
  65. /** The base URI of the configuration file **/
  66. private URI baseURI = null;
  67. /**
  68. * Default constructor
  69. * @param factory fop factory
  70. */
  71. public FopFactoryConfigurator(FopFactory factory) {
  72. super();
  73. this.factory = factory;
  74. }
  75. /**
  76. * Initializes user agent settings from the user configuration
  77. * file, if present: baseURL, resolution, default page size,...
  78. * @param factory fop factory
  79. * @throws FOPException fop exception
  80. */
  81. public void configure(FopFactory factory) throws FOPException { // CSOK: MethodLength
  82. // strict configuration
  83. if (cfg.getChild("strict-configuration", false) != null) {
  84. try {
  85. factory.setStrictUserConfigValidation(
  86. cfg.getChild("strict-configuration").getValueAsBoolean());
  87. } catch (ConfigurationException e) {
  88. LogUtil.handleException(log, e, false);
  89. }
  90. }
  91. boolean strict = factory.validateUserConfigStrictly();
  92. if (log.isDebugEnabled()) {
  93. log.debug("Initializing FopFactory Configuration"
  94. + "with " + (strict ? "strict" : "permissive") + " validation");
  95. }
  96. if (cfg.getChild("accessibility", false) != null) {
  97. try {
  98. this.factory.setAccessibility(
  99. cfg.getChild("accessibility").getValueAsBoolean());
  100. } catch (ConfigurationException e) {
  101. LogUtil.handleException(log, e, strict);
  102. }
  103. }
  104. // strict fo validation
  105. if (cfg.getChild("strict-validation", false) != null) {
  106. try {
  107. factory.setStrictValidation(
  108. cfg.getChild("strict-validation").getValueAsBoolean());
  109. } catch (ConfigurationException e) {
  110. LogUtil.handleException(log, e, strict);
  111. }
  112. }
  113. // base definitions for relative path resolution
  114. if (cfg.getChild("base", false) != null) {
  115. String path = cfg.getChild("base").getValue(null);
  116. if (baseURI != null) {
  117. path = baseURI.resolve(path).normalize().toString();
  118. }
  119. try {
  120. factory.setBaseURL(path);
  121. } catch (MalformedURLException mfue) {
  122. LogUtil.handleException(log, mfue, strict);
  123. }
  124. }
  125. if (cfg.getChild("hyphenation-base", false) != null) {
  126. String path = cfg.getChild("hyphenation-base").getValue(null);
  127. if (baseURI != null) {
  128. path = baseURI.resolve(path).normalize().toString();
  129. }
  130. try {
  131. factory.setHyphenBaseURL(path);
  132. } catch (MalformedURLException mfue) {
  133. LogUtil.handleException(log, mfue, strict);
  134. }
  135. }
  136. /**
  137. * Read configuration elements hyphenation-pattern,
  138. * construct a map ll_CC => filename, and set it on the factory
  139. */
  140. Configuration[] hyphPatConfig = cfg.getChildren("hyphenation-pattern");
  141. if (hyphPatConfig.length != 0) {
  142. Map/*<String,String>*/ hyphPatNames = new HashMap/*<String,String>*/();
  143. for (int i = 0; i < hyphPatConfig.length; ++i) {
  144. String lang;
  145. String country;
  146. String filename;
  147. StringBuffer error = new StringBuffer();
  148. String location = hyphPatConfig[i].getLocation();
  149. lang = hyphPatConfig[i].getAttribute("lang", null);
  150. if (lang == null) {
  151. addError("The lang attribute of a hyphenation-pattern configuration"
  152. + " element must exist (" + location + ")", error);
  153. } else if (!lang.matches("[a-zA-Z]{2}")) {
  154. addError("The lang attribute of a hyphenation-pattern configuration"
  155. + " element must consist of exactly two letters ("
  156. + location + ")", error);
  157. }
  158. lang = lang.toLowerCase();
  159. country = hyphPatConfig[i].getAttribute("country", null);
  160. if ("".equals(country)) {
  161. country = null;
  162. }
  163. if (country != null) {
  164. if (!country.matches("[a-zA-Z]{2}")) {
  165. addError("The country attribute of a hyphenation-pattern configuration"
  166. + " element must consist of exactly two letters ("
  167. + location + ")", error);
  168. }
  169. country = country.toUpperCase();
  170. }
  171. filename = hyphPatConfig[i].getValue(null);
  172. if (filename == null) {
  173. addError("The value of a hyphenation-pattern configuration"
  174. + " element may not be empty (" + location + ")", error);
  175. }
  176. if (error.length() != 0) {
  177. LogUtil.handleError(log, error.toString(), strict);
  178. continue;
  179. }
  180. String llccKey = HyphenationTreeCache.constructLlccKey(lang, country);
  181. hyphPatNames.put(llccKey, filename);
  182. if (log.isDebugEnabled()) {
  183. log.debug("Using hyphenation pattern filename " + filename
  184. + " for lang=\"" + lang + "\""
  185. + (country != null ? ", country=\"" + country + "\"" : ""));
  186. }
  187. }
  188. factory.setHyphPatNames(hyphPatNames);
  189. }
  190. // renderer options
  191. if (cfg.getChild("source-resolution", false) != null) {
  192. factory.setSourceResolution(
  193. cfg.getChild("source-resolution").getValueAsFloat(
  194. FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION));
  195. if (log.isDebugEnabled()) {
  196. log.debug("source-resolution set to: " + factory.getSourceResolution()
  197. + "dpi (px2mm=" + factory.getSourcePixelUnitToMillimeter() + ")");
  198. }
  199. }
  200. if (cfg.getChild("target-resolution", false) != null) {
  201. factory.setTargetResolution(
  202. cfg.getChild("target-resolution").getValueAsFloat(
  203. FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION));
  204. if (log.isDebugEnabled()) {
  205. log.debug("target-resolution set to: " + factory.getTargetResolution()
  206. + "dpi (px2mm=" + factory.getTargetPixelUnitToMillimeter()
  207. + ")");
  208. }
  209. }
  210. if (cfg.getChild("break-indent-inheritance", false) != null) {
  211. try {
  212. factory.setBreakIndentInheritanceOnReferenceAreaBoundary(
  213. cfg.getChild("break-indent-inheritance").getValueAsBoolean());
  214. } catch (ConfigurationException e) {
  215. LogUtil.handleException(log, e, strict);
  216. }
  217. }
  218. Configuration pageConfig = cfg.getChild("default-page-settings");
  219. if (pageConfig.getAttribute("height", null) != null) {
  220. factory.setPageHeight(
  221. pageConfig.getAttribute("height", FopFactoryConfigurator.DEFAULT_PAGE_HEIGHT));
  222. if (log.isInfoEnabled()) {
  223. log.info("Default page-height set to: " + factory.getPageHeight());
  224. }
  225. }
  226. if (pageConfig.getAttribute("width", null) != null) {
  227. factory.setPageWidth(
  228. pageConfig.getAttribute("width", FopFactoryConfigurator.DEFAULT_PAGE_WIDTH));
  229. if (log.isInfoEnabled()) {
  230. log.info("Default page-width set to: " + factory.getPageWidth());
  231. }
  232. }
  233. // prefer Renderer over IFDocumentHandler
  234. if (cfg.getChild(PREFER_RENDERER, false) != null) {
  235. try {
  236. factory.getRendererFactory().setRendererPreferred(
  237. cfg.getChild(PREFER_RENDERER).getValueAsBoolean());
  238. } catch (ConfigurationException e) {
  239. LogUtil.handleException(log, e, strict);
  240. }
  241. }
  242. // configure complex script support
  243. Configuration csConfig = cfg.getChild("complex-scripts");
  244. if (csConfig != null) {
  245. this.factory.setComplexScriptFeaturesEnabled
  246. (!csConfig.getAttributeAsBoolean ( "disabled", false ));
  247. }
  248. // configure font manager
  249. new FontManagerConfigurator(cfg, baseURI).configure(factory.getFontManager(), strict);
  250. // configure image loader framework
  251. configureImageLoading(cfg.getChild("image-loading", false), strict);
  252. }
  253. private static void addError(String message, StringBuffer error) {
  254. if (error.length() != 0) {
  255. error.append(". ");
  256. }
  257. error.append(message);
  258. }
  259. private void configureImageLoading(Configuration parent, boolean strict) throws FOPException {
  260. if (parent == null) {
  261. return;
  262. }
  263. ImageImplRegistry registry = factory.getImageManager().getRegistry();
  264. Configuration[] penalties = parent.getChildren("penalty");
  265. try {
  266. for (int i = 0, c = penalties.length; i < c; i++) {
  267. Configuration penaltyCfg = penalties[i];
  268. String className = penaltyCfg.getAttribute("class");
  269. String value = penaltyCfg.getAttribute("value");
  270. Penalty p = null;
  271. if (value.toUpperCase().startsWith("INF")) {
  272. p = Penalty.INFINITE_PENALTY;
  273. } else {
  274. try {
  275. p = Penalty.toPenalty(Integer.parseInt(value));
  276. } catch (NumberFormatException nfe) {
  277. LogUtil.handleException(log, nfe, strict);
  278. }
  279. }
  280. if (p != null) {
  281. registry.setAdditionalPenalty(className, p);
  282. }
  283. }
  284. } catch (ConfigurationException e) {
  285. LogUtil.handleException(log, e, strict);
  286. }
  287. }
  288. /**
  289. * Set the user configuration.
  290. * @param userConfigFile the configuration file
  291. * @throws IOException if an I/O error occurs
  292. * @throws SAXException if a parsing error occurs
  293. */
  294. public void setUserConfig(File userConfigFile) throws SAXException, IOException {
  295. try {
  296. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  297. setUserConfig(cfgBuilder.buildFromFile(userConfigFile));
  298. } catch (ConfigurationException e) {
  299. throw new FOPException(e);
  300. }
  301. }
  302. /**
  303. * Set the user configuration from an URI.
  304. * @param uri the URI to the configuration file
  305. * @throws IOException if an I/O error occurs
  306. * @throws SAXException if a parsing error occurs
  307. */
  308. public void setUserConfig(String uri) throws SAXException, IOException {
  309. try {
  310. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  311. setUserConfig(cfgBuilder.build(uri));
  312. } catch (ConfigurationException e) {
  313. throw new FOPException(e);
  314. }
  315. }
  316. /**
  317. * Set the user configuration.
  318. * @param cfg avalon configuration
  319. * @throws FOPException if a configuration problem occurs
  320. */
  321. public void setUserConfig(Configuration cfg) throws FOPException {
  322. this.cfg = cfg;
  323. setBaseURI();
  324. configure(this.factory);
  325. }
  326. /**
  327. * Get the avalon user configuration.
  328. * @return the user configuration
  329. */
  330. public Configuration getUserConfig() {
  331. return this.cfg;
  332. }
  333. /**
  334. * @return the baseURI
  335. */
  336. public URI getBaseURI() {
  337. return baseURI;
  338. }
  339. /**
  340. * @param baseURI the baseURI to set
  341. */
  342. public void setBaseURI(URI baseURI) {
  343. this.baseURI = baseURI;
  344. }
  345. private void setBaseURI() throws FOPException {
  346. String loc = cfg.getLocation();
  347. try {
  348. if (loc != null && loc.startsWith("file:")) {
  349. baseURI = new URI(loc);
  350. baseURI = baseURI.resolve(".").normalize();
  351. }
  352. if (baseURI == null) {
  353. baseURI = new File(System.getProperty("user.dir")).toURI();
  354. }
  355. } catch (URISyntaxException e) {
  356. throw new FOPException(e);
  357. }
  358. }
  359. }