Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

AFPResourceManager.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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.afp;
  19. import java.io.BufferedInputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.net.URI;
  24. import java.net.URISyntaxException;
  25. import java.util.Map;
  26. import org.apache.commons.io.IOUtils;
  27. import org.apache.commons.logging.Log;
  28. import org.apache.commons.logging.LogFactory;
  29. import org.apache.fop.afp.fonts.AFPFont;
  30. import org.apache.fop.afp.fonts.CharacterSet;
  31. import org.apache.fop.afp.modca.AbstractNamedAFPObject;
  32. import org.apache.fop.afp.modca.AbstractPageObject;
  33. import org.apache.fop.afp.modca.IncludeObject;
  34. import org.apache.fop.afp.modca.IncludedResourceObject;
  35. import org.apache.fop.afp.modca.PageSegment;
  36. import org.apache.fop.afp.modca.Registry;
  37. import org.apache.fop.afp.modca.ResourceGroup;
  38. import org.apache.fop.afp.modca.ResourceObject;
  39. import org.apache.fop.afp.util.AFPResourceUtil;
  40. import org.apache.fop.afp.util.ResourceAccessor;
  41. /**
  42. * Manages the creation and storage of document resources
  43. */
  44. public class AFPResourceManager {
  45. /** logging instance */
  46. private static Log log = LogFactory.getLog(AFPResourceManager.class);
  47. /** The AFP datastream (document tree) */
  48. private DataStream dataStream;
  49. /** Resource creation factory */
  50. private final Factory factory;
  51. private final AFPStreamer streamer;
  52. private final AFPDataObjectFactory dataObjectFactory;
  53. /** Maintain a reference count of instream objects for referencing purposes */
  54. private int instreamObjectCount = 0;
  55. /** a mapping of resourceInfo --> include name */
  56. private final Map<AFPResourceInfo, String> includeNameMap
  57. = new java.util.HashMap<AFPResourceInfo, String>();
  58. /** a mapping of resourceInfo --> page segment name */
  59. private Map<AFPResourceInfo, String> pageSegmentMap
  60. = new java.util.HashMap<AFPResourceInfo, String>();
  61. private AFPResourceLevelDefaults resourceLevelDefaults = new AFPResourceLevelDefaults();
  62. /**
  63. * Main constructor
  64. */
  65. public AFPResourceManager() {
  66. this.factory = new Factory();
  67. this.streamer = new AFPStreamer(factory);
  68. this.dataObjectFactory = new AFPDataObjectFactory(factory);
  69. }
  70. /**
  71. * Sets the outputstream
  72. *
  73. * @param paintingState the AFP painting state
  74. * @param outputStream the outputstream
  75. * @return a new AFP DataStream
  76. * @throws IOException thrown if an I/O exception of some sort has occurred
  77. */
  78. public DataStream createDataStream(AFPPaintingState paintingState, OutputStream outputStream)
  79. throws IOException {
  80. this.dataStream = streamer.createDataStream(paintingState);
  81. streamer.setOutputStream(outputStream);
  82. return this.dataStream;
  83. }
  84. /**
  85. * Returns the AFP DataStream
  86. *
  87. * @return the AFP DataStream
  88. */
  89. public DataStream getDataStream() {
  90. return this.dataStream;
  91. }
  92. /**
  93. * Tells the streamer to write
  94. *
  95. * @throws IOException thrown if an I/O exception of some sort has occurred.
  96. */
  97. public void writeToStream() throws IOException {
  98. streamer.close();
  99. }
  100. /**
  101. * Sets the default resource group file path
  102. *
  103. * @param filePath the default resource group file path
  104. */
  105. public void setDefaultResourceGroupFilePath(String filePath) {
  106. streamer.setDefaultResourceGroupFilePath(filePath);
  107. }
  108. /**
  109. * Tries to create an include of a data object that has been previously added to the
  110. * AFP data stream. If no such object was available, the method returns false which serves
  111. * as a signal that the object has to be created.
  112. * @param dataObjectInfo the data object info
  113. * @return true if the inclusion succeeded, false if the object was not available
  114. * @throws IOException thrown if an I/O exception of some sort has occurred.
  115. */
  116. public boolean tryIncludeObject(AFPDataObjectInfo dataObjectInfo) throws IOException {
  117. AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo();
  118. updateResourceInfoUri(resourceInfo);
  119. String objectName = includeNameMap.get(resourceInfo);
  120. if (objectName != null) {
  121. // an existing data resource so reference it by adding an include to the current page
  122. includeObject(dataObjectInfo, objectName);
  123. return true;
  124. }
  125. objectName = pageSegmentMap.get(resourceInfo);
  126. if (objectName != null) {
  127. // an existing data resource so reference it by adding an include to the current page
  128. includePageSegment(dataObjectInfo, objectName);
  129. return true;
  130. }
  131. return false;
  132. }
  133. /**
  134. * Creates a new data object in the AFP datastream
  135. *
  136. * @param dataObjectInfo the data object info
  137. *
  138. * @throws IOException thrown if an I/O exception of some sort has occurred.
  139. */
  140. public void createObject(AFPDataObjectInfo dataObjectInfo) throws IOException {
  141. if (tryIncludeObject(dataObjectInfo)) {
  142. //Object has already been produced and is available by inclusion, so return early.
  143. return;
  144. }
  145. AbstractNamedAFPObject namedObj = null;
  146. AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo();
  147. boolean useInclude = true;
  148. Registry.ObjectType objectType = null;
  149. // new resource so create
  150. if (dataObjectInfo instanceof AFPImageObjectInfo) {
  151. AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)dataObjectInfo;
  152. namedObj = dataObjectFactory.createImage(imageObjectInfo);
  153. } else if (dataObjectInfo instanceof AFPGraphicsObjectInfo) {
  154. AFPGraphicsObjectInfo graphicsObjectInfo = (AFPGraphicsObjectInfo)dataObjectInfo;
  155. namedObj = dataObjectFactory.createGraphic(graphicsObjectInfo);
  156. } else {
  157. // natively embedded data object
  158. namedObj = dataObjectFactory.createObjectContainer(dataObjectInfo);
  159. objectType = dataObjectInfo.getObjectType();
  160. useInclude = objectType != null && objectType.isIncludable();
  161. }
  162. AFPResourceLevel resourceLevel = resourceInfo.getLevel();
  163. ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel);
  164. useInclude &= resourceGroup != null;
  165. if (useInclude) {
  166. boolean usePageSegment = dataObjectInfo.isCreatePageSegment();
  167. // if it is to reside within a resource group at print-file or external level
  168. if (resourceLevel.isPrintFile() || resourceLevel.isExternal()) {
  169. if (usePageSegment) {
  170. String pageSegmentName = "S10" + namedObj.getName().substring(3);
  171. namedObj.setName(pageSegmentName);
  172. PageSegment seg = new PageSegment(pageSegmentName);
  173. seg.addObject(namedObj);
  174. namedObj = seg;
  175. }
  176. // wrap newly created data object in a resource object
  177. namedObj = dataObjectFactory.createResource(namedObj, resourceInfo, objectType);
  178. }
  179. // add data object into its resource group destination
  180. resourceGroup.addObject(namedObj);
  181. // create the include object
  182. String objectName = namedObj.getName();
  183. if (usePageSegment) {
  184. includePageSegment(dataObjectInfo, objectName);
  185. pageSegmentMap.put(resourceInfo, objectName);
  186. } else {
  187. includeObject(dataObjectInfo, objectName);
  188. // record mapping of resource info to data object resource name
  189. includeNameMap.put(resourceInfo, objectName);
  190. }
  191. } else {
  192. // not to be included so inline data object directly into the current page
  193. dataStream.getCurrentPage().addObject(namedObj);
  194. }
  195. }
  196. private void updateResourceInfoUri(AFPResourceInfo resourceInfo) {
  197. String uri = resourceInfo.getUri();
  198. if (uri == null) {
  199. uri = "/";
  200. }
  201. // if this is an instream data object adjust the uri to ensure that its unique
  202. if (uri.endsWith("/")) {
  203. uri += "#" + (++instreamObjectCount);
  204. resourceInfo.setUri(uri);
  205. }
  206. }
  207. private void includeObject(AFPDataObjectInfo dataObjectInfo,
  208. String objectName) {
  209. IncludeObject includeObject
  210. = dataObjectFactory.createInclude(objectName, dataObjectInfo);
  211. dataStream.getCurrentPage().addObject(includeObject);
  212. }
  213. /**
  214. * Handles font embedding. If a font is embeddable and has not already been embedded it will be.
  215. * @param afpFont the AFP font to be checked for embedding
  216. * @param charSet the associated character set
  217. * @throws IOException if there's a problem while embedding the external resources
  218. */
  219. public void embedFont(AFPFont afpFont, CharacterSet charSet)
  220. throws IOException {
  221. if (afpFont.isEmbeddable()) {
  222. //Embed fonts (char sets and code pages)
  223. if (charSet.getResourceAccessor() != null) {
  224. ResourceAccessor accessor = charSet.getResourceAccessor();
  225. createIncludedResource(
  226. charSet.getName(), accessor,
  227. ResourceObject.TYPE_FONT_CHARACTER_SET);
  228. createIncludedResource(
  229. charSet.getCodePage(), accessor,
  230. ResourceObject.TYPE_CODE_PAGE);
  231. }
  232. }
  233. }
  234. private void includePageSegment(AFPDataObjectInfo dataObjectInfo,
  235. String pageSegmentName) {
  236. int x = dataObjectInfo.getObjectAreaInfo().getX();
  237. int y = dataObjectInfo.getObjectAreaInfo().getY();
  238. AbstractPageObject currentPage = dataStream.getCurrentPage();
  239. boolean createHardPageSegments = true;
  240. currentPage.createIncludePageSegment(pageSegmentName, x, y, createHardPageSegments);
  241. }
  242. /**
  243. * Creates an included resource object by loading the contained object from a file.
  244. * @param resourceName the name of the resource
  245. * @param accessor resource accessor to access the resource with
  246. * @param resourceObjectType the resource object type ({@link ResourceObject}.*)
  247. * @throws IOException if an I/O error occurs while loading the resource
  248. */
  249. public void createIncludedResource(String resourceName, ResourceAccessor accessor,
  250. byte resourceObjectType) throws IOException {
  251. URI uri;
  252. try {
  253. uri = new URI(resourceName.trim());
  254. } catch (URISyntaxException e) {
  255. throw new IOException("Could not create URI from resource name: " + resourceName
  256. + " (" + e.getMessage() + ")");
  257. }
  258. createIncludedResource(resourceName, uri, accessor, resourceObjectType);
  259. }
  260. /**
  261. * Creates an included resource object by loading the contained object from a file.
  262. * @param resourceName the name of the resource
  263. * @param uri the URI for the resource
  264. * @param accessor resource accessor to access the resource with
  265. * @param resourceObjectType the resource object type ({@link ResourceObject}.*)
  266. * @throws IOException if an I/O error occurs while loading the resource
  267. */
  268. public void createIncludedResource(String resourceName, URI uri, ResourceAccessor accessor,
  269. byte resourceObjectType) throws IOException {
  270. AFPResourceLevel resourceLevel = new AFPResourceLevel(AFPResourceLevel.PRINT_FILE);
  271. AFPResourceInfo resourceInfo = new AFPResourceInfo();
  272. resourceInfo.setLevel(resourceLevel);
  273. resourceInfo.setName(resourceName);
  274. resourceInfo.setUri(uri.toASCIIString());
  275. String objectName = includeNameMap.get(resourceInfo);
  276. if (objectName == null) {
  277. if (log.isDebugEnabled()) {
  278. log.debug("Adding included resource: " + resourceName);
  279. }
  280. IncludedResourceObject resourceContent = new IncludedResourceObject(
  281. resourceName, accessor, uri);
  282. ResourceObject resourceObject = factory.createResource(resourceName);
  283. resourceObject.setDataObject(resourceContent);
  284. resourceObject.setType(resourceObjectType);
  285. ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel);
  286. resourceGroup.addObject(resourceObject);
  287. // record mapping of resource info to data object resource name
  288. includeNameMap.put(resourceInfo, resourceName);
  289. } else {
  290. //skip, already created
  291. }
  292. }
  293. /**
  294. * Creates an included resource extracting the named resource from an external source.
  295. * @param resourceName the name of the resource
  296. * @param uri the URI for the resource
  297. * @param accessor resource accessor to access the resource with
  298. * @throws IOException if an I/O error occurs while loading the resource
  299. */
  300. public void createIncludedResourceFromExternal(final String resourceName,
  301. final URI uri, final ResourceAccessor accessor) throws IOException {
  302. AFPResourceLevel resourceLevel = new AFPResourceLevel(AFPResourceLevel.PRINT_FILE);
  303. AFPResourceInfo resourceInfo = new AFPResourceInfo();
  304. resourceInfo.setLevel(resourceLevel);
  305. resourceInfo.setName(resourceName);
  306. resourceInfo.setUri(uri.toASCIIString());
  307. String resource = includeNameMap.get(resourceInfo);
  308. if (resource == null) {
  309. ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel);
  310. //resourceObject delegates write commands to copyNamedResource()
  311. //The included resource may already be wrapped in a resource object
  312. AbstractNamedAFPObject resourceObject = new AbstractNamedAFPObject(null) {
  313. @Override
  314. protected void writeContent(OutputStream os) throws IOException {
  315. InputStream inputStream = null;
  316. try {
  317. inputStream = accessor.createInputStream(uri);
  318. BufferedInputStream bin = new BufferedInputStream(inputStream);
  319. AFPResourceUtil.copyNamedResource(resourceName, bin, os);
  320. } finally {
  321. IOUtils.closeQuietly(inputStream);
  322. }
  323. }
  324. //bypass super.writeStart
  325. @Override
  326. protected void writeStart(OutputStream os) throws IOException { }
  327. //bypass super.writeEnd
  328. @Override
  329. protected void writeEnd(OutputStream os) throws IOException { }
  330. };
  331. resourceGroup.addObject(resourceObject);
  332. includeNameMap.put(resourceInfo, resourceName);
  333. }
  334. }
  335. /**
  336. * Sets resource level defaults. The existing defaults over merged with the ones passed in
  337. * as parameter.
  338. * @param defaults the new defaults
  339. */
  340. public void setResourceLevelDefaults(AFPResourceLevelDefaults defaults) {
  341. this.resourceLevelDefaults.mergeFrom(defaults);
  342. }
  343. /**
  344. * Returns the resource level defaults in use with this resource manager.
  345. * @return the resource level defaults
  346. */
  347. public AFPResourceLevelDefaults getResourceLevelDefaults() {
  348. return this.resourceLevelDefaults;
  349. }
  350. }