summaryrefslogtreecommitdiff
path: root/src/plugins/common/src/com/motorola/studio/android/common/utilities/FileUtil.java
blob: a3126fba4f8594010863fb85ee39bee38360c44a (plain)
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.motorola.studio.android.common.utilities;

import static com.motorola.studio.android.common.log.StudioLogger.warn;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;

import com.motorola.studio.android.common.CommonPlugin;
import com.motorola.studio.android.common.log.StudioLogger;
import com.motorola.studio.android.common.utilities.i18n.UtilitiesNLS;

/**
 * DESCRIPTION: This class provides utility methods to handle files, like
 * copying and deleting directories sub-trees.
 * 
 * USAGE: See public methods
 */
public class FileUtil
{
    public static final int OS_WINDOWS = 0;

    public static final int OS_LINUX = 1;

    public static final char[] MAC_SPECIAL_CHAR =
    {
            '\\', ' ', '\'', '"', '!', '@', '$', '&', '*', '(', ')', '=', '`', '[', ']', '{', '}',
            '^', '<', '>', ':', ';', '?', '|'
    };

    public static final char[] LINUX_SPECIAL_CHAR =
    {
            '\\', ' ', '\'', '"', '!', '$', '&', '*', '(', ')', '=', '`', '[', ']', '{', '}', '^',
            '<', '>', ':', ';', '?', '|'
    };

    public static final char ESCAPE_CHAR = '\\';

    private static final int BUFFER_SIZE = 1024;

