Clover coverage report - QedeqKernelSe Coverage Report
Coverage timestamp: Do Jan 11 2007 09:03:50 CET
file stats: LOC: 590   Methods: 27
NCLOC: 303   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
IoUtility.java 15,3% 22,4% 22,2% 20,4%
coverage coverage
 1    /* $Id: IoUtility.java,v 1.6 2006/10/20 20:23:08 m31 Exp $
 2    *
 3    * This file is part of the project "Hilbert II" - http://www.qedeq.org
 4    *
 5    * Copyright 2000-2006, Michael Meyling <mime@qedeq.org>.
 6    *
 7    * "Hilbert II" is free software; you can redistribute
 8    * it and/or modify it under the terms of the GNU General Public
 9    * License as published by the Free Software Foundation; either
 10    * version 2 of the License, or (at your option) any later version.
 11    *
 12    * This program is distributed in the hope that it will be useful,
 13    * but WITHOUT ANY WARRANTY; without even the implied warranty of
 14    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 15    * GNU General Public License for more details.
 16    */
 17   
 18    package org.qedeq.kernel.utility;
 19   
 20    import java.io.BufferedOutputStream;
 21    import java.io.BufferedReader;
 22    import java.io.BufferedWriter;
 23    import java.io.ByteArrayInputStream;
 24    import java.io.File;
 25    import java.io.FileInputStream;
 26    import java.io.FileOutputStream;
 27    import java.io.FileReader;
 28    import java.io.FileWriter;
 29    import java.io.IOException;
 30    import java.io.InputStream;
 31    import java.io.InputStreamReader;
 32    import java.io.Reader;
 33    import java.io.UnsupportedEncodingException;
 34    import java.net.URL;
 35    import java.util.Enumeration;
 36    import java.util.Properties;
 37   
 38   
 39    /**
 40    * A collection of useful static methods for input and output.
 41    *
 42    * LATER mime 20070101: use StringBuilder instead of StringBuffer if working under JDK 1.5
 43    *
 44    * @version $Revision: 1.6 $
 45    * @author Michael Meyling
 46    */
 47    public final class IoUtility {
 48   
 49    /**
 50    * Constructor, should never be called.
 51    */
 52  0 private IoUtility() {
 53    // don't call me
 54    }
 55   
 56    /**
 57    * Reads a file and returns the contents as a <code>String</code>.
 58    *
 59    * @param filename Name of the file (could include path).
 60    * @return Contents of file.
 61    * @throws IOException File exception occurred.
 62    */
 63  0 public static String loadFile(final String filename)
 64    throws IOException {
 65   
 66  0 final StringBuffer buffer = new StringBuffer();
 67  0 loadFile(filename, buffer);
 68  0 return buffer.toString();
 69    }
 70   
 71    /**
 72    * Reads contents of a file into a string buffer.
 73    *
 74    * @param filename Name of the file (could include path).
 75    * @param buffer Buffer to fill with file contents.
 76    * @throws IOException File exception occurred.
 77    */
 78  0 public static void loadFile(final String filename,
 79    final StringBuffer buffer)
 80    throws IOException {
 81  0 loadFile(new File(filename), buffer);
 82    }
 83   
 84    /**
 85    * Reads contents of a stream into a string buffer.
 86    *
 87    * @param in This stream will be loaded.
 88    * @param buffer Buffer to fill with file contents.
 89    * @throws IOException File exception occurred.
 90    */
 91  0 public static void loadStream(final InputStream in,
 92    final StringBuffer buffer)
 93    throws IOException {
 94   
 95  0 buffer.setLength(0);
 96  0 int c;
 97  0 while ((c = in.read()) >= 0) {
 98  0 buffer.append((char) c);
 99    }
 100    }
 101   
 102    /**
 103    * Reads contents of a file into a string buffer.
 104    *
 105    * @param file This file will be loaded.
 106    * @param buffer Buffer to fill with file contents.
 107    * @throws IOException File exception occurred.
 108    */
 109  3161 public static void loadFile(final File file,
 110    final StringBuffer buffer)
 111    throws IOException {
 112   
 113  3161 final int size = (int) file.length();
 114  3161 buffer.setLength(0);
 115  3161 final FileReader in = new FileReader(file);
 116  3161 final char[] data = new char[size];
 117  3161 int charsread = 0;
 118  3161 while (charsread < size) {
 119  3161 charsread += in.read(data, charsread, size - charsread);
 120    }
 121  3161 in.close();
 122  3161 buffer.insert(0, data);
 123    }
 124   
 125    /**
 126    * Reads a file and returns the contents as a <code>String</code>.
 127    *
 128    * @param file File to load from.
 129    * @return Contents of file.
 130    * @throws IOException File exception occurred.
 131    */
 132  0 public static final byte[] loadFileBinary(final File file) throws IOException {
 133  0 final int size = (int) file.length();
 134  0 final FileInputStream in = new FileInputStream(file);
 135  0 try {
 136  0 final byte[] data = new byte[size];
 137  0 int charsread = 0;
 138  0 while (charsread < size) {
 139  0 final int read = in.read(data, charsread, size - charsread);
 140  0 if (read == -1) {
 141  0 final byte[] result = new byte[charsread];
 142  0 System.arraycopy(data, 0, result, 0, charsread);
 143  0 return result;
 144    }
 145  0 charsread += read;
 146    }
 147  0 in.close();
 148  0 return data;
 149    } finally {
 150  0 closeStream(in);
 151    }
 152    }
 153   
 154    /**
 155    * Reads contents of a file into a string buffer.
 156    *
 157    * @param url This file will be loaded.
 158    * @param buffer Buffer to fill with file contents.
 159    * @throws IOException Reading failed.
 160    */
 161  0 public static void loadFile(final URL url, final StringBuffer buffer) throws IOException {
 162  0 InputStream in = null;
 163  0 BufferedReader dis = null;
 164  0 try {
 165  0 in = url.openStream();
 166  0 dis = new BufferedReader(new InputStreamReader(in));
 167  0 in.read();
 168   
 169  0 byte[] data = new byte[8 * 1024];
 170  0 int length;
 171   
 172  0 while ((length = in.read(data)) != -1) {
 173  0 buffer.append(new String(data, 0, length));
 174    }
 175    } finally {
 176  0 closeStream(in);
 177  0 closeReader(dis);
 178    }
 179    }
 180   
 181    /**
 182    * Convert String into a {@link Reader}.
 183    *
 184    * <a href="http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4094886">
 185    * Bug ID: 4094886</a>
 186    *
 187    * @param data Convert this.
 188    * @return Resulting reader.
 189    */
 190  0 public static final Reader stringToReader(final String data) {
 191  0 try {
 192  0 return new InputStreamReader(new ByteArrayInputStream(data.getBytes("ISO-8859-1")));
 193    } catch (UnsupportedEncodingException e) {
 194  0 throw new RuntimeException(e);
 195    }
 196    }
 197   
 198    /**
 199    * Saves a <code>String</code> into a file.
 200    *
 201    * @param filename Name of the file (could include path).
 202    * @param text Data to save in the file.
 203    * @throws IOException File exception occurred.
 204    */
 205  0 public static void saveFile(final String filename, final String text)
 206    throws IOException {
 207  0 saveFile(new File(filename), text);
 208    }
 209   
 210    /**
 211    * Saves a <code>StringBuffer</code> in a file.
 212    *
 213    * @param filename Name of the file (could include path).
 214    * @param text Data to save in the file.
 215    * @throws IOException File exception occurred.
 216    */
 217  0 public static void saveFile(final String filename, final StringBuffer text)
 218    throws IOException {
 219  0 saveFile(new File(filename), text.toString());
 220    }
 221   
 222   
 223    /**
 224    * Saves a <code>StringBuffer</code> in a file.
 225    *
 226    * @param file File to save into.
 227    * @param text Data to save in the file.
 228    * @throws IOException File exception occurred.
 229    */
 230  0 public static void saveFile(final File file, final StringBuffer text)
 231    throws IOException {
 232  0 saveFile(file, text.toString());
 233    }
 234   
 235   
 236    /**
 237    * Saves a <code>String</code> in a file.
 238    *
 239    * @param file File to save the data in.
 240    * @param text Data to save in the file.
 241    * @throws IOException File exception occurred.
 242    */
 243  1 public static void saveFile(final File file, final String text)
 244    throws IOException {
 245  1 BufferedWriter out = new BufferedWriter(
 246    new FileWriter(file));
 247  1 out.write(text);
 248  1 out.close();
 249    }
 250   
 251    /**
 252    * Saves a <code>String</code> in a file.
 253    *
 254    * @param file File to save the data in.
 255    * @param data Data to save in the file.
 256    * @throws IOException File exception occurred.
 257    */
 258  0 public static void saveFileBinary(final File file, final byte[] data)
 259    throws IOException {
 260  0 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
 261  0 out.write(data);
 262  0 out.close();
 263    }
 264   
 265    /**
 266    * Copies a file to a different location.
 267    *
 268    * @param from Copy source.
 269    * @param to Copy destination.
 270    * @throws IOException File exception occurred.
 271    */
 272  20 public static void copyFile(final File from, final File to)
 273    throws IOException {
 274    /*
 275    final byte[] data = loadFileBinary(from);
 276    saveFileBinary(to, data);
 277    */
 278   
 279  20 if (from.getAbsoluteFile().equals(to.getAbsoluteFile())) {
 280  0 return;
 281    }
 282  20 FileInputStream in = new FileInputStream(from);
 283  20 FileOutputStream out = new FileOutputStream(to);
 284   
 285  20 byte[] data = new byte[8 * 1024];
 286  20 int length;
 287   
 288  ? while ((length = in.read(data)) != -1) {
 289  134 out.write(data, 0, length);
 290    }
 291  20 in.close();
 292  20 out.close();
 293    }
 294   
 295   
 296    /**
 297    * Quotes a <code>String</code>. If no quotes exist in the
 298    * <code>String</code>, a quote character is appended at the
 299    * beginning and the end of the <code>String</code>.
 300    *
 301    * @param unquoted the unquoted <code>String</code>
 302    * @return quoted <code>String</code>
 303    * @throws NullPointerException if <code>unquoted == null</code>
 304    */
 305  0 public static String quote(final String unquoted) {
 306   
 307  0 String result = "\"";
 308   
 309  0 for (int i = 0; i < unquoted.length(); i++) {
 310  0 if (unquoted.charAt(i) == '\"') {
 311  0 result += "\"\"";
 312    } else {
 313  0 result += unquoted.charAt(i);
 314    }
 315    }
 316  0 result += '\"';
 317  0 return result;
 318    }
 319   
 320    /**
 321    * Tests if given <code>String</code> begins with a letter and contains
 322    * only letters and digits.
 323    *
 324    * @param text test this
 325    * @return is <code>text</code> only made of letters and digits and has
 326    * a leading letter?
 327    * @throws NullPointerException if <code>text == null</code>
 328    */
 329  0 public static boolean isLetterDigitString(final String text) {
 330  0 if (text.length() <= 0) {
 331  0 return false;
 332    }
 333  0 if (!Character.isLetter(text.charAt(0))) {
 334  0 return false;
 335    }
 336  0 for (int i = 1; i < text.length(); i++) {
 337  0 if (!Character.isLetterOrDigit(text.charAt(i))) {
 338  0 return false;
 339    }
 340    }
 341  0 return true;
 342    }
 343   
 344    /**
 345    * Delete file directory recursive.
 346    *
 347    * @param directory Directory to delete.
 348    * @return Was deletion successful?
 349    */
 350  0 public static boolean deleteDir(final File directory) {
 351    // to see if this directory is actually a symbolic link to a directory,
 352    // we want to get its canonical path - that is, we follow the link to
 353    // the file it's actually linked to
 354  0 File candir;
 355  0 try {
 356  0 candir = directory.getCanonicalFile();
 357    } catch (IOException e) {
 358  0 return false;
 359    }
 360   
 361    // a symbolic link has a different canonical path than its actual path,
 362    // unless it's a link to itself
 363  0 if (!candir.equals(directory.getAbsoluteFile())) {
 364    // this file is a symbolic link, and there's no reason for us to
 365    // follow it, because then we might be deleting something outside of
 366    // the directory we were told to delete
 367  0 return false;
 368    }
 369   
 370    // now we go through all of the files and subdirectories in the
 371    // directory and delete them one by one
 372  0 File[] files = candir.listFiles();
 373  0 if (files != null) {
 374  0 for (int i = 0; i < files.length; i++) {
 375  0 File file = files[i];
 376   
 377    // in case this directory is actually a symbolic link, or it's
 378    // empty, we want to try to delete the link before we try
 379    // anything
 380  0 boolean deleted = file.delete();
 381  0 if (!deleted) {
 382    // deleting the file failed, so maybe it's a non-empty
 383    // directory
 384  0 if (file.isDirectory()) {
 385  0 deleteDir(file);
 386    }
 387   
 388    // otherwise, there's nothing else we can do
 389    }
 390    }
 391    }
 392   
 393    // now that we tried to clear the directory out, we can try to delete it
 394    // again
 395  0 return directory.delete();
 396    }
 397   
 398   
 399    /**
 400    * Get amount of spaces.
 401    *
 402    * @param length number of spaces
 403    * @return String contains exactly <code>number</code> spaces
 404    */
 405  0 public static StringBuffer getSpaces(final int length) {
 406  0 final StringBuffer buffer = new StringBuffer(length >= 0 ? length : 0);
 407  0 for (int i = 0; i < length; i++) {
 408  0 buffer.append(' ');
 409    }
 410  0 return buffer;
 411    }
 412   
 413    /**
 414    * Get non qualified class name.
 415    *
 416    * @param clazz Class.
 417    * @return Non qualified class name.
 418    */
 419  1201 public static String getClassName(final Class clazz) {
 420  1201 return clazz.getName().substring(clazz.getName().lastIndexOf('.') + 1);
 421    }
 422   
 423    /**
 424    * Print current system properties to System.out.
 425    */
 426  0 public static void printAllSystemProperties() {
 427  0 Properties sysprops = System.getProperties();
 428  0 for (Enumeration e = sysprops.propertyNames(); e.hasMoreElements(); ) {
 429  0 String key = (String) e.nextElement();
 430  0 String value = sysprops.getProperty(key);
 431  0 System.out.println(key + "=" + value);
 432    }
 433    }
 434   
 435    /**
 436    * Get home directory of user.
 437    *
 438    * @return Home directory of user.
 439    */
 440  0 public static File getUserHomeDirectory() {
 441  0 return new File((String) System.getProperties().get("user.home"));
 442    }
 443   
 444    /**
 445    * Creates necessary parent directories for a file.
 446    *
 447    * @param file File.
 448    */
 449  10 public static void createNecessaryDirectories(final File file) {
 450  10 if (file.getParentFile() != null) {
 451  10 file.getParentFile().mkdirs();
 452    }
 453    }
 454   
 455    /**
 456    * Create relative address from <code>orgin</code> to <code>next</code>.
 457    *
 458    * @param orgin this is the original location
 459    * @param next this should be the next location
 460    * @return relative (or if necessary absolute) file path
 461    */
 462  0 public static final String createRelativePath(final File orgin, final File next) {
 463  0 try {
 464  0 if (orgin.equals(next)) {
 465  0 return "";
 466    }
 467  0 try {
 468  0 String org = orgin.getCanonicalPath().replace('\\', '/');
 469  0 if (orgin.isDirectory() && !org.endsWith("/")) {
 470  0 org += "/";
 471    }
 472  0 String nex = next.getCanonicalPath().replace('\\', '/');
 473  0 if (next.isDirectory() && !nex.endsWith("/")) {
 474  0 nex += "/";
 475    }
 476  0 int i = -1; // position of next '/'
 477  0 int j = 0; // position of last '/'
 478  0 while (0 <= (i = org.indexOf("/", j))) {
 479  0 if (i >= 0 && nex.length() > i
 480    && org.substring(j, i).equals(
 481    nex.substring(j, i))) {
 482  0 j = i + 1;
 483    } else {
 484  0 break;
 485    }
 486    }
 487  0 if (j > 0) {
 488  0 i = j;
 489  0 StringBuffer result = new StringBuffer(nex.length());
 490  0 while (0 <= (i = org.indexOf("/", i))) {
 491  0 i++;
 492  0 result.append("../");
 493    }
 494  0 result.append(nex.substring(j));
 495  0 return result.toString();
 496    }
 497  0 return "/" + nex;
 498    } catch (RuntimeException e) {
 499  0 return next.toString();
 500    }
 501    } catch (IOException e) {
 502  0 return next.toString();
 503    }
 504    }
 505   
 506    /**
 507    * Waits until a '\n' was read from System.in.
 508    */
 509  0 public static void waitln() {
 510  0 System.out.println("\n..press <return> to continue");
 511  0 try {
 512  0 (new java.io.BufferedReader(new java.io.InputStreamReader(
 513    System.in))).readLine();
 514    } catch (IOException e) {
 515    // ignore
 516    }
 517    }
 518   
 519    /**
 520    * Closes input stream without exception.
 521    *
 522    * @param in Input stream, maybe <code>null</code>.
 523    */
 524  0 public static void closeStream(final InputStream in) {
 525  0 if (in != null) {
 526  0 try {
 527  0 in.close();
 528    } catch (Exception e) {
 529    // ignore
 530    }
 531    }
 532    }
 533   
 534    /**
 535    * Closes input reader without exception.
 536    *
 537    * @param reader Reader, maybe <code>null</code>.
 538    */
 539  0 public static void closeReader(final Reader reader) {
 540  0 if (reader != null) {
 541  0 try {
 542  0 reader.close();
 543    } catch (Exception e) {
 544    // ignore
 545    }
 546    }
 547    }
 548   
 549    /**
 550    * Search for first line followed by whitespace and delete this string within the whole
 551    * text.
 552    * <p>
 553    * For example the following text
 554    *<pre>
 555    * Do you know the muffin man,
 556    * The muffin man, the muffin man,
 557    * Do you know the muffin man,
 558    * Who lives on Drury Lane?
 559    *</pre>
 560    * will be converted into:
 561    *<pre>
 562    *Do you know the muffin man,
 563    *The muffin man, the muffin man,
 564    *Do you know the muffin man,
 565    *Who lives on Drury Lane?
 566    *</pre>
 567    *
 568    * @param buffer Work on this text.
 569    */
 570  792 public static void deleteLineLeadingWhitespace(final StringBuffer buffer) {
 571  792 int start = -1;
 572  ? while (0 <= (start = buffer.indexOf("\n", start + 1))) {
 573  220 if (start + 1 < buffer.length() && '\n' != buffer.charAt(start + 1)) {
 574  195 break;
 575    }
 576    }
 577  792 if (start >= 0) {
 578  195 int next = start + 1;
 579  195 while (next < buffer.length() && Character.isWhitespace(buffer.charAt(next))
 580    && '\n' != buffer.charAt(next)) {
 581  2522 next++;
 582    }
 583  195 final String empty = buffer.substring(start, next);
 584  195 if (empty.length() > 0) {
 585  195 ReplaceUtility.replace(buffer, empty, "\n");
 586    }
 587    }
 588    }
 589   
 590    }