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

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