Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 5b9bffc93d4f43c46c558a1578ae4a787121f1c1 (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
/*******************************************************************************
 * Copyright (c) 2009, 2010, 2011, 2012 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
 *******************************************************************************/

package org.eclipse.linuxtools.tmf.ui.project.wizards;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.core.resources.IContainer;
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.IConfigurationElement;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.linuxtools.internal.tmf.ui.Activator;
import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTrace;
import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition;
import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace;
import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition;
import org.eclipse.linuxtools.tmf.core.TmfCommonConstants;
import org.eclipse.linuxtools.tmf.core.TmfProjectNature;
import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectElement;
import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectRegistry;
import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceElement;
import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceFolder;
import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceType;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.FileSystemElement;
import org.eclipse.ui.dialogs.WizardResourceImportPage;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
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 with the following changes:
 * <ul>
 * <li>A folder/file combined checkbox tree viewer to select traces
 * <li>Cherry-picking of traces in the file structure without re-creating the file hierarchy
 * <li>A trace types dropbox for optional characterization
 * </ul>
 * For our purpose, a trace can either be a single file or a whole directory sub-tree, whichever is reached first from
 * the root directory.
 * <p>
 *
 * @version 1.0
 * @author Francois Chouinard
 */
public class ImportTraceWizardPage extends WizardResourceImportPage {

    // ------------------------------------------------------------------------
    // Constants
    // ------------------------------------------------------------------------

    static private final String IMPORT_WIZARD_PAGE = "ImportTraceWizardPage"; //$NON-NLS-1$
    private static final String CUSTOM_TXT_CATEGORY = "Custom Text"; //$NON-NLS-1$
    private static final String CUSTOM_XML_CATEGORY = "Custom XML"; //$NON-NLS-1$
    private static final String DEFAULT_TRACE_ICON_PATH = "icons/elcl16/trace.gif"; //$NON-NLS-1$

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

    // Folder navigation start point (saved between invocations)
    private static String fRootDirectory = null;

    // Navigation folder content viewer and selector
    private CheckboxTreeViewer fFolderViewer;

    // Parent tracing project
    private IProject fProject;

    // Target import directory ('Traces' folder)
    private IFolder fTargetFolder;

    // ------------------------------------------------------------------------
    // 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);
    }

    /**
     * Constructor
     * @param workbench The workbench reference.
     * @param selection The current selection
     */
    public ImportTraceWizardPage(IWorkbench workbench, IStructuredSelection selection) {
        this(IMPORT_WIZARD_PAGE, 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) {
            TmfTraceFolder tmfTraceFolder = (TmfTraceFolder) element;
            fProject = tmfTraceFolder.getProject().getResource();
            traceFolder = tmfTraceFolder.getResource();
        } else if (element instanceof IProject) {
            IProject project = (IProject) element;
            try {
                if (project.hasNature(TmfProjectNature.ID)) {
                    traceFolder = (IFolder) project.findMember(TmfTraceFolder.TRACE_FOLDER_NAME);
                }
            } catch (CoreException e) {
            }
        }

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

    // ------------------------------------------------------------------------
    // WizardResourceImportPage
    // ------------------------------------------------------------------------
    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createControl(org.eclipse.swt.widgets.Composite)
     */
    @Override
    public void createControl(Composite parent) {
        super.createControl(parent);
        // Restore last directory if applicable
        if (fRootDirectory != null) {
            directoryNameField.setText(fRootDirectory);
            updateFromSourceField();
        }
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createSourceGroup(org.eclipse.swt.widgets.Composite)
     */
    @Override
    protected void createSourceGroup(Composite parent) {
        createDirectorySelectionGroup(parent);
        createFileSelectionGroup(parent);
        createTraceTypeGroup(parent);
        validateSourceGroup();
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createFileSelectionGroup(org.eclipse.swt.widgets.Composite)
     */
    @Override
    protected void createFileSelectionGroup(Composite parent) {

        // This Composite is only used for widget alignment purposes
        Composite composite = new Composite(parent, SWT.NONE);
        composite.setFont(parent.getFont());
        GridLayout layout = new GridLayout();
        composite.setLayout(layout);
        composite.setLayoutData(new GridData(GridData.FILL_BOTH));

        final int PREFERRED_LIST_HEIGHT = 150;

        fFolderViewer = new CheckboxTreeViewer(composite, SWT.BORDER);
        GridData data = new GridData(GridData.FILL_BOTH);
        data.heightHint = PREFERRED_LIST_HEIGHT;
        fFolderViewer.getTree().setLayoutData(data);
        fFolderViewer.getTree().setFont(parent.getFont());

        fFolderViewer.setContentProvider(getFileProvider());
        fFolderViewer.setLabelProvider(new WorkbenchLabelProvider());
        fFolderViewer.addCheckStateListener(new ICheckStateListener() {
            @Override
            public void checkStateChanged(CheckStateChangedEvent event) {
                Object elem = event.getElement();
                if (elem instanceof FileSystemElement) {
                    FileSystemElement element = (FileSystemElement) elem;
                    if (fFolderViewer.getGrayed(element)) {
                        fFolderViewer.setSubtreeChecked(element, false);
                        fFolderViewer.setGrayed(element, false);
                    } else if (event.getChecked()) {
                        fFolderViewer.setSubtreeChecked(event.getElement(), true);
                    } else {
                        fFolderViewer.setParentsGrayed(element, true);
                        if (!element.isDirectory()) {
                            fFolderViewer.setGrayed(element, false);
                        }
                    }
                    updateWidgetEnablements();
                }
            }
        });
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getFolderProvider()
     */
    @Override
    protected ITreeContentProvider getFolderProvider() {
        return null;
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getFileProvider()
     */
    @Override
    protected ITreeContentProvider getFileProvider() {
        return new WorkbenchContentProvider() {
            @Override
            public Object[] getChildren(Object o) {
                if (o instanceof FileSystemElement) {
                    FileSystemElement element = (FileSystemElement) o;
                    populateChildren(element);
                    // For our purpose, we need folders + files
                    Object[] folders = element.getFolders().getChildren();
                    Object[] files = element.getFiles().getChildren();

                    List<Object> result = new LinkedList<Object>();
                    for (Object folder : folders) {
                        result.add(folder);
                    }
                    for (Object file : files) {
                        result.add(file);
                    }

                    return result.toArray();
                }
                return new Object[0];
            }
        };
    }

    private static void populateChildren(FileSystemElement parent) {
        // Do not re-populate if the job was done already...
        FileSystemStructureProvider provider = FileSystemStructureProvider.INSTANCE;
        if (parent.getFolders().size() == 0 && parent.getFiles().size() == 0) {
            Object fileSystemObject = parent.getFileSystemObject();
            List<?> children = provider.getChildren(fileSystemObject);
            if (children != null) {
                Iterator<?> iterator = children.iterator();
                while (iterator.hasNext()) {
                    Object child = iterator.next();
                    String label = provider.getLabel(child);
                    FileSystemElement element = new FileSystemElement(label, parent, provider.isFolder(child));
                    element.setFileSystemObject(child);
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getSelectedResources()
     */
    @Override
    protected List<FileSystemElement> getSelectedResources() {
        List<FileSystemElement> resources = new ArrayList<FileSystemElement>();
        Object[] checkedItems = fFolderViewer.getCheckedElements();
        for (Object item : checkedItems) {
            if (item instanceof FileSystemElement && !fFolderViewer.getGrayed(item)) {
                resources.add((FileSystemElement) item);
            }
        }
        return resources;
    }

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

    /**
     * The directory name field
     */
    protected Combo directoryNameField;
    /**
     * The directory browse button.
     */
    protected Button directoryBrowseButton;
    private boolean entryChanged = false;

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

        Composite directoryContainerGroup = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout();
        layout.numColumns = 3;
        directoryContainerGroup.setLayout(layout);
        directoryContainerGroup.setFont(parent.getFont());
        directoryContainerGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

        // Label ("Trace directory:")
        Label groupLabel = new Label(directoryContainerGroup, SWT.NONE);
        groupLabel.setText(Messages.ImportTraceWizard_DirectoryLocation);
        groupLabel.setFont(parent.getFont());

        // Directory name entry field
        directoryNameField = new Combo(directoryContainerGroup, SWT.BORDER);
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
        data.widthHint = SIZING_TEXT_FIELD_WIDTH;
        directoryNameField.setLayoutData(data);
        directoryNameField.setFont(parent.getFont());

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

        directoryNameField.addKeyListener(new KeyListener() {
            @Override
            public void keyPressed(KeyEvent e) {
                // If there has been a key pressed then mark as dirty
                entryChanged = true;
                if (e.character == SWT.CR) { // Windows...
                    entryChanged = false;
                    updateFromSourceField();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        });

        directoryNameField.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                // Do nothing when getting focus
            }

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

        // Browse button
        directoryBrowseButton = new Button(directoryContainerGroup, SWT.PUSH);
        directoryBrowseButton.setText(Messages.ImportTraceWizard_BrowseButton);
        directoryBrowseButton.addListener(SWT.Selection, this);
        directoryBrowseButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
        directoryBrowseButton.setFont(parent.getFont());
        setButtonLayoutData(directoryBrowseButton);
    }

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

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardResourceImportPage#handleEvent(org.eclipse.swt.widgets.Event)
     */
    @Override
    public void handleEvent(Event event) {
        if (event.widget == directoryBrowseButton) {
            handleSourceDirectoryBrowseButtonPressed();
        }
        super.handleEvent(event);
    }

    /**
     * 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);
            setSourceName(selectedDirectory);
        }
    }

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

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

        return sourceDirectory;
    }

    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 String getSourceDirectoryName() {
        return getSourceDirectoryName(directoryNameField.getText());
    }

    private void updateFromSourceField() {
        setSourceName(directoryNameField.getText());
        updateWidgetEnablements();
    }

    private void setSourceName(String path) {
        if (path.length() > 0) {
            String[] currentItems = directoryNameField.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;
                directoryNameField.setItems(newItems);
                selectionIndex = oldLength;
            }
            directoryNameField.select(selectionIndex);
        }
        resetSelection();
    }

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

    private void resetSelection() {
        FileSystemElement root = getFileSystemTree();
        populateListViewer(root);
    }

    private void populateListViewer(final Object treeElement) {
        fFolderViewer.setInput(treeElement);
    }

    private FileSystemElement getFileSystemTree() {
        File sourceDirectory = getSourceDirectory();
        if (sourceDirectory == null) {
            return null;
        }
        return selectFiles(sourceDirectory, FileSystemStructureProvider.INSTANCE);
    }

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

    private static FileSystemElement createRootElement(Object fileSystemObject,
            IImportStructureProvider provider) {

        boolean isContainer = provider.isFolder(fileSystemObject);
        String elementLabel = provider.getLabel(fileSystemObject);

        FileSystemElement dummyParent = new FileSystemElement("", null, true); //$NON-NLS-1$
        FileSystemElement element = new FileSystemElement(elementLabel, dummyParent, isContainer);
        element.setFileSystemObject(fileSystemObject);

        // Get the first level
        populateChildren(element);

        return dummyParent;
    }

    // ------------------------------------------------------------------------
    // Trace Type Group
    // ------------------------------------------------------------------------

    private Combo fTraceTypes;

    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);
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
        fTraceTypes.setLayoutData(data);
        fTraceTypes.setFont(parent.getFont());

        String[] availableTraceTypes = getAvailableTraceTypes();
        fTraceTypes.setItems(availableTraceTypes);

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

            @Override
            public void widgetDefaultSelected(SelectionEvent e) {
            }
        });
    }

    // The mapping of available trace type IDs to their corresponding configuration element
    private final Map<String, IConfigurationElement> fTraceTypeAttributes = new HashMap<String, IConfigurationElement>();
    private final Map<String, IConfigurationElement> fTraceCategories = new HashMap<String, IConfigurationElement>();
    private final Map<String, IConfigurationElement> fTraceAttributes = new HashMap<String, IConfigurationElement>();

    private String[] getAvailableTraceTypes() {

        // Populate the Categories and Trace Types
        IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(TmfTraceType.TMF_TRACE_TYPE_ID);
        for (IConfigurationElement ce : config) {
            String elementName = ce.getName();
            if (elementName.equals(TmfTraceType.TYPE_ELEM)) {
                String traceTypeId = ce.getAttribute(TmfTraceType.ID_ATTR);
                fTraceTypeAttributes.put(traceTypeId, ce);
            } else if (elementName.equals(TmfTraceType.CATEGORY_ELEM)) {
                String categoryId = ce.getAttribute(TmfTraceType.ID_ATTR);
                fTraceCategories.put(categoryId, ce);
            }
        }

        // Generate the list of Category:TraceType to populate the ComboBox
        List<String> traceTypes = new ArrayList<String>();
        for (String typeId : fTraceTypeAttributes.keySet()) {
            IConfigurationElement ce = fTraceTypeAttributes.get(typeId);
            String traceTypeName = getCategory(ce) + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR); //$NON-NLS-1$
            fTraceAttributes.put(traceTypeName, ce);
            traceTypes.add(traceTypeName);
        }
        Collections.sort(traceTypes);

        // add the custom trace types
        for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) {
            String traceTypeName = CUSTOM_TXT_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$
            traceTypes.add(traceTypeName);
        }
        for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) {
            String traceTypeName = CUSTOM_XML_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$
            traceTypes.add(traceTypeName);
        }

        // Format result
        return traceTypes.toArray(new String[traceTypes.size()]);
    }

    private String getCategory(IConfigurationElement ce) {
        String categoryId = ce.getAttribute(TmfTraceType.CATEGORY_ATTR);
        if (categoryId != null) {
            IConfigurationElement category = fTraceCategories.get(categoryId);
            if (category != null && !category.getName().equals("")) { //$NON-NLS-1$
                return category.getAttribute(TmfTraceType.NAME_ATTR);
            }
        }
        return "[no category]"; //$NON-NLS-1$
    }

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

    private Button overwriteExistingResourcesCheckbox;
    private Button createLinksInWorkspaceButton;

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardDataTransferPage#createOptionsGroupButtons(org.eclipse.swt.widgets.Group)
     */
    @Override
    protected void createOptionsGroupButtons(Group optionsGroup) {

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

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

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

        updateWidgetEnablements();
    }

    // ------------------------------------------------------------------------
    // Determine if the finish button can be enabled
    // ------------------------------------------------------------------------

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.dialogs.WizardDataTransferPage#validateSourceGroup()
     */
    @Override
    public boolean validateSourceGroup() {

        File sourceDirectory = getSourceDirectory();
        if (sourceDirectory == null) {
            setMessage(Messages.ImportTraceWizard_SelectTraceSourceEmpty);
            return false;
        }

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

        List<FileSystemElement> resourcesToImport = getSelectedResources();
        if (resourcesToImport.size() == 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 (createLinksInWorkspaceButton == null || !createLinksInWorkspaceButton.getSelection()) {
                setMessage(null);
                setErrorMessage(Messages.ImportTraceWizard_HaveToCreateLinksUnderAVirtualFolder);
                return false;
            }
        }

        // Perform trace validation
        String traceTypeName = fTraceTypes.getText();
        if (traceTypeName != null && !"".equals(traceTypeName) && //$NON-NLS-1$
            !traceTypeName.startsWith(CUSTOM_TXT_CATEGORY) && !traceTypeName.startsWith(CUSTOM_XML_CATEGORY)) {

            List<File> traces = isolateTraces();
            for (File trace : traces) {
                ITmfTrace<?> tmfTrace = null;
                try {
                    IConfigurationElement ce = fTraceAttributes.get(traceTypeName);
                    tmfTrace = (ITmfTrace<?>) ce.createExecutableExtension(TmfTraceType.TRACE_TYPE_ATTR);
                    if (tmfTrace != null && !tmfTrace.validate(fProject, trace.getAbsolutePath())) {
                        setMessage(null);
                        setErrorMessage(Messages.ImportTraceWizard_TraceValidationFailed);
                        tmfTrace.dispose();
                        return false;
                    }
                } catch (CoreException e) {
                } finally {
                    if (tmfTrace != null) {
                        tmfTrace.dispose();
                    }
                }
            }
        }

        setErrorMessage(null);
        return true;
    }

    private List<File> isolateTraces() {

        List<File> traces = new ArrayList<File>();

        // Get the selection
        List<FileSystemElement> selectedResources = getSelectedResources();
        Iterator<FileSystemElement> resources = selectedResources.iterator();

        // Get the sorted list of unique entries
        Map<String, File> fileSystemObjects = new HashMap<String, File>();
        while (resources.hasNext()) {
            File resource = (File) resources.next().getFileSystemObject();
            String key = resource.getAbsolutePath();
            fileSystemObjects.put(key, resource);
        }
        List<String> files = new ArrayList<String>(fileSystemObjects.keySet());
        Collections.sort(files);

        // After sorting, traces correspond to the unique prefixes
        String prefix = null;
        for (int i = 0; i < files.size(); i++) {
            File file = fileSystemObjects.get(files.get(i));
            String name = file.getAbsolutePath();
            if (prefix == null || !name.startsWith(prefix)) {
                prefix = name; // new prefix
                traces.add(file);
            }
        }

        return traces;
    }

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

    /**
     * Finish the import.
     * @return <code>true</code> if successful else false
     */
    public boolean finish() {
        // Ensure source is valid
        File sourceDir = new File(getSourceDirectoryName());
        if (!sourceDir.isDirectory()) {
            setErrorMessage(Messages.ImportTraceWizard_InvalidTraceDirectory);
            return false;
        }

        String sourceDirPath;
        try {
            sourceDirPath = sourceDir.getCanonicalPath();
        } catch (IOException e) {
            MessageDialog.openInformation(getContainer().getShell(), Messages.ImportTraceWizard_Information,
                    Messages.ImportTraceWizard_InvalidTraceDirectory);
            return false;
        }

        // Save directory for next import operation
        fRootDirectory = getSourceDirectoryName();

        List<FileSystemElement> selectedResources = getSelectedResources();
        Iterator<FileSystemElement> resources = selectedResources.iterator();

        // Use a map to end up with unique resources (getSelectedResources() can return duplicates)
        Map<String, File> fileSystemObjects = new HashMap<String, File>();
        while (resources.hasNext()) {
            File file = (File) resources.next().getFileSystemObject();
            String key = file.getAbsolutePath();
            fileSystemObjects.put(key, file);
        }

        if (fileSystemObjects.size() > 0) {
            boolean ok = importResources(sourceDirPath, fileSystemObjects);
            String traceBundle = null;
            String traceTypeId = null;
            String traceIcon = null;
            String traceType = fTraceTypes.getText();
            boolean traceTypeOK = false;
            if (traceType.startsWith(CUSTOM_TXT_CATEGORY)) {
                for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) {
                    if (traceType.equals(CUSTOM_TXT_CATEGORY + " : " + def.definitionName)) { //$NON-NLS-1$
                        traceTypeOK = true;
                        traceBundle = Activator.getDefault().getBundle().getSymbolicName();
                        traceTypeId = CustomTxtTrace.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$
                        traceIcon = DEFAULT_TRACE_ICON_PATH;
                        break;
                    }
                }
            } else if (traceType.startsWith(CUSTOM_XML_CATEGORY)) {
                for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) {
                    if (traceType.equals(CUSTOM_XML_CATEGORY + " : " + def.definitionName)) { //$NON-NLS-1$
                        traceTypeOK = true;
                        traceBundle = Activator.getDefault().getBundle().getSymbolicName();
                        traceTypeId = CustomXmlTrace.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$
                        traceIcon = DEFAULT_TRACE_ICON_PATH;
                        break;
                    }
                }
            } else {
                IConfigurationElement ce = fTraceAttributes.get(traceType);
                if (ce != null) {
                    traceTypeOK = true;
                    traceBundle = ce.getContributor().getName();
                    traceTypeId = ce.getAttribute(TmfTraceType.ID_ATTR);
                    traceIcon = ce.getAttribute(TmfTraceType.ICON_ATTR);
                }
            }
            if (ok && traceTypeOK && !traceType.equals("")) { //$NON-NLS-1$
                // Tag the selected traces with their type
                List<String> files = new ArrayList<String>(fileSystemObjects.keySet());
                Collections.sort(files, new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        String v1 = o1 + File.separatorChar;
                        String v2 = o2 + File.separatorChar;
                        return v1.compareTo(v2);
                    }
                });
                // After sorting, traces correspond to the unique prefixes
                String prefix = null;
                for (int i = 0; i < files.size(); i++) {
                    File file = fileSystemObjects.get(files.get(i));
                    String name = file.getAbsolutePath() + File.separatorChar;
                    if (fTargetFolder != null && (prefix == null || !name.startsWith(prefix))) {
                        prefix = name; // new prefix
                        IResource resource = fTargetFolder.findMember(file.getName());
                        if (resource != null) {
                            try {
                                // Set the trace properties for this resource
                                resource.setPersistentProperty(TmfCommonConstants.TRACEBUNDLE, traceBundle);
                                resource.setPersistentProperty(TmfCommonConstants.TRACETYPE, traceTypeId);
                                resource.setPersistentProperty(TmfCommonConstants.TRACEICON, traceIcon);
                                TmfProjectElement tmfProject = TmfProjectRegistry.getProject(resource.getProject());
                                if (tmfProject != null) {
                                    for (TmfTraceElement traceElement : tmfProject.getTracesFolder().getTraces()) {
                                        if (traceElement.getName().equals(resource.getName())) {
                                            traceElement.refreshTraceType();
                                            break;
                                        }
                                    }
                                }
                            } catch (CoreException e) {
                                Activator.getDefault().logError("Error importing trace resource " + resource.getName(), e); //$NON-NLS-1$
                            }
                        }
                    }
                }
            }
            return ok;
        }

        MessageDialog.openInformation(getContainer().getShell(), Messages.ImportTraceWizard_Information,
                Messages.ImportTraceWizard_SelectTraceNoneSelected);
        return false;
    }

    private boolean importResources(String rootDirectory, Map<String, File> fileSystemObjects) {

        // Determine the sorted canonical list of items to import
        List<File> fileList = new ArrayList<File>();
        for (Entry<String, File> entry : fileSystemObjects.entrySet()) {
            fileList.add(entry.getValue());
        }
        Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                String v1 = o1.getAbsolutePath() + File.separatorChar;
                String v2 = o2.getAbsolutePath() + File.separatorChar;
                return v1.compareTo(v2);
            }
        });

        // Perform a distinct import operation for everything that has the same prefix
        // (distinct prefixes correspond to traces - we don't want to re-create parent structures)
        boolean ok = true;
        boolean isLinked = createLinksInWorkspaceButton.getSelection();
        for (int i = 0; i < fileList.size(); i++) {
            File resource = fileList.get(i);
            File parentFolder = new File(resource.getParent());

            List<File> subList = new ArrayList<File>();
            subList.add(resource);
            if (resource.isDirectory()) {
                String prefix = resource.getAbsolutePath() + File.separatorChar;
                boolean hasSamePrefix = true;
                for (int j = i + 1; j < fileList.size() && hasSamePrefix; j++) {
                    File res = fileList.get(j);
                    hasSamePrefix = res.getAbsolutePath().startsWith(prefix);
                    if (hasSamePrefix) {
                        // Import children individually if not linked
                        if (!isLinked) {
                            subList.add(res);
                        }
                        i = j;
                    }
                }
            }

            // Perform the import operation for this subset
            FileSystemStructureProvider fileSystemStructureProvider = FileSystemStructureProvider.INSTANCE;
            ImportOperation operation = new ImportOperation(getContainerFullPath(), parentFolder, fileSystemStructureProvider, this,
                    subList);
            operation.setContext(getShell());
            ok = executeImportOperation(operation);
        }

        return ok;
    }

    private boolean executeImportOperation(ImportOperation op) {
        initializeOperation(op);

        try {
            getContainer().run(true, true, op);
        } catch (InterruptedException e) {
            return false;
        } catch (InvocationTargetException e) {
            displayErrorDialog(e.getTargetException());
            return false;
        }

        IStatus status = op.getStatus();
        if (!status.isOK()) {
            ErrorDialog.openError(getContainer().getShell(), Messages.ImportTraceWizard_ImportProblem, null, status);
            return false;
        }

        return true;
    }

    private void initializeOperation(ImportOperation op) {
        op.setCreateContainerStructure(false);
        op.setOverwriteResources(overwriteExistingResourcesCheckbox.getSelection());
        op.setCreateLinks(createLinksInWorkspaceButton.getSelection());
        op.setVirtualFolders(false);
    }

}

Back to the top