File: IOUtils.java

package info (click to toggle)
libbase 1.1.6-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 944 kB
  • sloc: java: 8,709; xml: 1,522; makefile: 18
file content (925 lines) | stat: -rw-r--r-- 25,695 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
/*
 * This program is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
 * Foundation.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
 * or from the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * Copyright (c) 2007 - 2009 Pentaho Corporation and Contributors.  All rights reserved.
 */

package org.pentaho.reporting.libraries.base.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.io.StringWriter;
import java.net.URL;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.sql.Clob;
import java.sql.SQLException;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

/**
 * The IOUtils provide some IO related helper methods.
 *
 * @author Thomas Morgner.
 */
public class IOUtils
{
  /**
   * the singleton instance of the utility package.
   */
  private static IOUtils instance;
  private static final Log logger = LogFactory.getLog(IOUtils.class);
  /**
   * DefaultConstructor.
   */
  private IOUtils()
  {
  }

  /**
   * Gets the singleton instance of the utility package.
   *
   * @return the singleton instance.
   */
  public static synchronized IOUtils getInstance()
  {
    if (instance == null)
    {
      instance = new IOUtils();
    }
    return instance;
  }

  /**
   * Checks, whether the URL uses a file based protocol.
   *
   * @param url the url.
   * @return true, if the url is file based.
   */
  private boolean isFileStyleProtocol(final URL url)
  {
    if (url == null)
    {
      throw new NullPointerException();
    }

    final String protocol = url.getProtocol();
    if ("http".equals(protocol))
    {
      return true;
    }
    if ("https".equals(protocol))
    {
      return true;
    }
    if ("ftp".equals(protocol))
    {
      return true;
    }
    if ("file".equals(protocol))
    {
      return true;
    }
    if ("jar".equals(protocol))
    {
      return true;
    }
    return false;
  }

  /**
   * Parses the given name and returns the name elements as List of Strings.
   *
   * @param name the name, that should be parsed.
   * @return the parsed name.
   */
  private List parseName(final String name)
  {
    final ArrayList list = new ArrayList();
    final StringTokenizer strTok = new StringTokenizer(name, "/");
    while (strTok.hasMoreElements())
    {
      final String s = (String) strTok.nextElement();
      if (s.length() != 0)
      {
        list.add(s);
      }
    }
    return list;
  }

  /**
   * Transforms the name list back into a single string, separated with "/".
   *
   * @param name  the name list.
   * @param query the (optional) query for the URL.
   * @return the constructed name.
   */
  private String formatName(final List name, final String query)
  {
    final StringBuffer b = new StringBuffer(128);
    final Iterator it = name.iterator();
    while (it.hasNext())
    {
      b.append(it.next());
      if (it.hasNext())
      {
        b.append('/');
      }
    }
    if (query != null)
    {
      b.append('?');
      b.append(query);
    }
    return b.toString();
  }

  /**
   * Compares both name lists, and returns the last common index shared between the two lists.
   *
   * @param baseName the name created using the base url.
   * @param urlName  the target url name.
   * @return the number of shared elements.
   */
  private int startsWithUntil(final List baseName, final List urlName)
  {
    final int minIdx = Math.min(urlName.size(), baseName.size());
    for (int i = 0; i < minIdx; i++)
    {
      final String baseToken = (String) baseName.get(i);
      final String urlToken = (String) urlName.get(i);
      if (!baseToken.equals(urlToken))
      {
        return i;
      }
    }
    return minIdx;
  }

  /**
   * Checks, whether the URL points to the same service. A service is equal if the protocol, host and port are equal.
   *
   * @param url     a url
   * @param baseUrl an other url, that should be compared.
   * @return true, if the urls point to the same host and port and use the same protocol, false otherwise.
   */
  private boolean isSameService(final URL url, final URL baseUrl)
  {
    if (!url.getProtocol().equals(baseUrl.getProtocol()))
    {
      return false;
    }
    if (!url.getHost().equals(baseUrl.getHost()))
    {
      return false;
    }
    if (url.getPort() != baseUrl.getPort())
    {
      return false;
    }
    return true;
  }

