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

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