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

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

Removed call to deprecated function URLDecoder::decode(String).

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