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.

URIish.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. /*
  2. * Copyright (C) 2009, Mykola Nikishov <mn@mn.com.ua>
  3. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  5. * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
  6. * Copyright (C) 2013, Robin Stocker <robin@nibor.org>
  7. * Copyright (C) 2015, Patrick Steinhardt <ps@pks.im>
  8. * and other copyright owners as documented in the project's IP log.
  9. *
  10. * This program and the accompanying materials are made available
  11. * under the terms of the Eclipse Distribution License v1.0 which
  12. * accompanies this distribution, is reproduced below, and is
  13. * available at http://www.eclipse.org/org/documents/edl-v10.php
  14. *
  15. * All rights reserved.
  16. *
  17. * Redistribution and use in source and binary forms, with or
  18. * without modification, are permitted provided that the following
  19. * conditions are met:
  20. *
  21. * - Redistributions of source code must retain the above copyright
  22. * notice, this list of conditions and the following disclaimer.
  23. *
  24. * - Redistributions in binary form must reproduce the above
  25. * copyright notice, this list of conditions and the following
  26. * disclaimer in the documentation and/or other materials provided
  27. * with the distribution.
  28. *
  29. * - Neither the name of the Eclipse Foundation, Inc. nor the
  30. * names of its contributors may be used to endorse or promote
  31. * products derived from this software without specific prior
  32. * written permission.
  33. *
  34. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  35. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  36. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  38. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  39. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  41. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  42. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  43. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  44. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  45. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  46. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  47. */
  48. package org.eclipse.jgit.transport;
  49. import static java.nio.charset.StandardCharsets.UTF_8;
  50. import java.io.ByteArrayOutputStream;
  51. import java.io.File;
  52. import java.io.Serializable;
  53. import java.net.URISyntaxException;
  54. import java.net.URL;
  55. import java.util.BitSet;
  56. import java.util.regex.Matcher;
  57. import java.util.regex.Pattern;
  58. import org.eclipse.jgit.internal.JGitText;
  59. import org.eclipse.jgit.lib.Constants;
  60. import org.eclipse.jgit.util.RawParseUtils;
  61. import org.eclipse.jgit.util.StringUtils;
  62. /**
  63. * This URI like construct used for referencing Git archives over the net, as
  64. * well as locally stored archives. It is similar to RFC 2396 URI's, but also
  65. * support SCP and the malformed file://&lt;path&gt; syntax (as opposed to the correct
  66. * file:&lt;path&gt; syntax.
  67. */
  68. public class URIish implements Serializable {
  69. /**
  70. * Part of a pattern which matches the scheme part (git, http, ...) of an
  71. * URI. Defines one capturing group containing the scheme without the
  72. * trailing colon and slashes
  73. */
  74. private static final String SCHEME_P = "([a-z][a-z0-9+-]+)://"; //$NON-NLS-1$
  75. /**
  76. * Part of a pattern which matches the optional user/password part (e.g.
  77. * root:pwd@ in git://root:pwd@host.xyz/a.git) of URIs. Defines two
  78. * capturing groups: the first containing the user and the second containing
  79. * the password
  80. */
  81. private static final String OPT_USER_PWD_P = "(?:([^/:]+)(?::([^\\\\/]+))?@)?"; //$NON-NLS-1$
  82. /**
  83. * Part of a pattern which matches the host part of URIs. Defines one
  84. * capturing group containing the host name.
  85. */
  86. private static final String HOST_P = "((?:[^\\\\/:]+)|(?:\\[[0-9a-f:]+\\]))"; //$NON-NLS-1$
  87. /**
  88. * Part of a pattern which matches the optional port part of URIs. Defines
  89. * one capturing group containing the port without the preceding colon.
  90. */
  91. private static final String OPT_PORT_P = "(?::(\\d*))?"; //$NON-NLS-1$
  92. /**
  93. * Part of a pattern which matches the ~username part (e.g. /~root in
  94. * git://host.xyz/~root/a.git) of URIs. Defines no capturing group.
  95. */
  96. private static final String USER_HOME_P = "(?:/~(?:[^\\\\/]+))"; //$NON-NLS-1$
  97. /**
  98. * Part of a pattern which matches the optional drive letter in paths (e.g.
  99. * D: in file:///D:/a.txt). Defines no capturing group.
  100. */
  101. private static final String OPT_DRIVE_LETTER_P = "(?:[A-Za-z]:)?"; //$NON-NLS-1$
  102. /**
  103. * Part of a pattern which matches a relative path. Relative paths don't
  104. * start with slash or drive letters. Defines no capturing group.
  105. */
  106. private static final String RELATIVE_PATH_P = "(?:(?:[^\\\\/]+[\\\\/]+)*[^\\\\/]+[\\\\/]*)"; //$NON-NLS-1$
  107. /**
  108. * Part of a pattern which matches a relative or absolute path. Defines no
  109. * capturing group.
  110. */
  111. private static final String PATH_P = "(" + OPT_DRIVE_LETTER_P + "[\\\\/]?" //$NON-NLS-1$ //$NON-NLS-2$
  112. + RELATIVE_PATH_P + ")"; //$NON-NLS-1$
  113. private static final long serialVersionUID = 1L;
  114. /**
  115. * A pattern matching standard URI: </br>
  116. * <code>scheme "://" user_password? hostname? portnumber? path</code>
  117. */
  118. private static final Pattern FULL_URI = Pattern.compile("^" // //$NON-NLS-1$
  119. + SCHEME_P //
  120. + "(?:" // start a group containing hostname and all options only //$NON-NLS-1$
  121. // availabe when a hostname is there
  122. + OPT_USER_PWD_P //
  123. + HOST_P //
  124. + OPT_PORT_P //
  125. + "(" // open a group capturing the user-home-dir-part //$NON-NLS-1$
  126. + (USER_HOME_P + "?") //$NON-NLS-1$
  127. + "(?:" // start non capturing group for host //$NON-NLS-1$
  128. // separator or end of line
  129. + "[\\\\/])|$" //$NON-NLS-1$
  130. + ")" // close non capturing group for the host//$NON-NLS-1$
  131. // separator or end of line
  132. + ")?" // close the optional group containing hostname //$NON-NLS-1$
  133. + "(.+)?" //$NON-NLS-1$
  134. + "$"); //$NON-NLS-1$
  135. /**
  136. * A pattern matching the reference to a local file. This may be an absolute
  137. * path (maybe even containing windows drive-letters) or a relative path.
  138. */
  139. private static final Pattern LOCAL_FILE = Pattern.compile("^" // //$NON-NLS-1$
  140. + "([\\\\/]?" + PATH_P + ")" // //$NON-NLS-1$ //$NON-NLS-2$
  141. + "$"); //$NON-NLS-1$
  142. /**
  143. * A pattern matching a URI for the scheme 'file' which has only ':/' as
  144. * separator between scheme and path. Standard file URIs have '://' as
  145. * separator, but java.io.File.toURI() constructs those URIs.
  146. */
  147. private static final Pattern SINGLE_SLASH_FILE_URI = Pattern.compile("^" // //$NON-NLS-1$
  148. + "(file):([\\\\/](?![\\\\/])" // //$NON-NLS-1$
  149. + PATH_P //
  150. + ")$"); //$NON-NLS-1$
  151. /**
  152. * A pattern matching a SCP URI's of the form user@host:path/to/repo.git
  153. */
  154. private static final Pattern RELATIVE_SCP_URI = Pattern.compile("^" // //$NON-NLS-1$
  155. + OPT_USER_PWD_P //
  156. + HOST_P //
  157. + ":(" // //$NON-NLS-1$
  158. + ("(?:" + USER_HOME_P + "[\\\\/])?") // //$NON-NLS-1$ //$NON-NLS-2$
  159. + RELATIVE_PATH_P //
  160. + ")$"); //$NON-NLS-1$
  161. /**
  162. * A pattern matching a SCP URI's of the form user@host:/path/to/repo.git
  163. */
  164. private static final Pattern ABSOLUTE_SCP_URI = Pattern.compile("^" // //$NON-NLS-1$
  165. + OPT_USER_PWD_P //
  166. + "([^\\\\/:]{2,})" // //$NON-NLS-1$
  167. + ":(" // //$NON-NLS-1$
  168. + "[\\\\/]" + RELATIVE_PATH_P // //$NON-NLS-1$
  169. + ")$"); //$NON-NLS-1$
  170. private String scheme;
  171. private String path;
  172. private String rawPath;
  173. private String user;
  174. private String pass;
  175. private int port = -1;
  176. private String host;
  177. /**
  178. * Parse and construct an {@link org.eclipse.jgit.transport.URIish} from a
  179. * string
  180. *
  181. * @param s
  182. * a {@link java.lang.String} object.
  183. * @throws java.net.URISyntaxException
  184. */
  185. public URIish(String s) throws URISyntaxException {
  186. if (StringUtils.isEmptyOrNull(s)) {
  187. throw new URISyntaxException("The uri was empty or null", //$NON-NLS-1$
  188. JGitText.get().cannotParseGitURIish);
  189. }
  190. Matcher matcher = SINGLE_SLASH_FILE_URI.matcher(s);
  191. if (matcher.matches()) {
  192. scheme = matcher.group(1);
  193. rawPath = cleanLeadingSlashes(matcher.group(2), scheme);
  194. path = unescape(rawPath);
  195. return;
  196. }
  197. matcher = FULL_URI.matcher(s);
  198. if (matcher.matches()) {
  199. scheme = matcher.group(1);
  200. user = unescape(matcher.group(2));
  201. pass = unescape(matcher.group(3));
  202. // empty ports are in general allowed, except for URLs like
  203. // file://D:/path for which it is more desirable to parse with
  204. // host=null and path=D:/path
  205. String portString = matcher.group(5);
  206. if ("file".equals(scheme) && "".equals(portString)) { //$NON-NLS-1$ //$NON-NLS-2$
  207. rawPath = cleanLeadingSlashes(
  208. n2e(matcher.group(4)) + ":" + portString //$NON-NLS-1$
  209. + n2e(matcher.group(6)) + n2e(matcher.group(7)),
  210. scheme);
  211. } else {
  212. host = unescape(matcher.group(4));
  213. if (portString != null && portString.length() > 0) {
  214. port = Integer.parseInt(portString);
  215. }
  216. rawPath = cleanLeadingSlashes(
  217. n2e(matcher.group(6)) + n2e(matcher.group(7)), scheme);
  218. }
  219. path = unescape(rawPath);
  220. return;
  221. }
  222. matcher = RELATIVE_SCP_URI.matcher(s);
  223. if (matcher.matches()) {
  224. user = matcher.group(1);
  225. pass = matcher.group(2);
  226. host = matcher.group(3);
  227. rawPath = matcher.group(4);
  228. path = rawPath;
  229. return;
  230. }
  231. matcher = ABSOLUTE_SCP_URI.matcher(s);
  232. if (matcher.matches()) {
  233. user = matcher.group(1);
  234. pass = matcher.group(2);
  235. host = matcher.group(3);
  236. rawPath = matcher.group(4);
  237. path = rawPath;
  238. return;
  239. }
  240. matcher = LOCAL_FILE.matcher(s);
  241. if (matcher.matches()) {
  242. rawPath = matcher.group(1);
  243. path = rawPath;
  244. return;
  245. }
  246. throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish);
  247. }
  248. private static int parseHexByte(byte c1, byte c2) {
  249. return ((RawParseUtils.parseHexInt4(c1) << 4)
  250. | RawParseUtils.parseHexInt4(c2));
  251. }
  252. private static String unescape(String s) throws URISyntaxException {
  253. if (s == null)
  254. return null;
  255. if (s.indexOf('%') < 0)
  256. return s;
  257. byte[] bytes = s.getBytes(UTF_8);
  258. byte[] os = new byte[bytes.length];
  259. int j = 0;
  260. for (int i = 0; i < bytes.length; ++i) {
  261. byte c = bytes[i];
  262. if (c == '%') {
  263. if (i + 2 >= bytes.length)
  264. throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish);
  265. byte c1 = bytes[i + 1];
  266. byte c2 = bytes[i + 2];
  267. int val;
  268. try {
  269. val = parseHexByte(c1, c2);
  270. } catch (ArrayIndexOutOfBoundsException e) {
  271. throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish);
  272. }
  273. os[j++] = (byte) val;
  274. i += 2;
  275. } else
  276. os[j++] = c;
  277. }
  278. return RawParseUtils.decode(os, 0, j);
  279. }
  280. private static final BitSet reservedChars = new BitSet(127);
  281. static {
  282. for (byte b : Constants.encodeASCII("!*'();:@&=+$,/?#[]")) //$NON-NLS-1$
  283. reservedChars.set(b);
  284. }
  285. /**
  286. * Escape unprintable characters optionally URI-reserved characters
  287. *
  288. * @param s
  289. * The Java String to encode (may contain any character)
  290. * @param escapeReservedChars
  291. * true to escape URI reserved characters
  292. * @param encodeNonAscii
  293. * encode any non-ASCII characters
  294. * @return a URI-encoded string
  295. */
  296. private static String escape(String s, boolean escapeReservedChars,
  297. boolean encodeNonAscii) {
  298. if (s == null)
  299. return null;
  300. ByteArrayOutputStream os = new ByteArrayOutputStream(s.length());
  301. byte[] bytes = s.getBytes(UTF_8);
  302. for (int i = 0; i < bytes.length; ++i) {
  303. int b = bytes[i] & 0xFF;
  304. if (b <= 32 || (encodeNonAscii && b > 127) || b == '%'
  305. || (escapeReservedChars && reservedChars.get(b))) {
  306. os.write('%');
  307. byte[] tmp = Constants.encodeASCII(String.format("%02x", //$NON-NLS-1$
  308. Integer.valueOf(b)));
  309. os.write(tmp[0]);
  310. os.write(tmp[1]);
  311. } else {
  312. os.write(b);
  313. }
  314. }
  315. byte[] buf = os.toByteArray();
  316. return RawParseUtils.decode(buf, 0, buf.length);
  317. }
  318. private String n2e(String s) {
  319. if (s == null)
  320. return ""; //$NON-NLS-1$
  321. else
  322. return s;
  323. }
  324. // takes care to cut of a leading slash if a windows drive letter or a
  325. // user-home-dir specifications are
  326. private String cleanLeadingSlashes(String p, String s) {
  327. if (p.length() >= 3
  328. && p.charAt(0) == '/'
  329. && p.charAt(2) == ':'
  330. && (p.charAt(1) >= 'A' && p.charAt(1) <= 'Z' || p.charAt(1) >= 'a'
  331. && p.charAt(1) <= 'z'))
  332. return p.substring(1);
  333. else if (s != null && p.length() >= 2 && p.charAt(0) == '/'
  334. && p.charAt(1) == '~')
  335. return p.substring(1);
  336. else
  337. return p;
  338. }
  339. /**
  340. * Construct a URIish from a standard URL.
  341. *
  342. * @param u
  343. * the source URL to convert from.
  344. */
  345. public URIish(URL u) {
  346. scheme = u.getProtocol();
  347. path = u.getPath();
  348. path = cleanLeadingSlashes(path, scheme);
  349. try {
  350. rawPath = u.toURI().getRawPath();
  351. rawPath = cleanLeadingSlashes(rawPath, scheme);
  352. } catch (URISyntaxException e) {
  353. throw new RuntimeException(e); // Impossible
  354. }
  355. final String ui = u.getUserInfo();
  356. if (ui != null) {
  357. final int d = ui.indexOf(':');
  358. user = d < 0 ? ui : ui.substring(0, d);
  359. pass = d < 0 ? null : ui.substring(d + 1);
  360. }
  361. port = u.getPort();
  362. host = u.getHost();
  363. }
  364. /**
  365. * Create an empty, non-configured URI.
  366. */
  367. public URIish() {
  368. // Configure nothing.
  369. }
  370. private URIish(URIish u) {
  371. this.scheme = u.scheme;
  372. this.rawPath = u.rawPath;
  373. this.path = u.path;
  374. this.user = u.user;
  375. this.pass = u.pass;
  376. this.port = u.port;
  377. this.host = u.host;
  378. }
  379. /**
  380. * Whether this URI references a repository on another system.
  381. *
  382. * @return true if this URI references a repository on another system.
  383. */
  384. public boolean isRemote() {
  385. return getHost() != null;
  386. }
  387. /**
  388. * Get host name part.
  389. *
  390. * @return host name part or null
  391. */
  392. public String getHost() {
  393. return host;
  394. }
  395. /**
  396. * Return a new URI matching this one, but with a different host.
  397. *
  398. * @param n
  399. * the new value for host.
  400. * @return a new URI with the updated value.
  401. */
  402. public URIish setHost(String n) {
  403. final URIish r = new URIish(this);
  404. r.host = n;
  405. return r;
  406. }
  407. /**
  408. * Get protocol name
  409. *
  410. * @return protocol name or null for local references
  411. */
  412. public String getScheme() {
  413. return scheme;
  414. }
  415. /**
  416. * Return a new URI matching this one, but with a different scheme.
  417. *
  418. * @param n
  419. * the new value for scheme.
  420. * @return a new URI with the updated value.
  421. */
  422. public URIish setScheme(String n) {
  423. final URIish r = new URIish(this);
  424. r.scheme = n;
  425. return r;
  426. }
  427. /**
  428. * Get path name component
  429. *
  430. * @return path name component
  431. */
  432. public String getPath() {
  433. return path;
  434. }
  435. /**
  436. * Get path name component
  437. *
  438. * @return path name component
  439. */
  440. public String getRawPath() {
  441. return rawPath;
  442. }
  443. /**
  444. * Return a new URI matching this one, but with a different path.
  445. *
  446. * @param n
  447. * the new value for path.
  448. * @return a new URI with the updated value.
  449. */
  450. public URIish setPath(String n) {
  451. final URIish r = new URIish(this);
  452. r.path = n;
  453. r.rawPath = n;
  454. return r;
  455. }
  456. /**
  457. * Return a new URI matching this one, but with a different (raw) path.
  458. *
  459. * @param n
  460. * the new value for path.
  461. * @return a new URI with the updated value.
  462. * @throws java.net.URISyntaxException
  463. */
  464. public URIish setRawPath(String n) throws URISyntaxException {
  465. final URIish r = new URIish(this);
  466. r.path = unescape(n);
  467. r.rawPath = n;
  468. return r;
  469. }
  470. /**
  471. * Get user name requested for transfer
  472. *
  473. * @return user name requested for transfer or null
  474. */
  475. public String getUser() {
  476. return user;
  477. }
  478. /**
  479. * Return a new URI matching this one, but with a different user.
  480. *
  481. * @param n
  482. * the new value for user.
  483. * @return a new URI with the updated value.
  484. */
  485. public URIish setUser(String n) {
  486. final URIish r = new URIish(this);
  487. r.user = n;
  488. return r;
  489. }
  490. /**
  491. * Get password requested for transfer
  492. *
  493. * @return password requested for transfer or null
  494. */
  495. public String getPass() {
  496. return pass;
  497. }
  498. /**
  499. * Return a new URI matching this one, but with a different password.
  500. *
  501. * @param n
  502. * the new value for password.
  503. * @return a new URI with the updated value.
  504. */
  505. public URIish setPass(String n) {
  506. final URIish r = new URIish(this);
  507. r.pass = n;
  508. return r;
  509. }
  510. /**
  511. * Get port number requested for transfer or -1 if not explicit
  512. *
  513. * @return port number requested for transfer or -1 if not explicit
  514. */
  515. public int getPort() {
  516. return port;
  517. }
  518. /**
  519. * Return a new URI matching this one, but with a different port.
  520. *
  521. * @param n
  522. * the new value for port.
  523. * @return a new URI with the updated value.
  524. */
  525. public URIish setPort(int n) {
  526. final URIish r = new URIish(this);
  527. r.port = n > 0 ? n : -1;
  528. return r;
  529. }
  530. /** {@inheritDoc} */
  531. @Override
  532. public int hashCode() {
  533. int hc = 0;
  534. if (getScheme() != null)
  535. hc = hc * 31 + getScheme().hashCode();
  536. if (getUser() != null)
  537. hc = hc * 31 + getUser().hashCode();
  538. if (getPass() != null)
  539. hc = hc * 31 + getPass().hashCode();
  540. if (getHost() != null)
  541. hc = hc * 31 + getHost().hashCode();
  542. if (getPort() > 0)
  543. hc = hc * 31 + getPort();
  544. if (getPath() != null)
  545. hc = hc * 31 + getPath().hashCode();
  546. return hc;
  547. }
  548. /** {@inheritDoc} */
  549. @Override
  550. public boolean equals(Object obj) {
  551. if (!(obj instanceof URIish))
  552. return false;
  553. final URIish b = (URIish) obj;
  554. if (!eq(getScheme(), b.getScheme()))
  555. return false;
  556. if (!eq(getUser(), b.getUser()))
  557. return false;
  558. if (!eq(getPass(), b.getPass()))
  559. return false;
  560. if (!eq(getHost(), b.getHost()))
  561. return false;
  562. if (getPort() != b.getPort())
  563. return false;
  564. if (!eq(getPath(), b.getPath()))
  565. return false;
  566. return true;
  567. }
  568. private static boolean eq(String a, String b) {
  569. if (a == b)
  570. return true;
  571. if (StringUtils.isEmptyOrNull(a) && StringUtils.isEmptyOrNull(b))
  572. return true;
  573. if (a == null || b == null)
  574. return false;
  575. return a.equals(b);
  576. }
  577. /**
  578. * Obtain the string form of the URI, with the password included.
  579. *
  580. * @return the URI, including its password field, if any.
  581. */
  582. public String toPrivateString() {
  583. return format(true, false);
  584. }
  585. /** {@inheritDoc} */
  586. @Override
  587. public String toString() {
  588. return format(false, false);
  589. }
  590. private String format(boolean includePassword, boolean escapeNonAscii) {
  591. final StringBuilder r = new StringBuilder();
  592. if (getScheme() != null) {
  593. r.append(getScheme());
  594. r.append("://"); //$NON-NLS-1$
  595. }
  596. if (getUser() != null) {
  597. r.append(escape(getUser(), true, escapeNonAscii));
  598. if (includePassword && getPass() != null) {
  599. r.append(':');
  600. r.append(escape(getPass(), true, escapeNonAscii));
  601. }
  602. }
  603. if (getHost() != null) {
  604. if (getUser() != null && getUser().length() > 0)
  605. r.append('@');
  606. r.append(escape(getHost(), false, escapeNonAscii));
  607. if (getScheme() != null && getPort() > 0) {
  608. r.append(':');
  609. r.append(getPort());
  610. }
  611. }
  612. if (getPath() != null) {
  613. if (getScheme() != null) {
  614. if (!getPath().startsWith("/") && !getPath().isEmpty()) //$NON-NLS-1$
  615. r.append('/');
  616. } else if (getHost() != null)
  617. r.append(':');
  618. if (getScheme() != null)
  619. if (escapeNonAscii)
  620. r.append(escape(getPath(), false, escapeNonAscii));
  621. else
  622. r.append(getRawPath());
  623. else
  624. r.append(getPath());
  625. }
  626. return r.toString();
  627. }
  628. /**
  629. * Get the URI as an ASCII string.
  630. *
  631. * @return the URI as an ASCII string. Password is not included.
  632. */
  633. public String toASCIIString() {
  634. return format(false, true);
  635. }
  636. /**
  637. * Convert the URI including password, formatted with only ASCII characters
  638. * such that it will be valid for use over the network.
  639. *
  640. * @return the URI including password, formatted with only ASCII characters
  641. * such that it will be valid for use over the network.
  642. */
  643. public String toPrivateASCIIString() {
  644. return format(true, true);
  645. }
  646. /**
  647. * Get the "humanish" part of the path. Some examples of a 'humanish' part
  648. * for a full path:
  649. * <table summary="path vs humanish path" border="1">
  650. * <tr>
  651. * <th>Path</th>
  652. * <th>Humanish part</th>
  653. * </tr>
  654. * <tr>
  655. * <td><code>/path/to/repo.git</code></td>
  656. * <td rowspan="4"><code>repo</code></td>
  657. * </tr>
  658. * <tr>
  659. * <td><code>/path/to/repo.git/</code></td>
  660. * </tr>
  661. * <tr>
  662. * <td><code>/path/to/repo/.git</code></td>
  663. * </tr>
  664. * <tr>
  665. * <td><code>/path/to/repo/</code></td>
  666. * </tr>
  667. * <tr>
  668. * <td><code>localhost</code></td>
  669. * <td><code>ssh://localhost/</code></td>
  670. * </tr>
  671. * <tr>
  672. * <td><code>/path//to</code></td>
  673. * <td>an empty string</td>
  674. * </tr>
  675. * </table>
  676. *
  677. * @return the "humanish" part of the path. May be an empty string. Never
  678. * {@code null}.
  679. * @throws java.lang.IllegalArgumentException
  680. * if it's impossible to determine a humanish part, or path is
  681. * {@code null} or empty
  682. * @see #getPath
  683. */
  684. public String getHumanishName() throws IllegalArgumentException {
  685. String s = getPath();
  686. if ("/".equals(s) || "".equals(s)) //$NON-NLS-1$ //$NON-NLS-2$
  687. s = getHost();
  688. if (s == null) // $NON-NLS-1$
  689. throw new IllegalArgumentException();
  690. String[] elements;
  691. if ("file".equals(scheme) || LOCAL_FILE.matcher(s).matches()) //$NON-NLS-1$
  692. elements = s.split("[\\" + File.separatorChar + "/]"); //$NON-NLS-1$ //$NON-NLS-2$
  693. else
  694. elements = s.split("/+"); //$NON-NLS-1$
  695. if (elements.length == 0)
  696. throw new IllegalArgumentException();
  697. String result = elements[elements.length - 1];
  698. if (Constants.DOT_GIT.equals(result))
  699. result = elements[elements.length - 2];
  700. else if (result.endsWith(Constants.DOT_GIT_EXT))
  701. result = result.substring(0, result.length()
  702. - Constants.DOT_GIT_EXT.length());
  703. return result;
  704. }
  705. }