PageRenderTime 54ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/bundles/plugins-trunk/XInsert/src/Utilities.java

#
Java | 500 lines | 150 code | 45 blank | 305 comment | 53 complexity | b38943519feec2fe8056e38c3ef82b31 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. /*
  2. * 18/01/2000 v1.1
  3. *
  4. * Utilities.java - Some utilities for XInsert
  5. * Copyright (C) 1999 Romain Guy (version 1.1 additions Dominic Stolerman)
  6. * powerteam@chez.com
  7. * www.chez.com/powerteam
  8. *
  9. * This program is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU General Public License
  11. * as published by the Free Software Foundation; either version 2
  12. * of the License, or any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software
  21. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  22. */
  23. import java.io.*;
  24. import java.util.*;
  25. import java.awt.Toolkit;
  26. import org.gjt.sp.jedit.*;
  27. import javax.swing.ImageIcon;
  28. import javax.swing.JOptionPane;
  29. public class Utilities {
  30. /** This constant defines an open dialog box. */
  31. public static final int OPEN = 0;
  32. /** This constant defines a save dialog box. */
  33. public static final int SAVE = 1;
  34. /**
  35. * We may need to load and display images.
  36. * @param picture The path to the image
  37. * @param source The class 'root'
  38. * @return An <code>ImageIcon</code>
  39. */
  40. public static ImageIcon getIcon(String picture) {
  41. return new ImageIcon(Toolkit.getDefaultToolkit().getImage(Utilities.class.getResource(picture)));
  42. }
  43. /**
  44. * Display a confirm message in a dialog box.
  45. * @param parent The View parent
  46. * @param title The title
  47. * @param message The message to display
  48. */
  49. /*
  50. public static int showConfirm(View parent, String title, String message) {
  51. return JOptionPane.showConfirmDialog(parent, message, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
  52. }
  53. */
  54. /**
  55. * Display a sample message in a dialog box.
  56. * @param message The message to display
  57. */
  58. /* public static void showMessage(String message) {
  59. JOptionPane.showMessageDialog(null, message, "Message", JOptionPane.INFORMATION_MESSAGE);
  60. } */
  61. /**
  62. * Display an error message in a dialog box.
  63. * @param message The message to display
  64. */
  65. /* public static void showError(String message) {
  66. JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
  67. } */
  68. /**
  69. * Display a sample message in a dialog box.
  70. * @param message The message to display
  71. */
  72. /* public static void showMessage(String title, String message) {
  73. JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
  74. } */
  75. /**
  76. * Constructs a new path from current user path. This is an easy way to get a path
  77. * if the user specified, for example, "..\Java" as new path. This method will return
  78. * the argument if this one is a path to a root (i.e, if <code>change</code> is equal
  79. * to C:\Jdk, constructPath will return C:\Jdk).
  80. * @param change The modification to apply to the path
  81. * @see Utils#beginsWithRoot(String), Utils#getRoot(String)
  82. */
  83. /* public static String constructPath(String change) {
  84. if (beginsWithRoot(change))
  85. return change;
  86. String newPath = getUserDirectory();
  87. char current;
  88. char lastChar = '\0';
  89. boolean toAdd = false;
  90. StringBuffer buf = new StringBuffer(change.length());
  91. for (int i = 0; i < change.length(); i++) {
  92. switch ((current = change.charAt(i))) {
  93. case '.':
  94. if (lastChar == '.') {
  95. String parent = (new File(newPath)).getParent();
  96. if (parent != null) newPath = parent;
  97. } else if (lastChar != '\0' && lastChar != '\\' && lastChar != '/') buf.append('.');
  98. lastChar = '.';
  99. break;
  100. case '\\': case '/':
  101. if (lastChar == '\0')
  102. newPath = getRoot(newPath);
  103. else {
  104. if (!newPath.endsWith("\\"))
  105. newPath += File.separator + buf.toString();
  106. else
  107. newPath += buf.toString();
  108. buf = new StringBuffer();
  109. toAdd = false;
  110. }
  111. lastChar = '\\';
  112. break;
  113. case '~':
  114. if (i < change.length() - 1) {
  115. if (change.charAt(i + 1) == '\\' || change.charAt(i + 1) == '/')
  116. newPath = System.getProperties().getProperty("user.home");
  117. else
  118. buf.append('~');
  119. } else if (i == 0)
  120. newPath = System.getProperties().getProperty("user.home");
  121. else
  122. buf.append('~');
  123. lastChar = '~';
  124. break;
  125. default:
  126. lastChar = current;
  127. buf.append(current);
  128. toAdd = true;
  129. break;
  130. }
  131. }
  132. if (toAdd) {
  133. if (!newPath.endsWith(File.separator))
  134. newPath += File.separator + buf.toString();
  135. else
  136. newPath += buf.toString();
  137. }
  138. return newPath;
  139. }
  140. /**
  141. * It can be necessary to check if a path specified by the user is an absolute
  142. * path (i.e C:\Gfx\3d\Utils is absolute whereas ..\Jext is relative).
  143. * @param path The path to check
  144. * @return <code>true</code> if <code>path</code> begins with a root name
  145. */
  146. /*
  147. public static boolean beginsWithRoot(String path) {
  148. File roots[] = (new File(path)).listRoots();
  149. for (int i = 0; i < roots.length; i++)
  150. if (path.regionMatches(true, 0, roots[i].getPath(), 0, roots[i].getPath().length())) return true;
  151. return false;
  152. }
  153. /**
  154. * Returns user directory.
  155. */
  156. public static String getUserDirectory() {
  157. return System.getProperty("user.dir");
  158. }
  159. /**
  160. * Returns user's home directory.
  161. */
  162. /*
  163. public static String getHomeDirectory() {
  164. return System.getProperty("user.home");
  165. }
  166. /**
  167. * It can be necessary to determine which is the root of a path.
  168. * For example, the root of D:\Projects\Java is D:\.
  169. * @param path The path used to get a root
  170. * @return The root which contais the specified path
  171. */
  172. /*
  173. public static String getRoot(String path) {
  174. File roots[] = (new File(path)).listRoots();
  175. for (int i = 0; i < roots.length; i++)
  176. if (path.startsWith(roots[i].getPath())) return roots[i].getPath();
  177. return path;
  178. }
  179. /**
  180. * Returns the number of leading white space characters in the
  181. * specified string.
  182. * @param str The string
  183. */
  184. /*
  185. public static int getLeadingWhiteSpace(String str) {
  186. int whitespace = 0;
  187. loop: for (; whitespace < str.length(); ) {
  188. switch(str.charAt(whitespace)) {
  189. case ' ': case '\t':
  190. whitespace++;
  191. break;
  192. default:
  193. break loop;
  194. }
  195. }
  196. return whitespace;
  197. }
  198. /**
  199. * When the user has to specify file names, he can use wildcards (*, ?). This methods
  200. * handles the usage of these wildcards.
  201. * @param s Wilcards
  202. * @param sort Set to true will sort file names
  203. * @return An array of String which contains all files matching <code>s</code>
  204. * in current directory.
  205. */
  206. public static String[] getWildCardMatches(String s, boolean sort) {
  207. return getWildCardMatches(null, s, sort);
  208. }
  209. /**
  210. * When the user has to specify file names, he can use wildcards (*, ?). This methods
  211. * handles the usage of these wildcards.
  212. * @param path The path were to search
  213. * @param s Wilcards
  214. * @param sort Set to true will sort file names
  215. * @return An array of String which contains all files matching <code>s</code>
  216. * in current directory.
  217. */
  218. public static String[] getWildCardMatches(String path, String s, boolean sort) {
  219. String args = new String(s.trim());
  220. String files[];
  221. Vector filesThatMatchVector = new Vector();
  222. String filesThatMatch[];
  223. if (path == null)
  224. files = (new File(getUserDirectory())).list();
  225. else
  226. files = (new File(path)).list();
  227. for (int i = 0; i < files.length; i++) {
  228. if (match(args, files[i])) {
  229. File temp = new File(getUserDirectory(), files[i]);
  230. filesThatMatchVector.addElement(new String(temp.getName()));
  231. }
  232. }
  233. filesThatMatch = new String[filesThatMatchVector.size()];
  234. filesThatMatchVector.copyInto(filesThatMatch);
  235. if (sort) sortStrings(filesThatMatch);
  236. return filesThatMatch;
  237. }
  238. /**
  239. * This method can determine if a String matches a pattern of wildcards
  240. * @param pattern The pattern used for comparison
  241. * @param string The String to be checked
  242. * @return true if <code>string</code> matches <code>pattern</code>
  243. */
  244. public static boolean match(String pattern, String string) {
  245. for (int p = 0; ; p++) {
  246. for (int s = 0; ; p++, s++) {
  247. boolean sEnd = (s >= string.length());
  248. boolean pEnd = (p >= pattern.length() || pattern.charAt(p) == '|');
  249. if (sEnd && pEnd)
  250. return true;
  251. if (sEnd || pEnd)
  252. break;
  253. if (pattern.charAt(p) == '?')
  254. continue;
  255. if (pattern.charAt(p) == '*') {
  256. int i;
  257. p++;
  258. for (i = string.length(); i >= s; --i)
  259. if (match(pattern.substring(p), string.substring(i))) return true;
  260. break;
  261. }
  262. if (pattern.charAt(p) != string.charAt(s))
  263. break;
  264. }
  265. p = pattern.indexOf('|', p);
  266. if (p == -1)
  267. return false;
  268. }
  269. }
  270. /**
  271. * Quick sort an array of Strings.
  272. * @param string Strings to be sorted
  273. */
  274. public static void sortStrings(String[] strings) {
  275. sortStrings(strings, 0, strings.length - 1);
  276. }
  277. /**
  278. * Quick sort an array of Strings.
  279. * @param a Strings to be sorted
  280. * @param lo0 Lower bound
  281. * @param hi0 Higher bound
  282. */
  283. public static void sortStrings(String a[], int lo0, int hi0) {
  284. int lo = lo0;
  285. int hi = hi0;
  286. String mid;
  287. if (hi0 > lo0) {
  288. mid = a[(lo0 + hi0) / 2];
  289. while (lo <= hi) {
  290. while (lo < hi0 && a[lo].compareTo(mid) < 0)
  291. ++lo;
  292. while (hi > lo0 && a[hi].compareTo(mid) > 0)
  293. --hi;
  294. if (lo <= hi) {
  295. swap(a, lo, hi);
  296. ++lo;
  297. --hi;
  298. }
  299. }
  300. if (lo0 < hi)
  301. sortStrings(a, lo0, hi);
  302. if (lo < hi0)
  303. sortStrings(a, lo, hi0);
  304. }
  305. }
  306. /**
  307. * Swaps two Strings.
  308. * @param a The array to be swapped
  309. * @param i First String index
  310. * @param j Second String index
  311. */
  312. public static void swap(String a[], int i, int j) {
  313. String T;
  314. T = a[i];
  315. a[i] = a[j];
  316. a[j] = T;
  317. }
  318. /**
  319. * Because a lot of people still use JDK 1.1, we need this method
  320. * to create an array of Files from an array of String.
  321. * @param names Names of the files
  322. * @param construct Set it to true if names does not contain full paths
  323. * @return An array of Files
  324. */
  325. /*
  326. public static File[] listFiles(String[] names, boolean construct) {
  327. File[] files = new File[names.length];
  328. String path = getUserDirectory();
  329. if (construct) {
  330. if (!path.endsWith(File.separator))
  331. path += File.separator;
  332. }
  333. for (int i = 0; i < files.length; i++) {
  334. if (construct)
  335. files[i] = new File(path + names[i]);
  336. else
  337. files[i] = new File(names[i]);
  338. }
  339. return files;
  340. }
  341. /**
  342. * Create a blank String.
  343. * @param len Amount of spaces contained in the String
  344. * @return A blank <code>String</code>
  345. */
  346. /*
  347. public static String createWhiteSpace(int len) {
  348. StringBuffer buf = new StringBuffer();
  349. for (int i = 0; i < len; i++)
  350. buf.append(' ');
  351. return buf.toString();
  352. }
  353. /**
  354. * Some String can be too long to be correctly displayed on the screen.
  355. * Mainly when it is a path to a file. This method truncate a String.
  356. * @param longString The <code>String</code> to be truncated
  357. * @param maxLength The maximum length of the <code>String</code>
  358. * @return The truncated string
  359. */
  360. /*
  361. public static String getShortStringOf(String longString, int maxLength) {
  362. int len = longString.length();
  363. if (len < maxLength)
  364. return longString;
  365. else
  366. return longString.substring(0, maxLength / 2) + "..." + longString.substring(len - (maxLength / 2));
  367. }
  368. /**
  369. * Checks if a <code>String</code> matches true. Values that return true are:
  370. * <ul><li>true</li>
  371. * <li>yes</li>
  372. * <li>1</li><li>on</li></ul>
  373. * Values that return false are:
  374. * <ul><li>false</li>
  375. * <li>no</li>
  376. * <li>0</li><li>off</li></ul>
  377. * If the input is null or none of these values it returns the default value.
  378. *
  379. * @param input The String to check
  380. * @param defVal The Default value
  381. * @since v1.1
  382. */
  383. public static boolean checkIfTrue(String input, boolean defVal) {
  384. if(input == null) return defVal;
  385. if(input.equalsIgnoreCase("true")
  386. || input.equalsIgnoreCase("yes")
  387. || input.equalsIgnoreCase("1")
  388. || input.equalsIgnoreCase("on"))
  389. return true;
  390. else if(input.equalsIgnoreCase("false")
  391. || input.equalsIgnoreCase("no")
  392. || input.equalsIgnoreCase("0")
  393. || input.equalsIgnoreCase("off"))
  394. return false;
  395. return defVal;
  396. }
  397. public static String replace(String input, String oldPart, String newPart) {
  398. int len = oldPart.length();
  399. int newLen = newPart.length();
  400. int start = 0;
  401. while((start = input.indexOf(oldPart, start)) != -1) {
  402. input = input.substring(0, start) + newPart + input.substring(start + len);
  403. start += newLen; //else if oldPart appears in newPart replaces it --> infinaite loop
  404. }
  405. return input;
  406. }
  407. public static String[] findStrings(String input) {
  408. char quot1 = '\"';
  409. char quot2 = '\'';
  410. Vector v = new Vector(10);
  411. StreamTokenizer sT = new StreamTokenizer(new StringReader(input));
  412. sT.quoteChar(quot1);
  413. sT.quoteChar(quot2);
  414. int i;
  415. try {
  416. while((i = sT.nextToken()) != sT.TT_EOF) {
  417. if(i == sT.TT_WORD || i == quot1 || i == quot2) {
  418. v.add(sT.sval);
  419. }
  420. }
  421. } catch (IOException e) {
  422. e.printStackTrace();
  423. }
  424. String[] strings = new String[v.size()];
  425. v.copyInto(strings);
  426. return strings;
  427. }
  428. public static String trimStart(String input) {
  429. int str = 0;
  430. char[] val = input.toCharArray();
  431. while ((str < input.length()) && (val[str] <= ' ')) {
  432. str++;
  433. }
  434. return (str > 0) ? input.substring(str) : input;
  435. }
  436. }
  437. // End of Utilities.java