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.

FopConfParser.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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.FileInputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.net.URI;
  24. import java.net.URISyntaxException;
  25. import java.util.HashMap;
  26. import java.util.Map;
  27. import org.xml.sax.SAXException;
  28. import org.apache.avalon.framework.configuration.Configuration;
  29. import org.apache.avalon.framework.configuration.ConfigurationException;
  30. import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
  31. import org.apache.commons.logging.Log;
  32. import org.apache.commons.logging.LogFactory;
  33. import org.apache.xmlgraphics.image.loader.spi.ImageImplRegistry;
  34. import org.apache.xmlgraphics.image.loader.util.Penalty;
  35. import org.apache.fop.apps.io.ResourceResolver;
  36. import org.apache.fop.apps.io.ResourceResolverFactory;
  37. import org.apache.fop.apps.io.InternalResourceResolver;
  38. import org.apache.fop.fonts.FontManagerConfigurator;
  39. import org.apache.fop.hyphenation.HyphenationTreeCache;
  40. import org.apache.fop.util.LogUtil;
  41. /**
  42. * Parses the FOP configuration file and returns a {@link FopFactoryBuilder} which builds a
  43. * {@link FopFactory}.
  44. */
  45. public class FopConfParser {
  46. private static final String PREFER_RENDERER = "prefer-renderer";
  47. private final Log log = LogFactory.getLog(FopConfParser.class);
  48. private final FopFactoryBuilder fopFactoryBuilder;
  49. /**
  50. * Constructor that takes the FOP conf in the form of an {@link InputStream}. A default base URI
  51. * must be given as a fall-back mechanism for URI resolution.
  52. *
  53. * @param fopConfStream the fop conf input stream
  54. * @param enviro the profile of the FOP deployment environment
  55. * @throws SAXException if a SAX error was thrown parsing the FOP conf
  56. * @throws IOException if an I/O error is thrown while parsing the FOP conf
  57. */
  58. public FopConfParser(InputStream fopConfStream, EnvironmentProfile enviro)
  59. throws SAXException, IOException {
  60. DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
  61. Configuration cfg;
  62. try {
  63. cfg = cfgBuilder.build(fopConfStream);
  64. } catch (ConfigurationException e) {
  65. throw new FOPException(e);
  66. }
  67. // The default base URI is taken from the directory in which the fopConf resides
  68. fopFactoryBuilder = new FopFactoryBuilder(enviro).setConfiguration(cfg);
  69. configure(enviro.getDefaultBaseURI(), enviro.getResourceResolver(), cfg);
  70. }
  71. /**
  72. * Constructor that takes the FOP conf in the form of an {@link InputStream}. A default base URI
  73. * must be given as a fall-back mechanism for URI resolution.
  74. *
  75. * @param fopConfStream the fop conf input stream
  76. * @param defaultBaseURI the default base URI
  77. * @param resourceResolver the URI resolver
  78. * @throws SAXException if a SAX error was thrown parsing the FOP conf
  79. * @throws IOException if an I/O error is thrown while parsing the FOP conf
  80. */
  81. public FopConfParser(InputStream fopConfStream, URI defaultBaseURI,
  82. ResourceResolver resourceResolver) throws SAXException, IOException {
  83. this(fopConfStream, EnvironmentalProfileFactory.createDefault(defaultBaseURI, resourceResolver));
  84. }
  85. /**
  86. * Constructor that takes the FOP conf in the form of an {@link InputStream}. A default base URI
  87. * must be given as a fall-back mechanism for URI resolution. The default URI resolvers is used.
  88. *
  89. * @param fopConfStream the fop conf input stream
  90. * @param defaultBaseURI the default base URI
  91. * @throws SAXException if a SAX error was thrown parsing the FOP conf
  92. * @throws IOException if an I/O error is thrown while parsing the FOP conf
  93. */
  94. public FopConfParser(InputStream fopConfStream, URI defaultBaseURI) throws SAXException,
  95. IOException {
  96. this(fopConfStream, defaultBaseURI, ResourceResolverFactory.createDefaultResourceResolver());
  97. }
  98. /**
  99. * Constructor that takes the FOP conf and uses the default URI resolver.
  100. *
  101. * @param fopConfFile the FOP conf file
  102. * @throws SAXException if a SAX error was thrown parsing the FOP conf
  103. * @throws IOException if an I/O error is thrown while parsing the FOP conf
  104. */
  105. public FopConfParser(File fopConfFile) throws SAXException, IOException {
  106. this(fopConfFile, ResourceResolverFactory.createDefaultResourceResolver());
  107. }
  108. /**
  109. * Constructor that parses the FOP conf and uses the URI resolver given.
  110. *
  111. * @param fopConfFile the FOP conf file
  112. * @param resourceResolver the URI resolver
  113. * @throws SAXException if a SAX error was thrown parsing the FOP conf
  114. * @throws IOException if an I/O error is thrown while parsing the FOP conf
  115. */
  116. public FopConfParser(File fopConfFile, ResourceResolver resourceResolver)
  117. throws SAXException, IOException {
  118. this(new FileInputStream(fopConfFile),
  119. fopConfFile.getAbsoluteFile().getParentFile().toURI(), resourceResolver);
  120. }
  121. private void configure(final URI defaultBaseURI, final ResourceResolver resourceResolver,
  122. Configuration cfg) throws FOPException {
  123. if (log.isDebugEnabled()) {
  124. log.debug("Initializing FopFactory Configuration");
  125. }
  126. // TODO: This makes this variable both strict FO and user-config validation, is that right?
  127. boolean strict = false;
  128. // strict fo validation
  129. if (cfg.getChild("strict-validation", false) != null) {
  130. try {
  131. strict = cfg.getChild("strict-validation").getValueAsBoolean();
  132. fopFactoryBuilder.setStrictUserConfigValidation(strict);
  133. } catch (ConfigurationException e) {
  134. LogUtil.handleException(log, e, false);
  135. }
  136. }
  137. if (cfg.getChild("accessibility", false) != null) {
  138. try {
  139. fopFactoryBuilder.setAccessibility(cfg.getChild("accessibility").getValueAsBoolean());
  140. } catch (ConfigurationException e) {
  141. LogUtil.handleException(log, e, false);
  142. }
  143. }
  144. // base definitions for relative path resolution
  145. if (cfg.getChild("base", false) != null) {
  146. try {
  147. URI confUri = InternalResourceResolver.getBaseURI(cfg.getChild("base").getValue(null));
  148. fopFactoryBuilder.setBaseURI(defaultBaseURI.resolve(confUri));
  149. } catch (URISyntaxException use) {
  150. LogUtil.handleException(log, use, strict);
  151. }
  152. }
  153. // renderer options
  154. if (cfg.getChild("source-resolution", false) != null) {
  155. float srcRes = cfg.getChild("source-resolution").getValueAsFloat(
  156. FopFactoryConfig.DEFAULT_SOURCE_RESOLUTION);
  157. fopFactoryBuilder.setSourceResolution(srcRes);
  158. if (log.isDebugEnabled()) {
  159. log.debug("source-resolution set to: " + srcRes + "dpi");
  160. }
  161. }
  162. if (cfg.getChild("target-resolution", false) != null) {
  163. float targetRes = cfg.getChild("target-resolution").getValueAsFloat(
  164. FopFactoryConfig.DEFAULT_TARGET_RESOLUTION);
  165. fopFactoryBuilder.setTargetResolution(targetRes);
  166. if (log.isDebugEnabled()) {
  167. log.debug("target-resolution set to: " + targetRes + "dpi");
  168. }
  169. }
  170. if (cfg.getChild("break-indent-inheritance", false) != null) {
  171. try {
  172. fopFactoryBuilder.setBreakIndentInheritanceOnReferenceAreaBoundary(
  173. cfg.getChild("break-indent-inheritance").getValueAsBoolean());
  174. } catch (ConfigurationException e) {
  175. LogUtil.handleException(log, e, strict);
  176. }
  177. }
  178. Configuration pageConfig = cfg.getChild("default-page-settings");
  179. if (pageConfig.getAttribute("height", null) != null) {
  180. String pageHeight = pageConfig.getAttribute("height",
  181. FopFactoryConfig.DEFAULT_PAGE_HEIGHT);
  182. fopFactoryBuilder.setPageHeight(pageHeight);
  183. if (log.isInfoEnabled()) {
  184. log.info("Default page-height set to: " + pageHeight);
  185. }
  186. }
  187. if (pageConfig.getAttribute("width", null) != null) {
  188. String pageWidth = pageConfig.getAttribute("width",
  189. FopFactoryConfig.DEFAULT_PAGE_WIDTH);
  190. fopFactoryBuilder.setPageWidth(pageWidth);
  191. if (log.isInfoEnabled()) {
  192. log.info("Default page-width set to: " + pageWidth);
  193. }
  194. }
  195. if (cfg.getChild("complex-scripts") != null) {
  196. Configuration csConfig = cfg.getChild("complex-scripts");
  197. fopFactoryBuilder.setComplexScriptFeatures(!csConfig.getAttributeAsBoolean("disabled",
  198. false));
  199. }
  200. setHyphPatNames(cfg, fopFactoryBuilder, strict);
  201. // prefer Renderer over IFDocumentHandler
  202. if (cfg.getChild(PREFER_RENDERER, false) != null) {
  203. try {
  204. fopFactoryBuilder.setPreferRenderer(
  205. cfg.getChild(PREFER_RENDERER).getValueAsBoolean());
  206. } catch (ConfigurationException e) {
  207. LogUtil.handleException(log, e, strict);
  208. }
  209. }
  210. // configure font manager
  211. new FontManagerConfigurator(cfg, fopFactoryBuilder.getBaseUri(), resourceResolver).configure(
  212. fopFactoryBuilder.getFontManager(), strict);
  213. // configure image loader framework
  214. configureImageLoading(cfg.getChild("image-loading", false), strict);
  215. }
  216. private void setHyphPatNames(Configuration cfg, FopFactoryBuilder builder, boolean strict)
  217. throws FOPException {
  218. Configuration[] hyphPatConfig = cfg.getChildren("hyphenation-pattern");
  219. if (hyphPatConfig.length != 0) {
  220. Map<String, String> hyphPatNames = new HashMap<String, String>();
  221. for (int i = 0; i < hyphPatConfig.length; ++i) {
  222. String lang;
  223. String country;
  224. String filename;
  225. StringBuffer error = new StringBuffer();
  226. String location = hyphPatConfig[i].getLocation();
  227. lang = hyphPatConfig[i].getAttribute("lang", null);
  228. if (lang == null) {
  229. addError("The lang attribute of a hyphenation-pattern configuration"
  230. + " element must exist (" + location + ")", error);
  231. } else if (!lang.matches("[a-zA-Z]{2}")) {
  232. addError("The lang attribute of a hyphenation-pattern configuration"
  233. + " element must consist of exactly two letters ("
  234. + location + ")", error);
  235. }
  236. lang = lang.toLowerCase();
  237. country = hyphPatConfig[i].getAttribute("country", null);
  238. if ("".equals(country)) {
  239. country = null;
  240. }
  241. if (country != null) {
  242. if (!country.matches("[a-zA-Z]{2}")) {
  243. addError("The country attribute of a hyphenation-pattern configuration"
  244. + " element must consist of exactly two letters ("
  245. + location + ")", error);
  246. }
  247. country = country.toUpperCase();
  248. }
  249. filename = hyphPatConfig[i].getValue(null);
  250. if (filename == null) {
  251. addError("The value of a hyphenation-pattern configuration"
  252. + " element may not be empty (" + location + ")", error);
  253. }
  254. if (error.length() != 0) {
  255. LogUtil.handleError(log, error.toString(), strict);
  256. continue;
  257. }
  258. String llccKey = HyphenationTreeCache.constructLlccKey(lang, country);
  259. hyphPatNames.put(llccKey, filename);
  260. if (log.isDebugEnabled()) {
  261. log.debug("Using hyphenation pattern filename " + filename
  262. + " for lang=\"" + lang + "\""
  263. + (country != null ? ", country=\"" + country + "\"" : ""));
  264. }
  265. }
  266. builder.setHyphPatNames(hyphPatNames);
  267. }
  268. }
  269. private static void addError(String message, StringBuffer error) {
  270. if (error.length() != 0) {
  271. error.append(". ");
  272. }
  273. error.append(message);
  274. }
  275. private void configureImageLoading(Configuration parent, boolean strict) throws FOPException {
  276. if (parent == null) {
  277. return;
  278. }
  279. ImageImplRegistry registry = fopFactoryBuilder.getImageManager().getRegistry();
  280. Configuration[] penalties = parent.getChildren("penalty");
  281. try {
  282. for (int i = 0, c = penalties.length; i < c; i++) {
  283. Configuration penaltyCfg = penalties[i];
  284. String className = penaltyCfg.getAttribute("class");
  285. String value = penaltyCfg.getAttribute("value");
  286. Penalty p = null;
  287. if (value.toUpperCase().startsWith("INF")) {
  288. p = Penalty.INFINITE_PENALTY;
  289. } else {
  290. try {
  291. p = Penalty.toPenalty(Integer.parseInt(value));
  292. } catch (NumberFormatException nfe) {
  293. LogUtil.handleException(log, nfe, strict);
  294. }
  295. }
  296. if (p != null) {
  297. registry.setAdditionalPenalty(className, p);
  298. }
  299. }
  300. } catch (ConfigurationException e) {
  301. LogUtil.handleException(log, e, strict);
  302. }
  303. }
  304. /**
  305. * Returns the {@link FopFactoryBuilder}.
  306. *
  307. * @return the object for configuring the {@link FopFactory}
  308. */
  309. public FopFactoryBuilder getFopFactoryBuilder() {
  310. return fopFactoryBuilder;
  311. }
  312. }