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.

StringUtils.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /*
  2. * Copyright 2011 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.utils;
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.UnsupportedEncodingException;
  19. import java.nio.ByteBuffer;
  20. import java.nio.CharBuffer;
  21. import java.nio.charset.CharacterCodingException;
  22. import java.nio.charset.Charset;
  23. import java.nio.charset.CharsetDecoder;
  24. import java.nio.charset.IllegalCharsetNameException;
  25. import java.nio.charset.UnsupportedCharsetException;
  26. import java.security.MessageDigest;
  27. import java.security.NoSuchAlgorithmException;
  28. import java.util.ArrayList;
  29. import java.util.Arrays;
  30. import java.util.Collection;
  31. import java.util.Collections;
  32. import java.util.Comparator;
  33. import java.util.LinkedHashSet;
  34. import java.util.List;
  35. import java.util.Set;
  36. import java.util.regex.Matcher;
  37. import java.util.regex.Pattern;
  38. import java.util.regex.PatternSyntaxException;
  39. /**
  40. * Utility class of string functions.
  41. *
  42. * @author James Moger
  43. *
  44. */
  45. public class StringUtils {
  46. /**
  47. * Returns true if the string is null or empty.
  48. *
  49. * @param value
  50. * @return true if string is null or empty
  51. */
  52. public static boolean isEmpty(String value) {
  53. return value == null || value.trim().length() == 0;
  54. }
  55. /**
  56. * Returns true if the character array represents an empty String.
  57. * An empty character sequence is defined as a sequence that
  58. * either has no characters at all, or no characters above
  59. * '\u0020' (space).
  60. *
  61. * @param value
  62. * @return true if value is null or represents an empty String
  63. */
  64. public static boolean isEmpty(char[] value) {
  65. if (value == null || value.length == 0) return true;
  66. for ( char c : value) if (c > '\u0020') return false;
  67. return true;
  68. }
  69. /**
  70. * Replaces carriage returns and line feeds with html line breaks.
  71. *
  72. * @param string
  73. * @return plain text with html line breaks
  74. */
  75. public static String breakLinesForHtml(String string) {
  76. return string.replace("\r\n", "<br/>").replace("\r", "<br/>").replace("\n", "<br/>");
  77. }
  78. /**
  79. * Prepare text for html presentation. Replace sensitive characters with
  80. * html entities.
  81. *
  82. * @param inStr
  83. * @param changeSpace
  84. * @return plain text escaped for html
  85. */
  86. public static String escapeForHtml(String inStr, boolean changeSpace) {
  87. return escapeForHtml(inStr, changeSpace, 4);
  88. }
  89. /**
  90. * Prepare text for html presentation. Replace sensitive characters with
  91. * html entities.
  92. *
  93. * @param inStr
  94. * @param changeSpace
  95. * @param tabLength
  96. * @return plain text escaped for html
  97. */
  98. public static String escapeForHtml(String inStr, boolean changeSpace, int tabLength) {
  99. StringBuilder retStr = new StringBuilder();
  100. int i = 0;
  101. while (i < inStr.length()) {
  102. if (inStr.charAt(i) == '&') {
  103. retStr.append("&amp;");
  104. } else if (inStr.charAt(i) == '<') {
  105. retStr.append("&lt;");
  106. } else if (inStr.charAt(i) == '>') {
  107. retStr.append("&gt;");
  108. } else if (inStr.charAt(i) == '\"') {
  109. retStr.append("&quot;");
  110. } else if (changeSpace && inStr.charAt(i) == ' ') {
  111. retStr.append("&nbsp;");
  112. } else if (changeSpace && inStr.charAt(i) == '\t') {
  113. for (int j = 0; j < tabLength; j++) {
  114. retStr.append("&nbsp;");
  115. }
  116. } else {
  117. retStr.append(inStr.charAt(i));
  118. }
  119. i++;
  120. }
  121. return retStr.toString();
  122. }
  123. /**
  124. * Decode html entities back into plain text characters.
  125. *
  126. * @param inStr
  127. * @return returns plain text from html
  128. */
  129. public static String decodeFromHtml(String inStr) {
  130. return inStr.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">")
  131. .replace("&quot;", "\"").replace("&nbsp;", " ");
  132. }
  133. /**
  134. * Encodes a url parameter by escaping troublesome characters.
  135. *
  136. * @param inStr
  137. * @return properly escaped url
  138. */
  139. public static String encodeURL(String inStr) {
  140. StringBuilder retStr = new StringBuilder();
  141. int i = 0;
  142. while (i < inStr.length()) {
  143. if (inStr.charAt(i) == '/') {
  144. retStr.append("%2F");
  145. } else if (inStr.charAt(i) == ' ') {
  146. retStr.append("%20");
  147. } else if (inStr.charAt(i) == '&') {
  148. retStr.append("%26");
  149. } else if (inStr.charAt(i) == '+') {
  150. retStr.append("%2B");
  151. } else {
  152. retStr.append(inStr.charAt(i));
  153. }
  154. i++;
  155. }
  156. return retStr.toString();
  157. }
  158. /**
  159. * Flatten the list of strings into a single string with the specified
  160. * separator.
  161. *
  162. * @param values
  163. * @param separator
  164. * @return flattened list
  165. */
  166. public static String flattenStrings(String[] values, String separator) {
  167. return flattenStrings(Arrays.asList(values), separator);
  168. }
  169. /**
  170. * Flatten the list of strings into a single string with a space separator.
  171. *
  172. * @param values
  173. * @return flattened list
  174. */
  175. public static String flattenStrings(Collection<String> values) {
  176. return flattenStrings(values, " ");
  177. }
  178. /**
  179. * Flatten the list of strings into a single string with the specified
  180. * separator.
  181. *
  182. * @param values
  183. * @param separator
  184. * @return flattened list
  185. */
  186. public static String flattenStrings(Collection<String> values, String separator) {
  187. StringBuilder sb = new StringBuilder();
  188. for (String value : values) {
  189. sb.append(value).append(separator);
  190. }
  191. if (sb.length() > 0) {
  192. // truncate trailing separator
  193. sb.setLength(sb.length() - separator.length());
  194. }
  195. return sb.toString().trim();
  196. }
  197. /**
  198. * Returns a string trimmed to a maximum length with trailing ellipses. If
  199. * the string length is shorter than the max, the original string is
  200. * returned.
  201. *
  202. * @param value
  203. * @param max
  204. * @return trimmed string
  205. */
  206. public static String trimString(String value, int max) {
  207. if (value.length() <= max) {
  208. return value;
  209. }
  210. return value.substring(0, max - 3) + "...";
  211. }
  212. /**
  213. * Left pad a string with the specified character, if the string length is
  214. * less than the specified length.
  215. *
  216. * @param input
  217. * @param length
  218. * @param pad
  219. * @return left-padded string
  220. */
  221. public static String leftPad(String input, int length, char pad) {
  222. if (input.length() < length) {
  223. StringBuilder sb = new StringBuilder();
  224. for (int i = 0, len = length - input.length(); i < len; i++) {
  225. sb.append(pad);
  226. }
  227. sb.append(input);
  228. return sb.toString();
  229. }
  230. return input;
  231. }
  232. /**
  233. * Right pad a string with the specified character, if the string length is
  234. * less then the specified length.
  235. *
  236. * @param input
  237. * @param length
  238. * @param pad
  239. * @return right-padded string
  240. */
  241. public static String rightPad(String input, int length, char pad) {
  242. if (input.length() < length) {
  243. StringBuilder sb = new StringBuilder();
  244. sb.append(input);
  245. for (int i = 0, len = length - input.length(); i < len; i++) {
  246. sb.append(pad);
  247. }
  248. return sb.toString();
  249. }
  250. return input;
  251. }
  252. /**
  253. * Calculates the SHA1 of the string.
  254. *
  255. * @param text
  256. * @return sha1 of the string
  257. */
  258. public static String getSHA1(String text) {
  259. try {
  260. byte[] bytes = text.getBytes("iso-8859-1");
  261. return getSHA1(bytes);
  262. } catch (UnsupportedEncodingException u) {
  263. throw new RuntimeException(u);
  264. }
  265. }
  266. /**
  267. * Calculates the SHA1 of the byte array.
  268. *
  269. * @param bytes
  270. * @return sha1 of the byte array
  271. */
  272. public static String getSHA1(byte[] bytes) {
  273. try {
  274. MessageDigest md = MessageDigest.getInstance("SHA-1");
  275. md.update(bytes, 0, bytes.length);
  276. byte[] digest = md.digest();
  277. return toHex(digest);
  278. } catch (NoSuchAlgorithmException t) {
  279. throw new RuntimeException(t);
  280. }
  281. }
  282. /**
  283. * Calculates the MD5 of the string.
  284. *
  285. * @param string
  286. * @return md5 of the string
  287. */
  288. public static String getMD5(String string) {
  289. try {
  290. return getMD5(string.getBytes("iso-8859-1"));
  291. } catch (UnsupportedEncodingException u) {
  292. throw new RuntimeException(u);
  293. }
  294. }
  295. /**
  296. * Calculates the MD5 of the string.
  297. *
  298. * @param string
  299. * @return md5 of the string
  300. */
  301. public static String getMD5(byte [] bytes) {
  302. try {
  303. MessageDigest md = MessageDigest.getInstance("MD5");
  304. md.reset();
  305. md.update(bytes);
  306. byte[] digest = md.digest();
  307. return toHex(digest);
  308. } catch (NoSuchAlgorithmException t) {
  309. throw new RuntimeException(t);
  310. }
  311. }
  312. /**
  313. * Returns the hex representation of the byte array.
  314. *
  315. * @param bytes
  316. * @return byte array as hex string
  317. */
  318. public static String toHex(byte[] bytes) {
  319. StringBuilder sb = new StringBuilder(bytes.length * 2);
  320. for (int i = 0; i < bytes.length; i++) {
  321. if ((bytes[i] & 0xff) < 0x10) {
  322. sb.append('0');
  323. }
  324. sb.append(Long.toString(bytes[i] & 0xff, 16));
  325. }
  326. return sb.toString();
  327. }
  328. /**
  329. * Returns the root path of the specified path. Returns a blank string if
  330. * there is no root path.
  331. *
  332. * @param path
  333. * @return root path or blank
  334. */
  335. public static String getRootPath(String path) {
  336. if (path.indexOf('/') > -1) {
  337. return path.substring(0, path.lastIndexOf('/'));
  338. }
  339. return "";
  340. }
  341. /**
  342. * Returns the path remainder after subtracting the basePath from the
  343. * fullPath.
  344. *
  345. * @param basePath
  346. * @param fullPath
  347. * @return the relative path
  348. */
  349. public static String getRelativePath(String basePath, String fullPath) {
  350. String bp = basePath.replace('\\', '/').toLowerCase();
  351. String fp = fullPath.replace('\\', '/').toLowerCase();
  352. if (fp.startsWith(bp)) {
  353. String relativePath = fullPath.substring(basePath.length()).replace('\\', '/');
  354. if (relativePath.length() > 0 && relativePath.charAt(0) == '/') {
  355. relativePath = relativePath.substring(1);
  356. }
  357. return relativePath;
  358. }
  359. return fullPath;
  360. }
  361. /**
  362. * Splits the space-separated string into a list of strings.
  363. *
  364. * @param value
  365. * @return list of strings
  366. */
  367. public static List<String> getStringsFromValue(String value) {
  368. return getStringsFromValue(value, " ");
  369. }
  370. /**
  371. * Splits the string into a list of string by the specified separator.
  372. *
  373. * @param value
  374. * @param separator
  375. * @return list of strings
  376. */
  377. public static List<String> getStringsFromValue(String value, String separator) {
  378. List<String> strings = new ArrayList<String>();
  379. try {
  380. String[] chunks = value.split(separator + "(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
  381. for (String chunk : chunks) {
  382. chunk = chunk.trim();
  383. if (chunk.length() > 0) {
  384. if (chunk.charAt(0) == '"' && chunk.charAt(chunk.length() - 1) == '"') {
  385. // strip double quotes
  386. chunk = chunk.substring(1, chunk.length() - 1).trim();
  387. }
  388. strings.add(chunk);
  389. }
  390. }
  391. } catch (PatternSyntaxException e) {
  392. throw new RuntimeException(e);
  393. }
  394. return strings;
  395. }
  396. /**
  397. * Validates that a name is composed of letters, digits, or limited other
  398. * characters.
  399. *
  400. * @param name
  401. * @return the first invalid character found or null if string is acceptable
  402. */
  403. public static Character findInvalidCharacter(String name) {
  404. char[] validChars = { '/', '.', '_', '-', '~', '+' };
  405. for (char c : name.toCharArray()) {
  406. if (!Character.isLetterOrDigit(c)) {
  407. boolean ok = false;
  408. for (char vc : validChars) {
  409. ok |= c == vc;
  410. }
  411. if (!ok) {
  412. return c;
  413. }
  414. }
  415. }
  416. return null;
  417. }
  418. /**
  419. * Simple fuzzy string comparison. This is a case-insensitive check. A
  420. * single wildcard * value is supported.
  421. *
  422. * @param value
  423. * @param pattern
  424. * @return true if the value matches the pattern
  425. */
  426. public static boolean fuzzyMatch(String value, String pattern) {
  427. if (value.equalsIgnoreCase(pattern)) {
  428. return true;
  429. }
  430. if (pattern.contains("*")) {
  431. boolean prefixMatches = false;
  432. boolean suffixMatches = false;
  433. int wildcard = pattern.indexOf('*');
  434. String prefix = pattern.substring(0, wildcard).toLowerCase();
  435. prefixMatches = value.toLowerCase().startsWith(prefix);
  436. if (pattern.length() > (wildcard + 1)) {
  437. String suffix = pattern.substring(wildcard + 1).toLowerCase();
  438. suffixMatches = value.toLowerCase().endsWith(suffix);
  439. return prefixMatches && suffixMatches;
  440. }
  441. return prefixMatches || suffixMatches;
  442. }
  443. return false;
  444. }
  445. /**
  446. * Compare two repository names for proper group sorting.
  447. *
  448. * @param r1
  449. * @param r2
  450. * @return
  451. */
  452. public static int compareRepositoryNames(String r1, String r2) {
  453. // sort root repositories first, alphabetically
  454. // then sort grouped repositories, alphabetically
  455. r1 = r1.toLowerCase();
  456. r2 = r2.toLowerCase();
  457. int s1 = r1.indexOf('/');
  458. int s2 = r2.indexOf('/');
  459. if (s1 == -1 && s2 == -1) {
  460. // neither grouped
  461. return r1.compareTo(r2);
  462. } else if (s1 > -1 && s2 > -1) {
  463. // both grouped
  464. return r1.compareTo(r2);
  465. } else if (s1 == -1) {
  466. return -1;
  467. } else if (s2 == -1) {
  468. return 1;
  469. }
  470. return 0;
  471. }
  472. /**
  473. * Sort grouped repository names.
  474. *
  475. * @param list
  476. */
  477. public static void sortRepositorynames(List<String> list) {
  478. Collections.sort(list, new Comparator<String>() {
  479. @Override
  480. public int compare(String o1, String o2) {
  481. return compareRepositoryNames(o1, o2);
  482. }
  483. });
  484. }
  485. public static String getColor(String value) {
  486. int cs = 0;
  487. for (char c : getMD5(value.toLowerCase()).toCharArray()) {
  488. cs += c;
  489. }
  490. int n = (cs % 360);
  491. float hue = ((float) n) / 360;
  492. return hsvToRgb(hue, 0.90f, 0.65f);
  493. }
  494. public static String hsvToRgb(float hue, float saturation, float value) {
  495. int h = (int) (hue * 6);
  496. float f = hue * 6 - h;
  497. float p = value * (1 - saturation);
  498. float q = value * (1 - f * saturation);
  499. float t = value * (1 - (1 - f) * saturation);
  500. switch (h) {
  501. case 0:
  502. return rgbToString(value, t, p);
  503. case 1:
  504. return rgbToString(q, value, p);
  505. case 2:
  506. return rgbToString(p, value, t);
  507. case 3:
  508. return rgbToString(p, q, value);
  509. case 4:
  510. return rgbToString(t, p, value);
  511. case 5:
  512. return rgbToString(value, p, q);
  513. default:
  514. throw new RuntimeException(
  515. "Something went wrong when converting from HSV to RGB. Input was " + hue + ", "
  516. + saturation + ", " + value);
  517. }
  518. }
  519. public static String rgbToString(float r, float g, float b) {
  520. String rs = Integer.toHexString((int) (r * 256));
  521. String gs = Integer.toHexString((int) (g * 256));
  522. String bs = Integer.toHexString((int) (b * 256));
  523. return "#" + rs + gs + bs;
  524. }
  525. /**
  526. * Strips a trailing ".git" from the value.
  527. *
  528. * @param value
  529. * @return a stripped value or the original value if .git is not found
  530. */
  531. public static String stripDotGit(String value) {
  532. if (value.toLowerCase().endsWith(".git")) {
  533. return value.substring(0, value.length() - 4);
  534. }
  535. return value;
  536. }
  537. /**
  538. * Count the number of lines in a string.
  539. *
  540. * @param value
  541. * @return the line count
  542. */
  543. public static int countLines(String value) {
  544. if (isEmpty(value)) {
  545. return 0;
  546. }
  547. return value.split("\n").length;
  548. }
  549. /**
  550. * Returns the file extension of a path.
  551. *
  552. * @param path
  553. * @return a blank string or a file extension
  554. */
  555. public static String getFileExtension(String path) {
  556. int lastDot = path.lastIndexOf('.');
  557. if (lastDot > -1) {
  558. return path.substring(lastDot + 1);
  559. }
  560. return "";
  561. }
  562. /**
  563. * Returns the file extension of a path.
  564. *
  565. * @param path
  566. * @return a blank string or a file extension
  567. */
  568. public static String stripFileExtension(String path) {
  569. int lastDot = path.lastIndexOf('.');
  570. if (lastDot > -1) {
  571. return path.substring(0, lastDot);
  572. }
  573. return path;
  574. }
  575. /**
  576. * Replace all occurences of a substring within a string with
  577. * another string.
  578. *
  579. * From Spring StringUtils.
  580. *
  581. * @param inString String to examine
  582. * @param oldPattern String to replace
  583. * @param newPattern String to insert
  584. * @return a String with the replacements
  585. */
  586. public static String replace(String inString, String oldPattern, String newPattern) {
  587. StringBuilder sb = new StringBuilder();
  588. int pos = 0; // our position in the old string
  589. int index = inString.indexOf(oldPattern);
  590. // the index of an occurrence we've found, or -1
  591. int patLen = oldPattern.length();
  592. while (index >= 0) {
  593. sb.append(inString.substring(pos, index));
  594. sb.append(newPattern);
  595. pos = index + patLen;
  596. index = inString.indexOf(oldPattern, pos);
  597. }
  598. sb.append(inString.substring(pos));
  599. // remember to append any characters to the right of a match
  600. return sb.toString();
  601. }
  602. /**
  603. * Decodes a string by trying several charsets until one does not throw a
  604. * coding exception. Last resort is to interpret as UTF-8 with illegal
  605. * character substitution.
  606. *
  607. * @param content
  608. * @param charsets optional
  609. * @return a string
  610. */
  611. public static String decodeString(byte [] content, String... charsets) {
  612. Set<String> sets = new LinkedHashSet<String>();
  613. if (!ArrayUtils.isEmpty(charsets)) {
  614. sets.addAll(Arrays.asList(charsets));
  615. }
  616. String value = null;
  617. sets.addAll(Arrays.asList("UTF-8", "ISO-8859-1", Charset.defaultCharset().name()));
  618. for (String charset : sets) {
  619. try {
  620. Charset cs = Charset.forName(charset);
  621. CharsetDecoder decoder = cs.newDecoder();
  622. CharBuffer buffer = decoder.decode(ByteBuffer.wrap(content));
  623. value = buffer.toString();
  624. break;
  625. } catch (CharacterCodingException e) {
  626. // ignore and advance to the next charset
  627. } catch (IllegalCharsetNameException e) {
  628. // ignore illegal charset names
  629. } catch (UnsupportedCharsetException e) {
  630. // ignore unsupported charsets
  631. }
  632. }
  633. if (value != null && value.startsWith("\uFEFF")) {
  634. // strip UTF-8 BOM
  635. return value.substring(1);
  636. }
  637. return value;
  638. }
  639. /**
  640. * Attempt to extract a repository name from a given url using regular
  641. * expressions. If no match is made, then return whatever trails after
  642. * the final / character.
  643. *
  644. * @param regexUrls
  645. * @return a repository path
  646. */
  647. public static String extractRepositoryPath(String url, String... urlpatterns) {
  648. for (String urlPattern : urlpatterns) {
  649. Pattern p = Pattern.compile(urlPattern);
  650. Matcher m = p.matcher(url);
  651. while (m.find()) {
  652. String repositoryPath = m.group(1);
  653. return repositoryPath;
  654. }
  655. }
  656. // last resort
  657. if (url.lastIndexOf('/') > -1) {
  658. return url.substring(url.lastIndexOf('/') + 1);
  659. }
  660. return url;
  661. }
  662. /**
  663. * Converts a string with \nnn sequences into a UTF-8 encoded string.
  664. * @param input
  665. * @return
  666. */
  667. public static String convertOctal(String input) {
  668. try {
  669. ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  670. Pattern p = Pattern.compile("(\\\\\\d{3})");
  671. Matcher m = p.matcher(input);
  672. int i = 0;
  673. while (m.find()) {
  674. bytes.write(input.substring(i, m.start()).getBytes("UTF-8"));
  675. // replace octal encoded value
  676. // strip leading \ character
  677. String oct = m.group().substring(1);
  678. bytes.write(Integer.parseInt(oct, 8));
  679. i = m.end();
  680. }
  681. if (bytes.size() == 0) {
  682. // no octal matches
  683. return input;
  684. } else {
  685. if (i < input.length()) {
  686. // add remainder of string
  687. bytes.write(input.substring(i).getBytes("UTF-8"));
  688. }
  689. }
  690. return bytes.toString("UTF-8");
  691. } catch (Exception e) {
  692. e.printStackTrace();
  693. }
  694. return input;
  695. }
  696. /**
  697. * Returns the first path element of a path string. If no path separator is
  698. * found in the path, an empty string is returned.
  699. *
  700. * @param path
  701. * @return the first element in the path
  702. */
  703. public static String getFirstPathElement(String path) {
  704. if (path.indexOf('/') > -1) {
  705. return path.substring(0, path.indexOf('/')).trim();
  706. }
  707. return "";
  708. }
  709. /**
  710. * Returns the last path element of a path string
  711. *
  712. * @param path
  713. * @return the last element in the path
  714. */
  715. public static String getLastPathElement(String path) {
  716. if (path.indexOf('/') > -1) {
  717. return path.substring(path.lastIndexOf('/') + 1);
  718. }
  719. return path;
  720. }
  721. /**
  722. * Variation of String.matches() which disregards case issues.
  723. *
  724. * @param regex
  725. * @param input
  726. * @return true if the pattern matches
  727. */
  728. public static boolean matchesIgnoreCase(String input, String regex) {
  729. Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
  730. Matcher m = p.matcher(input);
  731. return m.matches();
  732. }
  733. /**
  734. * Removes new line and carriage return chars from a string.
  735. * If input value is null an empty string is returned.
  736. *
  737. * @param input
  738. * @return a sanitized or empty string
  739. */
  740. public static String removeNewlines(String input) {
  741. if (input == null) {
  742. return "";
  743. }
  744. return input.replace('\n',' ').replace('\r', ' ').trim();
  745. }
  746. /**
  747. * Encode the username for user in an url.
  748. *
  749. * @param name
  750. * @return the encoded name
  751. */
  752. public static String encodeUsername(String name) {
  753. return name.replace("@", "%40").replace(" ", "%20").replace("\\", "%5C");
  754. }
  755. /**
  756. * Decode a username from an encoded url.
  757. *
  758. * @param name
  759. * @return the decoded name
  760. */
  761. public static String decodeUsername(String name) {
  762. return name.replace("%40", "@").replace("%20", " ").replace("%5C", "\\");
  763. }
  764. }