    /**
     * Copy full list of contents from a directory to another. The source
     * directory is not created within the target one.
     *
     * @param fromDir
     *           Source directory.
     * @param toDir
     *           Target directory.
     *           
     * @param IOException if I/O occurs         
     */
    public static void copyDir(File fromDir, File toDir) throws IOException
    {
        if ((fromDir != null) && fromDir.isDirectory() && fromDir.canRead() && (toDir != null)
                && toDir.isDirectory() && toDir.canWrite())
        {
            for (File child : fromDir.listFiles())
            {
                if (child.isFile())
                {
                    copyFile(child, new File(toDir, child.getName()));
                }
                else
                {
                    // create directory and copy its children recursively
                    File newDir = new File(toDir.getAbsolutePath(), child.getName());
                    newDir.mkdir();
                    copyDir(child, newDir);
                }
            }

            StudioLogger.info("The directory " + fromDir.getName() + " was successfully copied to " //$NON-NLS-1$ //$NON-NLS-2$
                    + toDir.getName() + "."); //$NON-NLS-1$

        }
        else
        {
            //error detected 
            String errorMessage = ""; //$NON-NLS-1$
            if (fromDir == null)
            {
                errorMessage = "Null pointer for source directory."; //$NON-NLS-1$
            }
            else
            {
                if (!fromDir.isDirectory())
                {
                    errorMessage = fromDir.getName() + " is not a directory."; //$NON-NLS-1$
                }
                else
                {
                    if (!fromDir.canRead())
                    {
                        errorMessage = "Cannot read from " + fromDir.getName() + "."; //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    else
                    {
                        if (toDir == null)
                        {
                            errorMessage = "Null pointer for destination directory."; //$NON-NLS-1$
                        }
                        else
                        {
                            if (!toDir.isDirectory())
                            {
                                errorMessage = toDir.getName() + " is not a directory."; //$NON-NLS-1$
                            }
                            else
                            {
                                if (!toDir.canWrite())
                                {
                                    errorMessage = "Cannot write to" + toDir.getName() + "."; //$NON-NLS-1$ //$NON-NLS-2$
                                }
                            }
                        }
                    }
                }
            }
            StudioLogger.error(errorMessage);
            throw new IOException("Error copying directory: " + errorMessage); //$NON-NLS-1$
        }
    }

    /**
     * Copies the source file to the given target.
     *
     * @param source -
     *           the absolute path of the source file.
     * @param target -
     *           the absolute path of the target file.
     */
    public static void copyFile(File source, File target) throws IOException
    {
        copyFile(source.getAbsolutePath(), target.getAbsolutePath());
    }

    /**
     * Copies the source file to the given target.
     *
     * @param source -
     *           the absolute path of the source file.
     * @param target -
     *           the absolute path of the target file.
     */
    private static void copyFile(String source, String target) throws IOException
    {
        FileChannel sourceFileChannel = null;
        FileChannel targetFileChannel = null;
        FileInputStream sourceFileInStream = null;
        FileOutputStream targetFileOutStream = null;
        try
        {
            sourceFileInStream = new FileInputStream(source);
            sourceFileChannel = sourceFileInStream.getChannel();
            targetFileOutStream = new FileOutputStream(target);
            targetFileChannel = targetFileOutStream.getChannel();
            targetFileChannel.transferFrom(sourceFileChannel, 0, sourceFileChannel.size());
            StudioLogger.info("The file " + source + " was successfully copied to " + target + "."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
        catch (IOException e)
        {
            StudioLogger.error("Error copying file" + source + "to " + target + "."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            throw e;
        }
        finally
        {
            try
            {
                if (sourceFileChannel != null)
                {
                    sourceFileChannel.close();
                }
            }
            catch (IOException e)
            {
                StudioLogger.error("Error closing file " + source + "."); //$NON-NLS-1$ //$NON-NLS-2$
                throw e;
            }

            try
            {
                if (targetFileChannel != null)
                {
                    targetFileChannel.close();
                }
            }
            catch (IOException e)
            {
                StudioLogger.error("Error closing file" + target + "."); //$NON-NLS-1$ //$NON-NLS-2$
                throw e;
            }

            try
            {
                if (sourceFileInStream != null)
                {
                    sourceFileInStream.close();
                }
            }
            catch (IOException e)
            {
                StudioLogger.error("Error closing file" + source + "."); //$NON-NLS-1$ //$NON-NLS-2$
                throw e;
            }

            try
            {
                if (targetFileOutStream != null)
                {
                    targetFileOutStream.close();
                }
            }
            catch (IOException e)
            {
                StudioLogger.error("Error closing file" + target + "."); //$NON-NLS-1$ //$NON-NLS-2$
                throw e;
            }

        }
    }

    /**
     * This method deletes the directory, all files and all subdirectories under
     * it. If a deletion fails, the method stops attempting to delete and
     * returns false.
     *
     * @param directory
     *           The directory to be deleted
     * @return Returns true if all deletions were successful. If the directory
     *         doesn't exist returns false.
     * @throws IOException
     *            When the parameter isn't a directory
     */
    public static boolean deleteDirRecursively(File directory) throws IOException
    {
        String dirName = ""; //$NON-NLS-1$

        boolean success = true;

        if (directory.exists())
        {
            if (directory.isDirectory())
            {
                dirName = directory.getName();
                File[] children = directory.listFiles();

                for (File element : children)
                {
                    if (element.isFile())
                    {
                        success = success && element.delete();
                    }
                    else
                    {
                        success = success && deleteDirRecursively(element);
                    }
                }

                success = success && directory.delete();
            }
            else
            {
                String errorMessage = directory.getName() + " is not a diretory."; //$NON-NLS-1$
                StudioLogger.error(errorMessage);
                throw new IOException(errorMessage);
            }
        }
        else
        {
            String errorMessage = "The directory does not exist."; //$NON-NLS-1$
            StudioLogger.error(errorMessage);
            success = false;
            throw new IOException(errorMessage);
        }

        if ((success) && (!dirName.equals(""))) //$NON-NLS-1$
        {
            StudioLogger.info("The directory " + dirName + "was successfully deleted."); //$NON-NLS-1$ //$NON-NLS-2$
        }

        return success;
    }

    /**
     * Delete a single file from the filesystem.
     *
     * @param fileToDelete
     *           A <code>File</code> object representing the file to be
     *           deleted.
     * @throws IOException
     *            if any problem occurs deleting the file.
     */
    public static void deleteFile(File fileToDelete) throws IOException
    {
        if ((fileToDelete != null) && fileToDelete.exists() && fileToDelete.isFile()
                && fileToDelete.canWrite())
        {
            fileToDelete.delete();
            StudioLogger.info("The file " + fileToDelete.getName() + "was successfully deleted."); //$NON-NLS-1$ //$NON-NLS-2$
        }
        else
        {
            String errorMessage = ""; //$NON-NLS-1$
            if (fileToDelete == null)
            {
                errorMessage = "Null pointer for file to delete."; //$NON-NLS-1$
            }
            else
            {
                if (!fileToDelete.exists())
                {
                    errorMessage = "The file " + fileToDelete.getName() + " does not exist."; //$NON-NLS-1$ //$NON-NLS-2$
                }
                else
                {
                    if (!fileToDelete.isFile())
                    {
                        errorMessage = fileToDelete.getName() + " is not a file."; //$NON-NLS-1$
                    }
                    else
                    {
                        if (!fileToDelete.canWrite())
                        {
                            errorMessage = "Cannot write to " + fileToDelete.getName(); //$NON-NLS-1$
                        }
                    }
                }

            }

            StudioLogger.error(errorMessage);
            throw new IOException("Cannot delete file: " + errorMessage); //$NON-NLS-1$
        }
    }

    /**
     * Delete a list of files from the filesystem.
     *
     * @param filesToDelete
     *           A list of <code>File</code> objects representing the files
     *           to be deleted.
     * @throws IOException
     *            if any problem occurs deleting the files.
     */
    public static void deleteFilesOnList(List<File> filesToDelete) throws IOException
    {
        for (File element : filesToDelete)
        {
            if (element.exists())
            {
                deleteFile((element));
            }
        }
    }

    /**
     * Return the File Size in Bytes.
     * 
     * @param root The root File, it can be a directory
     * @return The size of the file in bytes
     * @throws IOException
     */
    public static int getFileSize(File root) throws IOException
    {
        int size = 0;
        if (root.isDirectory())
        {
            for (File child : root.listFiles())
            {
                size += FileUtil.getFileSize(child);
            }
        }
        else if (root.isFile())
        {
            FileInputStream fis = new FileInputStream(root);
            int available;
            try
            {
                available = fis.available();
            }
            finally
            {
                try
                {
                    fis.close();
                }
                catch (IOException e)
                {
                    //Do thing.
                }
            }
            size = available;
        }
        return size;
    }

    /**
     * getExtension(String fileName)
     *
     * @param fileName
     *           returns the extension of a given file. "extension" here means
     *           the final part of the string after the last dot.
     *
     * @return String containing the extension
     */
    public static String getExtension(String fileName)
    {
        if (fileName != null)
        {
            int i = fileName.lastIndexOf(".") + 1; //$NON-NLS-1$
            return (i == 0) ? "" : fileName.substring(i); //$NON-NLS-1$
        }
        else
        {
            StudioLogger.error("The file " + fileName + " does not exist."); //$NON-NLS-1$ //$NON-NLS-2$
            return null;
        }
    }

    /**
     * Get the list of all File objects that compose the path to the given File
     * object
     *
     * @param aFile
     *           the file whose path must be retrieved.
     * @return a List with all the File objects that compose the path to the
     *         given File object.
     */
    public static List<File> getFilesComposingPath(File aFile)
    {
        List<File> fileList;

        if (aFile == null)
        {
            fileList = new ArrayList<File>();
        }
        else
        {
            fileList = getFilesComposingPath(aFile.getParentFile());
            fileList.add(aFile);
        }

        return fileList;
    }

    /**
     * Retrieve the relative filename to access a targetFile from a homeFile
     * parent directory. Notice that to actualy use a relative File object you
     * must use the following new File(homeDir, relativeFilename) because using
     * only new File(relativeFilename) would give you a file whose directory is
     * the one set in the "user.dir" property.
     *
     * @param homeDir
     *           the directory from where you want to access the targetFile
     * @param targetFile
     *           the absolute file or dir that you want to access via relative
     *           filename from the homeFile
     * @return the relative filename that describes the location of the
     *         targetFile referenced from the homeFile dir
     * @throws IOException
     */
    public static String getRelativeFilename(File homeDir, File targetFile) throws IOException
    {
        StringBuffer relativePath = new StringBuffer();

        List<File> homeDirList = getFilesComposingPath(getCanonicalFile(homeDir));
        List<File> targetDirList = getFilesComposingPath(getCanonicalFile(targetFile));

        if (homeDirList.size() == 0)
        {
            StudioLogger.info("Home Dir has no parent."); //$NON-NLS-1$
        }

        if (targetDirList.size() == 0)
        {
            StudioLogger.info("Target Dir has no parent."); //$NON-NLS-1$
        }

        // get the index of the last common directory between sourceFile and
        // targetFile
        int commonIndex = -1;

        for (int i = 0; (i < homeDirList.size()) && (i < targetDirList.size()); i++)
        {
            File aHomeDir = homeDirList.get(i);
            File aTargetDir = targetDirList.get(i);

            if (aHomeDir.equals(aTargetDir))
            {
                commonIndex = i;
            }
            else
            {
                break;
            }
        }

        // return from all remaining directories of the homeFile
        for (int i = commonIndex + 1; i < homeDirList.size(); i++)
        {
            relativePath.append(".."); //$NON-NLS-1$
            relativePath.append(File.separatorChar);
        }

        // enter into all directories of the target file
        // stops when reachs the file name and extension
        for (int i = commonIndex + 1; i < targetDirList.size(); i++)
        {
            File targetDir = targetDirList.get(i);
            relativePath.append(targetDir.getName());

            if (i != (targetDirList.size() - 1))
            {
                relativePath.append(File.separatorChar);
            }
        }

        return relativePath.toString();
    }

    /**
     * Return a list of file absolute paths under "baseDir" and under its subdirectories,
     * recursively.
     *
     * @param baseDirToList
     *           A string that represents the BaseDir to initial search.
     * @return A List of filepaths of files under the "baseDir".
     * @throws IOException
     *            If the "baseDir" can not be read.
     */
    public static List<String> listFilesRecursively(String baseDirToList) throws IOException
    {
        File baseDirToListFiles = new File(baseDirToList);
        List<String> listOfFiles = listFilesRecursively(baseDirToListFiles);

        return listOfFiles;
    }

    /**
     * Return a list of file absolute paths under "baseDir" and under its subdirectories,
     * recursively.
     *
     * @param baseDirToList
     *           A file object that represents the "baseDir".
     * @return A List of filepaths of files under the "baseDir".
     * @throws IOException
     *            If the "baseDir" can not be read.
     */
    public static List<String> listFilesRecursively(File baseDirToList) throws IOException
    {
        List<String> listOfFiles = new ArrayList<String>();

        if (baseDirToList.exists() && baseDirToList.isDirectory() && baseDirToList.canRead())
        {
            File[] children = baseDirToList.listFiles();

            for (File child : children)
            {
                if (child.isFile())
                {
                    listOfFiles.add(child.getAbsolutePath());
                }
                else
                {
                    List<String> temporaryList = listFilesRecursively(child);
                    listOfFiles.addAll(temporaryList);
                }
            }
        }
        else
        {
            String errorMessage = ""; //$NON-NLS-1$
            if (!baseDirToList.exists())
            {
                errorMessage = "The base dir does not exist."; //$NON-NLS-1$
            }
            else
            {
                if (!baseDirToList.isDirectory())
                {
                    errorMessage = baseDirToList.getName() + "is not a directory."; //$NON-NLS-1$
                }
                else
                {
                    if (!baseDirToList.canRead())
                    {
                        errorMessage = "Cannot fread from " + baseDirToList.getName() + "."; //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }
            }

            StudioLogger.error(errorMessage);
            throw new IOException("Error listing files: " + errorMessage); //$NON-NLS-1$
        }

        return listOfFiles;
    }

    /**
     * Calculate the canonical (an absolute filename without "\.\" and "\..\")
     * that describe the file described by the absoluteFilename.
     * @param absoluteFilename a file name that describe the full path of the file to use.
     * @return the canonical File objecta
     */
    public static File getCanonicalFile(String absoluteFilename)
    {
        return getCanonicalFile(new File(absoluteFilename));
    }

    /**
     * Calculate the canonical (an absolute filename without "\.\" and "\..\")
     * that describe the file described by the given location and filename.
     * @param location the directory of the file to be used
     * @param filename (or a relative filename) of the file to be used
     * @return the canonical File objecta
     */
    public static File getCanonicalFile(File location, String filename)
    {
        return getCanonicalFile(new File(location, filename));
    }

    /**
     * Calculate the canonical (an absolute filename without "\.\" and "\..\")
     * that describe the given file.
     * @param aFile the file whose cannonical path will be calculated
     * @return the canonical File objecta
     */
    public static File getCanonicalFile(File aFile)
    {
        File f = null;

        try
        {
            f = aFile.getCanonicalFile();
        }
        catch (IOException e)
        {
            // this should never happens
            StudioLogger.error(FileUtil.class, "FileUtil.getCanonicalFile: IOException e", e); //$NON-NLS-1$

            // since it's not possible to read from filesystem, return a File using String          
            String filename = aFile.getAbsolutePath();

            StringTokenizer st = new StringTokenizer(filename, File.separator);

            StringBuffer sb = new StringBuffer();

            while (st.hasMoreTokens())
            {
                String token = (String) st.nextElement();

                if (token.equals("..")) //$NON-NLS-1$
                {
                    int lastDirIndex = sb.lastIndexOf(File.separator);

                    // do not go back currently on the root directory
                    if (lastDirIndex > 2)
                    {
                        sb.delete(lastDirIndex, sb.length());
                    }
                }
                else if (!token.equals(".")) //$NON-NLS-1$
                {
                    if (sb.length() > 0)
                    {
                        sb.append(File.separator);
                    }

                    sb.append(token);

                    if (token.endsWith(":")) //$NON-NLS-1$
                    {
                        sb.append(File.separator);
                    }
                }
            }

            f = new File(sb.toString());
        }

        return f;
    }

    /**
     * Returns which is the OS.
     * @return
     *      a code corresponding to the proper OS
     */
    public static int getOS()
    {
        int result = -1;

        String osName = System.getProperty("os.name").toLowerCase(); //$NON-NLS-1$
        if (osName.indexOf("linux") > -1) //$NON-NLS-1$
        {
            result = OS_LINUX;
        }
        else if (osName.indexOf("windows") > -1) //$NON-NLS-1$
        {
            result = OS_WINDOWS;
        }

        return result;
    }

    /**
     *   Returns true if the OS is windows
     * @return true if the OS is windows
     */
    public static boolean isWindows()
    {
        return getOS() == OS_WINDOWS;
    }

    /**
     * Opens the stream;
     *
     * @param stream File Stream
     *
     * @return StringBuffer with the file content
     *
     * @throws IOException
     */
    public static StringBuffer openFile(InputStream stream) throws IOException
    {
        InputStreamReader streamReader = null;
        StringBuffer fileBuffer = new StringBuffer();
        BufferedReader reader = null;
        try
        {
            streamReader = new InputStreamReader(stream);
            reader = new BufferedReader(streamReader);
            char[] buffer = new char[1024];
            int line = reader.read(buffer);

            while (line > 0)
            {
                fileBuffer.append(buffer, 0, line);
                line = reader.read(buffer);
            }
        }
        finally
        {
            if (streamReader != null)
            {
                try
                {
                    streamReader.close();
                }
                catch (Exception e)
                {
                    //Do nothing.
                }
            }
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (Exception e)
                {
                    //Do nothing.
                }
            }
        }

        return fileBuffer;
    }

    /**
     * Reads a file into a string array
     * 
     * @param filename The file name
     * @return The file contents as a string array
     * @throws IOException 
     */
    public static String[] readFileAsArray(String filename) throws IOException
    {
        LinkedList<String> file = new LinkedList<String>();
        String[] lines = new String[0];
        String line;
        FileReader reader = null;
        LineNumberReader lineReader = null;

        try
        {
            reader = new FileReader(filename);
            lineReader = new LineNumberReader(reader);

            while ((line = lineReader.readLine()) != null)
            {
                file.add(line);
            }

            lines = new String[file.size()];
            lines = file.toArray(lines);
        }
        finally
        {
            try
            {
                lineReader.close();
                reader.close();
            }
            catch (Exception e)
            {
                // Do nothing
            }
        }

        return lines;
    }

    /**
     * Reads a file on workspace and returns an IDocument object with its content
     * 
     * @param file The file to read
     * @return The IDocument object containing the file contents
     * 
     * @throws CoreException
     */
    public static IDocument readFile(IFile file) throws CoreException
    {
        if (!canRead(file))
        {
            String errMsg = NLS.bind(UtilitiesNLS.EXC_FileUtil_TheFileCannotBeRead, file.getName());
            IStatus status = new Status(IStatus.ERROR, CommonPlugin.PLUGIN_ID, errMsg);

            throw new CoreException(status);
        }

        TextFileDocumentProvider documentProvider = new TextFileDocumentProvider();
        IDocument document = new Document();

        documentProvider.connect(file);
        document = documentProvider.getDocument(file);
        documentProvider.disconnect(file);

        return document;
    }

    /**
     * Saves the content of an IDocument object to a file on workspace
     * @param file The file
     * @param document The IDocument object
     * @param encoding The file encoding
     * @param overwrite If the file can be overwritten
     * @throws CoreException
     */
    public static void saveFile(IFile file, IDocument document, String encoding, boolean overwrite)
            throws CoreException
    {
        if (file.exists() && !overwrite)
        {
            String errMsg =
                    NLS.bind(UtilitiesNLS.EXC_FileUtil_CannotOverwriteTheFile, file.getName());
            IStatus status = new Status(IStatus.ERROR, CommonPlugin.PLUGIN_ID, errMsg);

            throw new CoreException(status);
        }

        if (!canWrite(file))
        {
            String errMsg = NLS.bind(UtilitiesNLS.EXC_FileUtil_ErrorWritingTheFile, file.getName());
            IStatus status = new Status(IStatus.ERROR, CommonPlugin.PLUGIN_ID, errMsg);

            throw new CoreException(status);
        }

        ByteArrayInputStream bais = null;

        try
        {
            bais = new ByteArrayInputStream(document.get().getBytes(encoding));
            file.setCharset(encoding, new NullProgressMonitor());
            file.setContents(bais, true, false, new NullProgressMonitor());
        }
        catch (UnsupportedEncodingException e1)
        {
            String errMsg =
                    NLS.bind(UtilitiesNLS.EXC_FileUtil_ErrorSettingTheFileEncoding, file.getName());
            IStatus status = new Status(IStatus.ERROR, CommonPlugin.PLUGIN_ID, errMsg);

            throw new CoreException(status);
        }
        finally
        {
            if (bais != null)
            {
                try
                {
                    bais.close();
                }
                catch (IOException e)
                {
                    // Do nothing.
                }
            }
        }
    }

    /**
     * Checks if a file can be read
     * 
     * @param file The file to be checked
     * @return true if the file can be read or false otherwise
     */
    public static boolean canRead(IFile file)
    {
        boolean canRead = true;
        InputStream is = null;

        try
        {
            if (file.exists())
            {
                file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
                is = file.getContents();
                is.read();
            }
        }
        catch (CoreException e)
        {
            canRead = false;
        }
        catch (IOException e)
        {
            canRead = false;
        }
        finally
        {
            if (is != null)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {
                    // do nothing               
                }
            }
        }

        return canRead;
    }

    /**
     * Checks if a file can be written
     * 
     * @param file the file to be checked
     * @return true if the file can be written or false otherwise
     */
    public static boolean canWrite(IFile file)
    {
        boolean canWrite = true;

        if (file.exists() && canRead(file))
        {
            canWrite = !file.isReadOnly();
        }
        else
        {
            IFolder parent = (IFolder) file.getParent();

            if (!parent.isAccessible())
            {
                canWrite = false;
            }
            else
            {
                try
                {
                    if (parent.members() == null)
                    {
                        canWrite = false;
                    }
                    else
                    {
                        NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();
                        file.create(null, true, nullProgressMonitor);
                        file.refreshLocal(IResource.DEPTH_ZERO, nullProgressMonitor);
                        file.delete(true, nullProgressMonitor);
                    }
                }
                catch (CoreException e)
                {
                    canWrite = false;
                }
            }
        }

        return canWrite;
    }

    /**
     * Checks if a File object can be read
     * 
     * @param file the File object
     * 
     * @return true if the File object can be read or false otherwise
     */
    public static boolean canRead(File file)
    {
        boolean canRead = false;

        if ((file != null) && file.exists())
        {
            FileInputStream fis = null;

            try
            {
                if (file.isFile())
                {
                    fis = new FileInputStream(file);
                    fis.read();
                    canRead = true;
                }
                else
                {
                    String[] children = file.list();

                    if (children != null)
                    {
                        canRead = true;
                    }
                }
            }
            catch (Exception e)
            {
                // Do nothing. canRead is false already
            }
            finally
            {
                try
                {
                    if (fis != null)
                    {
                        fis.close();
                    }
                }
                catch (IOException e)
                {
                    // Do nothing
                }
            }
        }

        return canRead;
    }

    /**
     * Checks if a File object can be written
     * 
     * @param file the File object
     * 
     * @return true if the File object can be written or false otherwise
     */
    public static boolean canWrite(File file)
    {
        boolean canWrite = false;

        if (file != null)
        {
            FileOutputStream fos = null;

            try
            {
                if (!file.exists())
                {
                    canWrite = file.createNewFile();

                    if (canWrite)
                    {
                        file.delete();
                    }
                }
                else if (file.isDirectory())
                {
                    File tempFile = File.createTempFile("StudioForAndroidFSChecking", null, file); //$NON-NLS-1$

                    if (tempFile.exists())
                    {
                        canWrite = true;
                        tempFile.delete();
                    }
                }
                else if (file.isFile())
                {
                    fos = new FileOutputStream(file);
                    fos.getFD();
                    canWrite = true;
                }
            }
            catch (Exception e)
            {
                // Do nothing. canWrite is false already
            }
            finally
            {
                if (fos != null)
                {
                    try
                    {
                        fos.close();
                    }
                    catch (IOException e)
                    {
                        // Do nothing
                    }
                }
            }
        }

        return canWrite;
    }

    /**
     * Unpack a zip file.
     * 
     * @param file the file
     * @param destination the destination path or null to unpack at the same directory of file
     * @return true if unpacked, false otherwise
     */
    public static boolean unpackZipFile(File file, String destination, IProgressMonitor monitor)
    {
        SubMonitor subMonitor = SubMonitor.convert(monitor);
        ZipFile zipFile = null;

        String extractDestination = destination != null ? destination : file.getParent();
        if (!extractDestination.endsWith(File.separator))
        {
            extractDestination += File.separator;
        }

        boolean unziped = true;
        try
        {
            zipFile = new ZipFile(file);
        }
        catch (Throwable e)
        {
            unziped = false;
            StudioLogger.error(FileUtil.class, "Error extracting file: " + file.getAbsolutePath() //$NON-NLS-1$
                    + " to " + extractDestination, e); //$NON-NLS-1$

        }
        if (zipFile != null)
        {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            subMonitor.beginTask("Extracting files", Collections.list(entries).size()); //$NON-NLS-1$
            entries = zipFile.entries();
            InputStream input = null;
            OutputStream output = null;
            while (entries.hasMoreElements())
            {
                try
                {
                    ZipEntry entry = entries.nextElement();
                    File newFile = new File(extractDestination + entry.getName());
                    if (entry.isDirectory())
                    {
                        newFile.mkdirs();
                    }
                    else
                    {
                        newFile.getParentFile().mkdirs();
                        if (newFile.createNewFile())
                        {
                            input = zipFile.getInputStream(entry);
                            output = new BufferedOutputStream(new FileOutputStream(newFile));
                            copyStreams(input, output);
                        }
                    }
                }
                catch (Throwable t)
                {
                    unziped = false;
                    StudioLogger.error(FileUtil.class,
                            "Error extracting file: " + file.getAbsolutePath() + " to " //$NON-NLS-1$ //$NON-NLS-2$
                                    + extractDestination, t);
                }
                finally
                {
                    try
                    {
                        if (input != null)
                        {
                            input.close();
                        }
                        if (output != null)
                        {
                            output.close();
                        }
                    }
                    catch (Throwable t)
                    {
                        //do nothing
                    }
                    subMonitor.worked(1);
                }
            }
        }
        return unziped;
    }

    public static boolean extractZipArchive(File file, File destination,
            List<String> selectedEntries, IProgressMonitor monitor) throws IOException
    {
        SubMonitor subMonitor = SubMonitor.convert(monitor);
        ZipFile zipFile = null;
        CRC32 crc = new CRC32();
        byte[] buf = new byte[BUFFER_SIZE];

        File extractDestination = destination != null ? destination : file.getParentFile();

        if (!extractDestination.exists())
        {
            extractDestination.mkdirs();
        }

        boolean unziped = true;
        try
        {
            zipFile = new ZipFile(file);
        }
        catch (Throwable e)
        {
            unziped = false;
            StudioLogger.error(FileUtil.class, "Error extracting file: " + file.getAbsolutePath() //$NON-NLS-1$
                    + " to " + extractDestination, e); //$NON-NLS-1$

        }
        if (zipFile != null)
        {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            subMonitor.beginTask("Extracting files", Collections.list(entries).size()); //$NON-NLS-1$
            entries = zipFile.entries();
            InputStream input = null;
            FileOutputStream output = null;
            int diagReturn = IDialogConstants.YES_ID;
            while (entries.hasMoreElements())
            {
                crc.reset();
                try
                {
                    ZipEntry entry = entries.nextElement();
                    if (selectedEntries.contains(entry.getName()))
                    {
                        File newFile = new File(extractDestination, entry.getName());
                        if ((diagReturn != IDialogConstants.YES_TO_ALL_ID) && newFile.exists())
                        {
                            diagReturn =
                                    EclipseUtils.showQuestionYesAllCancelDialog(
                                            UtilitiesNLS.FileUtil_File_Exists_Title, NLS.bind(
                                                    UtilitiesNLS.FileUtil_File_Exists_Message,
                                                    newFile.getAbsolutePath()));
                        }

                        if ((diagReturn == IDialogConstants.YES_ID)
                                || (diagReturn == IDialogConstants.YES_TO_ALL_ID))
                        {
                            newFile.delete();
                            if (entry.isDirectory())
                            {
                                newFile.mkdirs();
                            }
                            else
                            {
                                newFile.getParentFile().mkdirs();
                                if (newFile.createNewFile())
                                {
                                    input = zipFile.getInputStream(entry);
                                    output = new FileOutputStream(newFile);
                                    int length = 0;
                                    while ((length = input.read(buf, 0, BUFFER_SIZE)) > 1)
                                    {
                                        output.write(buf, 0, length);
                                        crc.update(buf, 0, length);
                                    }

                                    if (crc.getValue() != entry.getCrc())
                                    {
                                        throw new IOException();
                                    }

                                }
                            }
                        }
                        else
                        {
                            diagReturn = IDialogConstants.YES_ID; //Attempt to extract next entry
                        }
                    }
                }
                catch (IOException e)
                {
                    unziped = false;
                    StudioLogger.error(FileUtil.class,
                            "Error extracting file: " + file.getAbsolutePath() + " to " //$NON-NLS-1$ //$NON-NLS-2$
                                    + extractDestination, e);
                    throw e;
                }
                catch (Throwable t)
                {
                    unziped = false;
                    StudioLogger.error(FileUtil.class,
                            "Error extracting file: " + file.getAbsolutePath() + " to " //$NON-NLS-1$ //$NON-NLS-2$
                                    + extractDestination, t);
                }
                finally
                {
                    try
                    {
                        if (input != null)
                        {
                            input.close();
                        }
                        if (output != null)
                        {
                            output.close();
                        }
                    }
                    catch (Throwable t)
                    {
                        //do nothing
                    }
                    subMonitor.worked(1);
                }
            }
        }
        return unziped;

    }

    /**
     * Unpack a tar file.
     * 
     * @param file the file
     * @param destination the destination path or null to unpack at the same directory of file
     * @return true if unpacked, false otherwise
     */
    public static boolean unpackTarFile(File artifactFile, String destination)
    {
        boolean unpacked = true;

        String extractDestination = destination != null ? destination : artifactFile.getParent();
        if (!extractDestination.endsWith(File.separator))
        {
            extractDestination += File.separator;
        }

        List<String> commandList = new LinkedList<String>();
        commandList.add("tar"); //$NON-NLS-1$

        String fileName = artifactFile.getName();

        //tar.gz or tgz
        if (fileName.endsWith("gz")) //$NON-NLS-1$
        {
            commandList.add("xzf"); //$NON-NLS-1$
        }
        //tar.bz2
        else if (fileName.endsWith("bz2")) //$NON-NLS-1$
        {
            commandList.add("xjf"); //$NON-NLS-1$
        }
        //tar
        else if (fileName.endsWith("tar")) //$NON-NLS-1$
        {
            commandList.add("xf"); //$NON-NLS-1$
        }
        else
        {
            unpacked = false;
        }

        if (unpacked)
        {
            commandList.add(artifactFile.getAbsolutePath());
            File target = new File(extractDestination);
            if (target.exists() && target.isDirectory() && target.canWrite())
            {
                try
                {
                    Process p =
                            Runtime.getRuntime().exec(commandList.toArray(new String[0]), null,
                                    target);
                    try
                    {
                        p.waitFor();
                    }
                    catch (InterruptedException e)
                    {
                        //do nothing
                    }
                    if (p.exitValue() != 0)
                    {
                        unpacked = false;

                    }
                }
                catch (IOException e)
                {
                    unpacked = false;
                }
            }
        }

        return unpacked;
    }

    /**
     * Copy the input stream to the output stream
     * @param inputStream
     * @param outputStream
     * @throws IOException
     */
    public static void copyStreams(InputStream inputStream, OutputStream outputStream)
            throws IOException
    {
        byte[] buffer = new byte[1024];
        int length;

        while ((length = inputStream.read(buffer)) >= 0)
        {
            outputStream.write(buffer, 0, length);
        }
    }

    /**
     * Add a directory to a Project
     * @param project
     * @param parentFolder
     * @param folderName
     * @param monitor
     * @throws CoreException
     */
    public static void createProjectFolder(IProject project, String parentFolder,
            String folderName, IProgressMonitor monitor) throws CoreException
    {
        monitor.beginTask(UtilitiesNLS.UI_Project_Creating_Folder_Task, 100);

        try
        {
            monitor.setTaskName(UtilitiesNLS.UI_Project_Verifying_Folder_Task);
            if (folderName.length() > 0)
            {
                monitor.worked(10);
                IFolder folder = project.getFolder(parentFolder + folderName);
                monitor.worked(10);
                if (!folder.exists())
                {
                    monitor.worked(10);
                    if (FileUtil.canWrite(folder.getLocation().toFile()))
                    {
                        monitor.worked(10);
                        monitor.setTaskName(UtilitiesNLS.UI_Project_Creating_Folder_Task);
                        folder.create(true, true, new SubProgressMonitor(monitor, 60));
                    }
                    else
                    {
                        String errMsg =
                                NLS.bind(
                                        UtilitiesNLS.EXC_Project_CannotCreateFolderReadOnlyWorkspace,
                                        folder.getLocation().toFile().toString());
                        IStatus status = new Status(IStatus.ERROR, CommonPlugin.PLUGIN_ID, errMsg);
                        throw new CoreException(status);
                    }
                }
            }
        }
        finally
        {
            monitor.done();
        }
    }

    /**
     * Given a directory descriptor represented by a {@link File}, creates it
     * only if it does not exist. In case it does, try to create another
     * one with its name plus "-1". If it does exists, try to create it with
     * its name plus "+2", and so on... 
     * <br>
     * Note that the directory is not fisically created. To do so, on must
     * use the method {@link File#mkdir()}.
     * 
     * @param directory Directory to be created.
     * 
     * @return Returns the created directory as a {@link File}.
     */
    public static File createUniqueDirectoryDescriptor(File directory)
    {
        if (directory.exists())
        {
            boolean exists = true;
            int counter = 1;
            String rootPath = directory.getAbsolutePath();
            while (exists)
            {
                directory = new File(rootPath + "-" + counter); //$NON-NLS-1$
                exists = directory.exists();
                counter++;
            }
        }

        return directory;
    }

    /**
     * Return path with special characters escaped.
     * Special characters are system dependent, there is a set for linux and another for mac.
     * If {@code operationalSystem} is windows, the path is returned unchanged.
     * 
     * @param path to be escaped.
     * @param operatingSystem the target operation system that the path will be used. 
     * @return path with special characters escaped.
     * */
    public static String getEscapedPath(String path, String operatingSystem)
    {
        char[] specialCharSet = null;

        if (operatingSystem.equals(Platform.OS_LINUX))
        {
            specialCharSet = LINUX_SPECIAL_CHAR;
        }
        else if (operatingSystem.equals(Platform.OS_MACOSX))
        {
            specialCharSet = MAC_SPECIAL_CHAR;
        }

        if ((path != null) && (specialCharSet != null))
        {
            for (char c : specialCharSet)
            {
                CharSequence target = String.valueOf(c);
                CharSequence replacement = new String("\\" + String.valueOf(c)); //$NON-NLS-1$
                path = path.replace(target, replacement);
            }
        }

        return path;
    }

    /**
     * Return path with special characters escaped.
     * Special characters are system dependent, there is a set for linux and another for mac.
     * If the system is windows, returns the path unchanged.
     * 
     * @param path to be escaped
     * @return path with special characters escaped.
     * */
    public static String getEscapedPath(String path)
    {
        return getEscapedPath(path, Platform.getOS());
    }

    /**
     * Return path with special characters unescaped.
     * Special characters are system dependent, there is a set for linux and another for mac.
     * If the system is windows, returns the path unchanged.
     * 
     * @param path to be unescaped
     * @return path with special characters unescaped.
     * */
    public static String getUnescapedPath(String path)
    {
        char[] specialCharSet = null;

        if (Platform.getOS().equals(Platform.OS_LINUX))
        {
            specialCharSet = LINUX_SPECIAL_CHAR;
        }
        else if (Platform.getOS().equals(Platform.OS_MACOSX))
        {
            specialCharSet = MAC_SPECIAL_CHAR;
        }

        if ((path != null) && (specialCharSet != null))
        {
            for (char c : specialCharSet)
            {
                CharSequence target = new String("\\") + String.valueOf(c); //$NON-NLS-1$
                CharSequence replacement = String.valueOf(c);
                path = path.replace(target, replacement);
            }
        }

        return path;
    }

    public static String removeUnescapedQuotes(String path, String quoteReplacement)
    {
        //remove quotes and double quotes
        char quotes[] =
        {
                '\'', '"'
        };

        boolean escaped = false;

        for (int i = 0; i < path.length(); i++)
        {
            if (escaped == false)
            {
                if (path.charAt(i) == ESCAPE_CHAR)
                {
                    escaped = true;
                }
                else
                {
                    for (char quote : quotes)
                    {
                        if (path.charAt(i) == quote)
                        {
                            //split the string in two parts:
                            // - part1: before the quote
                            String part1 = path.substring(0, i);
                            // - part2: after the quote
                            String part2 = path.substring(i + 1, path.length());

                            //concatenate part1 and part2 with quoteReplacement in-between
                            //if quoteReplacement is the empty string (""), then part1 and part2 are juxtaposed
                            path = part1.concat(quoteReplacement).concat(part2);
                        }
                    }
                }
            }
            else
            {
                //current character is escaped, next character can't be escaped
                escaped = false;
            }
        }
        return path;
    }

    /**
     * Unescape characters and remove quotes and double quotes.
     * Special characters are system dependent, there is a set for linux and another for mac.
     * If the system is windows, returns the path unchanged.
     * 
     * @param path to be cleaned.
     * @param quoteReplacement string that will replace quotes and double quotes.
     * @return path without quotes, double quotes and special characters unescaped.
     * */
    public static String getCleanPath(String path, String quoteReplacement)
    {

        path = removeUnescapedQuotes(path, quoteReplacement);
        path = getUnescapedPath(path);

        return path;
    }

    public static String calculateMd5Sum(File file) throws IOException
    {
        String md5Sum = null;

        BigInteger hash = null;
        FileInputStream fis;
        fis = new FileInputStream(file);
        byte[] buf = new byte[1500000];

        try
        {
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); //$NON-NLS-1$
            int bytesRead = 0;
            while ((bytesRead = fis.read(buf)) > 0)
            {
                digest.update(buf, 0, bytesRead);
            }

            hash = new BigInteger(1, digest.digest());
            md5Sum = hash.toString(16);
        }
        catch (NoSuchAlgorithmException e)
        {
            // This exception should not happen, because we are using a valid
            // hard
            // coded value for the algorithm name. However, if it happens, log
            // it.
            warn("MOTODEV Studio could not find an instance of the MessageDigest for the MD5 algorithm"); //$NON-NLS-1$
            throw new IOException(UtilitiesNLS.FileUtil_Get_MD5_Algorithm_Failed);
        }
        finally
        {
            if (fis != null)
            {
                fis.close();
            }
        }

        if (md5Sum == null)
        {
            throw new IOException(NLS.bind(UtilitiesNLS.FileUtil_MD5_Calculation_Failed,
                    file.getAbsolutePath()));
        }

        return md5Sum;
    }

    /**
     * This method is responsible to copy informed source file to informed
     * target.
     * 
     * @param sourceFile
     * @param targetFile
     * @throws IOException
     */
    public static void copy(File sourceFile, File targetFile) throws IOException
    {
        OutputStream outputStream = new FileOutputStream(targetFile);
        InputStream inputStream = new FileInputStream(sourceFile);
        try
        {
            int length;
            byte[] buffer = new byte[FileUtil.BUFFER_SIZE];
            while ((length = inputStream.read(buffer)) >= 0)
            {
                outputStream.write(buffer, 0, length);
            }
        }
        catch (IOException e)
        {
            throw new IOException("Error copying file:" + sourceFile.getAbsolutePath() + //$NON-NLS-1$
                    " to " + targetFile.getAbsolutePath()); //$NON-NLS-1$
        }
        finally
        {
            outputStream.close();
            inputStream.close();
        }
    }

    /**
     * This method normalize a directory path.
     * 
     * @param folder Full path to a directory
     * @return The normalized path.
     */
    public static String normalizePath(String folder)
    {
        return folder.endsWith(File.separator) ? folder : folder + File.separator;
    }

    /**
     * Delete the specified file, recursively as necessary.
     * 
     * @param file The file to delete
     */
    public static void delete(File file)
    {
        if (file.exists())
        {
            if (file.isDirectory())
            {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++)
                {
                    delete(files[i]);
                }
            }
            file.delete();
        }
    }

    /**
     * Delete the specified file, recursively as necessary.
     * 
     * @param fileName The file to delete
     */
    public static void delete(String fileName)
    {
        delete(new File(fileName));
    }

    /**
     * This method creates the specified directory.
     * 
     * @param directory The directory to create.
     * @throws IOException
     */
    public static void mkdir(String directory) throws IOException
    {
        File f = new File(directory);
        if (f.exists())
        {
            if (f.isFile())
            {
                throw new IOException("Error creating directory:" + directory); //$NON-NLS-1$
            }
        }
        else
        {
            if (!f.mkdirs())
            {
                throw new IOException("Error creating directory:" + directory); //$NON-NLS-1$
            }
        }
    }

}