Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

POIXMLDocumentPart.java 31KB

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