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.

POIXMLDocumentPart.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi;
  16. import java.io.IOException;
  17. import java.net.URI;
  18. import java.util.*;
  19. import java.util.Map.Entry;
  20. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  21. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  22. import org.apache.poi.openxml4j.opc.OPCPackage;
  23. import org.apache.poi.openxml4j.opc.PackagePart;
  24. import org.apache.poi.openxml4j.opc.PackagePartName;
  25. import org.apache.poi.openxml4j.opc.PackageRelationship;
  26. import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
  27. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  28. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  29. import org.apache.poi.openxml4j.opc.TargetMode;
  30. import org.apache.poi.util.POILogFactory;
  31. import org.apache.poi.util.POILogger;
  32. import org.apache.xmlbeans.XmlOptions;
  33. /**
  34. * Represents an entry of a OOXML package.
  35. *
  36. * <p>
  37. * Each POIXMLDocumentPart keeps a reference to the underlying a {@link org.apache.poi.openxml4j.opc.PackagePart}.
  38. * </p>
  39. *
  40. * @author Yegor Kozlov
  41. */
  42. public class POIXMLDocumentPart {
  43. private static final POILogger logger = POILogFactory.getLogger(POIXMLDocumentPart.class);
  44. public static final XmlOptions DEFAULT_XML_OPTIONS;
  45. static {
  46. DEFAULT_XML_OPTIONS = new XmlOptions();
  47. DEFAULT_XML_OPTIONS.setSaveOuter();
  48. DEFAULT_XML_OPTIONS.setUseDefaultNamespace();
  49. DEFAULT_XML_OPTIONS.setSaveAggressiveNamespaces();
  50. }
  51. private PackagePart packagePart;
  52. private PackageRelationship packageRel;
  53. private POIXMLDocumentPart parent;
  54. private Map<String,POIXMLDocumentPart> relations = new LinkedHashMap<String,POIXMLDocumentPart>();
  55. /**
  56. * Get the PackagePart that is the target of a relationship.
  57. *
  58. * @param rel The relationship
  59. * @param pkg The package to fetch from
  60. * @return The target part
  61. * @throws InvalidFormatException
  62. */
  63. protected static PackagePart getTargetPart(OPCPackage pkg, PackageRelationship rel)
  64. throws InvalidFormatException {
  65. PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
  66. PackagePart part = pkg.getPart(relName);
  67. if (part == null) {
  68. throw new IllegalArgumentException("No part found for relationship " + rel);
  69. }
  70. return part;
  71. }
  72. /**
  73. * Counter that provides the amount of incoming relations from other parts
  74. * to this part.
  75. */
  76. private int relationCounter = 0;
  77. int incrementRelationCounter() {
  78. relationCounter++;
  79. return relationCounter;
  80. }
  81. int decrementRelationCounter() {
  82. relationCounter--;
  83. return relationCounter;
  84. }
  85. int getRelationCounter() {
  86. return relationCounter;
  87. }
  88. /**
  89. * Construct POIXMLDocumentPart representing a "core document" package part.
  90. */
  91. public POIXMLDocumentPart(OPCPackage pkg) {
  92. PackageRelationship coreRel = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT).getRelationship(0);
  93. this.packagePart = pkg.getPart(coreRel);
  94. this.packageRel = coreRel;
  95. }
  96. /**
  97. * Creates new POIXMLDocumentPart - called by client code to create new parts from scratch.
  98. *
  99. * @see #createRelationship(POIXMLRelation, POIXMLFactory, int, boolean)
  100. */
  101. public POIXMLDocumentPart(){
  102. }
  103. /**
  104. * Creates an POIXMLDocumentPart representing the given package part and relationship.
  105. * Called by {@link #read(POIXMLFactory, java.util.Map)} when reading in an exisiting file.
  106. *
  107. * @param part - The package part that holds xml data represenring this sheet.
  108. * @param rel - the relationship of the given package part
  109. * @see #read(POIXMLFactory, java.util.Map)
  110. */
  111. public POIXMLDocumentPart(PackagePart part, PackageRelationship rel){
  112. this.packagePart = part;
  113. this.packageRel = rel;
  114. }
  115. /**
  116. * Creates an POIXMLDocumentPart representing the given package part, relationship and parent
  117. * Called by {@link #read(POIXMLFactory, java.util.Map)} when reading in an exisiting file.
  118. *
  119. * @param parent - Parent part
  120. * @param part - The package part that holds xml data represenring this sheet.
  121. * @param rel - the relationship of the given package part
  122. * @see #read(POIXMLFactory, java.util.Map)
  123. */
  124. public POIXMLDocumentPart(POIXMLDocumentPart parent, PackagePart part, PackageRelationship rel){
  125. this.packagePart = part;
  126. this.packageRel = rel;
  127. this.parent = parent;
  128. }
  129. /**
  130. * When you open something like a theme, call this to
  131. * re-base the XML Document onto the core child of the
  132. * current core document
  133. */
  134. protected final void rebase(OPCPackage pkg) throws InvalidFormatException {
  135. PackageRelationshipCollection cores =
  136. packagePart.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
  137. if(cores.size() != 1) {
  138. throw new IllegalStateException(
  139. "Tried to rebase using " + PackageRelationshipTypes.CORE_DOCUMENT +
  140. " but found " + cores.size() + " parts of the right type"
  141. );
  142. }
  143. packageRel = cores.getRelationship(0);
  144. packagePart = POIXMLDocument.getTargetPart(pkg, packageRel);
  145. }
  146. /**
  147. * Provides access to the underlying PackagePart
  148. *
  149. * @return the underlying PackagePart
  150. */
  151. public final PackagePart getPackagePart(){
  152. return packagePart;
  153. }
  154. /**
  155. * Provides access to the PackageRelationship that identifies this POIXMLDocumentPart
  156. *
  157. * @return the PackageRelationship that identifies this POIXMLDocumentPart
  158. */
  159. public final PackageRelationship getPackageRelationship(){
  160. return packageRel;
  161. }
  162. /**
  163. * Returns the list of child relations for this POIXMLDocumentPart
  164. *
  165. * @return child relations
  166. */
  167. public final List<POIXMLDocumentPart> getRelations(){
  168. return Collections.unmodifiableList(new ArrayList<POIXMLDocumentPart>(relations.values()));
  169. }
  170. /**
  171. * Returns the target {@link POIXMLDocumentPart}, where a
  172. * {@link PackageRelationship} is set from the {@link PackagePart} of this
  173. * {@link POIXMLDocumentPart} to the {@link PackagePart} of the target
  174. * {@link POIXMLDocumentPart} with a {@link PackageRelationship#getId()}
  175. * matching the given parameter value.
  176. *
  177. * @param id
  178. * The relation id to look for
  179. * @return the target part of the relation, or null, if none exists
  180. */
  181. public final POIXMLDocumentPart getRelationById(String id) {
  182. return relations.get(id);
  183. }
  184. /**
  185. * Returns the {@link PackageRelationship#getId()} of the
  186. * {@link PackageRelationship}, that sources from the {@link PackagePart} of
  187. * this {@link POIXMLDocumentPart} to the {@link PackagePart} of the given
  188. * parameter value.
  189. *
  190. * @param part
  191. * The {@link POIXMLDocumentPart} for which the according
  192. * relation-id shall be found.
  193. * @return The value of the {@link PackageRelationship#getId()} or null, if
  194. * parts are not related.
  195. */
  196. public final String getRelationId(POIXMLDocumentPart part) {
  197. Iterator<Entry<String, POIXMLDocumentPart>> iter = relations.entrySet().iterator();
  198. while (iter.hasNext())
  199. {
  200. Entry<String, POIXMLDocumentPart> entry = iter.next();
  201. if (entry.getValue() == part) {
  202. return entry.getKey();
  203. }
  204. }
  205. return null;
  206. }
  207. /**
  208. * Add a new child POIXMLDocumentPart
  209. *
  210. * @param part the child to add
  211. */
  212. public final void addRelation(String id,POIXMLDocumentPart part){
  213. relations.put(id,part);
  214. part.incrementRelationCounter();
  215. }
  216. /**
  217. * Remove the relation to the specified part in this package and remove the
  218. * part, if it is no longer needed.
  219. */
  220. protected final void removeRelation(POIXMLDocumentPart part){
  221. removeRelation(part,true);
  222. }
  223. /**
  224. * Remove the relation to the specified part in this package and remove the
  225. * part, if it is no longer needed and flag is set to true.
  226. *
  227. * @param part
  228. * The related part, to which the relation shall be removed.
  229. * @param removeUnusedParts
  230. * true, if the part shall be removed from the package if not
  231. * needed any longer.
  232. */
  233. protected final boolean removeRelation(POIXMLDocumentPart part, boolean removeUnusedParts){
  234. String id = getRelationId(part);
  235. if (id == null) {
  236. // part is not related with this POIXMLDocumentPart
  237. return false;
  238. }
  239. /* decrement usage counter */
  240. part.decrementRelationCounter();
  241. /* remove packagepart relationship */
  242. getPackagePart().removeRelationship(id);
  243. /* remove POIXMLDocument from relations */
  244. relations.remove(id);
  245. if (removeUnusedParts) {
  246. /* if last relation to target part was removed, delete according target part */
  247. if (part.getRelationCounter() == 0) {
  248. try {
  249. part.onDocumentRemove();
  250. } catch (IOException e) {
  251. throw new POIXMLException(e);
  252. }
  253. getPackagePart().getPackage().removePart(part.getPackagePart());
  254. }
  255. }
  256. return true;
  257. }
  258. /**
  259. * Returns the parent POIXMLDocumentPart. All parts except root have not-null parent.
  260. *
  261. * @return the parent POIXMLDocumentPart or <code>null</code> for the root element.
  262. */
  263. public final POIXMLDocumentPart getParent(){
  264. return parent;
  265. }
  266. @Override
  267. public String toString(){
  268. return packagePart == null ? null : packagePart.toString();
  269. }
  270. /**
  271. * Save the content in the underlying package part.
  272. * Default implementation is empty meaning that the package part is left unmodified.
  273. *
  274. * Sub-classes should override and add logic to marshal the "model" into Ooxml4J.
  275. *
  276. * For example, the code saving a generic XML entry may look as follows:
  277. * <pre><code>
  278. * protected void commit() throws IOException {
  279. * PackagePart part = getPackagePart();
  280. * OutputStream out = part.getOutputStream();
  281. * XmlObject bean = getXmlBean(); //the "model" which holds changes in memory
  282. * bean.save(out, DEFAULT_XML_OPTIONS);
  283. * out.close();
  284. * }
  285. * </code></pre>
  286. *
  287. */
  288. protected void commit() throws IOException {
  289. }
  290. /**
  291. * Save changes in the underlying OOXML package.
  292. * Recursively fires {@link #commit()} for each package part
  293. *
  294. * @param alreadySaved context set containing already visited nodes
  295. */
  296. protected final void onSave(Set<PackagePart> alreadySaved) throws IOException{
  297. commit();
  298. alreadySaved.add(this.getPackagePart());
  299. for(POIXMLDocumentPart p : relations.values()){
  300. if (!alreadySaved.contains(p.getPackagePart())) {
  301. p.onSave(alreadySaved);
  302. }
  303. }
  304. }
  305. /**
  306. * Create a new child POIXMLDocumentPart
  307. *
  308. * @param descriptor the part descriptor
  309. * @param factory the factory that will create an instance of the requested relation
  310. * @return the created child POIXMLDocumentPart
  311. */
  312. public final POIXMLDocumentPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory){
  313. return createRelationship(descriptor, factory, -1, false);
  314. }
  315. public final POIXMLDocumentPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx){
  316. return createRelationship(descriptor, factory, idx, false);
  317. }
  318. /**
  319. * Create a new child POIXMLDocumentPart
  320. *
  321. * @param descriptor the part descriptor
  322. * @param factory the factory that will create an instance of the requested relation
  323. * @param idx part number
  324. * @param noRelation if true, then no relationship is added.
  325. * @return the created child POIXMLDocumentPart
  326. */
  327. protected final POIXMLDocumentPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx, boolean noRelation){
  328. try {
  329. PackagePartName ppName = PackagingURIHelper.createPartName(descriptor.getFileName(idx));
  330. PackageRelationship rel = null;
  331. PackagePart part = packagePart.getPackage().createPart(ppName, descriptor.getContentType());
  332. if(!noRelation) {
  333. /* only add to relations, if according relationship is being created. */
  334. rel = packagePart.addRelationship(ppName, TargetMode.INTERNAL, descriptor.getRelation());
  335. }
  336. POIXMLDocumentPart doc = factory.newDocumentPart(descriptor);
  337. doc.packageRel = rel;
  338. doc.packagePart = part;
  339. doc.parent = this;
  340. if(!noRelation) {
  341. /* only add to relations, if according relationship is being created. */
  342. addRelation(rel.getId(),doc);
  343. }
  344. return doc;
  345. } catch (Exception e){
  346. throw new POIXMLException(e);
  347. }
  348. }
  349. /**
  350. * Iterate through the underlying PackagePart and create child POIXMLFactory instances
  351. * using the specified factory
  352. *
  353. * @param factory the factory object that creates POIXMLFactory instances
  354. * @param context context map containing already visited noted keyed by targetURI
  355. */
  356. protected void read(POIXMLFactory factory, Map<PackagePart, POIXMLDocumentPart> context) throws OpenXML4JException {
  357. PackageRelationshipCollection rels = packagePart.getRelationships();
  358. for (PackageRelationship rel : rels) {
  359. if(rel.getTargetMode() == TargetMode.INTERNAL){
  360. URI uri = rel.getTargetURI();
  361. PackagePart p;
  362. if(uri.getRawFragment() != null) {
  363. /*
  364. * For internal references (e.g. '#Sheet1!A1') the package part is null
  365. */
  366. p = null;
  367. } else {
  368. PackagePartName relName = PackagingURIHelper.createPartName(uri);
  369. p = packagePart.getPackage().getPart(relName);
  370. if(p == null) {
  371. logger.log(POILogger.ERROR, "Skipped invalid entry " + rel.getTargetURI());
  372. continue;
  373. }
  374. }
  375. if (!context.containsKey(p)) {
  376. POIXMLDocumentPart childPart = factory.createDocumentPart(this, rel, p);
  377. childPart.parent = this;
  378. addRelation(rel.getId(),childPart);
  379. if(p != null){
  380. context.put(p, childPart);
  381. if(p.hasRelationships()) childPart.read(factory, context);
  382. }
  383. }
  384. else {
  385. addRelation(rel.getId(),context.get(p));
  386. }
  387. }
  388. }
  389. }
  390. /**
  391. * Fired when a new package part is created
  392. */
  393. protected void onDocumentCreate() throws IOException {
  394. }
  395. /**
  396. * Fired when a package part is read
  397. */
  398. protected void onDocumentRead() throws IOException {
  399. }
  400. /**
  401. * Get the PackagePart that is the target of a relationship.
  402. *
  403. * @param rel The relationship
  404. * @return The target part
  405. * @throws InvalidFormatException
  406. */
  407. protected PackagePart getTargetPart(PackageRelationship rel) throws InvalidFormatException {
  408. return getTargetPart(getPackagePart().getPackage(), rel);
  409. }
  410. /**
  411. * Fired when a package part is about to be removed from the package
  412. */
  413. protected void onDocumentRemove() throws IOException {
  414. }
  415. }