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