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

Last change on this file since 5581 was 5581, checked in by mdewsnip, 21 years ago

Many formatting, structural and code improvements.

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