  /**
   * Creates a relative url by stripping the common parts of the the url. If the baseFile denotes a directory,
   * it must end with a slash.
   *
   * @param targetFile     the to be stripped url
   * @param baseFile the base url, to which the <code>url</code> is relative to.
   * @return the relative url, or the url unchanged, if there is no relation beween both URLs.
   */
  public String createRelativePath(final String targetFile, final String baseFile)
  {
    if (targetFile == null)
    {
      throw new NullPointerException("targetFile must not be null.");
    }
    if (baseFile == null)
    {
      throw new NullPointerException("baseFile must not be null.");
    }

    // If the URL contains a query, ignore that URL; do not
    // attemp to modify it...
    final List baseName = parseName(baseFile);
    if (baseName.isEmpty())
    {
      return targetFile;
    }
    final List urlName = parseName(targetFile);
    if (urlName.isEmpty())
    {
      return targetFile;
    }

    if ((baseFile.length() > 0 && baseFile.charAt(baseFile.length() - 1) == '/') == false)
    {
      // remove trailing slashes and ensure that the last element in baseName points to a directory
      baseName.remove(baseName.size() - 1);
    }

    // if both urls are identical, then return the plain file name...
    if (baseFile.equals(targetFile))
    {
      return (String) urlName.get(urlName.size() - 1);
    }

    int commonIndex = startsWithUntil(urlName, baseName);
    if (commonIndex == 0)
    {
      return targetFile;
    }

    if (commonIndex == urlName.size())
    {
      // correct the base index if there is some weird mapping
      // detected,
      // fi. the file url is fully included in the base url:
      //
      // base: /file/test/funnybase
      // file: /file/test
      //
      // this could be a valid configuration whereever virtual
      // mappings are allowed.
      commonIndex -= 1;
    }

    final ArrayList retval = new ArrayList();
    if ((baseName.size() + 1) != urlName.size())
    {
      final int levels = baseName.size() - commonIndex;
      for (int i = 0; i < levels; i++)
      {
        retval.add("..");
      }
    }

    retval.addAll(urlName.subList(commonIndex, urlName.size()));
    return formatName(retval, null);
  }

  /**
   * Creates a relative url by stripping the common parts of the the url. If the base-URL denotes a directory,
   * it must end with a slash.
   *
   * @param url     the to be stripped url
   * @param baseURL the base url, to which the <code>url</code> is relative to.
   * @return the relative url, or the url unchanged, if there is no relation beween both URLs.
   */
  public String createRelativeURL(final URL url, final URL baseURL)
  {
    if (url == null)
    {
      throw new NullPointerException("content url must not be null.");
    }
    if (baseURL == null)
    {
      throw new NullPointerException("baseURL must not be null.");
    }
    if (isFileStyleProtocol(url) && isSameService(url, baseURL))
    {

      // If the URL contains a query, ignore that URL; do not
      // attemp to modify it...
      final List urlName = parseName(getPath(url));
      final List baseName = parseName(getPath(baseURL));
      final String query = getQuery(url);

      if (!isPath(baseURL))
      {
        baseName.remove(baseName.size() - 1);
      }

      // if both urls are identical, then return the plain file name...
      if (String.valueOf(url).equals(String.valueOf(baseURL)))
      {
        return (String) urlName.get(urlName.size() - 1);
      }

      int commonIndex = startsWithUntil(urlName, baseName);
      if (commonIndex == 0)
      {
        return url.toExternalForm();
      }

      if (commonIndex == urlName.size())
      {
        // correct the base index if there is some weird mapping
        // detected,
        // fi. the file url is fully included in the base url:
        //
        // base: /file/test/funnybase
        // file: /file/test
        //
        // this could be a valid configuration whereever virtual
        // mappings are allowed.
        commonIndex -= 1;
      }

      final ArrayList retval = new ArrayList();
      if (baseName.size() != urlName.size())
      {
        final int levels = baseName.size() - commonIndex;
        for (int i = 0; i < levels; i++)
        {
          retval.add("..");
        }
      }

      retval.addAll(urlName.subList(commonIndex, urlName.size()));
      return formatName(retval, query);
    }
    return url.toExternalForm();
  }

  /**
   * Returns <code>true</code> if the URL represents a path, and <code>false</code> otherwise.
   *
   * @param baseURL the URL.
   * @return A boolean.
   */
  private boolean isPath(final URL baseURL)
  {
    final String path = getPath(baseURL);
    if (path.length() > 0 && path.charAt(path.length() - 1) == '/')
    {
      return true;
    }
    else if ("file".equals(baseURL.getProtocol()))
    {
      final File f = new File(path);
      try
      {
        if (f.isDirectory())
        {
          return true;
        }
      }
      catch (SecurityException se)
      {
        // ignored ...
      }
    }
    return false;
  }

