Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 88ccb1977fbecf25d49e33e7e8bd763bc93e6319 (plain) (blame)
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
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
/*******************************************************************************
 * Copyright (c) 2009, 2015 Ericsson and others.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Francois Chouinard - Initial API and implementation
 *   Francois Chouinard - Got rid of dependency on internal platform class
 *   Francois Chouinard - Complete re-design
 *   Anna Dushistova(Montavista) - [383047] NPE while importing a CFT trace
 *   Matthew Khouzam - Moved out some common functions
 *   Patrick Tasse - Add sorting of file system elements
 *   Bernd Hufmann - Re-design of trace selection and trace validation
 *   Marc-Andre Laperle - Preserve folder structure on import
 *   Marc-Andre Laperle - Extract archives during import
 *   Marc-Andre Laperle - Add support for Gzip (non-Tar)
 *******************************************************************************/

package org.eclipse.tracecompass.internal.tmf.ui.project.wizards.importtrace;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.eclipse.core.resources.IContainer;
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.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
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.core.runtime.URIUtil;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.layout.PixelConverter;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.tracecompass.internal.tmf.ui.Activator;
import org.eclipse.tracecompass.tmf.core.TmfCommonConstants;
import org.eclipse.tracecompass.tmf.core.TmfProjectNature;
import org.eclipse.tracecompass.tmf.core.project.model.TmfTraceImportException;
import org.eclipse.tracecompass.tmf.core.project.model.TmfTraceType;
import org.eclipse.tracecompass.tmf.core.project.model.TraceTypeHelper;
import org.eclipse.tracecompass.tmf.core.util.Pair;
import org.eclipse.tracecompass.tmf.ui.project.model.TmfProjectElement;
import org.eclipse.tracecompass.tmf.ui.project.model.TmfProjectRegistry;
import org.eclipse.tracecompass.tmf.ui.project.model.TmfTraceFolder;
import org.eclipse.tracecompass.tmf.ui.project.model.TmfTraceTypeUIUtils;
import org.eclipse.tracecompass.tmf.ui.project.model.TmfTracesFolder;
import org.eclipse.tracecompass.tmf.ui.project.model.TraceUtils;
import org.eclipse.ui.dialogs.FileSystemElement;
import org.eclipse.ui.dialogs.IOverwriteQuery;
import org.eclipse.ui.dialogs.WizardResourceImportPage;
import org.eclipse.ui.ide.dialogs.ResourceTreeAndListGroup;
import org.eclipse.ui.internal.ide.DialogUtil;
import org.eclipse.ui.internal.ide.dialogs.IElementFilter;
import org.eclipse.ui.internal.wizards.datatransfer.ArchiveFileManipulations;
import org.eclipse.ui.internal.wizards.datatransfer.ILeveledImportStructureProvider;
import org.eclipse.ui.internal.wizards.datatransfer.TarEntry;
import org.eclipse.ui.internal.wizards.datatransfer.TarException;
import org.eclipse.ui.internal.wizards.datatransfer.TarFile;
import org.eclipse.ui.internal.wizards.datatransfer.TarLeveledStructureProvider;
import org.eclipse.ui.internal.wizards.datatransfer.ZipLeveledStructureProvider;
import org.eclipse.ui.model.AdaptableList;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.model.WorkbenchViewerComparator;
import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
import org.eclipse.ui.wizards.datatransfer.IImportStructureProvider;
import org.eclipse.ui.wizards.datatransfer.ImportOperation;

/**
 * A variant of the standard resource import wizard for importing traces to
 * given tracing project. If no project or tracing project was selected the
 * wizard imports it to the default tracing project which is created if
 * necessary.
 *
 * In our case traces could be files or a directory structure. This wizard
 * supports both cases. It imports traces for a selected trace type or, if no
 * trace type is selected, it tries to detect the trace type automatically.
 * However, the automatic detection is a best-effort and cannot guarantee that
 * the detection is successful. The reason for this is that there might be
 * multiple trace types that can be assigned to a single trace.
 *
 *
 * @author Francois Chouinard
 */
@SuppressWarnings("restriction")
public class ImportTraceWizardPage extends WizardResourceImportPage {

    // ------------------------------------------------------------------------
    // Constants
    // ------------------------------------------------------------------------
    private static final String IMPORT_WIZARD_PAGE_NAME = "ImportTraceWizardPage"; //$NON-NLS-1$
    private static final String IMPORT_WIZARD_ROOT_DIRECTORY_ID = ".import_root_directory_id"; //$NON-NLS-1$;
    private static final String IMPORT_WIZARD_ARCHIVE_FILE_NAME_ID = ".import_archive_file_name_id"; //$NON-NLS-1$
    private static final String IMPORT_WIZARD_IMPORT_UNRECOGNIZED_ID = ".import_unrecognized_traces_id"; //$NON-NLS-1$
    private static final String IMPORT_WIZARD_PRESERVE_FOLDERS_ID = ".import_preserve_folders_id"; //$NON-NLS-1$
    private static final String IMPORT_WIZARD_IMPORT_FROM_DIRECTORY_ID = ".import_from_directory"; //$NON-NLS-1$

    // constant from WizardArchiveFileResourceImportPage1
    private static final String[] FILE_IMPORT_MASK = { "*.jar;*.zip;*.tar;*.tar.gz;*.tgz;*.gz", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
    private static final String TRACE_IMPORT_TEMP_FOLDER = ".traceImport"; //$NON-NLS-1$

    /**
     * A special trace type value to communicate that automatic trace type
     * detection will occur instead of setting a specific trace type when
     * importing the traces.
     */
    public static final String TRACE_TYPE_AUTO_DETECT = Messages.ImportTraceWizard_AutoDetection;

    /**
     * Preserve the folder structure of the import traces.
     */
    public static final int OPTION_PRESERVE_FOLDER_STRUCTURE = 1 << 1;
    /**
     * Create links to the trace files instead of copies.
     */
    public static final int OPTION_CREATE_LINKS_IN_WORKSPACE = 1 << 2;
    /**
     * Import files that were not recognized as the selected trace type.
     */
    public static final int OPTION_IMPORT_UNRECOGNIZED_TRACES = 1 << 3;
    /**
     * Overwrite existing resources without prompting.
     */
    public static final int OPTION_OVERWRITE_EXISTING_RESOURCES = 1 << 4;

    // ------------------------------------------------------------------------
    // Attributes
    // ------------------------------------------------------------------------

    // Target import directory ('Traces' folder)
    private IFolder fTargetFolder;
    // Target Trace folder element
    private TmfTraceFolder fTraceFolderElement;
    // Flag to handle destination folder change event
    private Boolean fIsDestinationChanged = false;
    private final Object fSyncObject = new Object();
    // Combo box containing trace types
    private Combo fTraceTypes;
    // Button to ignore unrecognized traces or not
    private Button fImportUnrecognizedButton;
    // Button to overwrite existing resources or not
    private Button fOverwriteExistingResourcesCheckbox;
    // Button to link or copy traces to workspace
    private Button fCreateLinksInWorkspaceButton;
    // Button to preserve folder structure
    private Button fPreserveFolderStructureButton;
    private boolean entryChanged = false;
    // The import from directory radio button
    private Button fImportFromDirectoryRadio;
    // The import from archive radio button
    private Button fImportFromArchiveRadio;
    // Flag to remember the "create links" checkbox when it gets disabled by
    // the import from archive radio button
    private Boolean fPreviousCreateLinksValue = true;

    /** The archive name field */
    protected Combo fArchiveNameField;
    /** The archive browse button. */
    protected Button fArchiveBrowseButton;
    /** The directory name field */
    protected Combo directoryNameField;
    /** The directory browse button. */
    protected Button directoryBrowseButton;

    private ResourceTreeAndListGroup fSelectionGroup;

    // Keep trace of the selection root so that we can dispose its related
    // resources
    private TraceFileSystemElement fSelectionGroupRoot;

    // ------------------------------------------------------------------------
    // Constructors
    // ------------------------------------------------------------------------

    /**
     * Constructor. Creates the trace wizard page.
     *
     * @param name
     *            The name of the page.
     * @param selection
     *            The current selection
     */
    protected ImportTraceWizardPage(String name, IStructuredSelection selection) {
        super(name, selection);
        setTitle(Messages.ImportTraceWizard_FileSystemTitle);
        setDescription(Messages.ImportTraceWizard_ImportTrace);

        // Locate the target trace folder
        IFolder traceFolder = null;
        Object element = selection.getFirstElement();

        if (element instanceof TmfTraceFolder) {
            fTraceFolderElement = (TmfTraceFolder) element;
            traceFolder = fTraceFolderElement.getResource();
        } else if (element instanceof IProject) {
            IProject project = (IProject) element;
            try {
                if (project.hasNature(TmfProjectNature.ID)) {
                    TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true);
                    fTraceFolderElement = projectElement.getTracesFolder();
                    traceFolder = project.getFolder(TmfTracesFolder.TRACES_FOLDER_NAME);
                }
            } catch (CoreException e) {
            }
        }

        // If no tracing project was selected or trace folder doesn't exist use
        // default tracing project
        if (traceFolder == null) {
            IProject project = TmfProjectRegistry.createProject(
                    TmfCommonConstants.DEFAULT_TRACE_PROJECT_NAME, null, new NullProgressMonitor());
            TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true);
            fTraceFolderElement = projectElement.getTracesFolder();
            traceFolder = project.getFolder(TmfTracesFolder.TRACES_FOLDER_NAME);
        }

