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

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