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

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