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

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

Major CDM rewrite so it uses DOM.

  • 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_COLLECTIONMETA_ICONCOLLECTION = "collectionmeta iconcollection";
72 static final public String CFG_CLASSIFY = "classify";
73 static final public String CFG_CLASSIFY_BUTTONNAME = "-buttonname";
74 static final public String CFG_CLASSIFY_HFILE = "-hfile";
75 static final public String CFG_CLASSIFY_METADATA = "-metadata";
76 static final public String CFG_CLASSIFY_SORT = "-sort";
77 static final public String CFG_CREATOR = "creator";
78 static final public String CFG_FORMAT = "format";
79 static final public String CFG_MAINTAINER = "maintainer";
80 /** Definition of an important directory name, in this case the parent directory of all the collections in the gsdl. */
81 static final public String COL_DIR = "collect" + File.separator;
82 static final public String COLLECTION_DEMO = "greenstone demo";
83 static final public String COLLECTION_DEMO_DIRECTORY = "demo" + File.separator;
84 static final public String COLLECTION_DLS = "Development Library Subset";
85 static final public String COLLECTION_DLS_DIRECTORY = "dls" + File.separator;
86 static final public String COLLECTION_TREE = "Collection";
87 /** Definition of an important directory name, in this case the file the collection configuration is expect to be in. */
88 static final public String CONFIG_DIR = "etc" + File.separator + "collect.cfg";
89 /** The default file name for the urls missing any file. */
90 static final public String DEFAULT_FILE = "index.html";
91 static final public String DEFAULT_NAMESPACE = "gsp";
92 /** The default protocol header for those urls missing any protocol. */
93 static final public String DEFAULT_PROTOCOL = "http://";
94 /** The default dictionary to load. */
95 static final public String DICTIONARY = "dictionary";
96 static final public String DLS_MDS = "dls.mds";
97 static final public String ENGLISH_VALUE = "en";
98 /** Definition of an important directory name, in this case the etc (or extra information) directory for the collection. */
99 static final public String ETC_DIR = "etc" + File.separator;
100 static final public String EXTRACTED_METADATA_NAMESPACE = "ex";
101 /** The location of the default greenstone metadata file. */
102 static final public String GREENSTONEDIRECTORYMETADATA_TEMPLATE = "xml/metadata.xml";
103 /** Definition of an important directory name, in this case the private web cache directory for the collection. */
104 static final public String GCACHE_DIR = "gcache" + File.separator;
105 static final public String GLI_ARCHIVE = "GLI.jar";
106 /** Definition of an important directory name, in this case the location of help documentation. */
107 static final public String HELP_DIR = BASE_DIR + "help" + File.separator;
108 /** Definition of an important directory name, in this case the import directory for the collection. */
109 static final public String IMPORT_DIR = "gimport" + File.separator;
110 /** Definition of an important directory name, in this case the index directory for the collection. */
111 static final public String INDEX_DIR = "index" + File.separator;
112 static final public String LANGUAGE_ATTRIBUTE = "language";
113 /** Definition of an important directory name, in this case the log directory for the collection. */
114 static final public String LOG_DIR = "log" + File.separator;
115 /** Definition of an important directory name, in this case the location of the expected collection metadata sets.. */
116 static final public String META_DIR = "metadata" + File.separator; // Col. Copy
117 /** Definition of an important directory name, in this case the location of the default metadata sets. */
118 static final public String METADATA_DIR = BASE_DIR + "metadata" + File.separator;
119 static final public String METADATA_EXTRACTED = "extracted.mds";
120 /** The location the gatherer expects to find metadata set information. */
121 static final public String METADATA_SET_TEMPLATE = "xml/template.mds";
122 static final public String METADATA_VALUE_TEMPLATE = "xml/template.mdv";
123 static final public String METADATA_XML = "metadata.xml";
124 static final public String NAME_ELEMENT = "Name";
125 /** Definition of an important directory name, in this case the import directory for the collection. */
126 static final public String OLD_IMPORT_DIR = "import" + File.separator;
127 /** The default name of the perl executable under unix. */
128 static final public String PERL_EXECUTABLE_UNIX = "perl";
129 /** The default name of the perl executable under windows. */
130 static final public String PERL_EXECUTABLE_WINDOWS = "Perl.exe";
131 /** The default profile file */
132 static final public String PROFILE_TEMPLATE = "xml/protemp.xml";
133 /** The name of the Gatherer. */
134 static final public String PROGRAM_NAME = "Greenstone Librarian Interface";
135 /** The current version of the Gatherer. */
136 static final public String PROGRAM_VERSION = "ver 2.0";
137 /** Definition of an important directory name, in this case the location of the recycled files location. */
138 static final public String RECYCLE = BASE_DIR + "recycle" + File.separator;
139 /** Definition of an important directory name, in this case the location of image and other resources. */
140 static final public String RES_DIR = BASE_DIR + "resource" + File.separator;
141 static final public String SERVER_EXE = "server.exe";
142 /** Definition of an important directory name, in this case the location of opening (or welcome) screen html. */
143 static final public String WELCOME_DIR = BASE_DIR + "welcome" + File.separator;
144 static final public String WORKSPACE_TREE = "Workspace";
145 static final public String XML_DIRECTORY = "xml" + File.separator;
146 // These are out of alphabetic order to avoid forward reference error.
147 /** The default icon to produce a 'help-icon' sized blank space before a menu entry. */
148 static final public ImageIcon BLANK_ICON = new ImageIcon(ClassLoader.getSystemResource("images/blank.gif"));
149 /** The default error icon image. */
150 static final public ImageIcon ERROR_ICON = new ImageIcon(ClassLoader.getSystemResource("images/error.gif"));
151 static final public ImageIcon HELP_ICON = new ImageIcon(ClassLoader.getSystemResource("images/help.gif"));
152 /** The image for a toggle button whose state is 'on'. */
153 static final public ImageIcon ON_ICON = new ImageIcon(ClassLoader.getSystemResource("images/check.gif"));
154 /** The image for a toggle button whose state is 'off'. */
155 static final public ImageIcon OFF_ICON = new ImageIcon(ClassLoader.getSystemResource("images/cross.gif"));
156 /** Method to turn a file from with the system file tree into a tree path for insertion into a tree.
157 * @param file The <strong>File</strong> whose tree path you are attempting to discover.
158 * @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.
159 * @return A <strong>TreePath</strong> which traverses the file system tree to the specified file.
160 */
161 public static TreePath createTreePath(File file, boolean in_col) {
162 TreePath path = null;
163 // Get the absolute path of the file.
164 String abs_path = file.getAbsolutePath();
165 while(file != null) {
166 // If we are looking for a node within our collection, we expect
167 // its path from root to be <col_name>/... without any higher
168 // details and without gimport. So if we encounter a gimport we
169 // skip to its parent, add that, then return.
170 if(in_col && file.getName().equals("gimport")) {
171 file = file.getParentFile();
172 if(path == null) {
173 path = new TreePath(file.getName());
174 }
175 else {
176 path = path.pathByAddingChild(file.getName());
177 }
178 file = null;
179 }
180 else {
181 if(path == null) {
182 path = new TreePath(file.getName());
183 }
184 else {
185 path = path.pathByAddingChild(file.getName());
186 }
187 file = file.getParentFile();
188 }
189 }
190 // Unfortunately we've created the path in reverse order so we have to
191 // reverse it.
192 Object temp[] = new Object[path.getPathCount()];
193 for(int i = 0; i < temp.length; i++) {
194 temp[(temp.length - 1) - i] = path.getPathComponent(i);
195 }
196 return new TreePath(temp);
197 }
198 /** Decodes a string of text so its safe to use in a Greenstone configuration file. Esentially replaces "\n" with a newline.
199 * @param raw The <strong>String</strong> before decoding, read from the configuration file..
200 * @return A <strong>String</strong> ready to be placed in a component.
201 */
202 static public String decodeGreenstone(String raw) {
203 raw = raw.replaceAll("&apos;", "\'");
204 raw = raw.replaceAll("&gt;", ">");
205 raw = raw.replaceAll("&lt;", "<");
206 raw = raw.replaceAll("&quot;", "\"");
207 raw = raw.replaceAll("&#39;", "\'");
208 raw = raw.replaceAll("\\\\n", "\n");
209 return raw;
210 }
211 /** 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.
212 * @param encoded The url-safe <strong>String</strong> to be decoded.
213 * @return The decoded <strong>String</strong>.
214 */
215 public static String decodeString(String encoded) {
216 String decoded = "";
217 for(int i = 0; i < encoded.length(); i++) {
218 if(encoded.charAt(i) == '%') {
219 if(hexidecimal(encoded.charAt(i+1)) != -1
220 && hexidecimal(encoded.charAt(i+2)) != -1) {
221 char unsafe_chr = (char)
222 ((hexidecimal(encoded.charAt(i+1)) * 16) +
223 hexidecimal(encoded.charAt(i+2)));
224 decoded = decoded + unsafe_chr;
225 i = i + 2;
226 }
227 }
228 else {
229 decoded = decoded + encoded.charAt(i);
230 }
231 }
232 return decoded;
233 }
234 /** 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.
235 * @param file The <strong>File</strong> you want to delete.
236 * @return A <i>boolean</i> which is <i>true</i> if the file specified was successfully deleted, <i>false</i> otherwise.
237 */
238 static public boolean delete(File file) {
239 boolean result = true;
240 // If files a directory, delete files children.
241 if(file.isDirectory()) {
242 File files[] = file.listFiles();
243 for(int i = 0; files != null && result && i < files.length; i++) {
244 result = delete(files[i]);
245 }
246 }
247 if(result) {
248 // Delete file.
249 return file.delete();
250 }
251 return result;
252 }
253 /** Generate a depth first enumeration of a tree. */
254 static public EnumeratedVector depthFirstEnumeration(TreeNode node, EnumeratedVector result) {
255 result.add(node);
256 for(int i = 0; i < node.getChildCount(); i++) {
257 depthFirstEnumeration(node.getChildAt(i), result);
258 }
259 return result;
260 }
261 /** Encodes a string of text so its safe to use in a Greenstone configuration file. Esentially replaces newlines with their escaped form.
262 * @param raw The <strong>String</strong> before encoding.
263 * @return A <strong>String</strong> which is safe to write to the configuration file.
264 */
265 static public String encodeGreenstone(String raw) {
266 raw = raw.replaceAll("<", "&lt;");
267 raw = raw.replaceAll(">", "&gt;");
268 return raw.replaceAll("\n", "\\\\n");
269 }
270
271 /** 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. */
272 static public boolean export(Document document, String filename) {
273 return export(document, new File(filename));
274 }
275
276 static public boolean export(Document document, File file) {
277 try {
278 OutputStream os = new FileOutputStream(file);
279 // Create an output format for our document.
280 OutputFormat f = new OutputFormat(document);
281 f.setIndenting(true);
282 f.setLineWidth(0);
283 f.setPreserveSpace(false);
284 // Create the necessary writer stream for serialization.
285 OutputStreamWriter osw = new OutputStreamWriter(os);
286 Writer w = new BufferedWriter(osw);
287 // Generate a new serializer from the above.
288 XMLSerializer s = new XMLSerializer(w, f);
289 s.asDOMSerializer();
290 // Finally serialize the document to file.
291 s.serialize(document);
292 // And close.
293 os.close();
294 return true;
295 }
296 // 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.
297 catch (FileNotFoundException fnf_exception) {
298 if(!file.getName().endsWith(METADATA_XML)) {
299 fnf_exception.printStackTrace();
300 return false;
301 }
302 return true;
303 }
304 catch (IOException ioe) {
305 ioe.printStackTrace();
306 return false;
307 }
308 }
309
310 /** Given a starting directory, searches for the collect.cfg file and returns it if found.
311 * @return The collect.cfg File or null if not found.
312 */
313 static final public File findConfigFile(File start) {
314 if(start == null) {
315 return null;
316 }
317 // See if the collect.cfg files here.
318 File collect_cfg = new File(start, "collect.cfg");
319 if(collect_cfg.exists()) {
320 return collect_cfg;
321 }
322 // Search for the existance of collect.cfg in a etc directory.
323 File etc_dir = new File(start, "etc" + File.separator + "collect.cfg");
324 if(etc_dir.exists()) {
325 return etc_dir;
326 }
327 // Otherwise search this directories parent if its not null.
328 return findConfigFile(start.getParentFile());
329 }
330
331 /** Convert a long, detailing the length of a file in bytes, into a nice human readable string using b, kb, Mb and Gb. */
332 static final public String BYTE_SUFFIX = " b";
333 static final public long GIGABYTE = 1024000000l;
334 static final public String GIGABYTE_SUFFIX = " Gb";
335 static final public long KILOBYTE = 1024l;
336 static final public String KILOBYTE_SUFFIX = " kb";
337 static final public long MEGABYTE = 1024000l;
338 static final public String MEGABYTE_SUFFIX = " mb";
339 static final public String formatFileLength(long length) {
340 StringBuffer result = new StringBuffer("");
341 float number = 0f;
342 String suffix = null;
343 // Determine the floating point number and the suffix (radix) used.
344 if(length >= GIGABYTE) {
345 number = (float) length / (float) GIGABYTE;
346 suffix = GIGABYTE_SUFFIX;
347 }
348 else if(length >= MEGABYTE) {
349 number = (float) length / (float) MEGABYTE;
350 suffix = MEGABYTE_SUFFIX;
351 }
352 else if(length >= KILOBYTE) {
353 number = (float) length / (float) KILOBYTE;
354 suffix = KILOBYTE_SUFFIX;
355 }
356 else {
357 number = (float) length;
358 suffix = BYTE_SUFFIX;
359 }
360 // 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.
361 String number_str = Float.toString(number);
362 char number_char[] = number_str.toCharArray();
363 int pos = 0;
364 // Print the characters up to the '.'
365 while(number_char != null && pos < number_char.length && number_char[pos] != '.') {
366 result.append(number_char[pos]);
367 pos++;
368 }
369 if(pos < number_char.length) {
370 // Print the '.' and at most two characters after it
371 result.append(number_char[pos]);
372 pos++;
373 for(int i = 0; i < 2 && pos < number_char.length; i++, pos++) {
374 result.append(number_char[pos]);
375 }
376 // Search through the remaining string for 'E'
377 while(pos < number_char.length && number_char[pos] != 'E') {
378 pos++;
379 }
380 // If we still have string then we found an E. Copy the remaining string.
381 while(pos < number_char.length) {
382 result.append(number_char[pos]);
383 pos++;
384 }
385 }
386 // Add suffix
387 result.append(suffix);
388 // Done
389 return result.toString();
390 }
391
392 /** This method formats a given string, using HTML markup, so its width does not exceed the given width and its appearance if justified.
393 * @param text The <strong>String</strong> requiring formatting.
394 * @param width The maximum width per line as an <i>int</i>.
395 * @return A <strong>String</strong> formatted so as to have no line longer than the specified width.
396 * 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.
397 */
398 static public String formatHTMLWidth(String text, int width) {
399 HTMLStringTokenizer html = new HTMLStringTokenizer(text);
400 int current_width = 0;
401 int threshold = width / 2;
402 Stack lines = new Stack();
403 String line = "";
404 while(html.hasMoreTokens()) {
405 String token = html.nextToken();
406 while(token != null) {
407 if(html.isTag()) {
408 // Insert smart HTML tag code here.
409 token = null;
410 }
411 else {
412 // If the token is bigger than two thirds width, before we've even started break it down.
413 if(current_width + 1 + token.length() > width && token.length() > threshold) {
414 String prefix = token.substring(0, width - 1 - current_width);
415 token = token.substring(prefix.length());
416 if(current_width == 0) {
417 line = line + prefix;
418 }
419 else {
420 line = line + " " + prefix;
421 }
422 lines.push(line);
423 line = "";
424 current_width = 0;
425 }
426 // If adding the next token would push us over the maximum line width.
427 else if(current_width + 1 + token.length() > width) {
428 line = space(line, width, current_width);
429 lines.push(line);
430 line = token;
431 current_width = token.length();
432 token = null;
433 }
434 // Otherwise we should be able to just add the token, give or take.
435 else {
436 if(current_width == 0) {
437 line = line + token;
438 current_width = token.length();
439 }
440 else {
441 // Special case for standard punctuation which may exist after a tag like so:
442 // My name is <scratchy>Slim Shady</scratchy>. <-- Annoying punctuation.
443 if(token.equals(".") || token.equals(",") || token.equals("!") || token.equals("?")) {
444 line = line + token;
445 current_width = current_width + 1;
446 }
447 else {
448 line = line + " " + token;
449 current_width = current_width + 1 + token.length();
450 }
451 }
452 token = null;
453 }
454 }
455 }
456 }
457 String result = line;
458 while(!lines.empty()) {
459 result = (String)lines.pop() + "<BR>" + result;
460 }
461 // Replace ' ' with "&nbsp;"
462 boolean tag = false;
463 int pos = 0;
464 while(pos < result.length()) {
465 if(result.charAt(pos) == '<') {
466 tag = true;
467 }
468 else if(result.charAt(pos) == '>') {
469 tag = false;
470 }
471 else if(result.charAt(pos) == ' ' && !tag) {
472 String prefix = result.substring(0, pos);
473 String suffix = result.substring(pos + 1);
474 result = prefix + "&nbsp;" + suffix;
475 }
476 pos++;
477 }
478 result = "<HTML>" + result + "</HTML>";
479 return result;
480 }
481 /** Format the given filename path string so that it is no longer than the given width. If it is wider replace starting directories with ...
482 * @param key The key <strong>String</Strong> used to retrieve a phrase from the dictionary for this item.
483 * @param raw The raw filename path <strong>String</strong>.
484 * @param width The maximum width as an <i>int</i>.
485 * @return A path <strong>String</strong> no longer than width.
486 */
487 static public String formatPath(String key, String raw, int width) {
488 JLabel label = new JLabel(Gatherer.dictionary.get(key, raw));
489 int position = -1;
490 while(label.getPreferredSize().width > width && (position = raw.indexOf(File.separator)) != -1) {
491 raw = "..." + raw.substring(position + 1);
492 label.setText(Gatherer.dictionary.get(key, raw));
493 }
494 if(raw.indexOf(File.separator) == -1 && raw.startsWith("...")) {
495 raw = raw.substring(3);
496 }
497 return raw;
498 }
499
500 /** Method which constructs the archive directory given a certain collection.
501 * @param col_dir The location of the collection directory as a <strong>String</strong>.
502 * @return The location of the given collections archive directory, also as a <strong>String</strong>.
503 */
504 static public String getArchiveDir(String gsdl_path, String col_name) {
505 return gsdl_path + File.separator + COL_DIR + col_name + File.separator + ARCHIVE_DIR;
506 }
507 /** Method which constructs the build directory given a certain collection.
508 * @param col_dir The location of the collection directory as a <strong>String</strong>.
509 * @return The location of the given collections build directory, also as a <strong>String</strong>.
510 */
511 static public String getBuildDir(String col_dir) {
512 if(col_dir == null) {
513 return BASE_DIR + BUILD_DIR;
514 }
515 return col_dir + BUILD_DIR;
516 }
517 /** Builds the private cache dir by appending col_dir and 'cache'.
518 * @param col_dir A String representing the directory path of the current collection.
519 * @return A String representing the path to the private file cache within the current collection.
520 */
521 public static String getCacheDir(String col_dir) {
522 return col_dir + GCACHE_DIR;
523 }
524 /** Method which constructs the collection directory for Greenstone.
525 * @param gsdl_path The location of the gsdl installation directory as a <strong>String</strong>.
526 * @return The location of the collection directory, also as a <strong>String</strong>.
527 */
528 public static String getCollectionDir(String gsdl_path) {
529 return gsdl_path + COL_DIR;
530 }
531 /** Method which constructs the configuration file given a certain collection.
532 * @param col_dir The location of the collection directory as a <strong>String</strong>.
533 * @return The location of the given collections configuration file, also as a <strong>String</strong>.
534 */
535 static public String getConfigDir(String col_dir) {
536 return col_dir + CONFIG_DIR;
537 }
538
539 static public String getDateString() {
540 Calendar current = Calendar.getInstance();
541 String day_name = null;
542 switch(current.get(Calendar.DAY_OF_WEEK)) {
543 case Calendar.MONDAY: day_name = "Mon"; break;
544 case Calendar.TUESDAY: day_name = "Tue"; break;
545 case Calendar.WEDNESDAY: day_name = "Wed"; break;
546 case Calendar.THURSDAY: day_name = "Thu"; break;
547 case Calendar.FRIDAY: day_name = "Fri"; break;
548 case Calendar.SATURDAY: day_name = "Sat"; break;
549 case Calendar.SUNDAY: day_name = "Sun"; break;
550 default: day_name = "";
551 }
552 String month_name = null;
553 switch(current.get(Calendar.MONTH)) {
554 case Calendar.JANUARY: month_name = "Jan"; break;
555 case Calendar.FEBRUARY: month_name = "Feb"; break;
556 case Calendar.MARCH: month_name = "Mar"; break;
557 case Calendar.APRIL: month_name = "Apr"; break;
558 case Calendar.MAY: month_name = "May"; break;
559 case Calendar.JUNE: month_name = "Jun"; break;
560 case Calendar.JULY: month_name = "Jul"; break;
561 case Calendar.AUGUST: month_name = "Aug"; break;
562 case Calendar.SEPTEMBER: month_name = "Sep"; break;
563 case Calendar.OCTOBER: month_name = "Oct"; break;
564 case Calendar.NOVEMBER: month_name = "Nov"; break;
565 case Calendar.DECEMBER: month_name = "Dec"; break;
566 default: month_name = "";
567 }
568 int day = current.get(Calendar.DAY_OF_MONTH);
569 int hour = current.get(Calendar.HOUR_OF_DAY);
570 int minute = current.get(Calendar.MINUTE);
571 int second = current.get(Calendar.SECOND);
572 int year = current.get(Calendar.YEAR);
573
574 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);
575 }
576
577 /** Retrieves and formats the depth field of the config file to four characters.
578 * @param length The length of the desired string as an <i>int</i>.
579 * @return A <strong>String</strong> representation of the mirroring depth padded to length characters.
580 */
581 public static String getDepthString(int length) {
582 return pad("" + Gatherer.self.config.getInt("mirroring.depth", false), length);
583 }
584 /** Method which constructs the etc directory given a certain collection.
585 * @param col_dir The location of the collection directory as a <strong>String</strong>.
586 * @return The location of the given collections etc directory, also as a <strong>String</strong>.
587 */
588 public static String getEtcDir(String col_dir) {
589 return col_dir + ETC_DIR;
590 }
591 /** Method to retrieve an image icon with the given filename found in classpath or the resouces directory.
592 * @return The specified <strong>ImageIcon</strong>, or an error image replacement if no such images exists.
593 */
594 static public ImageIcon getImage(String filename) {
595 ImageIcon image = null;
596 try {
597 image = new ImageIcon(ClassLoader.getSystemResource("images/" + Gatherer.dictionary.get("Version") + "/" + filename));
598 }
599 catch(NullPointerException exception) {
600 image = new ImageIcon(ClassLoader.getSystemResource("images/" + filename));
601 }
602 if(image == null) {
603 image = ERROR_ICON;
604 }
605 return image;
606 }
607
608 /** Method which constructs the import directory given a certain collection.
609 * @param col_dir The location of the collection directory as a <strong>String</strong>.
610 * @return The location of the given collections import directory, also as a <strong>String</strong>.
611 */
612 public static String getImportDir(String col_dir) {
613 return col_dir + IMPORT_DIR;
614 }
615 /** Method which constructs the index directory given a certain collection.
616 * @param col_dir The location of the collection directory as a <strong>String</strong>.
617 * @return The location of the given collections index directory, also as a <strong>String</strong>.
618 */
619 static public String getIndexDir(String col_dir) {
620 return col_dir + INDEX_DIR;
621 }
622 /** Method which constructs the log directory given a certain collection.
623 * @param col_dir The location of the collection directory as a <strong>String</strong>.
624 * @return The location of the given collections log directory, also as a <strong>String</strong>.
625 */
626 public static String getLogDir(String col_dir) {
627 return col_dir + LOG_DIR;
628 }
629 /** Determine this machines name.
630 * @return The name as a <strong>String</strong>.
631 */
632 static public String getMachineName() {
633 try {
634 return InetAddress.getLocalHost().getHostName();
635 }
636 catch(UnknownHostException ex) {
637 }
638 return "Unknown Machine";
639 }
640 /** Method which constructs the metadata directory given a certain collection.
641 * @param col_dir The location of the collection directory as a <strong>String</strong>.
642 * @return The location of the given collections metadata directory, also as a <strong>String</strong>.
643 */
644 static public String getMetadataDir(String col_dir) {
645 return col_dir + META_DIR;
646 }
647
648
649 static public File getRecycleDirectory() {
650 return new File(RECYCLE);
651 }
652
653 /** Determine whether a character is a hexidecimal one.
654 * @param chr The <i>char</i> in question.
655 * @return An <i>int</i> representing the value of the hexidecimal character or -1 if not a hexidecimal.
656 */
657 public static int hexidecimal(char chr) {
658 switch(chr) {
659 case '0':
660 return 0;
661 case '1':
662 return 1;
663 case '2':
664 return 2;
665 case '3':
666 return 3;
667 case '4':
668 return 4;
669 case '5':
670 return 5;
671 case '6':
672 return 6;
673 case '7':
674 return 7;
675 case '8':
676 return 8;
677 case '9':
678 return 9;
679 case 'A':
680 return 10;
681 case 'B':
682 return 11;
683 case 'C':
684 return 12;
685 case 'D':
686 return 13;
687 case 'E':
688 return 14;
689 case 'F':
690 return 15;
691 default:
692 return -1;
693 }
694 }
695
696 /** A string is a valid hierarchy index if it matches '[0-9](\.[0-9])*' */
697 static public boolean isIndex(String raw) {
698 boolean result = true;
699 for(int i = 0; result && i < raw.length(); i++) {
700 char c = raw.charAt(i);
701 if(Character.isDigit(c) || (c == '.' && (i != 0 || i != raw.length() - 1))) {
702 // Valid index
703 }
704 else {
705 result = false;
706 }
707 }
708 return result;
709 }
710
711 /** Method to determine if the host system is Microsoft Windows based.
712 * @return A <i>boolean</i> which is <i>true</i> if the platform is Windows, <i>false</i> otherwise.
713 */
714 public static boolean isWindows() {
715 Properties props = System.getProperties();
716 String os_name = props.getProperty("os.name","");
717 if(os_name.startsWith("Windows")) {
718 return true;
719 }
720 return false;
721 }
722 /** Takes a string and a desired length and pads out the string to the length by adding spaces to the left.
723 * @param str The target <strong>String</strong> that needs to be padded.
724 * @param length The desired length of the string as an <i>int</i>.
725 * @return A <strong>String</strong> made from appending space characters with the string until it has a length equal to length.
726 */
727 public static String pad(String str, int length) {
728 return pad(str, length, ' ', true);
729 }
730 public static String pad(String str_raw, int length, char fill, boolean end) {
731 StringBuffer str = new StringBuffer(str_raw);
732 while(str.length() < length) {
733 if(end) {
734 str.insert(0, fill);
735 }
736 else {
737 str.append(fill);
738 }
739 }
740 return str.toString();
741 }
742
743 /** 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. */
744 static public Document parse(String filename, boolean use_classloader) {
745 File file = null;
746 if(use_classloader) {
747 try {
748 URL url = ClassLoader.getSystemResource(filename);
749 file = new File(URLDecoder.decode(url.getFile(), "UTF-8"));
750 url = null;
751 }
752 catch (Exception error) {
753 // Most likely file name.
754 file = new File("classes" + File.separator + filename);
755 //Gatherer.printStackTrace(error);
756 }
757 }
758 if(file == null) {
759 file = new File(filename);
760 }
761 return parse(file, true);
762 }
763 /** Parse in a xml document from a given file. */
764 static public Document parse(File file) {
765 return parse(file, true);
766 }
767 /** Parse in a xml document from a given file. */
768 static public Document parse(File file, boolean noisey) {
769 Document document = null;
770 try {
771 FileInputStream fis = new FileInputStream(file);
772 InputStreamReader isr = new InputStreamReader(fis);
773 Reader r = new BufferedReader(isr);
774 InputSource isc = new InputSource(r);
775 DOMParser parser = new DOMParser();
776 parser.setFeature("http://xml.org/sax/features/validation", false);
777 parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
778 // May or may not be ignored, the documentation for Xerces is contradictory. If it works then parsing -should- be faster.
779 parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", true);
780 parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
781 parser.parse(isc);
782 document = parser.getDocument();
783 isr.close();
784 fis.close();
785 parser = null;
786 isc = null;
787 r = null;
788 isr = null;
789 fis = null;
790 file = null;
791 }
792 catch (Exception error) {
793 if(noisey) {
794 error.printStackTrace();
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}
Note: See TracBrowser for help on using the repository browser.