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.

PackagingURIHelper.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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.nio.ByteBuffer;
  19. import java.nio.charset.StandardCharsets;
  20. import java.util.regex.Pattern;
  21. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  22. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  23. import org.apache.poi.util.POILogFactory;
  24. import org.apache.poi.util.POILogger;
  25. /**
  26. * Helper for part and pack URI.
  27. *
  28. * @author Julien Chable, CDubet, Kim Ung
  29. * @version 0.1
  30. */
  31. public final class PackagingURIHelper {
  32. // FIXME: this class implements a lot of path joining and splitting logic that
  33. // is already implemented in java.nio.file.Path.
  34. // This class should heavily leverage Java library code to reduce the number of lines of code that POI has to maintain and test
  35. private final static POILogger _logger = POILogFactory.getLogger(PackagingURIHelper.class);
  36. /**
  37. * Package root URI.
  38. */
  39. private static URI packageRootUri;
  40. /**
  41. * Extension name of a relationship part.
  42. */
  43. public static final String RELATIONSHIP_PART_EXTENSION_NAME = ".rels";
  44. /**
  45. * Segment name of a relationship part.
  46. */
  47. public static final String RELATIONSHIP_PART_SEGMENT_NAME = "_rels";
  48. /**
  49. * Segment name of the package properties folder.
  50. */
  51. public static final String PACKAGE_PROPERTIES_SEGMENT_NAME = "docProps";
  52. /**
  53. * Core package properties art name.
  54. */
  55. public static final String PACKAGE_CORE_PROPERTIES_NAME = "core.xml";
  56. /**
  57. * Forward slash URI separator.
  58. */
  59. public static final char FORWARD_SLASH_CHAR = '/';
  60. /**
  61. * Forward slash URI separator.
  62. */
  63. public static final String FORWARD_SLASH_STRING = "/";
  64. /**
  65. * Package relationships part URI
  66. */
  67. public static final URI PACKAGE_RELATIONSHIPS_ROOT_URI;
  68. /**
  69. * Package relationships part name.
  70. */
  71. public static final PackagePartName PACKAGE_RELATIONSHIPS_ROOT_PART_NAME;
  72. /**
  73. * Core properties part URI.
  74. */
  75. public static final URI CORE_PROPERTIES_URI;
  76. /**
  77. * Core properties partname.
  78. */
  79. public static final PackagePartName CORE_PROPERTIES_PART_NAME;
  80. /**
  81. * Root package URI.
  82. */
  83. public static final URI PACKAGE_ROOT_URI;
  84. /**
  85. * Root package part name.
  86. */
  87. public static final PackagePartName PACKAGE_ROOT_PART_NAME;
  88. /* Static initialization */
  89. static {
  90. // Make URI
  91. URI uriPACKAGE_ROOT_URI = null;
  92. URI uriPACKAGE_RELATIONSHIPS_ROOT_URI = null;
  93. URI uriPACKAGE_PROPERTIES_URI = null;
  94. try {
  95. uriPACKAGE_ROOT_URI = new URI("/");
  96. uriPACKAGE_RELATIONSHIPS_ROOT_URI = new URI(FORWARD_SLASH_CHAR
  97. + RELATIONSHIP_PART_SEGMENT_NAME + FORWARD_SLASH_CHAR
  98. + RELATIONSHIP_PART_EXTENSION_NAME);
  99. packageRootUri = new URI("/");
  100. uriPACKAGE_PROPERTIES_URI = new URI(FORWARD_SLASH_CHAR
  101. + PACKAGE_PROPERTIES_SEGMENT_NAME + FORWARD_SLASH_CHAR
  102. + PACKAGE_CORE_PROPERTIES_NAME);
  103. } catch (URISyntaxException e) {
  104. // Should never happen in production as all data are fixed
  105. }
  106. PACKAGE_ROOT_URI = uriPACKAGE_ROOT_URI;
  107. PACKAGE_RELATIONSHIPS_ROOT_URI = uriPACKAGE_RELATIONSHIPS_ROOT_URI;
  108. CORE_PROPERTIES_URI = uriPACKAGE_PROPERTIES_URI;
  109. // Make part name from previous URI
  110. PackagePartName tmpPACKAGE_ROOT_PART_NAME = null;
  111. PackagePartName tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = null;
  112. PackagePartName tmpCORE_PROPERTIES_URI = null;
  113. try {
  114. tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI);
  115. tmpCORE_PROPERTIES_URI = createPartName(CORE_PROPERTIES_URI);
  116. tmpPACKAGE_ROOT_PART_NAME = new PackagePartName(PACKAGE_ROOT_URI,
  117. false);
  118. } catch (InvalidFormatException e) {
  119. // Should never happen in production as all data are fixed
  120. }
  121. PACKAGE_RELATIONSHIPS_ROOT_PART_NAME = tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME;
  122. CORE_PROPERTIES_PART_NAME = tmpCORE_PROPERTIES_URI;
  123. PACKAGE_ROOT_PART_NAME = tmpPACKAGE_ROOT_PART_NAME;
  124. }
  125. private static final Pattern missingAuthPattern = Pattern.compile("\\w+://");
  126. /**
  127. * Gets the URI for the package root.
  128. *
  129. * @return URI of the package root.
  130. */
  131. public static URI getPackageRootUri() {
  132. return packageRootUri;
  133. }
  134. /**
  135. * Know if the specified URI is a relationship part name.
  136. *
  137. * @param partUri
  138. * URI to check.
  139. * @return <i>true</i> if the URI <i>false</i>.
  140. */
  141. public static boolean isRelationshipPartURI(URI partUri) {
  142. if (partUri == null)
  143. throw new IllegalArgumentException("partUri");
  144. return partUri.getPath().matches(
  145. ".*" + RELATIONSHIP_PART_SEGMENT_NAME + ".*"
  146. + RELATIONSHIP_PART_EXTENSION_NAME + "$");
  147. }
  148. /**
  149. * Get file name from the specified URI.
  150. */
  151. public static String getFilename(URI uri) {
  152. if (uri != null) {
  153. String path = uri.getPath();
  154. int len = path.length();
  155. int num2 = len;
  156. while (--num2 >= 0) {
  157. char ch1 = path.charAt(num2);
  158. if (ch1 == PackagingURIHelper.FORWARD_SLASH_CHAR)
  159. return path.substring(num2 + 1, len);
  160. }
  161. }
  162. return "";
  163. }
  164. /**
  165. * Get the file name without the trailing extension.
  166. */
  167. public static String getFilenameWithoutExtension(URI uri) {
  168. String filename = getFilename(uri);
  169. int dotIndex = filename.lastIndexOf(".");
  170. if (dotIndex == -1)
  171. return filename;
  172. return filename.substring(0, dotIndex);
  173. }
  174. /**
  175. * Get the directory path from the specified URI.
  176. */
  177. public static URI getPath(URI uri) {
  178. if (uri != null) {
  179. String path = uri.getPath();
  180. int num2 = path.length();
  181. while (--num2 >= 0) {
  182. char ch1 = path.charAt(num2);
  183. if (ch1 == PackagingURIHelper.FORWARD_SLASH_CHAR) {
  184. try {
  185. return new URI(path.substring(0, num2));
  186. } catch (URISyntaxException e) {
  187. return null;
  188. }
  189. }
  190. }
  191. }
  192. return null;
  193. }
  194. /**
  195. * Combine two URIs.
  196. *
  197. * @param prefix the prefix URI
  198. * @param suffix the suffix URI
  199. *
  200. * @return the combined URI
  201. */
  202. public static URI combine(URI prefix, URI suffix) {
  203. URI retUri;
  204. try {
  205. retUri = new URI(combine(prefix.getPath(), suffix.getPath()));
  206. } catch (URISyntaxException e) {
  207. throw new IllegalArgumentException(
  208. "Prefix and suffix can't be combine !");
  209. }
  210. return retUri;
  211. }
  212. /**
  213. * Combine a string URI with a prefix and a suffix.
  214. */
  215. public static String combine(String prefix, String suffix) {
  216. if (!prefix.endsWith(FORWARD_SLASH_STRING) && !suffix.startsWith(FORWARD_SLASH_STRING))
  217. return prefix + FORWARD_SLASH_CHAR + suffix;
  218. else if (prefix.endsWith(FORWARD_SLASH_STRING) ^ suffix.startsWith(FORWARD_SLASH_STRING))
  219. return prefix + suffix;
  220. else
  221. return "";
  222. }
  223. /**
  224. * Fully relativize the source part URI against the target part URI.
  225. *
  226. * @param sourceURI
  227. * The source part URI.
  228. * @param targetURI
  229. * The target part URI.
  230. * @param msCompatible if true then remove leading slash from the relativized URI.
  231. * This flag violates [M1.4]: A part name shall start with a forward slash ('/') character, but
  232. * allows generating URIs compatible with MS Office and OpenOffice.
  233. * @return A fully relativize part name URI ('word/media/image1.gif',
  234. * '/word/document.xml' => 'media/image1.gif') else
  235. * <code>null</code>.
  236. */
  237. public static URI relativizeURI(URI sourceURI, URI targetURI, boolean msCompatible) {
  238. StringBuilder retVal = new StringBuilder();
  239. String[] segmentsSource = sourceURI.getPath().split("/", -1);
  240. String[] segmentsTarget = targetURI.getPath().split("/", -1);
  241. // If the source URI is empty
  242. if (segmentsSource.length == 0) {
  243. throw new IllegalArgumentException(
  244. "Can't relativize an empty source URI !");
  245. }
  246. // If target URI is empty
  247. if (segmentsTarget.length == 0) {
  248. throw new IllegalArgumentException(
  249. "Can't relativize an empty target URI !");
  250. }
  251. // If the source is the root, then the relativized
  252. // form must actually be an absolute URI
  253. if(sourceURI.toString().equals("/")) {
  254. String path = targetURI.getPath();
  255. if(msCompatible && path.length() > 0 && path.charAt(0) == '/') {
  256. try {
  257. targetURI = new URI(path.substring(1));
  258. } catch (Exception e) {
  259. _logger.log(POILogger.WARN, e);
  260. return null;
  261. }
  262. }
  263. return targetURI;
  264. }
  265. // Relativize the source URI against the target URI.
  266. // First up, figure out how many steps along we can go
  267. // and still have them be the same
  268. int segmentsTheSame = 0;
  269. for (int i = 0; i < segmentsSource.length && i < segmentsTarget.length; i++) {
  270. if (segmentsSource[i].equals(segmentsTarget[i])) {
  271. // Match so far, good
  272. segmentsTheSame++;
  273. } else {
  274. break;
  275. }
  276. }
  277. // If we didn't have a good match or at least except a first empty element
  278. if ((segmentsTheSame == 0 || segmentsTheSame == 1) &&
  279. segmentsSource[0].isEmpty() && segmentsTarget[0].isEmpty()) {
  280. for (int i = 0; i < segmentsSource.length - 2; i++) {
  281. retVal.append("../");
  282. }
  283. for (int i = 0; i < segmentsTarget.length; i++) {
  284. if (segmentsTarget[i].isEmpty())
  285. continue;
  286. retVal.append(segmentsTarget[i]);
  287. if (i != segmentsTarget.length - 1)
  288. retVal.append("/");
  289. }
  290. try {
  291. return new URI(retVal.toString());
  292. } catch (Exception e) {
  293. _logger.log(POILogger.WARN, e);
  294. return null;
  295. }
  296. }
  297. // Special case for where the two are the same
  298. if (segmentsTheSame == segmentsSource.length
  299. && segmentsTheSame == segmentsTarget.length) {
  300. if(sourceURI.equals(targetURI)){
  301. // if source and target are the same they should be resolved to the last segment,
  302. // Example: if a slide references itself, e.g. the source URI is
  303. // "/ppt/slides/slide1.xml" and the targetURI is "slide1.xml" then
  304. // this it should be relativized as "slide1.xml", i.e. the last segment.
  305. retVal.append(segmentsSource[segmentsSource.length - 1]);
  306. }
  307. } else {
  308. // Matched for so long, but no more
  309. // Do we need to go up a directory or two from
  310. // the source to get here?
  311. // (If it's all the way up, then don't bother!)
  312. if (segmentsTheSame == 1) {
  313. retVal.append("/");
  314. } else {
  315. for (int j = segmentsTheSame; j < segmentsSource.length - 1; j++) {
  316. retVal.append("../");
  317. }
  318. }
  319. // Now go from here on down
  320. for (int j = segmentsTheSame; j < segmentsTarget.length; j++) {
  321. if (retVal.length() > 0
  322. && retVal.charAt(retVal.length() - 1) != '/') {
  323. retVal.append("/");
  324. }
  325. retVal.append(segmentsTarget[j]);
  326. }
  327. }
  328. // if the target had a fragment then append it to the result
  329. String fragment = targetURI.getRawFragment();
  330. if (fragment != null) {
  331. retVal.append("#").append(fragment);
  332. }
  333. try {
  334. return new URI(retVal.toString());
  335. } catch (Exception e) {
  336. _logger.log(POILogger.WARN, e);
  337. return null;
  338. }
  339. }
  340. /**
  341. * Fully relativize the source part URI against the target part URI.
  342. *
  343. * @param sourceURI
  344. * The source part URI.
  345. * @param targetURI
  346. * The target part URI.
  347. * @return A fully relativize part name URI ('word/media/image1.gif',
  348. * '/word/document.xml' => 'media/image1.gif') else
  349. * <code>null</code>.
  350. */
  351. public static URI relativizeURI(URI sourceURI, URI targetURI) {
  352. return relativizeURI(sourceURI, targetURI, false);
  353. }
  354. /**
  355. * Resolve a source uri against a target.
  356. *
  357. * @param sourcePartUri
  358. * The source URI.
  359. * @param targetUri
  360. * The target URI.
  361. * @return The resolved URI.
  362. */
  363. public static URI resolvePartUri(URI sourcePartUri, URI targetUri) {
  364. if (sourcePartUri == null || sourcePartUri.isAbsolute()) {
  365. throw new IllegalArgumentException("sourcePartUri invalid - "
  366. + sourcePartUri);
  367. }
  368. if (targetUri == null || targetUri.isAbsolute()) {
  369. throw new IllegalArgumentException("targetUri invalid - "
  370. + targetUri);
  371. }
  372. return sourcePartUri.resolve(targetUri);
  373. }
  374. /**
  375. * Get URI from a string path.
  376. */
  377. public static URI getURIFromPath(String path) {
  378. URI retUri;
  379. try {
  380. retUri = toURI(path);
  381. } catch (URISyntaxException e) {
  382. throw new IllegalArgumentException("path");
  383. }
  384. return retUri;
  385. }
  386. /**
  387. * Get the source part URI from a specified relationships part.
  388. *
  389. * @param relationshipPartUri
  390. * The relationship part use to retrieve the source part.
  391. * @return The source part URI from the specified relationships part.
  392. */
  393. public static URI getSourcePartUriFromRelationshipPartUri(
  394. URI relationshipPartUri) {
  395. if (relationshipPartUri == null)
  396. throw new IllegalArgumentException(
  397. "Must not be null");
  398. if (!isRelationshipPartURI(relationshipPartUri))
  399. throw new IllegalArgumentException(
  400. "Must be a relationship part");
  401. if (relationshipPartUri.compareTo(PACKAGE_RELATIONSHIPS_ROOT_URI) == 0)
  402. return PACKAGE_ROOT_URI;
  403. String filename = relationshipPartUri.getPath();
  404. String filenameWithoutExtension = getFilenameWithoutExtension(relationshipPartUri);
  405. filename = filename
  406. .substring(0, ((filename.length() - filenameWithoutExtension
  407. .length()) - RELATIONSHIP_PART_EXTENSION_NAME.length()));
  408. filename = filename.substring(0, filename.length()
  409. - RELATIONSHIP_PART_SEGMENT_NAME.length() - 1);
  410. filename = combine(filename, filenameWithoutExtension);
  411. return getURIFromPath(filename);
  412. }
  413. /**
  414. * Create an OPC compliant part name by throwing an exception if the URI is
  415. * not valid.
  416. *
  417. * @param partUri
  418. * The part name URI to validate.
  419. * @return A valid part name object, else <code>null</code>.
  420. * @throws InvalidFormatException
  421. * Throws if the specified URI is not OPC compliant.
  422. */
  423. public static PackagePartName createPartName(URI partUri)
  424. throws InvalidFormatException {
  425. if (partUri == null)
  426. throw new IllegalArgumentException("partName");
  427. return new PackagePartName(partUri, true);
  428. }
  429. /**
  430. * Create an OPC compliant part name.
  431. *
  432. * @param partName
  433. * The part name to validate.
  434. * @return The correspondant part name if valid, else <code>null</code>.
  435. * @throws InvalidFormatException
  436. * Throws if the specified part name is not OPC compliant.
  437. * @see #createPartName(URI)
  438. */
  439. public static PackagePartName createPartName(String partName)
  440. throws InvalidFormatException {
  441. URI partNameURI;
  442. try {
  443. partNameURI = toURI(partName);
  444. } catch (URISyntaxException e) {
  445. throw new InvalidFormatException(e.getMessage());
  446. }
  447. return createPartName(partNameURI);
  448. }
  449. /**
  450. * Create an OPC compliant part name by resolving it using a base part.
  451. *
  452. * @param partName
  453. * The part name to validate.
  454. * @param relativePart
  455. * The relative base part.
  456. * @return The correspondant part name if valid, else <code>null</code>.
  457. * @throws InvalidFormatException
  458. * Throws if the specified part name is not OPC compliant.
  459. * @see #createPartName(URI)
  460. */
  461. public static PackagePartName createPartName(String partName,
  462. PackagePart relativePart) throws InvalidFormatException {
  463. URI newPartNameURI;
  464. try {
  465. newPartNameURI = resolvePartUri(
  466. relativePart.getPartName().getURI(), new URI(partName));
  467. } catch (URISyntaxException e) {
  468. throw new InvalidFormatException(e.getMessage());
  469. }
  470. return createPartName(newPartNameURI);
  471. }
  472. /**
  473. * Create an OPC compliant part name by resolving it using a base part.
  474. *
  475. * @param partName
  476. * The part name URI to validate.
  477. * @param relativePart
  478. * The relative base part.
  479. * @return The correspondant part name if valid, else <code>null</code>.
  480. * @throws InvalidFormatException
  481. * Throws if the specified part name is not OPC compliant.
  482. * @see #createPartName(URI)
  483. */
  484. public static PackagePartName createPartName(URI partName,
  485. PackagePart relativePart) throws InvalidFormatException {
  486. URI newPartNameURI = resolvePartUri(
  487. relativePart.getPartName().getURI(), partName);
  488. return createPartName(newPartNameURI);
  489. }
  490. /**
  491. * Validate a part URI by returning a boolean.
  492. * ([M1.1],[M1.3],[M1.4],[M1.5],[M1.6])
  493. *
  494. * (OPC Specifications 8.1.1 Part names) :
  495. *
  496. * Part Name Syntax
  497. *
  498. * The part name grammar is defined as follows:
  499. *
  500. * <i>part_name = 1*( "/" segment )
  501. *
  502. * segment = 1*( pchar )</i>
  503. *
  504. *
  505. * (pchar is defined in RFC 3986)
  506. *
  507. * @param partUri
  508. * The URI to validate.
  509. * @return <b>true</b> if the URI is valid to the OPC Specifications, else
  510. * <b>false</b>
  511. *
  512. * @see #createPartName(URI)
  513. */
  514. public static boolean isValidPartName(URI partUri) {
  515. if (partUri == null)
  516. throw new IllegalArgumentException("partUri");
  517. try {
  518. createPartName(partUri);
  519. return true;
  520. } catch (Exception e) {
  521. return false;
  522. }
  523. }
  524. /**
  525. * Decode a URI by converting all percent encoded character into a String
  526. * character.
  527. *
  528. * @param uri
  529. * The URI to decode.
  530. * @return The specified URI in a String with converted percent encoded
  531. * characters.
  532. */
  533. public static String decodeURI(URI uri) {
  534. StringBuilder retVal = new StringBuilder(64);
  535. String uriStr = uri.toASCIIString();
  536. char c;
  537. final int length = uriStr.length();
  538. for (int i = 0; i < length; ++i) {
  539. c = uriStr.charAt(i);
  540. if (c == '%') {
  541. // We certainly found an encoded character, check for length
  542. // now ( '%' HEXDIGIT HEXDIGIT)
  543. if (((length - i) < 2)) {
  544. throw new IllegalArgumentException("The uri " + uriStr
  545. + " contain invalid encoded character !");
  546. }
  547. // Decode the encoded character
  548. char decodedChar = (char) Integer.parseInt(uriStr.substring(
  549. i + 1, i + 3), 16);
  550. retVal.append(decodedChar);
  551. i += 2;
  552. continue;
  553. }
  554. retVal.append(c);
  555. }
  556. return retVal.toString();
  557. }
  558. /**
  559. * Build a part name where the relationship should be stored ((ex
  560. * /word/document.xml -> /word/_rels/document.xml.rels)
  561. *
  562. * @param partName
  563. * Source part URI
  564. * @return the full path (as URI) of the relation file
  565. * @throws InvalidOperationException
  566. * Throws if the specified URI is a relationshp part.
  567. */
  568. public static PackagePartName getRelationshipPartName(
  569. PackagePartName partName) {
  570. if (partName == null)
  571. throw new IllegalArgumentException("partName");
  572. if (PackagingURIHelper.PACKAGE_ROOT_URI.getPath().equals(
  573. partName.getURI().getPath()) )
  574. return PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME;
  575. if (partName.isRelationshipPartURI())
  576. throw new InvalidOperationException("Can't be a relationship part");
  577. String fullPath = partName.getURI().getPath();
  578. String filename = getFilename(partName.getURI());
  579. fullPath = fullPath.substring(0, fullPath.length() - filename.length());
  580. fullPath = combine(fullPath,
  581. PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME);
  582. fullPath = combine(fullPath, filename);
  583. fullPath = fullPath
  584. + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME;
  585. PackagePartName retPartName;
  586. try {
  587. retPartName = createPartName(fullPath);
  588. } catch (InvalidFormatException e) {
  589. // Should never happen in production as all data are fixed but in
  590. // case of return null:
  591. return null;
  592. }
  593. return retPartName;
  594. }
  595. /**
  596. * Convert a string to {@link java.net.URI}
  597. *
  598. * If part name is not a valid URI, it is resolved as follows:
  599. * <p>
  600. * 1. Percent-encode each open bracket ([) and close bracket (]).</li>
  601. * 2. Percent-encode each percent (%) character that is not followed by a hexadecimal notation of an octet value.</li>
  602. * 3. Un-percent-encode each percent-encoded unreserved character.
  603. * 4. Un-percent-encode each forward slash (/) and back slash (\).
  604. * 5. Convert all back slashes to forward slashes.
  605. * 6. If present in a segment containing non-dot (?.?) characters, remove trailing dot (?.?) characters from each segment.
  606. * 7. Replace each occurrence of multiple consecutive forward slashes (/) with a single forward slash.
  607. * 8. If a single trailing forward slash (/) is present, remove that trailing forward slash.
  608. * 9. Remove complete segments that consist of three or more dots.
  609. * 10. Resolve the relative reference against the base URI of the part holding the Unicode string, as it is defined
  610. * in ?5.2 of RFC 3986. The path component of the resulting absolute URI is the part name.
  611. *</p>
  612. *
  613. * @param value the string to be parsed into a URI
  614. * @return the resolved part name that should be OK to construct a URI
  615. *
  616. * TODO YK: for now this method does only (5). Finish the rest.
  617. */
  618. public static URI toURI(String value) throws URISyntaxException {
  619. //5. Convert all back slashes to forward slashes
  620. if (value.contains("\\")) {
  621. value = value.replace('\\', '/');
  622. }
  623. // URI fragemnts (those starting with '#') are not encoded
  624. // and may contain white spaces and raw unicode characters
  625. int fragmentIdx = value.indexOf('#');
  626. if(fragmentIdx != -1){
  627. String path = value.substring(0, fragmentIdx);
  628. String fragment = value.substring(fragmentIdx + 1);
  629. value = path + "#" + encode(fragment);
  630. }
  631. // trailing white spaces must be url-encoded, see Bugzilla 53282
  632. if(value.length() > 0 ){
  633. StringBuilder b = new StringBuilder();
  634. int idx = value.length() - 1;
  635. for(; idx >= 0; idx--){
  636. char c = value.charAt(idx);
  637. if(Character.isWhitespace(c) || c == '\u00A0') {
  638. b.append(c);
  639. } else {
  640. break;
  641. }
  642. }
  643. if(b.length() > 0){
  644. value = value.substring(0, idx+1) + encode(b.reverse().toString());
  645. }
  646. }
  647. // MS Office can insert URIs with missing authority, e.g. "http://" or "javascript://"
  648. // append a forward slash to avoid parse exception
  649. if(missingAuthPattern.matcher(value).matches()){
  650. value += "/";
  651. }
  652. return new URI(value);
  653. }
  654. /**
  655. * percent-encode white spaces and characters above 0x80.
  656. * <p>
  657. * Examples:
  658. * 'Apache POI' --> 'Apache%20POI'
  659. * 'Apache\u0410POI' --> 'Apache%04%10POI'
  660. *
  661. * @param s the string to encode
  662. * @return the encoded string
  663. */
  664. public static String encode(String s) {
  665. int n = s.length();
  666. if (n == 0) return s;
  667. ByteBuffer bb = ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8));
  668. StringBuilder sb = new StringBuilder();
  669. while (bb.hasRemaining()) {
  670. int b = bb.get() & 0xff;
  671. if (isUnsafe(b)) {
  672. sb.append('%');
  673. sb.append(hexDigits[(b >> 4) & 0x0F]);
  674. sb.append(hexDigits[(b >> 0) & 0x0F]);
  675. } else {
  676. sb.append((char)b);
  677. }
  678. }
  679. return sb.toString();
  680. }
  681. private final static char[] hexDigits = {
  682. '0', '1', '2', '3', '4', '5', '6', '7',
  683. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  684. };
  685. private static boolean isUnsafe(int ch) {
  686. return ch >= 0x80 || Character.isWhitespace(ch);
  687. }
  688. }