  /**
   * Implements the JDK 1.3 method URL.getPath(). The path is defined as URL.getFile() minus the (optional) query.
   *
   * @param url the URL
   * @return the path
   */
  private String getQuery(final URL url)
  {
    final String file = url.getFile();
    final int queryIndex = file.indexOf('?');
    if (queryIndex == -1)
    {
      return null;
    }
    return file.substring(queryIndex + 1);
  }

  /**
   * Implements the JDK 1.3 method URL.getPath(). The path is defined as URL.getFile() minus the (optional) query.
   *
   * @param url the URL
   * @return the path
   */
  private String getPath(final URL url)
  {
    final String file = url.getFile();
    final int queryIndex = file.indexOf('?');
    if (queryIndex == -1)
    {
      return file;
    }
    return file.substring(0, queryIndex);
  }

  /**
   * Copies the InputStream into the OutputStream, until the end of the stream has been reached. This method uses a
   * buffer of 4096 kbyte.
   *
   * @param in  the inputstream from which to read.
   * @param out the outputstream where the data is written to.
   * @throws java.io.IOException if a IOError occurs.
   */
  public void copyStreams(final InputStream in, final OutputStream out)
      throws IOException
  {
    copyStreams(in, out, 4096);
  }

  /**
   * Copies the InputStream into the OutputStream, until the end of the stream has been reached.
   *
   * @param in         the inputstream from which to read.
   * @param out        the outputstream where the data is written to.
   * @param buffersize the buffer size.
   * @throws java.io.IOException if a IOError occurs.
   */
  public void copyStreams(final InputStream in, final OutputStream out,
                          final int buffersize) throws IOException
  {
    // create a 4kbyte buffer to read the file
    final byte[] bytes = new byte[buffersize];

    // the input stream does not supply accurate available() data
    // the zip entry does not know the size of the data
    int bytesRead = in.read(bytes);
    while (bytesRead > -1)
    {
      out.write(bytes, 0, bytesRead);
      bytesRead = in.read(bytes);
    }
  }

  /**
   * Copies the contents of the Reader into the Writer, until the end of the stream has been reached. This method uses
   * a buffer of 4096 kbyte.
   *
   * @param in  the reader from which to read.
   * @param out the writer where the data is written to.
   * @throws java.io.IOException if a IOError occurs.
   */
  public void copyWriter(final Reader in, final Writer out)
      throws IOException
  {
    copyWriter(in, out, 4096);
  }

  /**
   * Copies the contents of the Reader into the Writer, until the end of the stream has been reached.
   *
   * @param in         the reader from which to read.
   * @param out        the writer where the data is written to.
   * @param buffersize the buffer size.
   * @throws java.io.IOException if a IOError occurs.
   */
  public void copyWriter(final Reader in, final Writer out,
                         final int buffersize)
      throws IOException
  {
    // create a 4kbyte buffer to read the file
    final char[] bytes = new char[buffersize];

    // the input stream does not supply accurate available() data
    // the zip entry does not know the size of the data
    int bytesRead = in.read(bytes);
    while (bytesRead > -1)
    {
      out.write(bytes, 0, bytesRead);
      bytesRead = in.read(bytes);
    }
  }

  /**
   * Reads the given number of bytes into the target array. This method does not return until all bytes are read. In
   * case a end-of-stream is reached, the method throws an Exception.
   *
   * @param in the inputstream from where to read.
   * @param data the array where to store the data.
   * @param offset the offset in the array where to store the data.
   * @param length the number of bytes to be read.
   * @throws IOException if an IO error occured or the End of the stream has been reached.
   */
  public void readFully (final InputStream in,
                         final byte[] data,
                         final int offset,
                         final int length) throws IOException
  {
    int bytesToRead = length;
    int bytesRead = 0;
    do
    {
      final int size = in.read(data, offset + bytesRead, bytesToRead);
      if (size == -1)
      {
        throw new IOException("End-Of-File reached");
      }
      bytesToRead = bytesToRead - size;
      bytesRead += size;
    }
    while(bytesToRead > 0);
  }

  /**
   * Reads the given number of bytes into the target array. This method does not return until all bytes are read. In
   * case a end-of-stream is reached, the method throws an Exception.
   *
   * @param in the inputstream from where to read.
   * @param data the array where to store the data.
   * @param offset the offset in the array where to store the data.
   * @param length the number of bytes to be read.
   * @throws IOException if an IO error occured or the End of the stream has been reached.
   */
  public int readSafely (final InputStream in,
                         final byte[] data,
                         final int offset,
                         final int length) throws IOException
  {
    int bytesToRead = length;
    int bytesRead = 0;
    do
    {
      final int size = in.read(data, offset + bytesRead, bytesToRead);
      if (size == -1)
      {
        return bytesRead;
      }
      bytesToRead = bytesToRead - size;
      bytesRead += size;
    }
    while(bytesToRead > 0);

    // end of file reached ..
    return 0;
  }