        // Set the target trace folder
        if (traceFolder != null) {
            fTargetFolder = traceFolder;
            String path = traceFolder.getFullPath().toString();
            setContainerFieldValue(path);
        }
    }

    /**
     * Constructor
     *
     * @param selection
     *            The current selection
     */
    public ImportTraceWizardPage(IStructuredSelection selection) {
        this(IMPORT_WIZARD_PAGE_NAME, selection);
    }

    /**
     * Create the import source selection widget. (Copied from
     * WizardResourceImportPage but instead always uses the internal
     * ResourceTreeAndListGroup to keep compatibility with Kepler)
     */
    @Override
    protected void createFileSelectionGroup(Composite parent) {

        // Just create with a dummy root.
        fSelectionGroup = new ResourceTreeAndListGroup(parent,
                new FileSystemElement("Dummy", null, true),//$NON-NLS-1$
                getFolderProvider(), new WorkbenchLabelProvider(),
                getFileProvider(), new WorkbenchLabelProvider(), SWT.NONE,
                DialogUtil.inRegularFontMode(parent));

        ICheckStateListener listener = new ICheckStateListener() {
            @Override
            public void checkStateChanged(CheckStateChangedEvent event) {
                updateWidgetEnablements();
            }
        };

        WorkbenchViewerComparator comparator = new WorkbenchViewerComparator();
        fSelectionGroup.setTreeComparator(comparator);
        fSelectionGroup.setListComparator(comparator);
        fSelectionGroup.addCheckStateListener(listener);

    }

    // ------------------------------------------------------------------------
    // WizardResourceImportPage
    // ------------------------------------------------------------------------

    @Override
    protected void createSourceGroup(Composite parent) {
        createSourceSelectionGroup(parent);
        createFileSelectionGroup(parent);
        createTraceTypeGroup(parent);
        validateSourceGroup();
    }

    @Override
    protected ITreeContentProvider getFileProvider() {
        return new WorkbenchContentProvider() {
            @Override
            public Object[] getChildren(Object object) {
                if (object instanceof TraceFileSystemElement) {
                    TraceFileSystemElement element = (TraceFileSystemElement) object;
                    return element.getFiles().getChildren(element);
                }
                return new Object[0];
            }
        };
    }

    @Override
    protected ITreeContentProvider getFolderProvider() {
        return new WorkbenchContentProvider() {
            @Override
            public Object[] getChildren(Object o) {
                if (o instanceof TraceFileSystemElement) {
                    TraceFileSystemElement element = (TraceFileSystemElement) o;
                    return element.getFolders().getChildren();
                }
                return new Object[0];
            }

            @Override
            public boolean hasChildren(Object o) {
                if (o instanceof TraceFileSystemElement) {
                    TraceFileSystemElement element = (TraceFileSystemElement) o;
                    if (element.isPopulated()) {
                        return getChildren(element).length > 0;
                    }
                    // If we have not populated then wait until asked
                    return true;
                }
                return false;
            }
        };
    }

    // ------------------------------------------------------------------------
    // Directory Selection Group (forked WizardFileSystemResourceImportPage1)
    // ------------------------------------------------------------------------

    /**
     * creates the source selection group.
     *
     * @param parent
     *            the parent composite
     */
    protected void createSourceSelectionGroup(Composite parent) {

        Composite sourceGroup = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout();
        layout.numColumns = 3;
        layout.makeColumnsEqualWidth = false;
        layout.marginWidth = 0;
        sourceGroup.setLayout(layout);
        sourceGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        // import from directory radio button
        fImportFromDirectoryRadio = new Button(sourceGroup, SWT.RADIO);
        fImportFromDirectoryRadio
                .setText(Messages.ImportTraceWizard_DirectoryLocation);

        // import location entry combo
        directoryNameField = createPathSelectionCombo(sourceGroup);
        createDirectoryBrowseButton(sourceGroup);

        // import from archive radio button
        fImportFromArchiveRadio = new Button(sourceGroup, SWT.RADIO);
        fImportFromArchiveRadio
                .setText(Messages.ImportTraceWizard_ArchiveLocation);

        // import location entry combo
        fArchiveNameField = createPathSelectionCombo(sourceGroup);
        createArchiveBrowseButton(sourceGroup);

        fImportFromDirectoryRadio.setSelection(true);
        fArchiveNameField.setEnabled(false);
        fArchiveBrowseButton.setEnabled(false);

        fImportFromDirectoryRadio.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                directoryRadioSelected();
            }
        });

        fImportFromArchiveRadio.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                archiveRadioSelected();
            }
        });
    }

    /**
     * Select or deselect all files in the file selection group
     *
     * @param checked
     *            whether or not the files should be checked
     */
    protected void setFileSelectionGroupChecked(boolean checked) {
        if (fSelectionGroup != null) {
            fSelectionGroup.setAllSelections(checked);
        }
    }

    /**
     * Create a combo that will be used to select a path to specify the source
     * of the import. The parent is assumed to have a GridLayout.
     *
     * @param parent
     *            the parent composite
     * @return the created path selection combo
     */
    protected Combo createPathSelectionCombo(Composite parent) {
        Combo pathSelectionCombo = new Combo(parent, SWT.BORDER);

        GridData layoutData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
        layoutData.widthHint = new PixelConverter(pathSelectionCombo).convertWidthInCharsToPixels(25);
        pathSelectionCombo.setLayoutData(layoutData);

        TraverseListener traverseListener = new TraverseListener() {
            @Override
            public void keyTraversed(TraverseEvent e) {
                if (e.detail == SWT.TRAVERSE_RETURN) {
                    e.doit = false;
                    entryChanged = false;
                    updateFromSourceField();
                }
            }
        };

        FocusAdapter focusAdapter = new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                // Clear the flag to prevent constant update
                if (entryChanged) {
                    entryChanged = false;
                    updateFromSourceField();
                }
            }
        };

        SelectionAdapter selectionAdapter = new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                entryChanged = false;
                updateFromSourceField();
            }
        };

        ModifyListener modifyListner = new ModifyListener() {
            @Override
            public void modifyText(ModifyEvent e) {
                entryChanged = true;
            }
        };

        pathSelectionCombo.addModifyListener(modifyListner);
        pathSelectionCombo.addTraverseListener(traverseListener);
        pathSelectionCombo.addFocusListener(focusAdapter);
        pathSelectionCombo.addSelectionListener(selectionAdapter);

        return pathSelectionCombo;
    }

    /**
     * Create the directory browse button.
     *
     * @param parent
     *            the parent composite
     */
    protected void createDirectoryBrowseButton(Composite parent) {
        directoryBrowseButton = createPathSelectionBrowseButton(parent);
        directoryBrowseButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                handleSourceDirectoryBrowseButtonPressed();
            }
        });
    }

    /**
     * Create the archive browse button.
     *
     * @param parent
     *            the parent composite
     */
    protected void createArchiveBrowseButton(Composite parent) {
        fArchiveBrowseButton = createPathSelectionBrowseButton(parent);
        fArchiveBrowseButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                handleArchiveBrowseButtonPressed(FILE_IMPORT_MASK);
            }
        });
    }

    /**
     * Create a browse button that will be used to browse for a path to specify
     * the source of the import. The parent is assumed to have a GridLayout.
     *
     * @param parent
     *            the parent composite
     * @return the created path selection combo
     */
    protected Button createPathSelectionBrowseButton(Composite parent) {
        Button pathSelectionBrowseButton = new Button(parent, SWT.PUSH);
        pathSelectionBrowseButton.setText(Messages.ImportTraceWizard_BrowseButton);
        setButtonLayoutData(pathSelectionBrowseButton);

        return pathSelectionBrowseButton;
    }

    private void archiveRadioSelected() {
        if (!isImportFromDirectory()) {
            directoryNameField.setEnabled(false);
            directoryBrowseButton.setEnabled(false);
            fArchiveNameField.setEnabled(true);
            fArchiveBrowseButton.setEnabled(true);
            updateFromSourceField();
            fArchiveNameField.setFocus();
            if (fCreateLinksInWorkspaceButton != null) {
                fPreviousCreateLinksValue = fCreateLinksInWorkspaceButton.getSelection();
                fCreateLinksInWorkspaceButton.setSelection(false);
                fCreateLinksInWorkspaceButton.setEnabled(false);
            }
        }
    }

    private void directoryRadioSelected() {
        if (isImportFromDirectory()) {
            directoryNameField.setEnabled(true);
            directoryBrowseButton.setEnabled(true);
            fArchiveNameField.setEnabled(false);
            fArchiveBrowseButton.setEnabled(false);
            updateFromSourceField();
            directoryNameField.setFocus();
            if (fCreateLinksInWorkspaceButton != null) {
                fCreateLinksInWorkspaceButton.setSelection(fPreviousCreateLinksValue);
                fCreateLinksInWorkspaceButton.setEnabled(true);
            }
        }
    }

    // ------------------------------------------------------------------------
    // Browse for the source directory
    // ------------------------------------------------------------------------

    @Override
    public void handleEvent(Event event) {
        if (event.widget == directoryBrowseButton) {
            handleSourceDirectoryBrowseButtonPressed();
        }

        // Avoid overwriting destination path without repeatedly trigger
        // call of handleEvent();
        synchronized (fSyncObject) {
            if (fIsDestinationChanged == false) {
                event.display.asyncExec(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (fSyncObject) {
                            fIsDestinationChanged = true;
                            String path = fTargetFolder.getFullPath().toString();
                            setContainerFieldValue(path);
                        }
                    }
                });
            } else {
                fIsDestinationChanged = false;
            }
        }
        super.handleEvent(event);
    }

    @Override
    protected void handleContainerBrowseButtonPressed() {
        // Do nothing so that destination directory cannot be changed.
    }

    /**
     * Handle the button pressed event
     */
    protected void handleSourceDirectoryBrowseButtonPressed() {
        String currentSource = directoryNameField.getText();
        DirectoryDialog dialog = new DirectoryDialog(directoryNameField.getShell(), SWT.SAVE | SWT.SHEET);
        dialog.setText(Messages.ImportTraceWizard_SelectTraceDirectoryTitle);
        dialog.setMessage(Messages.ImportTraceWizard_SelectTraceDirectoryMessage);
        dialog.setFilterPath(getSourceDirectoryName(currentSource));

        String selectedDirectory = dialog.open();
        if (selectedDirectory != null) {
            // Just quit if the directory is not valid
            if ((getSourceDirectory(selectedDirectory) == null) || selectedDirectory.equals(currentSource)) {
                return;
            }
            // If it is valid then proceed to populate
            setErrorMessage(null);
            setSourcePath(selectedDirectory);
        }
    }

    /**
     * Handle the button pressed event
     *
     * @param extensions
     *            file extensions used to filter files shown to the user
     */
    protected void handleArchiveBrowseButtonPressed(String[] extensions) {
        FileDialog dialog = new FileDialog(fArchiveNameField.getShell(), SWT.SHEET);
        dialog.setFilterExtensions(extensions);
        dialog.setText(Messages.ImportTraceWizard_SelectTraceArchiveTitle);
        String fileName = fArchiveNameField.getText().trim();
        if (!fileName.isEmpty()) {
            File path = new File(fileName).getParentFile();
            if (path != null && path.exists()) {
                dialog.setFilterPath(path.toString());
            }
        }

        String selectedArchive = dialog.open();
        if (selectedArchive != null) {
            setErrorMessage(null);
            setSourcePath(selectedArchive);
            updateWidgetEnablements();
        }
    }

    private File getSourceDirectory() {
        if (directoryNameField == null) {
            return null;
        }
        return getSourceDirectory(directoryNameField.getText());
    }

    private File getSourceArchiveFile() {
        if (fArchiveNameField == null) {
            return null;
        }

        return getSourceArchiveFile(fArchiveNameField.getText());
    }

    private String getSourceContainerPath() {
        if (isImportFromDirectory()) {
            File sourceDirectory = getSourceDirectory();
            if (sourceDirectory != null) {
                return sourceDirectory.getAbsolutePath();
            }
        }
        File sourceArchiveFile = getSourceArchiveFile();
        if (sourceArchiveFile != null) {
            return sourceArchiveFile.getParent();
        }
        return null;
    }

    private static File getSourceDirectory(String path) {
        File sourceDirectory = new File(getSourceDirectoryName(path));
        if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
            return null;
        }

        return sourceDirectory;
    }

    private static File getSourceArchiveFile(String path) {
        File sourceArchiveFile = new File(path);
        if (!sourceArchiveFile.exists() || sourceArchiveFile.isDirectory()) {
            return null;
        }

        return sourceArchiveFile;
    }

    private static String getSourceDirectoryName(String sourceName) {
        IPath result = new Path(sourceName.trim());
        if (result.getDevice() != null && result.segmentCount() == 0) {
            result = result.addTrailingSeparator();
        } else {
            result = result.removeTrailingSeparator();
        }
        return result.toOSString();
    }

    private void updateFromSourceField() {
        setSourcePath(getSourceField().getText());
        updateWidgetEnablements();
    }

    private Combo getSourceField() {
        if (directoryNameField == null) {
            return fArchiveNameField;
        }

        return directoryNameField.isEnabled() ? directoryNameField : fArchiveNameField;
    }

    /**
     * Set the source path that was selected by the user by various input
     * methods (Browse button, typing, etc).
     *
     * Clients can also call this to set the path programmatically (hard-coded
     * initial path) and this can also be overridden to be notified when the
     * source path changes.
     *
     * @param path
     *            the source path
     */
    protected void setSourcePath(String path) {
        Combo sourceField = getSourceField();
        if (sourceField == null) {
            return;
        }

        if (path.length() > 0) {
            String[] currentItems = sourceField.getItems();
            int selectionIndex = -1;
            for (int i = 0; i < currentItems.length; i++) {
                if (currentItems[i].equals(path)) {
                    selectionIndex = i;
                }
            }
            if (selectionIndex < 0) {
                int oldLength = currentItems.length;
                String[] newItems = new String[oldLength + 1];
                System.arraycopy(currentItems, 0, newItems, 0, oldLength);
                newItems[oldLength] = path;
                sourceField.setItems(newItems);
                selectionIndex = oldLength;
            }
            sourceField.select(selectionIndex);
        }
        resetSelection();
    }

    // ------------------------------------------------------------------------
    // File Selection Group (forked WizardFileSystemResourceImportPage1)
    // ------------------------------------------------------------------------
    private void resetSelection() {
        if (fSelectionGroupRoot != null) {
            disposeSelectionGroupRoot();
        }
        fSelectionGroupRoot = getFileSystemTree();
        fSelectionGroup.setRoot(fSelectionGroupRoot);
    }

    private void disposeSelectionGroupRoot() {
        if (fSelectionGroupRoot != null && fSelectionGroupRoot.getProvider() != null) {
            FileSystemObjectImportStructureProvider provider = fSelectionGroupRoot.getProvider();
            provider.dispose();
            fSelectionGroupRoot = null;
        }
    }

    private TraceFileSystemElement getFileSystemTree() {
        Pair<IFileSystemObject, FileSystemObjectImportStructureProvider> rootObjectAndProvider = getRootObjectAndProvider(getSourceFile());
        if (rootObjectAndProvider == null) {
            return null;
        }
        return selectFiles(rootObjectAndProvider.getFirst(), rootObjectAndProvider.getSecond());
    }

    @SuppressWarnings("resource")
    private Pair<IFileSystemObject, FileSystemObjectImportStructureProvider> getRootObjectAndProvider(File sourceFile) {
        if (sourceFile == null) {
            return null;
        }

        IFileSystemObject rootElement = null;
        FileSystemObjectImportStructureProvider importStructureProvider = null;

        // Import from directory
        if (!isArchiveFile(sourceFile)) {
            importStructureProvider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
            rootElement = importStructureProvider.getIFileSystemObject(sourceFile);
        } else {
            // Import from archive
            FileSystemObjectLeveledImportStructureProvider leveledImportStructureProvider = null;
            String archivePath = sourceFile.getAbsolutePath();
            if (isTarFile(archivePath)) {
                if (ensureTarSourceIsValid(archivePath)) {
                    // We close the file when we dispose the import provider,
                    // see disposeSelectionGroupRoot
                    TarFile tarFile = getSpecifiedTarSourceFile(archivePath);
                    leveledImportStructureProvider = new FileSystemObjectLeveledImportStructureProvider(new TarLeveledStructureProvider(tarFile), archivePath);
                }
            } else if (ensureZipSourceIsValid(archivePath)) {
                // We close the file when we dispose the import provider, see
                // disposeSelectionGroupRoot
                ZipFile zipFile = getSpecifiedZipSourceFile(archivePath);
                leveledImportStructureProvider = new FileSystemObjectLeveledImportStructureProvider(new ZipLeveledStructureProvider(zipFile), archivePath);
            } else if (ensureGzipSourceIsValid(archivePath)) {
                // We close the file when we dispose the import provider, see
                // disposeSelectionGroupRoot
                GzipFile zipFile = null;
                try {
                    zipFile = new GzipFile(archivePath);
                } catch (IOException e) {
                }
                leveledImportStructureProvider = new FileSystemObjectLeveledImportStructureProvider(new GzipLeveledStructureProvider(zipFile), archivePath);
            }
            if (leveledImportStructureProvider == null) {
                return null;
            }
            rootElement = leveledImportStructureProvider.getRoot();
            importStructureProvider = leveledImportStructureProvider;
        }

        if (rootElement == null) {
            return null;
        }

        return new Pair<>(rootElement, importStructureProvider);
    }

    /**
     * An import provider that makes use of the IFileSystemObject abstraction
     * instead of using plain file system objects (File, TarEntry, ZipEntry, etc)
     */
    private static class FileSystemObjectImportStructureProvider implements IImportStructureProvider {

        private IImportStructureProvider fImportProvider;
        private String fArchivePath;

        private FileSystemObjectImportStructureProvider(IImportStructureProvider importStructureProvider, String archivePath) {
            fImportProvider = importStructureProvider;
            fArchivePath = archivePath;
        }

        @Override
        public List<IFileSystemObject> getChildren(Object element) {
            @SuppressWarnings("rawtypes")
            List children = fImportProvider.getChildren(((IFileSystemObject) element).getRawFileSystemObject());
            List<IFileSystemObject> adapted = new ArrayList<>(children.size());
            for (Object o : children) {
                adapted.add(getIFileSystemObject(o));
            }
            return adapted;
        }

        public IFileSystemObject getIFileSystemObject(Object o) {
            if (o == null) {
                return null;
            }

            if (o instanceof File) {
                return new FileFileSystemObject((File) o);
            } else if (o instanceof TarEntry) {
                return new TarFileSystemObject((TarEntry) o, fArchivePath);
            } else if (o instanceof ZipEntry) {
                return new ZipFileSystemObject((ZipEntry) o, fArchivePath);
            } else if (o instanceof GzipEntry) {
                return new GzipFileSystemObject((GzipEntry) o, fArchivePath);
            }

            throw new IllegalArgumentException("Object type not handled"); //$NON-NLS-1$
        }

        @Override
        public InputStream getContents(Object element) {
            return fImportProvider.getContents(((IFileSystemObject) element).getRawFileSystemObject());
        }

        @Override
        public String getFullPath(Object element) {
            return fImportProvider.getFullPath(((IFileSystemObject) element).getRawFileSystemObject());
        }

        @Override
        public String getLabel(Object element) {
            return fImportProvider.getLabel(((IFileSystemObject) element).getRawFileSystemObject());
        }

        @Override
        public boolean isFolder(Object element) {
            return fImportProvider.isFolder(((IFileSystemObject) element).getRawFileSystemObject());
        }

        /**
         * Disposes of the resources associated with the provider.
         */
        public void dispose() {
        }
    }

    /**
     * An import provider that both supports using IFileSystemObject and adds
     * "archive functionality" by delegating to a leveled import provider
     * (TarLeveledStructureProvider, ZipLeveledStructureProvider)
     */
    private static class FileSystemObjectLeveledImportStructureProvider extends FileSystemObjectImportStructureProvider implements ILeveledImportStructureProvider {

        private ILeveledImportStructureProvider fLeveledImportProvider;

        private FileSystemObjectLeveledImportStructureProvider(ILeveledImportStructureProvider importStructureProvider, String archivePath) {
            super(importStructureProvider, archivePath);
            fLeveledImportProvider = importStructureProvider;
        }

        @Override
        public IFileSystemObject getRoot() {
            return getIFileSystemObject(fLeveledImportProvider.getRoot());
        }

        @Override
        public void setStrip(int level) {
            fLeveledImportProvider.setStrip(level);
        }

        @Override
        public int getStrip() {
            return fLeveledImportProvider.getStrip();
        }

        @Override
        public boolean closeArchive() {
            return fLeveledImportProvider.closeArchive();
        }

        @Override
        public void dispose() {
            super.dispose();
            closeArchive();
        }
    }

    @SuppressWarnings("resource")
    private boolean ensureZipSourceIsValid(String archivePath) {
        ZipFile specifiedFile = getSpecifiedZipSourceFile(archivePath);
        if (specifiedFile == null) {
            return false;
        }
        return ArchiveFileManipulations.closeZipFile(specifiedFile, getShell());
    }

    private boolean ensureTarSourceIsValid(String archivePath) {
        TarFile specifiedFile = getSpecifiedTarSourceFile(archivePath);
        if (specifiedFile == null) {
            return false;
        }
        return ArchiveFileManipulations.closeTarFile(specifiedFile, getShell());
    }

    private static ZipFile getSpecifiedZipSourceFile(String fileName) {
        if (fileName.length() == 0) {
            return null;
        }

        try {
            return new ZipFile(fileName);
        } catch (ZipException e) {
            // ignore
        } catch (IOException e) {
            // ignore
        }

        return null;
    }

    private static boolean isTarFile(String fileName) {
        TarFile specifiedTarSourceFile = getSpecifiedTarSourceFile(fileName);
        if (specifiedTarSourceFile != null) {
            try {
                specifiedTarSourceFile.close();
                return true;
            } catch (IOException e) {
            }
        }
        return false;
    }

    private static TarFile getSpecifiedTarSourceFile(String fileName) {
        if (fileName.length() == 0) {
            return null;
        }

        // FIXME: Work around Bug 463633. Remove this block once we move to Eclipse 4.5.
        if (new File(fileName).length() < 512) {
            return null;
        }

        try {
            return new TarFile(fileName);
        } catch (TarException | IOException e) {
            // ignore
        }

        return null;
    }

    private static boolean ensureGzipSourceIsValid(String archivePath) {
        return isGzipFile(archivePath);
    }

    private TraceFileSystemElement selectFiles(final IFileSystemObject rootFileSystemObject,
            final FileSystemObjectImportStructureProvider structureProvider) {
        final TraceFileSystemElement[] results = new TraceFileSystemElement[1];
        BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
            @Override
            public void run() {
                // Create the root element from the supplied file system object
                results[0] = createRootTraceFileElement(rootFileSystemObject, structureProvider);
            }
        });
        return results[0];
    }

    private static TraceFileSystemElement createRootTraceFileElement(IFileSystemObject element,
            FileSystemObjectImportStructureProvider provider) {
        boolean isContainer = provider.isFolder(element);
        String elementLabel = provider.getLabel(element);

        // Use an empty label so that display of the element's full name
        // doesn't include a confusing label
        TraceFileSystemElement dummyParent = new TraceFileSystemElement("", null, true, provider);//$NON-NLS-1$
        Object dummyParentFileSystemObject = element;
        Object rawFileSystemObject = element.getRawFileSystemObject();
        if (rawFileSystemObject instanceof File) {
            dummyParentFileSystemObject = provider.getIFileSystemObject(((File) rawFileSystemObject).getParentFile());
        }
        dummyParent.setFileSystemObject(dummyParentFileSystemObject);
        dummyParent.setPopulated();
        TraceFileSystemElement result = new TraceFileSystemElement(
                elementLabel, dummyParent, isContainer, provider);
        result.setFileSystemObject(element);

        // Get the files for the element so as to build the first level
        result.getFiles();

        return dummyParent;
    }

    // ------------------------------------------------------------------------
    // Trace Type Group
    // ------------------------------------------------------------------------
    private final void createTraceTypeGroup(Composite parent) {
        Composite composite = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout();
        layout.numColumns = 3;
        layout.makeColumnsEqualWidth = false;
        composite.setLayout(layout);
        composite.setFont(parent.getFont());
        GridData buttonData = new GridData(SWT.FILL, SWT.FILL, true, false);
        composite.setLayoutData(buttonData);

        // Trace type label ("Trace Type:")
        Label typeLabel = new Label(composite, SWT.NONE);
        typeLabel.setText(Messages.ImportTraceWizard_TraceType);
        typeLabel.setFont(parent.getFont());

        // Trace type combo
        fTraceTypes = new Combo(composite, SWT.BORDER | SWT.READ_ONLY);
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
        fTraceTypes.setLayoutData(data);
        fTraceTypes.setFont(parent.getFont());

        String[] availableTraceTypes = TmfTraceType.getAvailableTraceTypes();
        String[] traceTypeList = new String[availableTraceTypes.length + 1];
        traceTypeList[0] = TRACE_TYPE_AUTO_DETECT;
        for (int i = 0; i < availableTraceTypes.length; i++) {
            traceTypeList[i + 1] = availableTraceTypes[i];
        }
        fTraceTypes.setItems(traceTypeList);
        fTraceTypes.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                updateWidgetEnablements();
                boolean enabled = fTraceTypes.getText().equals(TRACE_TYPE_AUTO_DETECT);
                fImportUnrecognizedButton.setEnabled(enabled);
            }
        });
        fTraceTypes.select(0);

        // Unrecognized checkbox
        fImportUnrecognizedButton = new Button(composite, SWT.CHECK);
        fImportUnrecognizedButton.setSelection(true);
        fImportUnrecognizedButton.setText(Messages.ImportTraceWizard_ImportUnrecognized);
    }

    // ------------------------------------------------------------------------
    // Options
    // ------------------------------------------------------------------------

    @Override
    protected void createOptionsGroupButtons(Group optionsGroup) {

        // Overwrite checkbox
        fOverwriteExistingResourcesCheckbox = new Button(optionsGroup, SWT.CHECK);
        fOverwriteExistingResourcesCheckbox.setFont(optionsGroup.getFont());
        fOverwriteExistingResourcesCheckbox.setText(Messages.ImportTraceWizard_OverwriteExistingTrace);
        fOverwriteExistingResourcesCheckbox.setSelection(false);

        // Create links checkbox
        fCreateLinksInWorkspaceButton = new Button(optionsGroup, SWT.CHECK);
        fCreateLinksInWorkspaceButton.setFont(optionsGroup.getFont());
        fCreateLinksInWorkspaceButton.setText(Messages.ImportTraceWizard_CreateLinksInWorkspace);
        fCreateLinksInWorkspaceButton.setSelection(true);

        fCreateLinksInWorkspaceButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                updateWidgetEnablements();
            }
        });

        fPreserveFolderStructureButton = new Button(optionsGroup, SWT.CHECK);
        fPreserveFolderStructureButton.setFont(optionsGroup.getFont());
        fPreserveFolderStructureButton.setText(Messages.ImportTraceWizard_PreserveFolderStructure);
        fPreserveFolderStructureButton.setSelection(true);

        updateWidgetEnablements();
    }

    // ------------------------------------------------------------------------
    // Determine if the finish button can be enabled
    // ------------------------------------------------------------------------
    @Override
    public boolean validateSourceGroup() {

        File source = getSourceFile();
        if (source == null) {
            setMessage(Messages.ImportTraceWizard_SelectTraceSourceEmpty);
            setErrorMessage(null);
            return false;
        }

        if (sourceConflictsWithDestination(new Path(source.getPath()))) {
            setMessage(null);
            setErrorMessage(getSourceConflictMessage());
            return false;
        }

        if (!isImportFromDirectory() && !ensureTarSourceIsValid(source.getAbsolutePath()) && !ensureZipSourceIsValid(source.getAbsolutePath()) && !ensureGzipSourceIsValid(source.getAbsolutePath())) {
            setMessage(null);
            setErrorMessage(Messages.ImportTraceWizard_BadArchiveFormat);
            return false;
        }

        if (fSelectionGroup.getCheckedElementCount() == 0) {
            setMessage(null);
            setErrorMessage(Messages.ImportTraceWizard_SelectTraceNoneSelected);
            return false;
        }

        IContainer container = getSpecifiedContainer();
        if (container != null && container.isVirtual()) {
            if (Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, ResourcesPlugin.PREF_DISABLE_LINKING, false, null)) {
                setMessage(null);
                setErrorMessage(Messages.ImportTraceWizard_CannotImportFilesUnderAVirtualFolder);
                return false;
            }
            if (fCreateLinksInWorkspaceButton == null || !fCreateLinksInWorkspaceButton.getSelection()) {
                setMessage(null);
                setErrorMessage(Messages.ImportTraceWizard_HaveToCreateLinksUnderAVirtualFolder);
                return false;
            }
        }

        setErrorMessage(null);
        return true;
    }

    private File getSourceFile() {
        return isImportFromDirectory() ? getSourceDirectory() : getSourceArchiveFile();
    }

    private boolean isImportFromDirectory() {
        return fImportFromDirectoryRadio != null && fImportFromDirectoryRadio.getSelection();
    }

    private static boolean isArchiveFile(File sourceFile) {
        String absolutePath = sourceFile.getAbsolutePath();
        return isTarFile(absolutePath) || ArchiveFileManipulations.isZipFile(absolutePath) || isGzipFile(absolutePath);
    }

    private static boolean isGzipFile(String fileName) {
        if (!fileName.isEmpty()) {
            try (GzipFile specifiedTarSourceFile = new GzipFile(fileName);) {
                return true;
            } catch (IOException e) {
            }
        }
        return false;
    }

    @Override
    protected void restoreWidgetValues() {
        super.restoreWidgetValues();

        IDialogSettings settings = getDialogSettings();
        boolean value;
        if (fImportUnrecognizedButton != null) {
            if (settings.get(getPageStoreKey(IMPORT_WIZARD_IMPORT_UNRECOGNIZED_ID)) == null) {
                value = true;
            } else {
                value = settings.getBoolean(getPageStoreKey(IMPORT_WIZARD_IMPORT_UNRECOGNIZED_ID));
            }
            fImportUnrecognizedButton.setSelection(value);
        }

        if (fPreserveFolderStructureButton != null) {
            if (settings.get(getPageStoreKey(IMPORT_WIZARD_PRESERVE_FOLDERS_ID)) == null) {
                value = true;
            } else {
                value = settings.getBoolean(getPageStoreKey(IMPORT_WIZARD_PRESERVE_FOLDERS_ID));
            }
            fPreserveFolderStructureButton.setSelection(value);
        }

        if (settings.get(getPageStoreKey(IMPORT_WIZARD_IMPORT_FROM_DIRECTORY_ID)) == null) {
            value = true;
        } else {
            value = settings.getBoolean(getPageStoreKey(IMPORT_WIZARD_IMPORT_FROM_DIRECTORY_ID));
        }

        if (directoryNameField != null) {
            restoreComboValues(directoryNameField, settings, getPageStoreKey(IMPORT_WIZARD_ROOT_DIRECTORY_ID));
        }
        if (fArchiveNameField != null) {
            restoreComboValues(fArchiveNameField, settings, getPageStoreKey(IMPORT_WIZARD_ARCHIVE_FILE_NAME_ID));
        }

        if (fImportFromDirectoryRadio != null) {
            fImportFromDirectoryRadio.setSelection(value);
            if (value) {
                directoryRadioSelected();
            }
        }
        if (fImportFromArchiveRadio != null) {
            fImportFromArchiveRadio.setSelection(!value);
            if (!value) {
                archiveRadioSelected();
            }
        }
    }

    @Override
    protected void saveWidgetValues() {
        // Persist dialog settings
        IDialogSettings settings = getDialogSettings();
        if (fImportUnrecognizedButton != null) {
            settings.put(getPageStoreKey(IMPORT_WIZARD_IMPORT_UNRECOGNIZED_ID), fImportUnrecognizedButton.getSelection());
        }
        if (fPreserveFolderStructureButton != null) {
            settings.put(getPageStoreKey(IMPORT_WIZARD_PRESERVE_FOLDERS_ID), fPreserveFolderStructureButton.getSelection());
        }
        settings.put(getPageStoreKey(IMPORT_WIZARD_IMPORT_FROM_DIRECTORY_ID), isImportFromDirectory());

        if (directoryNameField != null) {
            saveComboValues(directoryNameField, settings, getPageStoreKey(IMPORT_WIZARD_ROOT_DIRECTORY_ID));
        }
        if (fArchiveNameField != null) {
            saveComboValues(fArchiveNameField, settings, getPageStoreKey(IMPORT_WIZARD_ARCHIVE_FILE_NAME_ID));
        }
    }

    private String getPageStoreKey(String key) {
        return getName() + key;
    }

    private static void restoreComboValues(Combo combo, IDialogSettings settings, String key) {
        String[] directoryNames = settings.getArray(key);
        if ((directoryNames != null) && (directoryNames.length != 0)) {
            for (int i = 0; i < directoryNames.length; i++) {
                combo.add(directoryNames[i]);
            }
        }
    }

    private void saveComboValues(Combo combo, IDialogSettings settings, String key) {
        // update names history
        String[] directoryNames = settings.getArray(key);
        if (directoryNames == null) {
            directoryNames = new String[0];
        }

        String items[] = combo.getItems();
        for (int i = 0; i < items.length; i++) {
            directoryNames = addToHistory(directoryNames, items[i]);
        }
        settings.put(key, directoryNames);
    }

    // ------------------------------------------------------------------------
    // Import the trace(s)
    // ------------------------------------------------------------------------

    /**
     * Finish the import.
     *
     * @return <code>true</code> if successful else <code>false</code>
     */
    public boolean finish() {
        String traceTypeLabel = getImportTraceTypeId();
        String traceId = null;
        if (!TRACE_TYPE_AUTO_DETECT.equals(traceTypeLabel)) {
            traceId = TmfTraceType.getTraceTypeId(traceTypeLabel);
        }

        // Save dialog settings
        saveWidgetValues();

        IPath baseSourceContainerPath = new Path(getSourceContainerPath());
        boolean importFromArchive = getSourceArchiveFile() != null;
        int importOptionFlags = getImportOptionFlags();

        final TraceValidateAndImportOperation operation = new TraceValidateAndImportOperation(traceId, baseSourceContainerPath, getContainerFullPath(), importFromArchive,
                importOptionFlags);

        IStatus status = Status.OK_STATUS;
        try {
            getContainer().run(true, true, new IRunnableWithProgress() {
                @Override
                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    operation.run(monitor);
                    monitor.done();
                }
            });

            status = operation.getStatus();
        } catch (InvocationTargetException e) {
            status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ImportTraceWizard_ImportProblem, e);
        } catch (InterruptedException e) {
            status = Status.CANCEL_STATUS;
        }
        if (!status.isOK()) {
            if (status.getSeverity() == IStatus.CANCEL) {
                setMessage(Messages.ImportTraceWizard_ImportOperationCancelled);
                setErrorMessage(null);
            } else {
                if (status.getException() != null) {
                    displayErrorDialog(status.getMessage() + ": " + status.getException()); //$NON-NLS-1$
                }
                setMessage(null);
                setErrorMessage(Messages.ImportTraceWizard_ImportProblem);
            }
            return false;
        }
        setErrorMessage(null);
        return true;
    }

    /**
     * Get the trace type id to import as. This can also return
     * {@link #TRACE_TYPE_AUTO_DETECT} to communicate that automatic trace type
     * detection will occur instead of setting a specific trace type when
     * importing the traces.
     *
     * @return the trace type id or {@link #TRACE_TYPE_AUTO_DETECT}
     */
    protected String getImportTraceTypeId() {
        return fTraceTypes.getText();
    }

    /**
     * Get import options in the form of flags (bits).
     *
     * @return the import flags.
     * @see #OPTION_CREATE_LINKS_IN_WORKSPACE
     * @see #OPTION_IMPORT_UNRECOGNIZED_TRACES
     * @see #OPTION_OVERWRITE_EXISTING_RESOURCES
     * @see #OPTION_PRESERVE_FOLDER_STRUCTURE
     */
    protected int getImportOptionFlags() {
        int flags = 0;
        if (fCreateLinksInWorkspaceButton != null && fCreateLinksInWorkspaceButton.getSelection()) {
            flags |= OPTION_CREATE_LINKS_IN_WORKSPACE;
        }
        if (fImportUnrecognizedButton != null && fImportUnrecognizedButton.getSelection()) {
            flags |= OPTION_IMPORT_UNRECOGNIZED_TRACES;
        }
        if (fOverwriteExistingResourcesCheckbox != null && fOverwriteExistingResourcesCheckbox.getSelection()) {
            flags |= OPTION_OVERWRITE_EXISTING_RESOURCES;
        }
        if (fPreserveFolderStructureButton != null && fPreserveFolderStructureButton.getSelection()) {
            flags |= OPTION_PRESERVE_FOLDER_STRUCTURE;
        }
        return flags;
    }

    @Override
    public void dispose() {
        super.dispose();
        disposeSelectionGroupRoot();
    }

    // ------------------------------------------------------------------------
    // Classes
    // ------------------------------------------------------------------------

    private class TraceValidateAndImportOperation {
        private IStatus fStatus;
        private String fTraceType;
        private IPath fDestinationContainerPath;
        private IPath fBaseSourceContainerPath;
        private boolean fImportFromArchive;
        private int fImportOptionFlags;
        private ImportConflictHandler fConflictHandler;
        private String fCurrentPath;

        private TraceValidateAndImportOperation(String traceId, IPath baseSourceContainerPath, IPath destinationContainerPath, boolean importFromArchive, int importOptionFlags) {
            fTraceType = traceId;
            fBaseSourceContainerPath = baseSourceContainerPath;
            fDestinationContainerPath = destinationContainerPath;
            fImportOptionFlags = importOptionFlags;
            fImportFromArchive = importFromArchive;

            boolean overwriteExistingResources = (importOptionFlags & OPTION_OVERWRITE_EXISTING_RESOURCES) != 0;
            if (overwriteExistingResources) {
                fConflictHandler = new ImportConflictHandler(getContainer().getShell(), fTraceFolderElement, ImportConfirmation.OVERWRITE_ALL);
            } else {
                fConflictHandler = new ImportConflictHandler(getContainer().getShell(), fTraceFolderElement, ImportConfirmation.SKIP);
            }
        }

        public void run(IProgressMonitor progressMonitor) {
            try {

                final List<TraceFileSystemElement> selectedFileSystemElements = new LinkedList<>();
                IElementFilter passThroughFilter = new IElementFilter() {

                    @Override
                    public void filterElements(Collection elements, IProgressMonitor monitor) {
                        selectedFileSystemElements.addAll(elements);
                    }

                    @Override
                    public void filterElements(Object[] elements, IProgressMonitor monitor) {
                        for (int i = 0; i < elements.length; i++) {
                            selectedFileSystemElements.add((TraceFileSystemElement) elements[i]);
                        }
                    }
                };

                // List fileSystemElements will be filled using the
                // passThroughFilter
                SubMonitor subMonitor = SubMonitor.convert(progressMonitor, 1);
                fSelectionGroup.getAllCheckedListItems(passThroughFilter, subMonitor);

                // Check if operation was cancelled.
                ModalContext.checkCanceled(subMonitor);

                // Temporary directory to contain any extracted files
                IFolder destTempFolder = fTargetFolder.getProject().getFolder(TRACE_IMPORT_TEMP_FOLDER);
                if (destTempFolder.exists()) {
                    SubProgressMonitor monitor = new SubProgressMonitor(subMonitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
                    destTempFolder.delete(true, monitor);
                }
                SubProgressMonitor monitor = new SubProgressMonitor(subMonitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
                destTempFolder.create(IResource.HIDDEN, true, monitor);

                subMonitor = SubMonitor.convert(progressMonitor, 2);
                String baseSourceLocation;
                if (fImportFromArchive) {
                    // When importing from archive, we first extract the
                    // *selected* files to a temporary folder then create new
                    // TraceFileSystemElements

                    SubMonitor archiveMonitor = SubMonitor.convert(subMonitor.newChild(1), 2);

                    // Extract selected files from source archive to temporary folder
                    extractArchiveContent(selectedFileSystemElements.iterator(), destTempFolder, archiveMonitor.newChild(1));

                    // Even if the files were extracted to temporary folder, they have to look like they originate from the source archive
                    baseSourceLocation = getRootElement(selectedFileSystemElements.get(0)).getSourceLocation();
                    // Extract additional archives contained in the extracted files (archives in archives)
                    List<TraceFileSystemElement> tempFolderFileSystemElements = createElementsForFolder(destTempFolder);
                    extractAllArchiveFiles(tempFolderFileSystemElements, destTempFolder, destTempFolder.getLocation(), archiveMonitor.newChild(1));
                } else {
                    SubMonitor directoryMonitor = SubMonitor.convert(subMonitor.newChild(1), 2);
                    // Import selected files, excluding archives (done in a later step)
                    importFileSystemElements(directoryMonitor.newChild(1), selectedFileSystemElements);

                    // Extract archives in selected files (if any) to temporary folder
                    extractAllArchiveFiles(selectedFileSystemElements, destTempFolder, fBaseSourceContainerPath, directoryMonitor.newChild(1));
                    // Even if the files were extracted to temporary folder, they have to look like they originate from the source folder
                    baseSourceLocation = URIUtil.toUnencodedString(fBaseSourceContainerPath.toFile().getCanonicalFile().toURI());
                }

                /* Import extracted files that are now in the temporary folder, if any */

                // We need to update the source container path because the
                // "preserve folder structure" option would create the
                // wrong trace folders otherwise.
                fBaseSourceContainerPath = destTempFolder.getLocation();
                List<TraceFileSystemElement> tempFolderFileSystemElements = createElementsForFolder(destTempFolder);
                calculateSourceLocations(tempFolderFileSystemElements, baseSourceLocation);
                // Never import extracted files as links, they would link to the
                // temporary directory that will be deleted
                fImportOptionFlags = fImportOptionFlags & ~OPTION_CREATE_LINKS_IN_WORKSPACE;
                SubMonitor importTempMonitor = subMonitor.newChild(1);
                importFileSystemElements(importTempMonitor, tempFolderFileSystemElements);

                if (destTempFolder.exists()) {
                    destTempFolder.delete(true, progressMonitor);
                }

                setStatus(Status.OK_STATUS);
            } catch (InterruptedException e) {
                setStatus(Status.CANCEL_STATUS);
            } catch (Exception e) {
                String errorMessage = Messages.ImportTraceWizard_ImportProblem + ": " + //$NON-NLS-1$
                        (fCurrentPath != null ? fCurrentPath : ""); //$NON-NLS-1$
                Activator.getDefault().logError(errorMessage, e);
                setStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, errorMessage, e));
            }
        }

        /**
         * Import a collection of file system elements into the workspace.
         */
        private void importFileSystemElements(IProgressMonitor monitor, List<TraceFileSystemElement> fileSystemElements)
                throws InterruptedException, TmfTraceImportException, CoreException, InvocationTargetException {
            SubMonitor subMonitor = SubMonitor.convert(monitor, fileSystemElements.size());

            ListIterator<TraceFileSystemElement> fileSystemElementsIter = fileSystemElements.listIterator();

            // Map to remember already imported directory traces
            final Map<String, TraceFileSystemElement> directoryTraces = new HashMap<>();
            while (fileSystemElementsIter.hasNext()) {
                ModalContext.checkCanceled(monitor);
                fCurrentPath = null;
                TraceFileSystemElement element = fileSystemElementsIter.next();
                IFileSystemObject fileSystemObject = element.getFileSystemObject();
                String resourcePath = element.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString());
                element.setDestinationContainerPath(computeDestinationContainerPath(new Path(resourcePath)));

                fCurrentPath = resourcePath;
                SubMonitor sub = subMonitor.newChild(1);
                if (element.isDirectory()) {
                    if (!directoryTraces.containsKey(resourcePath) && isDirectoryTrace(element)) {
                        directoryTraces.put(resourcePath, element);
                        validateAndImportTrace(element, sub);
                    }
                } else {
                    TraceFileSystemElement parentElement = (TraceFileSystemElement) element.getParent();
                    String parentPath = parentElement.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString());
                    parentElement.setDestinationContainerPath(computeDestinationContainerPath(new Path(parentPath)));
                    fCurrentPath = parentPath;
                    if (!directoryTraces.containsKey(parentPath)) {
                        if (isDirectoryTrace(parentElement)) {
                            directoryTraces.put(parentPath, parentElement);
                            validateAndImportTrace(parentElement, sub);
                        } else {
                            boolean validateFile = true;
                            TraceFileSystemElement grandParentElement = (TraceFileSystemElement) parentElement.getParent();
                            // Special case for LTTng trace that may contain index directory and files
                            if (grandParentElement != null) {
                                String grandParentPath = grandParentElement.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString());
                                grandParentElement.setDestinationContainerPath(computeDestinationContainerPath(new Path(parentPath)));
                                fCurrentPath = grandParentPath;
                                if (directoryTraces.containsKey(grandParentPath)) {
                                    validateFile = false;
                                } else if (isDirectoryTrace(grandParentElement)) {
                                    directoryTraces.put(grandParentPath, grandParentElement);
                                    validateAndImportTrace(grandParentElement, sub);
                                    validateFile = false;
                                }
                            }
                            if (validateFile && (fileSystemObject.exists())) {
                                validateAndImportTrace(element, sub);
                            }
                        }
                    }
                }
            }
        }

        /**
         * Generate a new list of file system elements for the specified folder.
         */
        private List<TraceFileSystemElement> createElementsForFolder(IFolder folder) {
            // Create the new import provider and root element based on the specified folder
            FileSystemObjectImportStructureProvider importStructureProvider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
            IFileSystemObject rootElement = importStructureProvider.getIFileSystemObject(new File(folder.getLocation().toOSString()));
            TraceFileSystemElement createRootElement = createRootTraceFileElement(rootElement, importStructureProvider);
            List<TraceFileSystemElement> list = new LinkedList<>();
            getAllChildren(list, createRootElement);
            return list;
        }

        /**
         * Extract all file system elements (File) to destination folder (typically workspace/TraceProject/.traceImport)
         */
        private void extractAllArchiveFiles(List<TraceFileSystemElement> fileSystemElements, IFolder destFolder, IPath baseSourceContainerPath, IProgressMonitor progressMonitor) throws InterruptedException, CoreException, InvocationTargetException {
            SubMonitor subMonitor = SubMonitor.convert(progressMonitor, fileSystemElements.size());
            ListIterator<TraceFileSystemElement> fileSystemElementsIter = fileSystemElements.listIterator();
            while (fileSystemElementsIter.hasNext()) {
                ModalContext.checkCanceled(subMonitor);

                SubMonitor elementProgress = subMonitor.newChild(1);
                TraceFileSystemElement element = fileSystemElementsIter.next();
                File archiveFile = (File) element.getFileSystemObject().getRawFileSystemObject();
                boolean isArchiveFileElement = element.getFileSystemObject() instanceof FileFileSystemObject && isArchiveFile(archiveFile);
                if (isArchiveFileElement) {
                    elementProgress = SubMonitor.convert(elementProgress, 4);
                    IPath relativeToSourceContainer = new Path(element.getFileSystemObject().getAbsolutePath(null)).makeRelativeTo(baseSourceContainerPath);
                    IFolder folder = safeCreateExtractedFolder(destFolder, relativeToSourceContainer, elementProgress.newChild(1));
                    extractArchiveToFolder(archiveFile, folder, elementProgress.newChild(1));

                    // Delete original archive, we don't want to import this, just the extracted content
                    IFile fileRes = destFolder.getFile(relativeToSourceContainer);
                    fileRes.delete(true, elementProgress.newChild(1));
                    IPath newPath = destFolder.getFullPath().append(relativeToSourceContainer);
                    // Rename extracted folder (.extract) to original archive name
                    folder.move(newPath, true, elementProgress.newChild(1));
                    folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(newPath);

                    // Create the new import provider and root element based on
                    // the newly extracted temporary folder
                    FileSystemObjectImportStructureProvider importStructureProvider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
                    IFileSystemObject rootElement = importStructureProvider.getIFileSystemObject(new File(folder.getLocation().toOSString()));
                    TraceFileSystemElement newElement = createRootTraceFileElement(rootElement, importStructureProvider);
                    List<TraceFileSystemElement> extractedChildren = new ArrayList<>();
                    getAllChildren(extractedChildren, newElement);
                    extractAllArchiveFiles(extractedChildren, folder, folder.getLocation(), progressMonitor);
                }
            }
        }

        /**
         * Extract a file (File) to a destination folder
         */
        private void extractArchiveToFolder(File sourceFile, IFolder destinationFolder, IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
            Pair<IFileSystemObject, FileSystemObjectImportStructureProvider> rootObjectAndProvider = getRootObjectAndProvider(sourceFile);
            TraceFileSystemElement rootElement = createRootTraceFileElement(rootObjectAndProvider.getFirst(), rootObjectAndProvider.getSecond());
            List<TraceFileSystemElement> fileSystemElements = new ArrayList<>();
            getAllChildren(fileSystemElements, rootElement);
            extractArchiveContent(fileSystemElements.listIterator(), destinationFolder, progressMonitor);
            rootObjectAndProvider.getSecond().dispose();
        }

        /**
         * Safely create a folder meant to receive extracted content by making sure there is no name clash.
         */
        private IFolder safeCreateExtractedFolder(IFolder destinationFolder, IPath relativeContainerRelativePath, IProgressMonitor monitor) throws CoreException {
            SubMonitor subMonitor = SubMonitor.convert(monitor, 2);
            IFolder extractedFolder;
            String suffix = ""; //$NON-NLS-1$
            int i = 2;
            while (true) {
                IPath fullPath = destinationFolder.getFullPath().append(relativeContainerRelativePath + ".extract" + suffix); //$NON-NLS-1$
                IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(fullPath);
                if (!folder.exists()) {
                    extractedFolder = folder;
                    break;
                }
                suffix = "(" + i + ")"; //$NON-NLS-1$//$NON-NLS-2$
                i++;
            }
            subMonitor.worked(1);

            TraceUtils.createFolder(extractedFolder, subMonitor.newChild(1));
            return extractedFolder;
        }

        private void calculateSourceLocations(List<TraceFileSystemElement> fileSystemElements, String baseSourceLocation) {
            for (TraceFileSystemElement element : fileSystemElements) {
                IPath tempRelative = new Path(element.getFileSystemObject().getAbsolutePath(null)).makeRelativeTo(fBaseSourceContainerPath);
                String sourceLocation = baseSourceLocation + tempRelative;
                element.setSourceLocation(sourceLocation);

                TraceFileSystemElement parentElement = (TraceFileSystemElement) element.getParent();
                tempRelative = new Path(parentElement.getFileSystemObject().getAbsolutePath(null)).makeRelativeTo(fBaseSourceContainerPath);
                sourceLocation = baseSourceLocation + tempRelative + '/';
                parentElement.setSourceLocation(sourceLocation);
            }
        }

        /**
         * Extract all file system elements (Tar, Zip elements) to destination folder (typically workspace/TraceProject/.traceImport or a subfolder of it)
         */
        private void extractArchiveContent(Iterator<TraceFileSystemElement> fileSystemElementsIter, IFolder tempFolder, IProgressMonitor progressMonitor) throws InterruptedException,
                InvocationTargetException {
            List<TraceFileSystemElement> subList = new ArrayList<>();
            // Collect all the elements
            while (fileSystemElementsIter.hasNext()) {
                ModalContext.checkCanceled(progressMonitor);
                TraceFileSystemElement element = fileSystemElementsIter.next();
                if (element.isDirectory()) {
                    Object[] array = element.getFiles().getChildren();
                    for (int i = 0; i < array.length; i++) {
                        subList.add((TraceFileSystemElement) array[i]);
                    }
                }
                subList.add(element);
            }

            TraceFileSystemElement root = getRootElement(subList.get(0));

            ImportProvider fileSystemStructureProvider = new ImportProvider();

            IOverwriteQuery myQueryImpl = new IOverwriteQuery() {
                @Override
                public String queryOverwrite(String file) {
                    return IOverwriteQuery.NO_ALL;
                }
            };

            progressMonitor.setTaskName(Messages.ImportTraceWizard_ExtractImportOperationTaskName);
            IPath containerPath = tempFolder.getFullPath();
            ImportOperation operation = new ImportOperation(containerPath, root, fileSystemStructureProvider, myQueryImpl, subList);
            operation.setContext(getShell());

            operation.setCreateContainerStructure(true);
            operation.setOverwriteResources(false);
            operation.setVirtualFolders(false);

            operation.run(new SubProgressMonitor(progressMonitor, subList.size(), SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
        }

        private TraceFileSystemElement getRootElement(TraceFileSystemElement element) {
            TraceFileSystemElement root = element;
            while (root.getParent() != null) {
                root = (TraceFileSystemElement) root.getParent();
            }
            return root;
        }

        /**
         * Get all the TraceFileSystemElements recursively.
         *
         * @param result
         *            the list accumulating the result
         * @param rootElement
         *            the root element of the file system to be imported
         */
        private void getAllChildren(List<TraceFileSystemElement> result, TraceFileSystemElement rootElement) {
            AdaptableList files = rootElement.getFiles();
            for (Object file : files.getChildren()) {
                result.add((TraceFileSystemElement) file);
            }

            AdaptableList folders = rootElement.getFolders();
            for (Object folder : folders.getChildren()) {
                getAllChildren(result, (TraceFileSystemElement) folder);
            }
        }

        private IPath computeDestinationContainerPath(Path resourcePath) {
            IPath destinationContainerPath = fDestinationContainerPath;

            // We need to figure out the new destination path relative to the
            // selected "base" source directory.
            // Here for example, the selected source directory is /home/user
            if ((fImportOptionFlags & OPTION_PRESERVE_FOLDER_STRUCTURE) != 0) {
                // /home/user/bar/foo/trace -> /home/user/bar/foo
                IPath sourceContainerPath = resourcePath.removeLastSegments(1);
                if (fBaseSourceContainerPath.equals(resourcePath)) {
                    // Use resourcePath directory if fBaseSourceContainerPath
                    // points to a directory trace
                    sourceContainerPath = resourcePath;
                }
                // /home/user/bar/foo, /home/user -> bar/foo
                IPath relativeContainerPath = sourceContainerPath.makeRelativeTo(fBaseSourceContainerPath);
                // project/Traces + bar/foo -> project/Traces/bar/foo
                destinationContainerPath = fDestinationContainerPath.append(relativeContainerPath);
            }
            return destinationContainerPath;
        }

        /**
         * Import a single file system element into the workspace.
         */
        private void validateAndImportTrace(TraceFileSystemElement fileSystemElement, IProgressMonitor monitor)
                throws TmfTraceImportException, CoreException, InvocationTargetException, InterruptedException {
            String parentContainerPath = fBaseSourceContainerPath.toOSString();
            String path = fileSystemElement.getFileSystemObject().getAbsolutePath(parentContainerPath);
            TraceTypeHelper traceTypeHelper = null;

            File file = (File) fileSystemElement.getFileSystemObject().getRawFileSystemObject();
            boolean isArchiveFileElement = fileSystemElement.getFileSystemObject() instanceof FileFileSystemObject && isArchiveFile(file);
            if (isArchiveFileElement) {
                // We'll be extracting this later, do not import as a trace
                return;
            }

            if (fTraceType == null) {
                // Auto Detection
                try {
                    traceTypeHelper = TmfTraceTypeUIUtils.selectTraceType(path, null, null);
                } catch (TmfTraceImportException e) {
                    // the trace did not match any trace type
                }
                if (traceTypeHelper == null) {
                    if ((fImportOptionFlags & OPTION_IMPORT_UNRECOGNIZED_TRACES) != 0) {
                        importResource(fileSystemElement, monitor);
                    }
                    return;
                }
            } else {
                boolean isDirectoryTraceType = TmfTraceType.isDirectoryTraceType(fTraceType);
                if (fileSystemElement.isDirectory() != isDirectoryTraceType) {
                    return;
                }
                traceTypeHelper = TmfTraceType.getTraceType(fTraceType);

                if (traceTypeHelper == null) {
                    // Trace type not found
                    throw new TmfTraceImportException(Messages.ImportTraceWizard_TraceTypeNotFound);
                }

                if (!traceTypeHelper.validate(path).isOK()) {
                    // Trace type exist but doesn't validate for given trace.
                    return;
                }
            }

            // Finally import trace
            IResource importedResource = importResource(fileSystemElement, monitor);
            if (importedResource != null) {
                TmfTraceTypeUIUtils.setTraceType(importedResource, traceTypeHelper);
            }

        }

        /**
         * Imports a trace resource to project. In case of name collision the
         * user will be asked to confirm overwriting the existing trace,
         * overwriting or skipping the trace to be imported.
         *
         * @param fileSystemElement
         *            trace file system object to import
         * @param monitor
         *            a progress monitor
         * @return the imported resource or null if no resource was imported
         *
         * @throws InvocationTargetException
         *             if problems during import operation
         * @throws InterruptedException
         *             if cancelled
         * @throws CoreException
         *             if problems with workspace
         */
        private IResource importResource(TraceFileSystemElement fileSystemElement, IProgressMonitor monitor)
                throws InvocationTargetException, InterruptedException, CoreException {

            IPath tracePath = getInitialDestinationPath(fileSystemElement);
            String newName = fConflictHandler.checkAndHandleNameClash(tracePath, monitor);
            if (newName == null) {
                return null;
            }
            fileSystemElement.setLabel(newName);

            List<TraceFileSystemElement> subList = new ArrayList<>();

            FileSystemElement parentFolder = fileSystemElement.getParent();

            IPath containerPath = fileSystemElement.getDestinationContainerPath();
            tracePath = containerPath.addTrailingSeparator().append(fileSystemElement.getLabel());
            boolean createLinksInWorkspace = (fImportOptionFlags & OPTION_CREATE_LINKS_IN_WORKSPACE) != 0;
            if (fileSystemElement.isDirectory() && !createLinksInWorkspace) {
                containerPath = tracePath;

                Object[] array = fileSystemElement.getFiles().getChildren();
                for (int i = 0; i < array.length; i++) {
                    subList.add((TraceFileSystemElement) array[i]);
                }
                parentFolder = fileSystemElement;

            } else {
                subList.add(fileSystemElement);
            }

            ImportProvider fileSystemStructureProvider = new ImportProvider();

            IOverwriteQuery myQueryImpl = new IOverwriteQuery() {
                @Override
                public String queryOverwrite(String file) {
                    return IOverwriteQuery.NO_ALL;
                }
            };

            monitor.setTaskName(Messages.ImportTraceWizard_ImportOperationTaskName + " " + fileSystemElement.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString())); //$NON-NLS-1$
            ImportOperation operation = new ImportOperation(containerPath, parentFolder, fileSystemStructureProvider, myQueryImpl, subList);
            operation.setContext(getShell());

            operation.setCreateContainerStructure(false);
            operation.setOverwriteResources(false);
            operation.setCreateLinks(createLinksInWorkspace);
            operation.setVirtualFolders(false);

            operation.run(new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
            String sourceLocation = fileSystemElement.getSourceLocation();
            IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(tracePath);
            if (sourceLocation != null) {
                resource.setPersistentProperty(TmfCommonConstants.SOURCE_LOCATION, sourceLocation);
            }

            return resource;
        }

        private boolean isDirectoryTrace(TraceFileSystemElement fileSystemElement) {
            String path = fileSystemElement.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString());
            if (TmfTraceType.isDirectoryTrace(path)) {
                return true;
            }
            return false;
        }

        /**
         * @return the initial destination path, before rename, if any
         */
        private IPath getInitialDestinationPath(TraceFileSystemElement fileSystemElement) {
            IPath traceFolderPath = fileSystemElement.getDestinationContainerPath();
            return traceFolderPath.append(fileSystemElement.getFileSystemObject().getLabel());
        }

        /**
         * Set the status for this operation
         *
         * @param status
         *            the status
         */
        protected void setStatus(IStatus status) {
            fStatus = status;
        }

        public IStatus getStatus() {
            return fStatus;
        }
    }

    /**
     * The <code>TraceFileSystemElement</code> is a
     * <code>FileSystemElement</code> that knows if it has been populated or
     * not.
     */
    private static class TraceFileSystemElement extends FileSystemElement {

        private boolean fIsPopulated = false;
        private String fLabel = null;
        private IPath fDestinationContainerPath;
        private FileSystemObjectImportStructureProvider fProvider;
        private String fSourceLocation;

        public TraceFileSystemElement(String name, FileSystemElement parent, boolean isDirectory, FileSystemObjectImportStructureProvider provider) {
            super(name, parent, isDirectory);
            fProvider = provider;
        }

        public void setDestinationContainerPath(IPath destinationContainerPath) {
            fDestinationContainerPath = destinationContainerPath;
        }

        public void setPopulated() {
            fIsPopulated = true;
        }

        public boolean isPopulated() {
            return fIsPopulated;
        }

        @Override
        public AdaptableList getFiles() {
            if (!fIsPopulated) {
                populateElementChildren();
            }
            return super.getFiles();
        }

        @Override
        public AdaptableList getFolders() {
            if (!fIsPopulated) {
                populateElementChildren();
            }
            return super.getFolders();
        }

        /**
         * Sets the label for the trace to be used when importing at trace.
         *
         * @param name
         *            the label for the trace
         */
        public void setLabel(String name) {
            fLabel = name;
        }

        /**
         * Returns the label for the trace to be used when importing at trace.
         *
         * @return the label of trace resource
         */
        public String getLabel() {
            if (fLabel == null) {
                return getFileSystemObject().getLabel();
            }
            return fLabel;
        }

        /**
         * The full path to the container that will contain the trace
         *
         * @return the destination container path
         */
        public IPath getDestinationContainerPath() {
            return fDestinationContainerPath;
        }

        /**
         * Populates the children of the specified parent
         * <code>FileSystemElement</code>
         */
        private void populateElementChildren() {
            List<IFileSystemObject> allchildren = fProvider.getChildren(this.getFileSystemObject());
            Object child = null;
            TraceFileSystemElement newelement = null;
            Iterator<IFileSystemObject> iter = allchildren.iterator();
            while (iter.hasNext()) {
                child = iter.next();
                newelement = new TraceFileSystemElement(fProvider.getLabel(child), this, fProvider.isFolder(child), fProvider);
                newelement.setFileSystemObject(child);
            }
            setPopulated();
        }

        public FileSystemObjectImportStructureProvider getProvider() {
            return fProvider;
        }

        @Override
        public IFileSystemObject getFileSystemObject() {
            Object fileSystemObject = super.getFileSystemObject();
            return (IFileSystemObject) fileSystemObject;
        }

        public String getSourceLocation() {
            if (fSourceLocation == null) {
                fSourceLocation = getFileSystemObject().getSourceLocation();
            }
            return fSourceLocation;
        }

        public void setSourceLocation(String sourceLocation) {
            fSourceLocation = sourceLocation;
        }
    }

    /**
     * This interface abstracts the differences between different kinds of
     * FileSystemObjects such as File, TarEntry, ZipEntry, etc. This allows
     * clients (TraceFileSystemElement, TraceValidateAndImportOperation) to
     * handle all the types transparently.
     */
    private interface IFileSystemObject {
        String getLabel();

        String getName();

        String getAbsolutePath(String parentContainerPath);

        String getSourceLocation();

        Object getRawFileSystemObject();

        boolean exists();
    }

    /**
     * The "File" implementation of an IFileSystemObject
     */
    private static class FileFileSystemObject implements IFileSystemObject {

        private File fFileSystemObject;

        private FileFileSystemObject(File fileSystemObject) {
            fFileSystemObject = fileSystemObject;
        }

        @Override
        public String getLabel() {
            String name = fFileSystemObject.getName();
            if (name.length() == 0) {
                return fFileSystemObject.getPath();
            }
            return name;
        }

        @Override
        public String getName() {
            return fFileSystemObject.getName();
        }

        @Override
        public String getAbsolutePath(String parentContainerPath) {
            return fFileSystemObject.getAbsolutePath();
        }

        @Override
        public boolean exists() {
            return fFileSystemObject.exists();
        }

        @Override
        public String getSourceLocation() {
            IResource sourceResource;
            String sourceLocation = null;
            if (fFileSystemObject.isDirectory()) {
                sourceResource = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
            } else {
                sourceResource = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
            }
            if (sourceResource != null && sourceResource.exists()) {
                try {
                    sourceLocation = sourceResource.getPersistentProperty(TmfCommonConstants.SOURCE_LOCATION);
                } catch (CoreException e) {
                    // Something went wrong with the already existing resource.
                    // This is not a problem, we'll assign a new location below.
                }
            }
            if (sourceLocation == null) {
                try {
                    sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.getCanonicalFile().toURI());
                } catch (IOException e) {
                    // Something went wrong canonicalizing the file. We can still use the URI but there might be extra ../ in it.
                    sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.toURI());
                }
            }
            return sourceLocation;
        }

        @Override
        public Object getRawFileSystemObject() {
            return fFileSystemObject;
        }
    }

    /**
     * The "Tar" implementation of an IFileSystemObject, entries can also be Gzipped and are uncompressed transparently.
     */
    private static class TarFileSystemObject implements IFileSystemObject {

        private TarEntry fFileSystemObject;
        private String fArchivePath;

        private TarFileSystemObject(TarEntry fileSystemObject, String archivePath) {
            fFileSystemObject = fileSystemObject;
            fArchivePath = archivePath;
        }

        @Override
        public String getLabel() {
            return new Path(fFileSystemObject.getName()).lastSegment();
        }

        @Override
        public String getName() {
            return fFileSystemObject.getName();
        }

        @Override
        public String getAbsolutePath(String parentContainerPath) {
            return new Path(parentContainerPath).append(fFileSystemObject.getName()).toOSString();
        }

        @Override
        public boolean exists() {
            return true;
        }

        @Override
        public String getSourceLocation() {
            File file = new File(fArchivePath);
            try {
                file = file.getCanonicalFile();
            } catch (IOException e) {
                // Will still work but might have extra ../ in the path
            }
            URI uri = file.toURI();
            IPath entryPath = new Path(fFileSystemObject.getName());

            URI jarURI = entryPath.isRoot() ? URIUtil.toJarURI(uri, Path.EMPTY) : URIUtil.toJarURI(uri, entryPath);
            return URIUtil.toUnencodedString(jarURI);
        }

        @Override
        public Object getRawFileSystemObject() {
            return fFileSystemObject;
        }
    }

    /**
     * The "GZIP" implementation of an IFileSystemObject. For a GZIP file that is not in a tar.
     */
    private static class GzipFileSystemObject implements IFileSystemObject {

        private GzipEntry fFileSystemObject;
        private String fArchivePath;

        private GzipFileSystemObject(GzipEntry fileSystemObject, String archivePath) {
            fFileSystemObject = fileSystemObject;
            fArchivePath = archivePath;
        }

        @Override
        public String getLabel() {
            return new Path(fFileSystemObject.getName()).lastSegment();
        }

        @Override
        public String getName() {
            return fFileSystemObject.getName();
        }

        @Override
        public String getAbsolutePath(String parentContainerPath) {
            return new Path(parentContainerPath).append(fFileSystemObject.getName()).toOSString();
        }

        @Override
        public boolean exists() {
            return true;
        }

        @Override
        public String getSourceLocation() {
            File file = new File(fArchivePath);
            try {
                file = file.getCanonicalFile();
            } catch (IOException e) {
                // Will still work but might have extra ../ in the path
            }
            URI uri = file.toURI();
            IPath entryPath = new Path(fFileSystemObject.getName());

            URI jarURI = entryPath.isRoot() ? URIUtil.toJarURI(uri, Path.EMPTY) : URIUtil.toJarURI(uri, entryPath);
            return URIUtil.toUnencodedString(jarURI);
        }

        @Override
        public Object getRawFileSystemObject() {
            return fFileSystemObject;
        }
    }

    /**
     * The "Zip" implementation of an IFileSystemObject
     */
    private static class ZipFileSystemObject implements IFileSystemObject {

        private ZipEntry fFileSystemObject;
        private String fArchivePath;

        private ZipFileSystemObject(ZipEntry fileSystemObject, String archivePath) {
            fFileSystemObject = fileSystemObject;
            fArchivePath = archivePath;
        }

        @Override
        public String getLabel() {
            return new Path(fFileSystemObject.getName()).lastSegment();
        }

        @Override
        public String getName() {
            return fFileSystemObject.getName();
        }

        @Override
        public String getAbsolutePath(String parentContainerPath) {
            return new Path(parentContainerPath).append(fFileSystemObject.getName()).toOSString();
        }

        @Override
        public boolean exists() {
            return true;
        }

        @Override
        public String getSourceLocation() {
            File file = new File(fArchivePath);
            try {
                file = file.getCanonicalFile();
            } catch (IOException e) {
                // Will still work but might have extra ../ in the path
            }
            URI uri = file.toURI();
            IPath entryPath = new Path(fFileSystemObject.getName());

            URI jarURI = entryPath.isRoot() ? URIUtil.toJarURI(uri, Path.EMPTY) : URIUtil.toJarURI(uri, entryPath);
            return URIUtil.toUnencodedString(jarURI);
        }

        @Override
        public Object getRawFileSystemObject() {
            return fFileSystemObject;
        }
    }

    private class ImportProvider implements IImportStructureProvider {

        ImportProvider() {
        }

        @Override
        public String getLabel(Object element) {
            TraceFileSystemElement resource = (TraceFileSystemElement) element;
            return resource.getLabel();
        }

        @Override
        public List getChildren(Object element) {
            TraceFileSystemElement resource = (TraceFileSystemElement) element;
            Object[] array = resource.getFiles().getChildren();
            List<Object> list = new ArrayList<>();
            for (int i = 0; i < array.length; i++) {
                list.add(array[i]);
            }
            return list;
        }

        @Override
        public InputStream getContents(Object element) {
            TraceFileSystemElement resource = (TraceFileSystemElement) element;
            return resource.getProvider().getContents(resource.getFileSystemObject());
        }

        @Override
        public String getFullPath(Object element) {
            TraceFileSystemElement resource = (TraceFileSystemElement) element;
            return resource.getProvider().getFullPath(resource.getFileSystemObject());
        }

        @Override
        public boolean isFolder(Object element) {
            TraceFileSystemElement resource = (TraceFileSystemElement) element;
            return resource.isDirectory();
        }
    }
}

Back to the top