Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

FopConfParser.java 15KB

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