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.

PackageRelationshipCollection.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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.openxml4j.opc;
  16. import java.net.URI;
  17. import java.net.URISyntaxException;
  18. import java.util.ArrayList;
  19. import java.util.Iterator;
  20. import java.util.Locale;
  21. import java.util.TreeMap;
  22. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  23. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  24. import org.apache.poi.util.DocumentHelper;
  25. import org.apache.poi.util.POILogFactory;
  26. import org.apache.poi.util.POILogger;
  27. import org.w3c.dom.Attr;
  28. import org.w3c.dom.Document;
  29. import org.w3c.dom.Element;
  30. import org.w3c.dom.NodeList;
  31. /**
  32. * Represents a collection of PackageRelationship elements that are owned by a
  33. * given PackagePart or the Package.
  34. *
  35. * @author Julien Chable, CDubettier
  36. * @version 0.1
  37. */
  38. public final class PackageRelationshipCollection implements
  39. Iterable<PackageRelationship> {
  40. private static POILogger logger = POILogFactory.getLogger(PackageRelationshipCollection.class);
  41. /**
  42. * Package relationships ordered by ID.
  43. */
  44. private TreeMap<String, PackageRelationship> relationshipsByID;
  45. /**
  46. * Package relationships ordered by type.
  47. */
  48. private TreeMap<String, PackageRelationship> relationshipsByType;
  49. /**
  50. * This relationshipPart.
  51. */
  52. private PackagePart relationshipPart;
  53. /**
  54. * Source part.
  55. */
  56. private PackagePart sourcePart;
  57. /**
  58. * This part name.
  59. */
  60. private PackagePartName partName;
  61. /**
  62. * Reference to the package.
  63. */
  64. private OPCPackage container;
  65. /**
  66. * The ID number of the next rID# to generate, or -1
  67. * if that is still to be determined.
  68. */
  69. private int nextRelationshipId = -1;
  70. /**
  71. * Constructor.
  72. */
  73. PackageRelationshipCollection() {
  74. relationshipsByID = new TreeMap<String, PackageRelationship>();
  75. relationshipsByType = new TreeMap<String, PackageRelationship>();
  76. }
  77. /**
  78. * Copy constructor.
  79. *
  80. * This collection will contain only elements from the specified collection
  81. * for which the type is compatible with the specified relationship type
  82. * filter.
  83. *
  84. * @param coll
  85. * Collection to import.
  86. * @param filter
  87. * Relationship type filter.
  88. */
  89. public PackageRelationshipCollection(PackageRelationshipCollection coll,
  90. String filter) {
  91. this();
  92. for (PackageRelationship rel : coll.relationshipsByID.values()) {
  93. if (filter == null || rel.getRelationshipType().equals(filter))
  94. addRelationship(rel);
  95. }
  96. }
  97. /**
  98. * Constructor.
  99. */
  100. public PackageRelationshipCollection(OPCPackage container)
  101. throws InvalidFormatException {
  102. this(container, null);
  103. }
  104. /**
  105. * Constructor.
  106. *
  107. * @throws InvalidFormatException
  108. * Throws if the format of the content part is invalid.
  109. *
  110. * @throws InvalidOperationException
  111. * Throws if the specified part is a relationship part.
  112. */
  113. public PackageRelationshipCollection(PackagePart part)
  114. throws InvalidFormatException {
  115. this(part._container, part);
  116. }
  117. /**
  118. * Constructor. Parse the existing package relationship part if one exists.
  119. *
  120. * @param container
  121. * The parent package.
  122. * @param part
  123. * The part that own this relationships collection. If <b>null</b>
  124. * then this part is considered as the package root.
  125. * @throws InvalidFormatException
  126. * If an error occurs during the parsing of the relatinships
  127. * part fo the specified part.
  128. */
  129. public PackageRelationshipCollection(OPCPackage container, PackagePart part)
  130. throws InvalidFormatException {
  131. this();
  132. if (container == null)
  133. throw new IllegalArgumentException("container");
  134. // Check if the specified part is not a relationship part
  135. if (part != null && part.isRelationshipPart())
  136. throw new IllegalArgumentException("part");
  137. this.container = container;
  138. this.sourcePart = part;
  139. this.partName = getRelationshipPartName(part);
  140. if ((container.getPackageAccess() != PackageAccess.WRITE)
  141. && container.containPart(this.partName)) {
  142. relationshipPart = container.getPart(this.partName);
  143. parseRelationshipsPart(relationshipPart);
  144. }
  145. }
  146. /**
  147. * Get the relationship part name of the specified part.
  148. *
  149. * @param part
  150. * The part .
  151. * @return The relationship part name of the specified part. Be careful,
  152. * only the correct name is returned, this method does not check if
  153. * the part really exist in a package !
  154. * @throws InvalidOperationException
  155. * Throws if the specified part is a relationship part.
  156. */
  157. private static PackagePartName getRelationshipPartName(PackagePart part)
  158. throws InvalidOperationException {
  159. PackagePartName partName;
  160. if (part == null) {
  161. partName = PackagingURIHelper.PACKAGE_ROOT_PART_NAME;
  162. } else {
  163. partName = part.getPartName();
  164. }
  165. return PackagingURIHelper.getRelationshipPartName(partName);
  166. }
  167. /**
  168. * Add the specified relationship to the collection.
  169. *
  170. * @param relPart
  171. * The relationship to add.
  172. */
  173. public void addRelationship(PackageRelationship relPart) {
  174. relationshipsByID.put(relPart.getId(), relPart);
  175. relationshipsByType.put(relPart.getRelationshipType(), relPart);
  176. }
  177. /**
  178. * Add a relationship to the collection.
  179. *
  180. * @param targetUri
  181. * Target URI.
  182. * @param targetMode
  183. * The target mode : INTERNAL or EXTERNAL
  184. * @param relationshipType
  185. * Relationship type.
  186. * @param id
  187. * Relationship ID.
  188. * @return The newly created relationship.
  189. * @see PackageAccess
  190. */
  191. public PackageRelationship addRelationship(URI targetUri,
  192. TargetMode targetMode, String relationshipType, String id) {
  193. if (id == null) {
  194. // Generate a unique ID is id parameter is null.
  195. if (nextRelationshipId == -1) {
  196. nextRelationshipId = size() + 1;
  197. }
  198. // Work up until we find a unique number (there could be gaps etc)
  199. do {
  200. id = "rId" + nextRelationshipId++;
  201. } while (relationshipsByID.get(id) != null);
  202. }
  203. PackageRelationship rel = new PackageRelationship(container,
  204. sourcePart, targetUri, targetMode, relationshipType, id);
  205. relationshipsByID.put(rel.getId(), rel);
  206. relationshipsByType.put(rel.getRelationshipType(), rel);
  207. return rel;
  208. }
  209. /**
  210. * Remove a relationship by its ID.
  211. *
  212. * @param id
  213. * The relationship ID to remove.
  214. */
  215. public void removeRelationship(String id) {
  216. if (relationshipsByID != null && relationshipsByType != null) {
  217. PackageRelationship rel = relationshipsByID.get(id);
  218. if (rel != null) {
  219. relationshipsByID.remove(rel.getId());
  220. relationshipsByType.values().remove(rel);
  221. }
  222. }
  223. }
  224. /**
  225. * Remove a relationship by its reference.
  226. *
  227. * @param rel
  228. * The relationship to delete.
  229. */
  230. public void removeRelationship(PackageRelationship rel) {
  231. if (rel == null)
  232. throw new IllegalArgumentException("rel");
  233. relationshipsByID.values().remove(rel);
  234. relationshipsByType.values().remove(rel);
  235. }
  236. /**
  237. * Retrieves a relationship by its index in the collection.
  238. *
  239. * @param index
  240. * Must be a value between [0-relationships_count-1]
  241. */
  242. public PackageRelationship getRelationship(int index) {
  243. if (index < 0 || index > relationshipsByID.values().size())
  244. throw new IllegalArgumentException("index");
  245. int i = 0;
  246. for (PackageRelationship rel : relationshipsByID.values()) {
  247. if (index == i++)
  248. return rel;
  249. }
  250. return null;
  251. }
  252. /**
  253. * Retrieves a package relationship based on its id.
  254. *
  255. * @param id
  256. * ID of the package relationship to retrieve.
  257. * @return The package relationship identified by the specified id.
  258. */
  259. public PackageRelationship getRelationshipByID(String id) {
  260. return relationshipsByID.get(id);
  261. }
  262. /**
  263. * Get the numbe rof relationships in the collection.
  264. */
  265. public int size() {
  266. return relationshipsByID.values().size();
  267. }
  268. /**
  269. * Parse the relationship part and add all relationship in this collection.
  270. *
  271. * @param relPart
  272. * The package part to parse.
  273. * @throws InvalidFormatException
  274. * Throws if the relationship part is invalid.
  275. */
  276. public void parseRelationshipsPart(PackagePart relPart)
  277. throws InvalidFormatException {
  278. try {
  279. logger.log(POILogger.DEBUG, "Parsing relationship: " + relPart.getPartName());
  280. Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream());
  281. // Browse default types
  282. Element root = xmlRelationshipsDoc.getDocumentElement();
  283. // Check OPC compliance M4.1 rule
  284. boolean fCorePropertiesRelationship = false;
  285. NodeList nodeList = root.getElementsByTagNameNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIP_TAG_NAME);
  286. int nodeCount = nodeList.getLength();
  287. for (int i = 0; i < nodeCount; i++) {
  288. Element element = (Element)nodeList.item(i);
  289. // Relationship ID
  290. String id = element.getAttribute(PackageRelationship.ID_ATTRIBUTE_NAME);
  291. // Relationship type
  292. String type = element.getAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME);
  293. /* Check OPC Compliance */
  294. // Check Rule M4.1
  295. if (type.equals(PackageRelationshipTypes.CORE_PROPERTIES))
  296. if (!fCorePropertiesRelationship)
  297. fCorePropertiesRelationship = true;
  298. else
  299. throw new InvalidFormatException(
  300. "OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !");
  301. /* End OPC Compliance */
  302. // TargetMode (default value "Internal")
  303. Attr targetModeAttr = element.getAttributeNode(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME);
  304. TargetMode targetMode = TargetMode.INTERNAL;
  305. if (targetModeAttr != null) {
  306. targetMode = targetModeAttr.getValue().toLowerCase(Locale.ROOT)
  307. .equals("internal") ? TargetMode.INTERNAL
  308. : TargetMode.EXTERNAL;
  309. }
  310. // Target converted in URI
  311. URI target = PackagingURIHelper.toURI("http://invalid.uri"); // dummy url
  312. String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
  313. try {
  314. // when parsing of the given uri fails, we can either
  315. // ignore this relationship, which leads to IllegalStateException
  316. // later on, or use a dummy value and thus enable processing of the
  317. // package
  318. target = PackagingURIHelper.toURI(value);
  319. } catch (URISyntaxException e) {
  320. logger.log(POILogger.ERROR, "Cannot convert " + value
  321. + " in a valid relationship URI-> dummy-URI used", e);
  322. }
  323. addRelationship(target, targetMode, type, id);
  324. }
  325. } catch (Exception e) {
  326. logger.log(POILogger.ERROR, e);
  327. throw new InvalidFormatException(e.getMessage());
  328. }
  329. }
  330. /**
  331. * Retrieves all relations with the specified type.
  332. *
  333. * @param typeFilter
  334. * Relationship type filter. If <b>null</b> then all
  335. * relationships are returned.
  336. * @return All relationships of the type specified by the filter.
  337. */
  338. public PackageRelationshipCollection getRelationships(String typeFilter) {
  339. PackageRelationshipCollection coll = new PackageRelationshipCollection(
  340. this, typeFilter);
  341. return coll;
  342. }
  343. /**
  344. * Get this collection's iterator.
  345. */
  346. public Iterator<PackageRelationship> iterator() {
  347. return relationshipsByID.values().iterator();
  348. }
  349. /**
  350. * Get an iterator of a collection with all relationship with the specified
  351. * type.
  352. *
  353. * @param typeFilter
  354. * Type filter.
  355. * @return An iterator to a collection containing all relationships with the
  356. * specified type contain in this collection.
  357. */
  358. public Iterator<PackageRelationship> iterator(String typeFilter) {
  359. ArrayList<PackageRelationship> retArr = new ArrayList<PackageRelationship>();
  360. for (PackageRelationship rel : relationshipsByID.values()) {
  361. if (rel.getRelationshipType().equals(typeFilter))
  362. retArr.add(rel);
  363. }
  364. return retArr.iterator();
  365. }
  366. /**
  367. * Clear all relationships.
  368. */
  369. public void clear() {
  370. relationshipsByID.clear();
  371. relationshipsByType.clear();
  372. }
  373. @Override
  374. public String toString() {
  375. String str;
  376. if (relationshipsByID == null) {
  377. str = "relationshipsByID=null";
  378. } else {
  379. str = relationshipsByID.size() + " relationship(s) = [";
  380. }
  381. if ((relationshipPart != null) && (relationshipPart._partName != null)) {
  382. str = str + "," + relationshipPart._partName;
  383. } else {
  384. str = str + ",relationshipPart=null";
  385. }
  386. // Source of this relationship
  387. if ((sourcePart != null) && (sourcePart._partName != null)) {
  388. str = str + "," + sourcePart._partName;
  389. } else {
  390. str = str + ",sourcePart=null";
  391. }
  392. if (partName != null) {
  393. str = str + "," + partName;
  394. } else {
  395. str = str + ",uri=null)";
  396. }
  397. return str + "]";
  398. }
  399. }