  /**
   * Extracts the file name from the URL.
   *
   * @param url the url.
   * @return the extracted filename.
   */
  public String getFileName(final URL url)
  {
    final String fileRaw = url.getFile();
    final int query = fileRaw.lastIndexOf('?');
    final String file;
    if (query == -1)
    {
      file = fileRaw;
    }
    else
    {
      file = fileRaw.substring(0, query);
    }

    // Now the processing is the same as if it is a string
    return getFileName(file);
  }

  /**
   * Extracts the last file name from the given pathname.
   *
   * @param path the path name.
   * @return the extracted filename.
   */
  public String getFileName(final String path)
  {
    // Check for slash and backslash
    final int last = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
    if (last < 0)
    {
      return path;
    }
    return path.substring(last + 1);
  }

  /**
   * Removes the file extension from the given file name.
   *
   * @param file the file name.
   * @return the file name without the file extension.
   */
  public String stripFileExtension(final String file)
  {
    final int idx = file.lastIndexOf('.');
    // handles unix hidden files and files without an extension.
    if (idx < 1)
    {
      return file;
    }
    return file.substring(0, idx);
  }

  /**
   * Returns the file extension of the given file name. The returned value will contain the dot.
   *
   * @param file the file name.
   * @return the file extension.
   */
  public String getFileExtension(final String file)
  {
    final int idx = file.lastIndexOf('.');
    // handles unix hidden files and files without an extension.
    if (idx < 1)
    {
      return "";
    }
    return file.substring(idx);
  }

  /**
   * Checks, whether the child directory is a subdirectory of the base directory.
   *
   * @param base  the base directory.
   * @param child the suspected child directory.
   * @return true, if the child is a subdirectory of the base directory.
   * @throws java.io.IOException if an IOError occured during the test.
   */
  public boolean isSubDirectory(File base, File child)
      throws IOException
  {
    base = base.getCanonicalFile();
    child = child.getCanonicalFile();

    File parentFile = child;
    while (parentFile != null)
    {
      if (base.equals(parentFile))
      {
        return true;
      }
      parentFile = parentFile.getParentFile();
    }
    return false;
  }


  /**
   * Returns a reference to a file with the specified name that is located somewhere on the classpath.  The code for
   * this method is an adaptation of code supplied by Dave Postill.
   *
   * @param name the filename.
   * @return a reference to a file or <code>null</code> if no file could be found.
   * @throws SecurityException if access to the system properties or filesystem is forbidden.
   * @noinspection AccessOfSystemProperties
   */
  public File findFileOnClassPath(final String name) throws SecurityException
  {

    final String classpath = System.getProperty("java.class.path");
    final String pathSeparator = System.getProperty("path.separator");

    final StringTokenizer tokenizer = new StringTokenizer(classpath, pathSeparator);

    while (tokenizer.hasMoreTokens())
    {
      final String pathElement = tokenizer.nextToken();

      final File directoryOrJar = new File(pathElement);
      final File absoluteDirectoryOrJar = directoryOrJar.getAbsoluteFile();

      if (absoluteDirectoryOrJar.isFile())
      {
        final File target = new File(absoluteDirectoryOrJar.getParent(), name);
        if (target.exists())
        {
          return target;
        }
      }
      else
      {
        final File target = new File(directoryOrJar, name);
        if (target.exists())
        {
          return target;
        }
      }

    }
    return null;

  }

