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

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