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 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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.ooxml;
  16. import java.io.IOException;
  17. import java.net.URI;
  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.LinkedHashMap;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  25. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  26. import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException;
  27. import org.apache.poi.openxml4j.opc.OPCPackage;
  28. import org.apache.poi.openxml4j.opc.PackagePart;
  29. import org.apache.poi.openxml4j.opc.PackagePartName;
  30. import org.apache.poi.openxml4j.opc.PackageRelationship;
  31. import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
  32. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  33. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  34. import org.apache.poi.openxml4j.opc.TargetMode;
  35. import org.apache.poi.util.IOUtils;
  36. import org.apache.poi.util.Internal;
  37. import org.apache.poi.util.POILogFactory;
  38. import org.apache.poi.util.POILogger;
  39. import org.apache.poi.xddf.usermodel.chart.XDDFChart;
  40. import org.apache.poi.xssf.usermodel.XSSFRelation;
  41. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  42. import org.apache.poi.xwpf.usermodel.XWPFRelation;
  43. /**
  44. * Represents an entry of a OOXML package.
  45. * <p>
  46. * Each POIXMLDocumentPart keeps a reference to the underlying a {@link org.apache.poi.openxml4j.opc.PackagePart}.
  47. * </p>
  48. */
  49. public class POIXMLDocumentPart {
  50. private static final POILogger logger = POILogFactory.getLogger(POIXMLDocumentPart.class);
  51. private String coreDocumentRel = PackageRelationshipTypes.CORE_DOCUMENT;
  52. private PackagePart packagePart;
  53. private POIXMLDocumentPart parent;
  54. private Map<String, RelationPart> relations = new LinkedHashMap<>();
  55. private boolean isCommitted = false;
  56. /**
  57. * to check whether embedded part is already committed
  58. *
  59. * @return return true if embedded part is committed
  60. * @since 4.1.2
  61. */
  62. public boolean isCommitted() {
  63. return isCommitted;
  64. }
  65. /**
  66. * setter method to set embedded part is committed
  67. *
  68. * @param isCommitted boolean value
  69. */
  70. public void setCommitted(boolean isCommitted) {
  71. this.isCommitted = isCommitted;
  72. }
  73. /**
  74. * The RelationPart is a cached relationship between the document, which contains the RelationPart,
  75. * and one of its referenced child document parts.
  76. * The child document parts may only belong to one parent, but it's often referenced by other
  77. * parents too, having varying {@link PackageRelationship#getId() relationship ids} pointing to it.
  78. */
  79. public static class RelationPart {
  80. private final PackageRelationship relationship;
  81. private final POIXMLDocumentPart documentPart;
  82. RelationPart(PackageRelationship relationship, POIXMLDocumentPart documentPart) {
  83. this.relationship = relationship;
  84. this.documentPart = documentPart;
  85. }
  86. /**
  87. * @return the cached relationship, which uniquely identifies this child document part within the parent
  88. */
  89. public PackageRelationship getRelationship() {
  90. return relationship;
  91. }
  92. /**
  93. * @param <T> the cast of the caller to a document sub class
  94. * @return the child document part
  95. */
  96. @SuppressWarnings("unchecked")
  97. public <T extends POIXMLDocumentPart> T getDocumentPart() {
  98. return (T) documentPart;
  99. }
  100. }
  101. /**
  102. * Counter that provides the amount of incoming relations from other parts
  103. * to this part.
  104. */
  105. private int relationCounter;
  106. int incrementRelationCounter() {
  107. relationCounter++;
  108. return relationCounter;
  109. }
  110. int decrementRelationCounter() {
  111. relationCounter--;
  112. return relationCounter;
  113. }
  114. int getRelationCounter() {
  115. return relationCounter;
  116. }
  117. /**
  118. * Construct POIXMLDocumentPart representing a "core document" package part.
  119. *
  120. * @param pkg the OPCPackage containing this document
  121. */
  122. public POIXMLDocumentPart(OPCPackage pkg) {
  123. this(pkg, PackageRelationshipTypes.CORE_DOCUMENT);
  124. }
  125. /**
  126. * Construct POIXMLDocumentPart representing a custom "core document" package part.
  127. *
  128. * @param pkg the OPCPackage containing this document
  129. * @param coreDocumentRel the relation type of this document
  130. */
  131. public POIXMLDocumentPart(OPCPackage pkg, String coreDocumentRel) {
  132. this(getPartFromOPCPackage(pkg, coreDocumentRel));
  133. this.coreDocumentRel = coreDocumentRel;
  134. }
  135. /**
  136. * Creates new POIXMLDocumentPart - called by client code to create new parts from scratch.
  137. *
  138. * @see #createRelationship(POIXMLRelation, POIXMLFactory, int, boolean)
  139. */
  140. public POIXMLDocumentPart() {
  141. }
  142. /**
  143. * Creates an POIXMLDocumentPart representing the given package part and relationship.
  144. * Called by {@link #read(POIXMLFactory, java.util.Map)} when reading in an existing file.
  145. *
  146. * @param part - The package part that holds xml data representing this sheet.
  147. * @see #read(POIXMLFactory, java.util.Map)
  148. * @since POI 3.14-Beta1
  149. */
  150. public POIXMLDocumentPart(PackagePart part) {
  151. this(null, part);
  152. }
  153. /**
  154. * Creates an POIXMLDocumentPart representing the given package part, relationship and parent
  155. * Called by {@link #read(POIXMLFactory, java.util.Map)} when reading in an existing file.
  156. *
  157. * @param parent - Parent part
  158. * @param part - The package part that holds xml data representing this sheet.
  159. * @see #read(POIXMLFactory, java.util.Map)
  160. * @since POI 3.14-Beta1
  161. */
  162. public POIXMLDocumentPart(POIXMLDocumentPart parent, PackagePart part) {
  163. this.packagePart = part;
  164. this.parent = parent;
  165. }
  166. /**
  167. * When you open something like a theme, call this to
  168. * re-base the XML Document onto the core child of the
  169. * current core document
  170. *
  171. * @param pkg the package to be rebased
  172. * @throws InvalidFormatException if there was an error in the core document relation
  173. * @throws IllegalStateException if there are more than one core document relations
  174. */
  175. protected final void rebase(OPCPackage pkg) throws InvalidFormatException {
  176. PackageRelationshipCollection cores =
  177. packagePart.getRelationshipsByType(coreDocumentRel);
  178. if (cores.size() != 1) {
  179. throw new IllegalStateException(
  180. "Tried to rebase using " + coreDocumentRel +
  181. " but found " + cores.size() + " parts of the right type"
  182. );
  183. }
  184. packagePart = packagePart.getRelatedPart(cores.getRelationship(0));
  185. }
  186. /**
  187. * Provides access to the underlying PackagePart
  188. *
  189. * @return the underlying PackagePart
  190. */
  191. public final PackagePart getPackagePart() {
  192. return packagePart;
  193. }
  194. /**
  195. * Returns the list of child relations for this POIXMLDocumentPart
  196. *
  197. * @return child relations
  198. */
  199. public final List<POIXMLDocumentPart> getRelations() {
  200. List<POIXMLDocumentPart> l = new ArrayList<>();
  201. for (RelationPart rp : relations.values()) {
  202. l.add(rp.getDocumentPart());
  203. }
  204. return Collections.unmodifiableList(l);
  205. }
  206. /**
  207. * Returns the list of child relations for this POIXMLDocumentPart
  208. *
  209. * @return child relations
  210. */
  211. public final List<RelationPart> getRelationParts() {
  212. List<RelationPart> l = new ArrayList<>(relations.values());
  213. return Collections.unmodifiableList(l);
  214. }
  215. /**
  216. * Returns the target {@link POIXMLDocumentPart}, where a
  217. * {@link PackageRelationship} is set from the {@link PackagePart} of this
  218. * {@link POIXMLDocumentPart} to the {@link PackagePart} of the target
  219. * {@link POIXMLDocumentPart} with a {@link PackageRelationship#getId()}
  220. * matching the given parameter value.
  221. *
  222. * @param id The relation id to look for
  223. * @return the target part of the relation, or null, if none exists
  224. */
  225. public final POIXMLDocumentPart getRelationById(String id) {
  226. RelationPart rp = getRelationPartById(id);
  227. return (rp == null) ? null : rp.getDocumentPart();
  228. }
  229. /**
  230. * Returns the target {@link RelationPart}, where a
  231. * {@link PackageRelationship} is set from the {@link PackagePart} of this
  232. * {@link POIXMLDocumentPart} to the {@link PackagePart} of the target
  233. * {@link POIXMLDocumentPart} with a {@link PackageRelationship#getId()}
  234. * matching the given parameter value.
  235. *
  236. * @param id The relation id to look for
  237. * @return the target relation part, or null, if none exists
  238. * @since 4.0.0
  239. */
  240. public final RelationPart getRelationPartById(String id) {
  241. return relations.get(id);
  242. }
  243. /**
  244. * Returns the first {@link PackageRelationship#getId()} of the
  245. * {@link PackageRelationship}, that sources from the {@link PackagePart} of
  246. * this {@link POIXMLDocumentPart} to the {@link PackagePart} of the given
  247. * parameter value.<p>
  248. * <p>
  249. * There can be multiple references to the given {@link POIXMLDocumentPart}
  250. * and only the first in the order of creation is returned.
  251. *
  252. * @param part The {@link POIXMLDocumentPart} for which the according
  253. * relation-id shall be found.
  254. * @return The value of the {@link PackageRelationship#getId()} or null, if
  255. * parts are not related.
  256. */
  257. public final String getRelationId(POIXMLDocumentPart part) {
  258. for (RelationPart rp : relations.values()) {
  259. if (rp.getDocumentPart() == part) {
  260. return rp.getRelationship().getId();
  261. }
  262. }
  263. return null;
  264. }
  265. /**
  266. * Add a new child POIXMLDocumentPart
  267. *
  268. * @param relId the preferred relation id, when null the next free relation id will be used
  269. * @param relationshipType the package relationship type
  270. * @param part the child to add
  271. * @return the new RelationPart
  272. * @since 3.14-Beta1
  273. */
  274. public final RelationPart addRelation(String relId, POIXMLRelation relationshipType, POIXMLDocumentPart part) {
  275. PackageRelationship pr = this.packagePart.findExistingRelation(part.getPackagePart());
  276. if (pr == null) {
  277. PackagePartName ppn = part.getPackagePart().getPartName();
  278. String relType = relationshipType.getRelation();
  279. pr = packagePart.addRelationship(ppn, TargetMode.INTERNAL, relType, relId);
  280. }
  281. addRelation(pr, part);
  282. return new RelationPart(pr, part);
  283. }
  284. /**
  285. * Add a new child POIXMLDocumentPart
  286. *
  287. * @param pr the relationship of the child
  288. * @param part the child to add
  289. */
  290. private void addRelation(PackageRelationship pr, POIXMLDocumentPart part) {
  291. relations.put(pr.getId(), new RelationPart(pr, part));
  292. part.incrementRelationCounter();
  293. }
  294. /**
  295. * Remove the relation to the specified part in this package and remove the
  296. * part, if it is no longer needed.<p>
  297. * <p>
  298. * If there are multiple relationships to the same part, this will only
  299. * remove the first relationship in the order of creation. The removal
  300. * via the part id ({@link #removeRelation(String)} is preferred.
  301. *
  302. * @param part the part which relation is to be removed from this document
  303. */
  304. protected final void removeRelation(POIXMLDocumentPart part) {
  305. removeRelation(part, true);
  306. }
  307. /**
  308. * Remove the relation to the specified part in this package and remove the
  309. * part, if it is no longer needed and flag is set to true.<p>
  310. * <p>
  311. * If there are multiple relationships to the same part, this will only
  312. * remove the first relationship in the order of creation. The removal
  313. * via the part id ({@link #removeRelation(String, boolean)} is preferred.
  314. *
  315. * @param part The related part, to which the relation shall be removed.
  316. * @param removeUnusedParts true, if the part shall be removed from the package if not
  317. * needed any longer.
  318. * @return true, if the relation was removed
  319. */
  320. protected final boolean removeRelation(POIXMLDocumentPart part, boolean removeUnusedParts) {
  321. String id = getRelationId(part);
  322. return removeRelation(id, removeUnusedParts);
  323. }
  324. /**
  325. * Remove the relation to the specified part in this package and remove the
  326. * part, if it is no longer needed.<p>
  327. * <p>
  328. * If there are multiple relationships to the same part, this will only
  329. * remove the first relationship in the order of creation. The removal
  330. * via the part id ({@link #removeRelation(String)} is preferred.
  331. *
  332. * @param partId the part id which relation is to be removed from this document
  333. * @since 4.0.0
  334. */
  335. protected final void removeRelation(String partId) {
  336. removeRelation(partId, true);
  337. }
  338. /**
  339. * Remove the relation to the specified part in this package and remove the
  340. * part, if it is no longer needed and flag is set to true.<p>
  341. *
  342. * @param partId The related part id, to which the relation shall be removed.
  343. * @param removeUnusedParts true, if the part shall be removed from the package if not
  344. * needed any longer.
  345. * @return true, if the relation was removed
  346. * @since 4.0.0
  347. */
  348. private final boolean removeRelation(String partId, boolean removeUnusedParts) {
  349. RelationPart rp = relations.get(partId);
  350. if (rp == null) {
  351. // part is not related with this POIXMLDocumentPart
  352. return false;
  353. }
  354. POIXMLDocumentPart part = rp.getDocumentPart();
  355. /* decrement usage counter */
  356. part.decrementRelationCounter();
  357. /* remove packagepart relationship */
  358. getPackagePart().removeRelationship(partId);
  359. /* remove POIXMLDocument from relations */
  360. relations.remove(partId);
  361. if (removeUnusedParts) {
  362. /* if last relation to target part was removed, delete according target part */
  363. if (part.getRelationCounter() == 0) {
  364. try {
  365. part.onDocumentRemove();
  366. } catch (IOException e) {
  367. throw new POIXMLException(e);
  368. }
  369. getPackagePart().getPackage().removePart(part.getPackagePart());
  370. }
  371. }
  372. return true;
  373. }
  374. /**
  375. * Returns the parent POIXMLDocumentPart. All parts except root have not-null parent.
  376. *
  377. * @return the parent POIXMLDocumentPart or <code>null</code> for the root element.
  378. */
  379. public final POIXMLDocumentPart getParent() {
  380. return parent;
  381. }
  382. @Override
  383. public String toString() {
  384. return packagePart == null ? "" : packagePart.toString();
  385. }
  386. /**
  387. * Save the content in the underlying package part.
  388. * Default implementation is empty meaning that the package part is left unmodified.
  389. * <p>
  390. * Sub-classes should override and add logic to marshal the "model" into Ooxml4J.
  391. * <p>
  392. * For example, the code saving a generic XML entry may look as follows:
  393. * <pre>
  394. * protected void commit() throws IOException {
  395. * PackagePart part = getPackagePart();
  396. * OutputStream out = part.getOutputStream();
  397. * XmlObject bean = getXmlBean(); //the "model" which holds changes in memory
  398. * bean.save(out, DEFAULT_XML_OPTIONS);
  399. * out.close();
  400. * }
  401. * </pre>
  402. *
  403. * @throws IOException a subclass may throw an IOException if the changes can't be committed
  404. */
  405. protected void commit() throws IOException {
  406. }
  407. /**
  408. * Save changes in the underlying OOXML package.
  409. * Recursively fires {@link #commit()} for each package part
  410. *
  411. * @param alreadySaved context set containing already visited nodes
  412. * @throws IOException a related part may throw an IOException if the changes can't be saved
  413. */
  414. protected final void onSave(Set<PackagePart> alreadySaved) throws IOException {
  415. //if part is already committed then return
  416. if (this.isCommitted) {
  417. return;
  418. }
  419. // this usually clears out previous content in the part...
  420. prepareForCommit();
  421. commit();
  422. alreadySaved.add(this.getPackagePart());
  423. for (RelationPart rp : relations.values()) {
  424. POIXMLDocumentPart p = rp.getDocumentPart();
  425. if (!alreadySaved.contains(p.getPackagePart())) {
  426. p.onSave(alreadySaved);
  427. }
  428. }
  429. }
  430. /**
  431. * Ensure that a memory based package part does not have lingering data from previous
  432. * commit() calls.
  433. * <p>
  434. * Note: This is overwritten for some objects, as *PictureData seem to store the actual content
  435. * in the part directly without keeping a copy like all others therefore we need to handle them differently.
  436. */
  437. protected void prepareForCommit() {
  438. PackagePart part = this.getPackagePart();
  439. if (part != null) {
  440. part.clear();
  441. }
  442. }
  443. /**
  444. * Create a new child POIXMLDocumentPart
  445. *
  446. * @param descriptor the part descriptor
  447. * @param factory the factory that will create an instance of the requested relation
  448. * @return the created child POIXMLDocumentPart
  449. * @throws PartAlreadyExistsException If rule M1.12 is not verified : Packages shall not contain
  450. * equivalent part names and package implementers shall neither
  451. * create nor recognize packages with equivalent part names.
  452. */
  453. public final POIXMLDocumentPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory) {
  454. return createRelationship(descriptor, factory, -1, false).getDocumentPart();
  455. }
  456. /**
  457. * Create a new child POIXMLDocumentPart
  458. *
  459. * @param descriptor the part descriptor
  460. * @param factory the factory that will create an instance of the requested relation
  461. * @param idx part number
  462. * @return the created child POIXMLDocumentPart
  463. * @throws PartAlreadyExistsException If rule M1.12 is not verified : Packages shall not contain
  464. * equivalent part names and package implementers shall neither
  465. * create nor recognize packages with equivalent part names.
  466. */
  467. public final POIXMLDocumentPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx) {
  468. return createRelationship(descriptor, factory, idx, false).getDocumentPart();
  469. }
  470. /**
  471. * Identifies the next available part number for a part of the given type,
  472. * if possible, otherwise -1 if none are available.
  473. * The found (valid) index can then be safely given to
  474. * {@link #createRelationship(POIXMLRelation, POIXMLFactory, int)} or
  475. * {@link #createRelationship(POIXMLRelation, POIXMLFactory, int, boolean)}
  476. * without naming clashes.
  477. * If parts with other types are already claiming a name for this relationship
  478. * type (eg a {@link XSSFRelation#CHART} using the drawing part namespace
  479. * normally used by {@link XSSFRelation#DRAWINGS}), those will be considered
  480. * when finding the next spare number.
  481. *
  482. * @param descriptor The relationship type to find the part number for
  483. * @param minIdx The minimum free index to assign, use -1 for any
  484. * @return The next free part number, or -1 if none available
  485. */
  486. @Internal
  487. public final int getNextPartNumber(POIXMLRelation descriptor, int minIdx) {
  488. OPCPackage pkg = packagePart.getPackage();
  489. try {
  490. String name = descriptor.getDefaultFileName();
  491. if (name.equals(descriptor.getFileName(9999))) {
  492. // Non-index based, check if default is free
  493. PackagePartName ppName = PackagingURIHelper.createPartName(name);
  494. if (pkg.containPart(ppName)) {
  495. // Default name already taken, not index based, nothing free
  496. return -1;
  497. } else {
  498. // Default name free
  499. return 0;
  500. }
  501. }
  502. // Default to searching from 1, unless they asked for 0+
  503. int idx = (minIdx < 0) ? 1 : minIdx;
  504. int maxIdx = minIdx + pkg.getParts().size();
  505. while (idx <= maxIdx) {
  506. name = descriptor.getFileName(idx);
  507. PackagePartName ppName = PackagingURIHelper.createPartName(name);
  508. if (!pkg.containPart(ppName)) {
  509. return idx;
  510. }
  511. idx++;
  512. }
  513. } catch (InvalidFormatException e) {
  514. // Give a general wrapped exception for the problem
  515. throw new POIXMLException(e);
  516. }
  517. return -1;
  518. }
  519. /**
  520. * Create a new child POIXMLDocumentPart
  521. *
  522. * @param descriptor the part descriptor
  523. * @param factory the factory that will create an instance of the requested relation
  524. * @param idx part number
  525. * @param noRelation if true, then no relationship is added.
  526. * @return the created child POIXMLDocumentPart
  527. * @throws PartAlreadyExistsException If rule M1.12 is not verified : Packages shall not contain
  528. * equivalent part names and package implementers shall neither
  529. * create nor recognize packages with equivalent part names.
  530. */
  531. public final RelationPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx, boolean noRelation) {
  532. try {
  533. PackagePartName ppName = PackagingURIHelper.createPartName(descriptor.getFileName(idx));
  534. PackageRelationship rel = null;
  535. PackagePart part = packagePart.getPackage().createPart(ppName, descriptor.getContentType());
  536. if (!noRelation) {
  537. /* only add to relations, if according relationship is being created. */
  538. rel = packagePart.addRelationship(ppName, TargetMode.INTERNAL, descriptor.getRelation());
  539. }
  540. POIXMLDocumentPart doc = factory.newDocumentPart(descriptor);
  541. doc.packagePart = part;
  542. doc.parent = this;
  543. if (!noRelation) {
  544. /* only add to relations, if according relationship is being created. */
  545. addRelation(rel, doc);
  546. }
  547. return new RelationPart(rel, doc);
  548. } catch (PartAlreadyExistsException pae) {
  549. // Return the specific exception so the user knows
  550. // that the name is already taken
  551. throw pae;
  552. } catch (Exception e) {
  553. // Give a general wrapped exception for the problem
  554. throw new POIXMLException(e);
  555. }
  556. }
  557. /**
  558. * Iterate through the underlying PackagePart and create child POIXMLFactory instances
  559. * using the specified factory
  560. *
  561. * @param factory the factory object that creates POIXMLFactory instances
  562. * @param context context map containing already visited noted keyed by targetURI
  563. * @throws OpenXML4JException thrown when a related part can't be read
  564. */
  565. protected void read(POIXMLFactory factory, Map<PackagePart, POIXMLDocumentPart> context) throws OpenXML4JException {
  566. PackagePart pp = getPackagePart();
  567. if (pp.getContentType().equals(XWPFRelation.GLOSSARY_DOCUMENT.getContentType())) {
  568. logger.log(POILogger.WARN,
  569. "POI does not currently support template.main+xml (glossary) parts. " +
  570. "Skipping this part for now.");
  571. return;
  572. }
  573. // add mapping a second time, in case of initial caller hasn't done so
  574. POIXMLDocumentPart otherChild = context.put(pp, this);
  575. if (otherChild != null && otherChild != this) {
  576. throw new POIXMLException("Unique PackagePart-POIXMLDocumentPart relation broken!");
  577. }
  578. if (!pp.hasRelationships()) return;
  579. PackageRelationshipCollection rels = packagePart.getRelationships();
  580. List<POIXMLDocumentPart> readLater = new ArrayList<>();
  581. // scan breadth-first, so parent-relations are hopefully the shallowest element
  582. for (PackageRelationship rel : rels) {
  583. if (rel.getTargetMode() == TargetMode.INTERNAL) {
  584. URI uri = rel.getTargetURI();
  585. // check for internal references (e.g. '#Sheet1!A1')
  586. PackagePartName relName;
  587. if (uri.getRawFragment() != null) {
  588. relName = PackagingURIHelper.createPartName(uri.getPath());
  589. } else {
  590. relName = PackagingURIHelper.createPartName(uri);
  591. }
  592. final PackagePart p = packagePart.getPackage().getPart(relName);
  593. if (p == null) {
  594. logger.log(POILogger.ERROR, "Skipped invalid entry " + rel.getTargetURI());
  595. continue;
  596. }
  597. POIXMLDocumentPart childPart = context.get(p);
  598. if (childPart == null) {
  599. childPart = factory.createDocumentPart(this, p);
  600. //here we are checking if part if embedded and excel then set it to chart class
  601. //so that at the time to writing we can also write updated embedded part
  602. if (this instanceof XDDFChart && childPart instanceof XSSFWorkbook) {
  603. ((XDDFChart) this).setWorkbook((XSSFWorkbook) childPart);
  604. }
  605. childPart.parent = this;
  606. // already add child to context, so other children can reference it
  607. context.put(p, childPart);
  608. readLater.add(childPart);
  609. }
  610. addRelation(rel, childPart);
  611. }
  612. }
  613. for (POIXMLDocumentPart childPart : readLater) {
  614. childPart.read(factory, context);
  615. }
  616. }
  617. /**
  618. * Get the PackagePart that is the target of a relationship from this Part.
  619. *
  620. * @param rel The relationship
  621. * @return The target part
  622. * @throws InvalidFormatException thrown if the related part has is erroneous
  623. */
  624. protected PackagePart getTargetPart(PackageRelationship rel) throws InvalidFormatException {
  625. return getPackagePart().getRelatedPart(rel);
  626. }
  627. /**
  628. * Fired when a new package part is created
  629. *
  630. * @throws IOException a subclass may throw an IOException on document creation
  631. */
  632. protected void onDocumentCreate() throws IOException {
  633. }
  634. /**
  635. * Fired when a package part is read
  636. *
  637. * @throws IOException a subclass may throw an IOException when a document is read
  638. */
  639. protected void onDocumentRead() throws IOException {
  640. }
  641. /**
  642. * Fired when a package part is about to be removed from the package
  643. *
  644. * @throws IOException a subclass may throw an IOException when a document is removed
  645. */
  646. protected void onDocumentRemove() throws IOException {
  647. }
  648. /**
  649. * Internal method, do not use!
  650. * <p>
  651. * This method only exists to allow access to protected {@link POIXMLDocumentPart#onDocumentRead()}
  652. * from {@link org.apache.poi.xwpf.usermodel.XWPFDocument} without reflection. It should be removed.
  653. *
  654. * @param part the part which is to be read
  655. * @throws IOException if the part can't be read
  656. */
  657. @Internal
  658. @Deprecated
  659. public static void _invokeOnDocumentRead(POIXMLDocumentPart part) throws IOException {
  660. part.onDocumentRead();
  661. }
  662. /**
  663. * Retrieves the core document part
  664. *
  665. * Since POI 4.1.2 - pkg is closed if this method throws an exception
  666. */
  667. private static PackagePart getPartFromOPCPackage(OPCPackage pkg, String coreDocumentRel) {
  668. PackageRelationship coreRel = pkg.getRelationshipsByType(coreDocumentRel).getRelationship(0);
  669. if (coreRel != null) {
  670. PackagePart pp = pkg.getPart(coreRel);
  671. if (pp == null) {
  672. IOUtils.closeQuietly(pkg);
  673. throw new POIXMLException("OOXML file structure broken/invalid - core document '" + coreRel.getTargetURI() + "' not found.");
  674. }
  675. return pp;
  676. }
  677. coreRel = pkg.getRelationshipsByType(PackageRelationshipTypes.STRICT_CORE_DOCUMENT).getRelationship(0);
  678. if (coreRel != null) {
  679. IOUtils.closeQuietly(pkg);
  680. throw new POIXMLException("Strict OOXML isn't currently supported, please see bug #57699");
  681. }
  682. IOUtils.closeQuietly(pkg);
  683. throw new POIXMLException("OOXML file structure broken/invalid - no core document found!");
  684. }
  685. }