  /**
   * Computes the absolute filename for the target file using the baseFile as root directory. If the baseFile is
   * null or empty, the target file will be normalized (all navigation elements like ".." are removed).
   *
   * @param targetFile the target file name.
   * @param baseFile the base file (can be null).
   * @return the absolute path.
   */
  public String getAbsolutePath (final String targetFile, final String baseFile)
  {
    if (targetFile == null)
    {
      throw new NullPointerException("targetFile must not be null.");
    }
    if (baseFile == null || "".equals(baseFile))
    {
      return stripNavigationPaths(targetFile);
    }

    if (targetFile.length() > 0 && targetFile.charAt(0) == '/')
    {
      return stripNavigationPaths(targetFile.substring(1));
    }

    final List baseName = parseName(baseFile);
    if (baseName.isEmpty())
    {
      return stripNavigationPaths(targetFile);
    }
    final List urlName = parseName(targetFile);
    if (urlName.isEmpty())
    {
      return stripNavigationPaths(baseFile);
    }

    if ((baseFile.length() > 0 &&
         baseFile.charAt(baseFile.length() - 1) == '/') == false)
    {
      // trailing slashes indicate directory,
      // so remove last entry if the basefile name does not end with a slash (ie it points to a file)
      baseName.remove(baseName.size() - 1);
      if (baseName.isEmpty())
      {
        return stripNavigationPaths(targetFile);
      }
    }

    for (int i = 0; i < urlName.size(); i++)
    {
      final String pathElement = (String) urlName.get(i);
      if ("".equals(pathElement) || pathElement == null)
      {
        continue;
      }
      if (".".equals(pathElement))
      {
        continue;
      }
      if ("..".equals(pathElement))
      {
        if (baseName.isEmpty() == false)
        {
          baseName.remove(baseName.size() - 1);
        }
        continue;
      }
      baseName.add(pathElement);
    }

    final String s = formatName(baseName, null);
    if (targetFile.length() > 0 && targetFile.charAt(targetFile.length() - 1) == '/')
    {
      return s + '/';
    }
    return s;
  }

  /**
   * Normalizes the given pathname.
   *
   * @param targetFile the target file to be normalized, never null.
   * @return the normalized filename.
   */
  private String stripNavigationPaths (final String targetFile)
  {
    final List list = parseName(targetFile);
    final int capacity = list.size();
    final List path = new ArrayList(capacity);
    for (int i = 0; i < capacity; i++)
    {
      final String pathElement = (String) list.get(i);
      if ("".equals(pathElement) || pathElement == null)
      {
        continue;
      }
      if (".".equals(pathElement))
      {
        continue;
      }
      if ("..".equals(pathElement))
      {
        if (path.isEmpty() == false)
        {
          path.remove(path.size() - 1);
        }
        continue;
      }
      path.add(pathElement);
    }

    final String s = formatName(path, null);
    if (targetFile.length() > 0 && targetFile.charAt(targetFile.length() - 1) == '/')
    {
      return s + '/';
    }
    return s;
  }

  /**
   * Returns the path-portion of the given path (anything before the last slash or backslash) or an empty string.
   *
   * @param path the path or filename from where to extract the path name.
   * @return the extracted path or a empty string.
   */
  public String getPath(final String path)
  {
    // Check for slash and backslash
    final int last = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
    if (last < 0)
    {
      return "";
    }
    return path.substring(0, last);
  }

  /**
   * Converts a SQL-Clob object into a String. If the Clob is larger than 2^31 characters, we cannot convert it.
   * If there are errors converting it, this method will log the cause and return null.
   *
   * @param clob the clob to be read as string.
   * @return the string or null in case of errors.
   */
  public String readClob(final Clob clob)
  {
    try
    {
      final long length = clob.length();
      if (length > Integer.MAX_VALUE)
      {
        logger.warn ("This CLOB contains more than 2^31 characters. We cannot handle that.");
        return null;
      }

      final Reader inStream = clob.getCharacterStream();
      final StringWriter outStream = new StringWriter((int) length);
      try
      {
        IOUtils.getInstance().copyWriter(inStream, outStream);
      }
      catch (IOException e)
      {
        logger.warn ("Copying the stream failed.", e);
      }
      try
      {
        inStream.close();
      }
      catch (IOException e)
      {
        logger.warn ("Failed to close input stream. No worries, we will be alright anyway.", e);
      }
      return outStream.toString();
    }
    catch (SQLException e)
    {
      return null;
    }
  }


  /**
   * Converts a SQL-Clob object into a String. If the Clob is larger than 2^31 characters, we cannot convert it.
   * If there are errors converting it, this method will log the cause and return null.
   *
   * @param clob the clob to be read as string.
   * @return the string or null in case of errors.
   */
  public byte[] readBlob(final Blob clob) throws SQLException
  {
    final long length = clob.length();
    if (length > Integer.MAX_VALUE)
    {
      logger.warn ("This CLOB contains more than 2^31 characters. We cannot handle that.");
      return null;
    }

    final InputStream inStream = clob.getBinaryStream();
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream((int) length);
    try
    {
      IOUtils.getInstance().copyStreams(inStream, outStream);
    }
    catch (IOException e)
    {
      logger.warn ("Copying the stream failed.", e);
    }
    try
    {
      inStream.close();
    }
    catch (IOException e)
    {
      logger.warn ("Failed to close input stream. No worries, we will be alright anyway.", e);
    }
    return outStream.toByteArray();
  }
}