source: trunk/gli/src/org/greenstone/gatherer/util/Utility.java@ 4318

Last change on this file since 4318 was 4318, checked in by jmt12, 21 years ago

New static strings

  • Property svn:keywords set to Author Date Id Revision
File size: 38.4 KB
Line 
1package org.greenstone.gatherer.util;
2/**
3 *#########################################################################
4 *
5 * A component of the Gatherer application, part of the Greenstone digital
6 * library suite from the New Zealand Digital Library Project at the
7 * University of Waikato, New Zealand.
8 *
9 * <BR><BR>
10 *
11 * Author: John Thompson, Greenstone Digital Library, University of Waikato
12 *
13 * <BR><BR>
14 *
15 * Copyright (C) 1999 New Zealand Digital Library Project
16 *
17 * <BR><BR>
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * <BR><BR>
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * <BR><BR>
32 *
33 * You should have received a copy of the GNU General Public License
34 * along with this program; if not, write to the Free Software
35 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
36 *########################################################################
37 */
38import java.awt.*;
39import java.io.*;
40import java.net.*;
41import java.util.*;
42import javax.swing.*;
43import javax.swing.tree.*;
44import org.apache.xerces.parsers.*;
45import org.apache.xml.serialize.*;
46import org.greenstone.gatherer.Gatherer;
47import org.greenstone.gatherer.util.HTMLStringTokenizer;
48import org.w3c.dom.*;
49import org.xml.sax.*;
50/** To provide a library of common methods, in a static context, for use in the Gatherer.
51 * @author John Thompson, Greenstone Digital Library, University of Waikato
52 * @version 2.3b
53 */
54public class Utility {
55 /** The default size of a gatherer progress bar, in either the download view or the build view. */
56 static final public Dimension PROGRESS_BAR_SIZE = new Dimension(580,65);
57 /** The number of kilobytes to use as a io buffer. */
58 static final public int FACTOR = 1;
59 /** The size of the io buffer, calculated as FACTOR * 1024. */
60 static final public int BUFFER_SIZE = FACTOR * 1024;
61 /** Definition of an important directory name, in this case the archive directory for the collection. */
62 static final public String ARCHIVE_DIR = "archives" + File.separator;
63 /** Definition of an important directory name, in this case the base dir, or the working directory of the Gatherer. */
64 static final public String BASE_DIR = System.getProperty("user.dir") + File.separator;
65 /** Definition of an important directory name, in this case the building directory for the collection. */
66 static final public String BUILD_DIR = "building" + File.separator;
67 /** Definition of an important directory name, in this case the public web cache for the Gatherer. */
68 static final public String CACHE_DIR = BASE_DIR + "cache" + File.separator;
69 static final public String CFG_COLLECTIONMETA_COLLECTIONNAME = "collectionmeta collectionname";
70 static final public String CFG_COLLECTIONMETA_COLLECTIONEXTRA = "collectionmeta collectionextra";
71 static final public String CFG_CLASSIFY = "classify";
72 static final public String CFG_CLASSIFY_HFILE = "-hfile";
73 static final public String CFG_CLASSIFY_METADATA = "-metadata";
74 static final public String CFG_CLASSIFY_SORT = "-sort";
75 static final public String CFG_CREATOR = "creator";
76 static final public String CFG_FORMAT = "format";
77 static final public String CFG_MAINTAINER = "maintainer";
78 /** Definition of an important directory name, in this case the parent directory of all the collections in the gsdl. */
79 static final public String COL_DIR = "collect" + File.separator;
80 static final public String COLLECTION_DEMO = "greenstone demo";
81 static final public String COLLECTION_DEMO_DIRECTORY = "demo" + File.separator;
82 static final public String COLLECTION_DLS = "Development Library Subset";
83 static final public String COLLECTION_DLS_DIRECTORY = "dls" + File.separator;
84 static final public String COLLECTION_TREE = "Collection";
85 /** Definition of an important directory name, in this case the file the collection configuration is expect to be in. */
86 static final public String CONFIG_DIR = "etc" + File.separator + "collect.cfg";
87 /** The default file name for the urls missing any file. */
88 static final public String DEFAULT_FILE = "index.html";
89 static final public String DEFAULT_NAMESPACE = "gsp";
90 /** The default protocol header for those urls missing any protocol. */
91 static final public String DEFAULT_PROTOCOL = "http://";
92 /** The default dictionary to load. */
93 static final public String DICTIONARY = "dictionary";
94 static final public String DLS_MDS = "dls.mds";
95 static final public String ENGLISH_VALUE = "en";
96 /** Definition of an important directory name, in this case the etc (or extra information) directory for the collection. */
97 static final public String ETC_DIR = "etc" + File.separator;
98 static final public String EXTRACTED_METADATA_NAMESPACE = "ex";
99 /** The location of the default greenstone metadata file. */
100 static final public String GREENSTONEDIRECTORYMETADATA_TEMPLATE = "xml/metadata.xml";
101 /** Definition of an important directory name, in this case the private web cache directory for the collection. */
102 static final public String GCACHE_DIR = "gcache" + File.separator;
103/** Definition of an important directory name, in this case the location of help documentation. */
104 static final public String HELP_DIR = BASE_DIR + "help" + File.separator;
105 /** Definition of an important directory name, in this case the import directory for the collection. */
106 static final public String IMPORT_DIR = "gimport" + File.separator;
107 /** Definition of an important directory name, in this case the index directory for the collection. */
108 static final public String INDEX_DIR = "index" + File.separator;
109 static final public String LANGUAGE_ATTRIBUTE = "language";
110 /** Definition of an important directory name, in this case the location of the expected collection metadata sets.. */
111 static final public String META_DIR = "metadata" + File.separator; // Col. Copy
112 /** Definition of an important directory name, in this case the location of the default metadata sets. */
113 static final public String METADATA_DIR = BASE_DIR + "metadata" + File.separator;
114 static final public String METADATA_EXTRACTED = "extracted.mds";
115 /** The location the gatherer expects to find metadata set information. */
116 static final public String METADATA_SET_TEMPLATE = "xml" + File.separator + "template.mds";
117 static final public String METADATA_VALUE_TEMPLATE = "xml" + File.separator + "template.mdv";
118 static final public String METADATA_XML = "metadata.xml";
119 static final public String NAME_ELEMENT = "Name";
120 /** Definition of an important directory name, in this case the import directory for the collection. */
121 static final public String OLD_IMPORT_DIR = "import" + File.separator;
122 /** The default name of the perl executable under unix. */
123 static final public String PERL_EXECUTABLE_UNIX = "perl";
124 /** The default name of the perl executable under windows. */
125 static final public String PERL_EXECUTABLE_WINDOWS = "Perl.exe";
126 /** The name of the Gatherer. */
127 static final public String PROGRAM_NAME = "The Librarian Interface";
128 /** The current version of the Gatherer. */
129 static final public String PROGRAM_VERSION = "ver 2.0";
130 /** Definition of an important directory name, in this case the location of the recycled files location. */
131 static final public String RECYCLE = BASE_DIR + "recycle" + File.separator;
132 /** Definition of an important directory name, in this case the location of image and other resources. */
133 static final public String RES_DIR = BASE_DIR + "resource" + File.separator;
134 static final public String SERVER_EXE = "server.exe";
135 /** Definition of an important directory name, in this case the location of opening (or welcome) screen html. */
136 static final public String WELCOME_DIR = BASE_DIR + "welcome" + File.separator;
137 static final public String WORKSPACE_TREE = "Workspace";
138 // These are out of alphabetic order to avoid forward reference error.
139 /** The default icon to produce a 'help-icon' sized blank space before a menu entry. */
140 static final public ImageIcon BLANK_ICON = new ImageIcon(ClassLoader.getSystemResource("images/blank.gif"));
141 /** The default error icon image. */
142 static final public ImageIcon ERROR_ICON = new ImageIcon(ClassLoader.getSystemResource("images/error.gif"));
143 static final public ImageIcon HELP_ICON = new ImageIcon(ClassLoader.getSystemResource("images/help.gif"));
144 /** The image for a toggle button whose state is 'on'. */
145 static final public ImageIcon ON_ICON = new ImageIcon(ClassLoader.getSystemResource("images/check.gif"));
146 /** The image for a toggle button whose state is 'off'. */
147 static final public ImageIcon OFF_ICON = new ImageIcon(ClassLoader.getSystemResource("images/cross.gif"));
148 /** Method to turn a file from with the system file tree into a tree path for insertion into a tree.
149 * @param file The <strong>File</strong> whose tree path you are attempting to discover.
150 * @param in_col A <i>boolean</i> indicating whether we are looking for a file within a collection of not. If <i>true</i> then the tree paths head in the collection name, and no element in the path refers to the import directory. Otherwise the paths head will be one of the system roots and all traversed file locations will exist in the path.
151 * @return A <strong>TreePath</strong> which traverses the file system tree to the specified file.
152 */
153 public static TreePath createTreePath(File file, boolean in_col) {
154 TreePath path = null;
155 // Get the absolute path of the file.
156 String abs_path = file.getAbsolutePath();
157 while(file != null) {
158 // If we are looking for a node within our collection, we expect
159 // its path from root to be <col_name>/... without any higher
160 // details and without gimport. So if we encounter a gimport we
161 // skip to its parent, add that, then return.
162 if(in_col && file.getName().equals("gimport")) {
163 file = file.getParentFile();
164 if(path == null) {
165 path = new TreePath(file.getName());
166 }
167 else {
168 path = path.pathByAddingChild(file.getName());
169 }
170 file = null;
171 }
172 else {
173 if(path == null) {
174 path = new TreePath(file.getName());
175 }
176 else {
177 path = path.pathByAddingChild(file.getName());
178 }
179 file = file.getParentFile();
180 }
181 }
182 // Unfortunately we've created the path in reverse order so we have to
183 // reverse it.
184 Object temp[] = new Object[path.getPathCount()];
185 for(int i = 0; i < temp.length; i++) {
186 temp[(temp.length - 1) - i] = path.getPathComponent(i);
187 }
188 return new TreePath(temp);
189 }
190 /** Decodes a string of text so its safe to use in a Greenstone configuration file. Esentially replaces "\n" with a newline.
191 * @param raw The <strong>String</strong> before decoding, read from the configuration file..
192 * @return A <strong>String</strong> ready to be placed in a component.
193 */
194 static public String decodeGreenstone(String raw) {
195 raw = raw.replaceAll("&apos;", "\'");
196 raw = raw.replaceAll("&gt;", ">");
197 raw = raw.replaceAll("&lt;", "<");
198 raw = raw.replaceAll("&quot;", "\"");
199 raw = raw.replaceAll("&#39;", "\'");
200 raw = raw.replaceAll("\\\\n", "\n");
201 return raw;
202 }
203 /** Takes a rfc2616 'safe' String and translates it back into its 'unsafe' form. Basically the native c wget decode_string() function, but without pointer stuff. If searches through the String looking for the pattern %xy where x and y are hexidecimal digits and where xy maps to a character.<BR> If x or y are not hexidecimal or % is followed by a \0 then the pattern is left as is.
204 * @param encoded The url-safe <strong>String</strong> to be decoded.
205 * @return The decoded <strong>String</strong>.
206 */
207 public static String decodeString(String encoded) {
208 String decoded = "";
209 for(int i = 0; i < encoded.length(); i++) {
210 if(encoded.charAt(i) == '%') {
211 if(hexidecimal(encoded.charAt(i+1)) != -1
212 && hexidecimal(encoded.charAt(i+2)) != -1) {
213 char unsafe_chr = (char)
214 ((hexidecimal(encoded.charAt(i+1)) * 16) +
215 hexidecimal(encoded.charAt(i+2)));
216 decoded = decoded + unsafe_chr;
217 i = i + 2;
218 }
219 }
220 else {
221 decoded = decoded + encoded.charAt(i);
222 }
223 }
224 return decoded;
225 }
226 /** It turns out that in Java you have to make sure a directory is empty before you delete it (much like unix I suppose), and so just like unix I'll have to set up a recursive delete function.
227 * @param file The <strong>File</strong> you want to delete.
228 * @return A <i>boolean</i> which is <i>true</i> if the file specified was successfully deleted, <i>false</i> otherwise.
229 */
230 static public boolean delete(File file) {
231 boolean result = true;
232 // If files a directory, delete files children.
233 if(file.isDirectory()) {
234 File files[] = file.listFiles();
235 for(int i = 0; files != null && result && i < files.length; i++) {
236 result = delete(files[i]);
237 }
238 }
239 if(result) {
240 // Delete file.
241 return file.delete();
242 }
243 return result;
244 }
245 /** Generate a depth first enumeration of a tree. */
246 static public EnumeratedVector depthFirstEnumeration(TreeNode node, EnumeratedVector result) {
247 result.add(node);
248 for(int i = 0; i < node.getChildCount(); i++) {
249 depthFirstEnumeration(node.getChildAt(i), result);
250 }
251 return result;
252 }
253 /** Encodes a string of text so its safe to use in a Greenstone configuration file. Esentially replaces newlines with their escaped form.
254 * @param raw The <strong>String</strong> before encoding.
255 * @return A <strong>String</strong> which is safe to write to the configuration file.
256 */
257 static public String encodeGreenstone(String raw) {
258 raw = raw.replaceAll("<", "&lt;");
259 raw = raw.replaceAll(">", "&gt;");
260 return raw.replaceAll("\n", "\\\\n");
261 }
262
263 /** Using this method we can request that a certain document be written, as valid XML, to a certain output stream. This makes use of the Xerces Serialization suite, which should in no way be confused with the usual method of Serialization used by Java. */
264 static public boolean export(Document document, String filename) {
265 return export(document, new File(filename));
266 }
267
268 static public boolean export(Document document, File file) {
269 try {
270 OutputStream os = new FileOutputStream(file);
271 // Create an output format for our document.
272 OutputFormat f = new OutputFormat(document);
273 f.setIndenting(true);
274 f.setLineWidth(256);
275 f.setPreserveSpace(false);
276 // Create the necessary writer stream for serialization.
277 OutputStreamWriter osw = new OutputStreamWriter(os);
278 Writer w = new BufferedWriter(osw);
279 // Generate a new serializer from the above.
280 XMLSerializer s = new XMLSerializer(w, f);
281 s.asDOMSerializer();
282 // Finally serialize the document to file.
283 s.serialize(document);
284 // And close.
285 os.close();
286 return true;
287 }
288 // A file not found exception is most likely thrown because the directory the metadata.xml file is attempting to be written to no longer has any files in it. I'll add a test in GDMDocument to test for this, but if it still happens ignore it (a non-existant directory can't really have metadata added to it any way.
289 catch (FileNotFoundException fnf_exception) {
290 if(!file.getName().endsWith(METADATA_XML)) {
291 fnf_exception.printStackTrace();
292 return false;
293 }
294 return true;
295 }
296 catch (IOException ioe) {
297 ioe.printStackTrace();
298 return false;
299 }
300 }
301
302 /** Given a starting directory, searches for the collect.cfg file and returns it if found.
303 * @return The collect.cfg File or null if not found.
304 */
305 static final public File findConfigFile(File start) {
306 if(start == null) {
307 return null;
308 }
309 // See if the collect.cfg files here.
310 File collect_cfg = new File(start, "collect.cfg");
311 if(collect_cfg.exists()) {
312 return collect_cfg;
313 }
314 // Search for the existance of collect.cfg in a etc directory.
315 File etc_dir = new File(start, "etc" + File.separator + "collect.cfg");
316 if(etc_dir.exists()) {
317 return etc_dir;
318 }
319 // Otherwise search this directories parent if its not null.
320 return findConfigFile(start.getParentFile());
321 }
322
323 /** Convert a long, detailing the length of a file in bytes, into a nice human readable string using b, kb, Mb and Gb. */
324 static final public String BYTE_SUFFIX = " b";
325 static final public long GIGABYTE = 1024000000l;
326 static final public String GIGABYTE_SUFFIX = " Gb";
327 static final public long KILOBYTE = 1024l;
328 static final public String KILOBYTE_SUFFIX = " kb";
329 static final public long MEGABYTE = 1024000l;
330 static final public String MEGABYTE_SUFFIX = " mb";
331 static final public String formatFileLength(long length) {
332 StringBuffer result = new StringBuffer("");
333 float number = 0f;
334 String suffix = null;
335 // Determine the floating point number and the suffix (radix) used.
336 if(length >= GIGABYTE) {
337 number = (float) length / (float) GIGABYTE;
338 suffix = GIGABYTE_SUFFIX;
339 }
340 else if(length >= MEGABYTE) {
341 number = (float) length / (float) MEGABYTE;
342 suffix = MEGABYTE_SUFFIX;
343 }
344 else if(length >= KILOBYTE) {
345 number = (float) length / (float) KILOBYTE;
346 suffix = KILOBYTE_SUFFIX;
347 }
348 else {
349 number = (float) length;
350 suffix = BYTE_SUFFIX;
351 }
352 // Create the formatted string remembering to round the number to 2.d.p. To do this copy everything in the number string from the start to the first occurance of '.' then copy two more digits. Finally search for and print anything that appears after (and including) the optional 'E' delimter.
353 String number_str = Float.toString(number);
354 char number_char[] = number_str.toCharArray();
355 int pos = 0;
356 // Print the characters up to the '.'
357 while(number_char != null && pos < number_char.length && number_char[pos] != '.') {
358 result.append(number_char[pos]);
359 pos++;
360 }
361 if(pos < number_char.length) {
362 // Print the '.' and at most two characters after it
363 result.append(number_char[pos]);
364 pos++;
365 for(int i = 0; i < 2 && pos < number_char.length; i++, pos++) {
366 result.append(number_char[pos]);
367 }
368 // Search through the remaining string for 'E'
369 while(pos < number_char.length && number_char[pos] != 'E') {
370 pos++;
371 }
372 // If we still have string then we found an E. Copy the remaining string.
373 while(pos < number_char.length) {
374 result.append(number_char[pos]);
375 pos++;
376 }
377 }
378 // Add suffix
379 result.append(suffix);
380 // Done
381 return result.toString();
382 }
383
384 /** This method formats a given string, using HTML markup, so its width does not exceed the given width and its appearance if justified.
385 * @param text The <strong>String</strong> requiring formatting.
386 * @param width The maximum width per line as an <i>int</i>.
387 * @return A <strong>String</strong> formatted so as to have no line longer than the specified width.
388 * TODO Currently HTML formatting tags are simply removed from the text, as the effects of spreading HTML tags over a break are undetermined. To solve this we need to associate tags with a certain text token so if it gets broken on to the next line the tags go with it, or if the tags cover a sequence of words that are broken we need to close then reopen the tags. However all this is a major task and well beyond anything I have time to 'muck-round' on.
389 */
390 static public String formatHTMLWidth(String text, int width) {
391 HTMLStringTokenizer html = new HTMLStringTokenizer(text);
392 int current_width = 0;
393 int threshold = width / 2;
394 Stack lines = new Stack();
395 String line = "";
396 while(html.hasMoreTokens()) {
397 String token = html.nextToken();
398 while(token != null) {
399 if(html.isTag()) {
400 // Insert smart HTML tag code here.
401 token = null;
402 }
403 else {
404 // If the token is bigger than two thirds width, before we've even started break it down.
405 if(current_width + 1 + token.length() > width && token.length() > threshold) {
406 String prefix = token.substring(0, width - 1 - current_width);
407 token = token.substring(prefix.length());
408 if(current_width == 0) {
409 line = line + prefix;
410 }
411 else {
412 line = line + " " + prefix;
413 }
414 lines.push(line);
415 line = "";
416 current_width = 0;
417 }
418 // If adding the next token would push us over the maximum line width.
419 else if(current_width + 1 + token.length() > width) {
420 line = space(line, width, current_width);
421 lines.push(line);
422 line = token;
423 current_width = token.length();
424 token = null;
425 }
426 // Otherwise we should be able to just add the token, give or take.
427 else {
428 if(current_width == 0) {
429 line = line + token;
430 current_width = token.length();
431 }
432 else {
433 // Special case for standard punctuation which may exist after a tag like so:
434 // My name is <scratchy>Slim Shady</scratchy>. <-- Annoying punctuation.
435 if(token.equals(".") || token.equals(",") || token.equals("!") || token.equals("?")) {
436 line = line + token;
437 current_width = current_width + 1;
438 }
439 else {
440 line = line + " " + token;
441 current_width = current_width + 1 + token.length();
442 }
443 }
444 token = null;
445 }
446 }
447 }
448 }
449 String result = line;
450 while(!lines.empty()) {
451 result = (String)lines.pop() + "<BR>" + result;
452 }
453 // Replace ' ' with "&nbsp;"
454 boolean tag = false;
455 int pos = 0;
456 while(pos < result.length()) {
457 if(result.charAt(pos) == '<') {
458 tag = true;
459 }
460 else if(result.charAt(pos) == '>') {
461 tag = false;
462 }
463 else if(result.charAt(pos) == ' ' && !tag) {
464 String prefix = result.substring(0, pos);
465 String suffix = result.substring(pos + 1);
466 result = prefix + "&nbsp;" + suffix;
467 }
468 pos++;
469 }
470 result = "<HTML>" + result + "</HTML>";
471 return result;
472 }
473 /** Format the given filename path string so that it is no longer than the given width. If it is wider replace starting directories with ...
474 * @param key The key <strong>String</Strong> used to retrieve a phrase from the dictionary for this item.
475 * @param raw The raw filename path <strong>String</strong>.
476 * @param width The maximum width as an <i>int</i>.
477 * @return A path <strong>String</strong> no longer than width.
478 */
479 static public String formatPath(String key, String raw, int width) {
480 JLabel label = new JLabel(Gatherer.dictionary.get(key, raw));
481 int position = -1;
482 while(label.getPreferredSize().width > width && (position = raw.indexOf(File.separator)) != -1) {
483 raw = "..." + raw.substring(position + 1);
484 label.setText(Gatherer.dictionary.get(key, raw));
485 }
486 if(raw.indexOf(File.separator) == -1 && raw.startsWith("...")) {
487 raw = raw.substring(3);
488 }
489 return raw;
490 }
491
492 /** Method which constructs the archive directory given a certain collection.
493 * @param col_dir The location of the collection directory as a <strong>String</strong>.
494 * @return The location of the given collections archive directory, also as a <strong>String</strong>.
495 */
496 static public String getArchiveDir(String gsdl_path, String col_name) {
497 return gsdl_path + File.separator + COL_DIR + col_name + File.separator + ARCHIVE_DIR;
498 }
499 /** Method which constructs the build directory given a certain collection.
500 * @param col_dir The location of the collection directory as a <strong>String</strong>.
501 * @return The location of the given collections build directory, also as a <strong>String</strong>.
502 */
503 static public String getBuildDir(String col_dir) {
504 if(col_dir == null) {
505 return BASE_DIR + BUILD_DIR;
506 }
507 return col_dir + BUILD_DIR;
508 }
509 /** Builds the private cache dir by appending col_dir and 'cache'.
510 * @param col_dir A String representing the directory path of the current collection.
511 * @return A String representing the path to the private file cache within the current collection.
512 */
513 public static String getCacheDir(String col_dir) {
514 return col_dir + GCACHE_DIR;
515 }
516 /** Method which constructs the collection directory for Greenstone.
517 * @param gsdl_path The location of the gsdl installation directory as a <strong>String</strong>.
518 * @return The location of the collection directory, also as a <strong>String</strong>.
519 */
520 public static String getCollectionDir(String gsdl_path) {
521 return gsdl_path + COL_DIR;
522 }
523 /** Method which constructs the configuration file given a certain collection.
524 * @param col_dir The location of the collection directory as a <strong>String</strong>.
525 * @return The location of the given collections configuration file, also as a <strong>String</strong>.
526 */
527 static public String getConfigDir(String col_dir) {
528 return col_dir + CONFIG_DIR;
529 }
530
531 static public String getDateString() {
532 Calendar current = Calendar.getInstance();
533 String day_name = null;
534 switch(current.get(Calendar.DAY_OF_WEEK)) {
535 case Calendar.MONDAY: day_name = "Mon"; break;
536 case Calendar.TUESDAY: day_name = "Tue"; break;
537 case Calendar.WEDNESDAY: day_name = "Wed"; break;
538 case Calendar.THURSDAY: day_name = "Thu"; break;
539 case Calendar.FRIDAY: day_name = "Fri"; break;
540 case Calendar.SATURDAY: day_name = "Sat"; break;
541 case Calendar.SUNDAY: day_name = "Sun"; break;
542 default: day_name = "";
543 }
544 String month_name = null;
545 switch(current.get(Calendar.MONTH)) {
546 case Calendar.JANUARY: month_name = "Jan"; break;
547 case Calendar.FEBRUARY: month_name = "Feb"; break;
548 case Calendar.MARCH: month_name = "Mar"; break;
549 case Calendar.APRIL: month_name = "Apr"; break;
550 case Calendar.MAY: month_name = "May"; break;
551 case Calendar.JUNE: month_name = "Jun"; break;
552 case Calendar.JULY: month_name = "Jul"; break;
553 case Calendar.AUGUST: month_name = "Aug"; break;
554 case Calendar.SEPTEMBER: month_name = "Sep"; break;
555 case Calendar.OCTOBER: month_name = "Oct"; break;
556 case Calendar.NOVEMBER: month_name = "Nov"; break;
557 case Calendar.DECEMBER: month_name = "Dec"; break;
558 default: month_name = "";
559 }
560 int day = current.get(Calendar.DAY_OF_MONTH);
561 int hour = current.get(Calendar.HOUR_OF_DAY);
562 int minute = current.get(Calendar.MINUTE);
563 int second = current.get(Calendar.SECOND);
564 int year = current.get(Calendar.YEAR);
565
566 return day_name + " " + month_name + " " + day + " " + year + " " + Utility.pad(String.valueOf(hour), 2, '0', true) + ":" + Utility.pad(String.valueOf(minute), 2, '0', true) + ":" + Utility.pad(String.valueOf(second), 2, '0', true);
567 }
568
569 /** Retrieves and formats the depth field of the config file to four characters.
570 * @param length The length of the desired string as an <i>int</i>.
571 * @return A <strong>String</strong> representation of the mirroring depth padded to length characters.
572 */
573 public static String getDepthString(int length) {
574 return pad("" + Gatherer.self.config.getInt("mirroring.depth", false), length);
575 }
576 /** Method which constructs the etc directory given a certain collection.
577 * @param col_dir The location of the collection directory as a <strong>String</strong>.
578 * @return The location of the given collections etc directory, also as a <strong>String</strong>.
579 */
580 public static String getEtcDir(String col_dir) {
581 return col_dir + ETC_DIR;
582 }
583 /** Method to retrieve an image icon with the given filename found in classpath or the resouces directory.
584 * @return The specified <strong>ImageIcon</strong>, or an error image replacement if no such images exists.
585 */
586 static public ImageIcon getImage(String filename) {
587 ImageIcon image = null;
588 try {
589 image = new ImageIcon(ClassLoader.getSystemResource("images/" + Gatherer.dictionary.get("Version") + File.separator + filename));
590 }
591 catch(Exception error_one) {
592 try {
593 image = new ImageIcon(ClassLoader.getSystemResource("images/" + filename));
594 }
595 catch (Exception error_two) {
596 if(Gatherer.dictionary != null) {
597 File locale_image_file = new File(RES_DIR + Gatherer.dictionary.get("Version") + File.separator + filename);
598 if(locale_image_file.exists()) {
599 image = new ImageIcon(locale_image_file.toString());
600 }
601 }
602 if(image == null) {
603 File image_file = new File(RES_DIR + filename);
604 if(image_file.exists()) {
605 image = new ImageIcon(image_file.toString());
606 }
607 }
608 }
609 }
610 if(image == null) {
611 image = ERROR_ICON;
612 }
613 return image;
614 }
615
616 /** Method which constructs the import directory given a certain collection.
617 * @param col_dir The location of the collection directory as a <strong>String</strong>.
618 * @return The location of the given collections import directory, also as a <strong>String</strong>.
619 */
620 public static String getImportDir(String col_dir) {
621 return col_dir + IMPORT_DIR;
622 }
623 /** Method which constructs the index directory given a certain collection.
624 * @param col_dir The location of the collection directory as a <strong>String</strong>.
625 * @return The location of the given collections index directory, also as a <strong>String</strong>.
626 */
627 static public String getIndexDir(String col_dir) {
628 return col_dir + INDEX_DIR;
629 }
630 /** Determine this machines name.
631 * @return The name as a <strong>String</strong>.
632 */
633 static public String getMachineName() {
634 try {
635 return InetAddress.getLocalHost().getHostName();
636 }
637 catch(UnknownHostException ex) {
638 }
639 return "Unknown Machine";
640 }
641 /** Method which constructs the metadata directory given a certain collection.
642 * @param col_dir The location of the collection directory as a <strong>String</strong>.
643 * @return The location of the given collections metadata directory, also as a <strong>String</strong>.
644 */
645 static public String getMetadataDir(String col_dir) {
646 return col_dir + META_DIR;
647 }
648
649
650 static public File getRecycleDirectory() {
651 return new File(RECYCLE);
652 }
653
654 /** Determine whether a character is a hexidecimal one.
655 * @param chr The <i>char</i> in question.
656 * @return An <i>int</i> representing the value of the hexidecimal character or -1 if not a hexidecimal.
657 */
658 public static int hexidecimal(char chr) {
659 switch(chr) {
660 case '0':
661 return 0;
662 case '1':
663 return 1;
664 case '2':
665 return 2;
666 case '3':
667 return 3;
668 case '4':
669 return 4;
670 case '5':
671 return 5;
672 case '6':
673 return 6;
674 case '7':
675 return 7;
676 case '8':
677 return 8;
678 case '9':
679 return 9;
680 case 'A':
681 return 10;
682 case 'B':
683 return 11;
684 case 'C':
685 return 12;
686 case 'D':
687 return 13;
688 case 'E':
689 return 14;
690 case 'F':
691 return 15;
692 default:
693 return -1;
694 }
695 }
696
697 /** A string is a valid hierarchy index if it matches '[0-9](\.[0-9])*' */
698 static public boolean isIndex(String raw) {
699 boolean result = true;
700 for(int i = 0; result && i < raw.length(); i++) {
701 char c = raw.charAt(i);
702 if(Character.isDigit(c) || (c == '.' && (i != 0 || i != raw.length() - 1))) {
703 // Valid index
704 }
705 else {
706 result = false;
707 }
708 }
709 return result;
710 }
711
712 /** Method to determine if the host system is Microsoft Windows based.
713 * @return A <i>boolean</i> which is <i>true</i> if the platform is Windows, <i>false</i> otherwise.
714 */
715 public static boolean isWindows() {
716 Properties props = System.getProperties();
717 String os_name = props.getProperty("os.name","");
718 if(os_name.startsWith("Windows")) {
719 return true;
720 }
721 return false;
722 }
723 /** Takes a string and a desired length and pads out the string to the length by adding spaces to the left.
724 * @param str The target <strong>String</strong> that needs to be padded.
725 * @param length The desired length of the string as an <i>int</i>.
726 * @return A <strong>String</strong> made from appending space characters with the string until it has a length equal to length.
727 */
728 public static String pad(String str, int length) {
729 return pad(str, length, ' ', true);
730 }
731 public static String pad(String str_raw, int length, char fill, boolean end) {
732 StringBuffer str = new StringBuffer(str_raw);
733 while(str.length() < length) {
734 if(end) {
735 str.insert(0, fill);
736 }
737 else {
738 str.append(fill);
739 }
740 }
741 return str.toString();
742 }
743
744 /** Parse in a xml document from a given filename. Note that this filename may need to be resolved by the class loader, especially for template files within a jar. */
745 static public Document parse(String filename, boolean use_classloader) {
746 File file = null;
747 if(use_classloader) {
748 try {
749 URL url = ClassLoader.getSystemResource(filename);
750 file = new File(URLDecoder.decode(url.getFile()));
751 url = null;
752 }
753 catch (Exception error) {
754 // Most likely file name.
755 file = new File("classes" + File.separator + filename);
756 //Gatherer.printStackTrace(error);
757 }
758 }
759 if(file == null) {
760 file = new File(filename);
761 }
762 return parse(file, true);
763 }
764 /** Parse in a xml document from a given file. */
765 static public Document parse(File file) {
766 return parse(file, true);
767 }
768 /** Parse in a xml document from a given file. */
769 static public Document parse(File file, boolean noisey) {
770 Document document = null;
771 try {
772 FileInputStream fis = new FileInputStream(file);
773 InputStreamReader isr = new InputStreamReader(fis);
774 Reader r = new BufferedReader(isr);
775 InputSource isc = new InputSource(r);
776 DOMParser parser = new DOMParser();
777 parser.setFeature("http://xml.org/sax/features/validation", false);
778 parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
779 // May or may not be ignored, the documentation for Xerces is contradictory. If it works then parsing -should- be faster.
780 parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", true);
781 parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
782 parser.parse(isc);
783 document = parser.getDocument();
784 isr.close();
785 fis.close();
786 parser = null;
787 isc = null;
788 r = null;
789 isr = null;
790 fis = null;
791 file = null;
792 }
793 catch (Exception error) {
794 if(noisey) {
795 Gatherer.printStackTrace(error);
796 }
797 }
798 return document;
799 }
800
801 /** Method to spread out a line of text so that is is justified to the given width, by attempting to widen white-spacing in a balanced way.
802 * @param original The <strong>String</strong> to justify.
803 * @param width The desired width as an <i>int</i>.
804 * @param current_width An <i>int</i> representing the current width of the string, which takes into account special characters.
805 * @return The newly justified <strong>String</strong>.
806 */
807 static public String space(String original, int width, int current_width) {
808 // Strip trailing whitespace.
809 while(original.charAt(original.length() - 1) == ' ') {
810 original = original.substring(0, original.length() - 2);
811 }
812 int diff = width - current_width;
813 // Now add diff spaces, one at each existing space.
814 int pos = 0;
815 while(diff > 0) {
816 if(pos == original.length()) {
817 pos = 0;
818 }
819 if(original.charAt(pos) == ' ') {
820 // Insert a space.
821 String prefix = original.substring(0, pos);
822 String suffix = original.substring(pos);
823 original = prefix + " " + suffix;
824 pos = pos + 2;
825 diff--;
826 }
827 pos++;
828 }
829 return original;
830 }
831 /** Method to strip new lines and extra spaces from a string. Used to restore text that has been mangled into width formatted blocks by the DOM parser.
832 * @param raw The <strong>Strong</strong> containing the mangled text.
833 * @return A <strong>String</strong> with new lines and extra spaces removed.
834 */
835 static public String stripNL(String raw_str) {
836 byte raw[] = raw_str.getBytes();
837 byte formatted[] = new byte[raw.length];
838 byte previous = '\0';
839 int j = 0;
840 for(int i = 0; i < raw.length; i++) {
841 if(raw[i] == '\n') {
842 // Skip new lines.
843 }
844 else if(raw[i] == '\t') {
845 // Skip tabs.
846 }
847 else if(raw[i] == ' ' && raw[i] == previous) {
848 // Skip erroneous whitespace.
849 }
850 else {
851 formatted[j] = raw[i];
852 j++;
853 }
854 previous = raw[i];
855 }
856 byte finish[] = new byte[j];
857 System.arraycopy(formatted, 0, finish, 0, j);
858 return new String(finish);
859 }
860 /** Trims the string text to the length specified removing end characters and adding if necessary.
861 * @param text A <strong>String</strong> which you wish to ensure is shorter than length.
862 * @param length An <i>int</i> specifying the strings maximum length after which its trimmed.
863 * @return The trimmed <strong>String</strong>.
864 */
865 public static String trim(String text, int length) {
866 if(text.length() > length) {
867 text = text.substring(0, length);
868 text = text + "...";
869 }
870 return text;
871 }
872
873 static public String trimCenter(String text, int length) {
874 if(text.length() > length) {
875 int half = (length - 3) / 2;
876 StringBuffer temp = new StringBuffer(text.substring(0, half));
877 temp.append("...");
878 temp.append(text.substring(text.length() - half));
879 text = temp.toString();
880 }
881 return text;
882 }
883 /** This method checks to see what registered file system root directorys are mounted, and returns only accessible ones. The exception is removable media drives (in particular floppy-disk drives) which will throw all sorts of error if we test them here. Instead they are assumed to be always accessible, but a test is conducted at the time you attempt to map them to test for actual accessibility (then at least the errors are thrown after the user tries to initiate the mapping of the drive which has no disk in it).
884 * @param roots A <strong>File[]</strong> containing all of the file system roots registered on this system.
885 * @return A filtered <strong>File[]</strong> containing only those drives that are accessible and/or are floppy-disk media drives.
886 */
887 public static File[] validateDrives(File roots[]) {
888 Vector valid = new Vector();
889 for(int i = 0; i < roots.length; i++) {
890 String name = roots[i].getAbsolutePath();
891 name = name.toLowerCase();
892 if(!name.startsWith("a:") && !name.startsWith("b:")) {
893 valid.add(roots[i]);
894 }
895 }
896 roots = new File[valid.size()];
897 for(int i = 0; i < roots.length; i++) {
898 roots[i] = (File)valid.get(i);
899 }
900 return roots;
901 }
902}
903
904
905
Note: See TracBrowser for help on using the repository browser.