tmf: Update copyright headers in tmf.ui
[deliverable/tracecompass.git] / org.eclipse.linuxtools.tmf.ui / src / org / eclipse / linuxtools / tmf / ui / project / wizards / ImportTraceWizardPage.java
1 /*******************************************************************************
2 * Copyright (c) 2009, 2013 Ericsson and others.
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Francois Chouinard - Initial API and implementation
11 * Francois Chouinard - Got rid of dependency on internal platform class
12 * Francois Chouinard - Complete re-design
13 * Anna Dushistova(Montavista) - [383047] NPE while importing a CFT trace
14 *******************************************************************************/
15
16 package org.eclipse.linuxtools.tmf.ui.project.wizards;
17
18 import java.io.File;
19 import java.io.IOException;
20 import java.lang.reflect.InvocationTargetException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30
31 import org.eclipse.core.resources.IContainer;
32 import org.eclipse.core.resources.IFolder;
33 import org.eclipse.core.resources.IProject;
34 import org.eclipse.core.resources.IResource;
35 import org.eclipse.core.resources.ResourcesPlugin;
36 import org.eclipse.core.runtime.CoreException;
37 import org.eclipse.core.runtime.IConfigurationElement;
38 import org.eclipse.core.runtime.IPath;
39 import org.eclipse.core.runtime.IStatus;
40 import org.eclipse.core.runtime.Path;
41 import org.eclipse.core.runtime.Platform;
42 import org.eclipse.jface.dialogs.ErrorDialog;
43 import org.eclipse.jface.dialogs.MessageDialog;
44 import org.eclipse.jface.viewers.CheckStateChangedEvent;
45 import org.eclipse.jface.viewers.CheckboxTreeViewer;
46 import org.eclipse.jface.viewers.ICheckStateListener;
47 import org.eclipse.jface.viewers.IStructuredSelection;
48 import org.eclipse.jface.viewers.ITreeContentProvider;
49 import org.eclipse.linuxtools.internal.tmf.ui.Activator;
50 import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTrace;
51 import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomTxtTraceDefinition;
52 import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTrace;
53 import org.eclipse.linuxtools.internal.tmf.ui.parsers.custom.CustomXmlTraceDefinition;
54 import org.eclipse.linuxtools.tmf.core.TmfCommonConstants;
55 import org.eclipse.linuxtools.tmf.core.TmfProjectNature;
56 import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
57 import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectElement;
58 import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectRegistry;
59 import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceElement;
60 import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceFolder;
61 import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceType;
62 import org.eclipse.swt.SWT;
63 import org.eclipse.swt.custom.BusyIndicator;
64 import org.eclipse.swt.events.FocusEvent;
65 import org.eclipse.swt.events.FocusListener;
66 import org.eclipse.swt.events.KeyEvent;
67 import org.eclipse.swt.events.KeyListener;
68 import org.eclipse.swt.events.SelectionAdapter;
69 import org.eclipse.swt.events.SelectionEvent;
70 import org.eclipse.swt.events.SelectionListener;
71 import org.eclipse.swt.layout.GridData;
72 import org.eclipse.swt.layout.GridLayout;
73 import org.eclipse.swt.widgets.Button;
74 import org.eclipse.swt.widgets.Combo;
75 import org.eclipse.swt.widgets.Composite;
76 import org.eclipse.swt.widgets.DirectoryDialog;
77 import org.eclipse.swt.widgets.Event;
78 import org.eclipse.swt.widgets.Group;
79 import org.eclipse.swt.widgets.Label;
80 import org.eclipse.ui.IWorkbench;
81 import org.eclipse.ui.dialogs.FileSystemElement;
82 import org.eclipse.ui.dialogs.WizardResourceImportPage;
83 import org.eclipse.ui.model.WorkbenchContentProvider;
84 import org.eclipse.ui.model.WorkbenchLabelProvider;
85 import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
86 import org.eclipse.ui.wizards.datatransfer.IImportStructureProvider;
87 import org.eclipse.ui.wizards.datatransfer.ImportOperation;
88
89 /**
90 * A variant of the standard resource import wizard with the following changes:
91 * <ul>
92 * <li>A folder/file combined checkbox tree viewer to select traces
93 * <li>Cherry-picking of traces in the file structure without re-creating the file hierarchy
94 * <li>A trace types dropbox for optional characterization
95 * </ul>
96 * For our purpose, a trace can either be a single file or a whole directory sub-tree, whichever is reached first from
97 * the root directory.
98 * <p>
99 *
100 * @version 1.0
101 * @author Francois Chouinard
102 */
103 public class ImportTraceWizardPage extends WizardResourceImportPage {
104
105 // ------------------------------------------------------------------------
106 // Constants
107 // ------------------------------------------------------------------------
108
109 static private final String IMPORT_WIZARD_PAGE = "ImportTraceWizardPage"; //$NON-NLS-1$
110 private static final String CUSTOM_TXT_CATEGORY = "Custom Text"; //$NON-NLS-1$
111 private static final String CUSTOM_XML_CATEGORY = "Custom XML"; //$NON-NLS-1$
112 private static final String DEFAULT_TRACE_ICON_PATH = "icons/elcl16/trace.gif"; //$NON-NLS-1$
113
114 // ------------------------------------------------------------------------
115 // Attributes
116 // ------------------------------------------------------------------------
117
118 // Folder navigation start point (saved between invocations)
119 private static String fRootDirectory = null;
120
121 // Navigation folder content viewer and selector
122 private CheckboxTreeViewer fFolderViewer;
123
124 // Parent tracing project
125 private IProject fProject;
126
127 // Target import directory ('Traces' folder)
128 private IFolder fTargetFolder;
129
130 // ------------------------------------------------------------------------
131 // Constructors
132 // ------------------------------------------------------------------------
133
134 /**
135 * Constructor.
136 * Creates the trace wizard page.
137 *
138 * @param name The name of the page.
139 * @param selection The current selection
140 */
141 protected ImportTraceWizardPage(String name, IStructuredSelection selection) {
142 super(name, selection);
143 }
144
145 /**
146 * Constructor
147 * @param workbench The workbench reference.
148 * @param selection The current selection
149 */
150 public ImportTraceWizardPage(IWorkbench workbench, IStructuredSelection selection) {
151 this(IMPORT_WIZARD_PAGE, selection);
152 setTitle(Messages.ImportTraceWizard_FileSystemTitle);
153 setDescription(Messages.ImportTraceWizard_ImportTrace);
154
155 // Locate the target trace folder
156 IFolder traceFolder = null;
157 Object element = selection.getFirstElement();
158
159 if (element instanceof TmfTraceFolder) {
160 TmfTraceFolder tmfTraceFolder = (TmfTraceFolder) element;
161 fProject = tmfTraceFolder.getProject().getResource();
162 traceFolder = tmfTraceFolder.getResource();
163 } else if (element instanceof IProject) {
164 IProject project = (IProject) element;
165 try {
166 if (project.hasNature(TmfProjectNature.ID)) {
167 traceFolder = (IFolder) project.findMember(TmfTraceFolder.TRACE_FOLDER_NAME);
168 }
169 } catch (CoreException e) {
170 }
171 }
172
173 // Set the target trace folder
174 if (traceFolder != null) {
175 fTargetFolder = traceFolder;
176 String path = traceFolder.getFullPath().toOSString();
177 setContainerFieldValue(path);
178 }
179 }
180
181 // ------------------------------------------------------------------------
182 // WizardResourceImportPage
183 // ------------------------------------------------------------------------
184 /*
185 * (non-Javadoc)
186 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createControl(org.eclipse.swt.widgets.Composite)
187 */
188 @Override
189 public void createControl(Composite parent) {
190 super.createControl(parent);
191 // Restore last directory if applicable
192 if (fRootDirectory != null) {
193 directoryNameField.setText(fRootDirectory);
194 updateFromSourceField();
195 }
196 }
197
198 /*
199 * (non-Javadoc)
200 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createSourceGroup(org.eclipse.swt.widgets.Composite)
201 */
202 @Override
203 protected void createSourceGroup(Composite parent) {
204 createDirectorySelectionGroup(parent);
205 createFileSelectionGroup(parent);
206 createTraceTypeGroup(parent);
207 validateSourceGroup();
208 }
209
210 /*
211 * (non-Javadoc)
212 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#createFileSelectionGroup(org.eclipse.swt.widgets.Composite)
213 */
214 @Override
215 protected void createFileSelectionGroup(Composite parent) {
216
217 // This Composite is only used for widget alignment purposes
218 Composite composite = new Composite(parent, SWT.NONE);
219 composite.setFont(parent.getFont());
220 GridLayout layout = new GridLayout();
221 composite.setLayout(layout);
222 composite.setLayoutData(new GridData(GridData.FILL_BOTH));
223
224 final int PREFERRED_LIST_HEIGHT = 150;
225
226 fFolderViewer = new CheckboxTreeViewer(composite, SWT.BORDER);
227 GridData data = new GridData(GridData.FILL_BOTH);
228 data.heightHint = PREFERRED_LIST_HEIGHT;
229 fFolderViewer.getTree().setLayoutData(data);
230 fFolderViewer.getTree().setFont(parent.getFont());
231
232 fFolderViewer.setContentProvider(getFileProvider());
233 fFolderViewer.setLabelProvider(new WorkbenchLabelProvider());
234 fFolderViewer.addCheckStateListener(new ICheckStateListener() {
235 @Override
236 public void checkStateChanged(CheckStateChangedEvent event) {
237 Object elem = event.getElement();
238 if (elem instanceof FileSystemElement) {
239 FileSystemElement element = (FileSystemElement) elem;
240 if (fFolderViewer.getGrayed(element)) {
241 fFolderViewer.setSubtreeChecked(element, false);
242 fFolderViewer.setGrayed(element, false);
243 } else if (event.getChecked()) {
244 fFolderViewer.setSubtreeChecked(event.getElement(), true);
245 } else {
246 fFolderViewer.setParentsGrayed(element, true);
247 if (!element.isDirectory()) {
248 fFolderViewer.setGrayed(element, false);
249 }
250 }
251 updateWidgetEnablements();
252 }
253 }
254 });
255 }
256
257 /*
258 * (non-Javadoc)
259 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getFolderProvider()
260 */
261 @Override
262 protected ITreeContentProvider getFolderProvider() {
263 return null;
264 }
265
266 /*
267 * (non-Javadoc)
268 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getFileProvider()
269 */
270 @Override
271 protected ITreeContentProvider getFileProvider() {
272 return new WorkbenchContentProvider() {
273 @Override
274 public Object[] getChildren(Object o) {
275 if (o instanceof FileSystemElement) {
276 FileSystemElement element = (FileSystemElement) o;
277 populateChildren(element);
278 // For our purpose, we need folders + files
279 Object[] folders = element.getFolders().getChildren();
280 Object[] files = element.getFiles().getChildren();
281
282 List<Object> result = new LinkedList<Object>();
283 for (Object folder : folders) {
284 result.add(folder);
285 }
286 for (Object file : files) {
287 result.add(file);
288 }
289
290 return result.toArray();
291 }
292 return new Object[0];
293 }
294 };
295 }
296
297 private static void populateChildren(FileSystemElement parent) {
298 // Do not re-populate if the job was done already...
299 FileSystemStructureProvider provider = FileSystemStructureProvider.INSTANCE;
300 if (parent.getFolders().size() == 0 && parent.getFiles().size() == 0) {
301 Object fileSystemObject = parent.getFileSystemObject();
302 List<?> children = provider.getChildren(fileSystemObject);
303 if (children != null) {
304 Iterator<?> iterator = children.iterator();
305 while (iterator.hasNext()) {
306 Object child = iterator.next();
307 String label = provider.getLabel(child);
308 FileSystemElement element = new FileSystemElement(label, parent, provider.isFolder(child));
309 element.setFileSystemObject(child);
310 }
311 }
312 }
313 }
314
315 /*
316 * (non-Javadoc)
317 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#getSelectedResources()
318 */
319 @Override
320 protected List<FileSystemElement> getSelectedResources() {
321 List<FileSystemElement> resources = new ArrayList<FileSystemElement>();
322 Object[] checkedItems = fFolderViewer.getCheckedElements();
323 for (Object item : checkedItems) {
324 if (item instanceof FileSystemElement && !fFolderViewer.getGrayed(item)) {
325 resources.add((FileSystemElement) item);
326 }
327 }
328 return resources;
329 }
330
331 // ------------------------------------------------------------------------
332 // Directory Selection Group (forked WizardFileSystemResourceImportPage1)
333 // ------------------------------------------------------------------------
334
335 /**
336 * The directory name field
337 */
338 protected Combo directoryNameField;
339 /**
340 * The directory browse button.
341 */
342 protected Button directoryBrowseButton;
343 private boolean entryChanged = false;
344
345 /**
346 * creates the directory selection group.
347 * @param parent the parent composite
348 */
349 protected void createDirectorySelectionGroup(Composite parent) {
350
351 Composite directoryContainerGroup = new Composite(parent, SWT.NONE);
352 GridLayout layout = new GridLayout();
353 layout.numColumns = 3;
354 directoryContainerGroup.setLayout(layout);
355 directoryContainerGroup.setFont(parent.getFont());
356 directoryContainerGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
357
358 // Label ("Trace directory:")
359 Label groupLabel = new Label(directoryContainerGroup, SWT.NONE);
360 groupLabel.setText(Messages.ImportTraceWizard_DirectoryLocation);
361 groupLabel.setFont(parent.getFont());
362
363 // Directory name entry field
364 directoryNameField = new Combo(directoryContainerGroup, SWT.BORDER);
365 GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
366 data.widthHint = SIZING_TEXT_FIELD_WIDTH;
367 directoryNameField.setLayoutData(data);
368 directoryNameField.setFont(parent.getFont());
369
370 directoryNameField.addSelectionListener(new SelectionAdapter() {
371 @Override
372 public void widgetSelected(SelectionEvent e) {
373 updateFromSourceField();
374 }
375 });
376
377 directoryNameField.addKeyListener(new KeyListener() {
378 @Override
379 public void keyPressed(KeyEvent e) {
380 // If there has been a key pressed then mark as dirty
381 entryChanged = true;
382 if (e.character == SWT.CR) { // Windows...
383 entryChanged = false;
384 updateFromSourceField();
385 }
386 }
387
388 @Override
389 public void keyReleased(KeyEvent e) {
390 }
391 });
392
393 directoryNameField.addFocusListener(new FocusListener() {
394 @Override
395 public void focusGained(FocusEvent e) {
396 // Do nothing when getting focus
397 }
398
399 @Override
400 public void focusLost(FocusEvent e) {
401 // Clear the flag to prevent constant update
402 if (entryChanged) {
403 entryChanged = false;
404 updateFromSourceField();
405 }
406 }
407 });
408
409 // Browse button
410 directoryBrowseButton = new Button(directoryContainerGroup, SWT.PUSH);
411 directoryBrowseButton.setText(Messages.ImportTraceWizard_BrowseButton);
412 directoryBrowseButton.addListener(SWT.Selection, this);
413 directoryBrowseButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
414 directoryBrowseButton.setFont(parent.getFont());
415 setButtonLayoutData(directoryBrowseButton);
416 }
417
418 // ------------------------------------------------------------------------
419 // Browse for the source directory
420 // ------------------------------------------------------------------------
421
422 /*
423 * (non-Javadoc)
424 * @see org.eclipse.ui.dialogs.WizardResourceImportPage#handleEvent(org.eclipse.swt.widgets.Event)
425 */
426 @Override
427 public void handleEvent(Event event) {
428 if (event.widget == directoryBrowseButton) {
429 handleSourceDirectoryBrowseButtonPressed();
430 }
431 super.handleEvent(event);
432 }
433
434 /**
435 * Handle the button pressed event
436 */
437 protected void handleSourceDirectoryBrowseButtonPressed() {
438 String currentSource = directoryNameField.getText();
439 DirectoryDialog dialog = new DirectoryDialog(directoryNameField.getShell(), SWT.SAVE | SWT.SHEET);
440 dialog.setText(Messages.ImportTraceWizard_SelectTraceDirectoryTitle);
441 dialog.setMessage(Messages.ImportTraceWizard_SelectTraceDirectoryMessage);
442 dialog.setFilterPath(getSourceDirectoryName(currentSource));
443
444 String selectedDirectory = dialog.open();
445 if (selectedDirectory != null) {
446 // Just quit if the directory is not valid
447 if ((getSourceDirectory(selectedDirectory) == null) || selectedDirectory.equals(currentSource)) {
448 return;
449 }
450 // If it is valid then proceed to populate
451 setErrorMessage(null);
452 setSourceName(selectedDirectory);
453 }
454 }
455
456 private File getSourceDirectory() {
457 return getSourceDirectory(directoryNameField.getText());
458 }
459
460 private static File getSourceDirectory(String path) {
461 File sourceDirectory = new File(getSourceDirectoryName(path));
462 if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
463 return null;
464 }
465
466 return sourceDirectory;
467 }
468
469 private static String getSourceDirectoryName(String sourceName) {
470 IPath result = new Path(sourceName.trim());
471 if (result.getDevice() != null && result.segmentCount() == 0) {
472 result = result.addTrailingSeparator();
473 } else {
474 result = result.removeTrailingSeparator();
475 }
476 return result.toOSString();
477 }
478
479 private String getSourceDirectoryName() {
480 return getSourceDirectoryName(directoryNameField.getText());
481 }
482
483 private void updateFromSourceField() {
484 setSourceName(directoryNameField.getText());
485 updateWidgetEnablements();
486 }
487
488 private void setSourceName(String path) {
489 if (path.length() > 0) {
490 String[] currentItems = directoryNameField.getItems();
491 int selectionIndex = -1;
492 for (int i = 0; i < currentItems.length; i++) {
493 if (currentItems[i].equals(path)) {
494 selectionIndex = i;
495 }
496 }
497 if (selectionIndex < 0) {
498 int oldLength = currentItems.length;
499 String[] newItems = new String[oldLength + 1];
500 System.arraycopy(currentItems, 0, newItems, 0, oldLength);
501 newItems[oldLength] = path;
502 directoryNameField.setItems(newItems);
503 selectionIndex = oldLength;
504 }
505 directoryNameField.select(selectionIndex);
506 }
507 resetSelection();
508 }
509
510 // ------------------------------------------------------------------------
511 // File Selection Group (forked WizardFileSystemResourceImportPage1)
512 // ------------------------------------------------------------------------
513
514 private void resetSelection() {
515 FileSystemElement root = getFileSystemTree();
516 populateListViewer(root);
517 }
518
519 private void populateListViewer(final Object treeElement) {
520 fFolderViewer.setInput(treeElement);
521 }
522
523 private FileSystemElement getFileSystemTree() {
524 File sourceDirectory = getSourceDirectory();
525 if (sourceDirectory == null) {
526 return null;
527 }
528 return selectFiles(sourceDirectory, FileSystemStructureProvider.INSTANCE);
529 }
530
531 private FileSystemElement selectFiles(final Object rootFileSystemObject, final IImportStructureProvider structureProvider) {
532 final FileSystemElement[] results = new FileSystemElement[1];
533 BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
534 @Override
535 public void run() {
536 // Create the root element from the supplied file system object
537 results[0] = createRootElement(rootFileSystemObject, structureProvider);
538 }
539 });
540 return results[0];
541 }
542
543 private static FileSystemElement createRootElement(Object fileSystemObject,
544 IImportStructureProvider provider) {
545
546 boolean isContainer = provider.isFolder(fileSystemObject);
547 String elementLabel = provider.getLabel(fileSystemObject);
548
549 FileSystemElement dummyParent = new FileSystemElement("", null, true); //$NON-NLS-1$
550 FileSystemElement element = new FileSystemElement(elementLabel, dummyParent, isContainer);
551 element.setFileSystemObject(fileSystemObject);
552
553 // Get the first level
554 populateChildren(element);
555
556 return dummyParent;
557 }
558
559 // ------------------------------------------------------------------------
560 // Trace Type Group
561 // ------------------------------------------------------------------------
562
563 private Combo fTraceTypes;
564
565 private final void createTraceTypeGroup(Composite parent) {
566 Composite composite = new Composite(parent, SWT.NONE);
567 GridLayout layout = new GridLayout();
568 layout.numColumns = 3;
569 layout.makeColumnsEqualWidth = false;
570 composite.setLayout(layout);
571 composite.setFont(parent.getFont());
572 GridData buttonData = new GridData(SWT.FILL, SWT.FILL, true, false);
573 composite.setLayoutData(buttonData);
574
575 // Trace type label ("Trace Type:")
576 Label typeLabel = new Label(composite, SWT.NONE);
577 typeLabel.setText(Messages.ImportTraceWizard_TraceType);
578 typeLabel.setFont(parent.getFont());
579
580 // Trace type combo
581 fTraceTypes = new Combo(composite, SWT.BORDER);
582 GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
583 fTraceTypes.setLayoutData(data);
584 fTraceTypes.setFont(parent.getFont());
585
586 String[] availableTraceTypes = getAvailableTraceTypes();
587 fTraceTypes.setItems(availableTraceTypes);
588
589 fTraceTypes.addSelectionListener(new SelectionListener() {
590 @Override
591 public void widgetSelected(SelectionEvent e) {
592 updateWidgetEnablements();
593 }
594
595 @Override
596 public void widgetDefaultSelected(SelectionEvent e) {
597 }
598 });
599 }
600
601 // The mapping of available trace type IDs to their corresponding configuration element
602 private final Map<String, IConfigurationElement> fTraceTypeAttributes = new HashMap<String, IConfigurationElement>();
603 private final Map<String, IConfigurationElement> fTraceCategories = new HashMap<String, IConfigurationElement>();
604 private final Map<String, IConfigurationElement> fTraceAttributes = new HashMap<String, IConfigurationElement>();
605
606 private String[] getAvailableTraceTypes() {
607
608 // Populate the Categories and Trace Types
609 IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(TmfTraceType.TMF_TRACE_TYPE_ID);
610 for (IConfigurationElement ce : config) {
611 String elementName = ce.getName();
612 if (elementName.equals(TmfTraceType.TYPE_ELEM)) {
613 String traceTypeId = ce.getAttribute(TmfTraceType.ID_ATTR);
614 fTraceTypeAttributes.put(traceTypeId, ce);
615 } else if (elementName.equals(TmfTraceType.CATEGORY_ELEM)) {
616 String categoryId = ce.getAttribute(TmfTraceType.ID_ATTR);
617 fTraceCategories.put(categoryId, ce);
618 }
619 }
620
621 // Generate the list of Category:TraceType to populate the ComboBox
622 List<String> traceTypes = new ArrayList<String>();
623 for (String typeId : fTraceTypeAttributes.keySet()) {
624 IConfigurationElement ce = fTraceTypeAttributes.get(typeId);
625 String traceTypeName = getCategory(ce) + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR); //$NON-NLS-1$
626 fTraceAttributes.put(traceTypeName, ce);
627 traceTypes.add(traceTypeName);
628 }
629 Collections.sort(traceTypes);
630
631 // add the custom trace types
632 for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) {
633 String traceTypeName = CUSTOM_TXT_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$
634 traceTypes.add(traceTypeName);
635 }
636 for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) {
637 String traceTypeName = CUSTOM_XML_CATEGORY + " : " + def.definitionName; //$NON-NLS-1$
638 traceTypes.add(traceTypeName);
639 }
640
641 // Format result
642 return traceTypes.toArray(new String[traceTypes.size()]);
643 }
644
645 private String getCategory(IConfigurationElement ce) {
646 String categoryId = ce.getAttribute(TmfTraceType.CATEGORY_ATTR);
647 if (categoryId != null) {
648 IConfigurationElement category = fTraceCategories.get(categoryId);
649 if (category != null && !category.getName().equals("")) { //$NON-NLS-1$
650 return category.getAttribute(TmfTraceType.NAME_ATTR);
651 }
652 }
653 return "[no category]"; //$NON-NLS-1$
654 }
655
656 // ------------------------------------------------------------------------
657 // Options
658 // ------------------------------------------------------------------------
659
660 private Button overwriteExistingResourcesCheckbox;
661 private Button createLinksInWorkspaceButton;
662
663 /*
664 * (non-Javadoc)
665 * @see org.eclipse.ui.dialogs.WizardDataTransferPage#createOptionsGroupButtons(org.eclipse.swt.widgets.Group)
666 */
667 @Override
668 protected void createOptionsGroupButtons(Group optionsGroup) {
669
670 // Overwrite checkbox
671 overwriteExistingResourcesCheckbox = new Button(optionsGroup, SWT.CHECK);
672 overwriteExistingResourcesCheckbox.setFont(optionsGroup.getFont());
673 overwriteExistingResourcesCheckbox.setText(Messages.ImportTraceWizard_OverwriteExistingTrace);
674 overwriteExistingResourcesCheckbox.setSelection(false);
675
676 // Create links checkbox
677 createLinksInWorkspaceButton = new Button(optionsGroup, SWT.CHECK);
678 createLinksInWorkspaceButton.setFont(optionsGroup.getFont());
679 createLinksInWorkspaceButton.setText(Messages.ImportTraceWizard_CreateLinksInWorkspace);
680 createLinksInWorkspaceButton.setSelection(true);
681
682 createLinksInWorkspaceButton.addSelectionListener(new SelectionAdapter() {
683 @Override
684 public void widgetSelected(SelectionEvent e) {
685 updateWidgetEnablements();
686 }
687 });
688
689 updateWidgetEnablements();
690 }
691
692 // ------------------------------------------------------------------------
693 // Determine if the finish button can be enabled
694 // ------------------------------------------------------------------------
695
696 /*
697 * (non-Javadoc)
698 * @see org.eclipse.ui.dialogs.WizardDataTransferPage#validateSourceGroup()
699 */
700 @Override
701 public boolean validateSourceGroup() {
702
703 File sourceDirectory = getSourceDirectory();
704 if (sourceDirectory == null) {
705 setMessage(Messages.ImportTraceWizard_SelectTraceSourceEmpty);
706 return false;
707 }
708
709 if (sourceConflictsWithDestination(new Path(sourceDirectory.getPath()))) {
710 setMessage(null);
711 setErrorMessage(getSourceConflictMessage());
712 return false;
713 }
714
715 List<FileSystemElement> resourcesToImport = getSelectedResources();
716 if (resourcesToImport.size() == 0) {
717 setMessage(null);
718 setErrorMessage(Messages.ImportTraceWizard_SelectTraceNoneSelected);
719 return false;
720 }
721
722 IContainer container = getSpecifiedContainer();
723 if (container != null && container.isVirtual()) {
724 if (Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, ResourcesPlugin.PREF_DISABLE_LINKING, false, null)) {
725 setMessage(null);
726 setErrorMessage(Messages.ImportTraceWizard_CannotImportFilesUnderAVirtualFolder);
727 return false;
728 }
729 if (createLinksInWorkspaceButton == null || !createLinksInWorkspaceButton.getSelection()) {
730 setMessage(null);
731 setErrorMessage(Messages.ImportTraceWizard_HaveToCreateLinksUnderAVirtualFolder);
732 return false;
733 }
734 }
735
736 // Perform trace validation
737 String traceTypeName = fTraceTypes.getText();
738 if (traceTypeName != null && !"".equals(traceTypeName) && //$NON-NLS-1$
739 !traceTypeName.startsWith(CUSTOM_TXT_CATEGORY) && !traceTypeName.startsWith(CUSTOM_XML_CATEGORY)) {
740
741 List<File> traces = isolateTraces();
742 for (File trace : traces) {
743 ITmfTrace tmfTrace = null;
744 try {
745 IConfigurationElement ce = fTraceAttributes.get(traceTypeName);
746 tmfTrace = (ITmfTrace) ce.createExecutableExtension(TmfTraceType.TRACE_TYPE_ATTR);
747 if (tmfTrace != null && !tmfTrace.validate(fProject, trace.getAbsolutePath())) {
748 setMessage(null);
749 setErrorMessage(Messages.ImportTraceWizard_TraceValidationFailed);
750 tmfTrace.dispose();
751 return false;
752 }
753 } catch (CoreException e) {
754 } finally {
755 if (tmfTrace != null) {
756 tmfTrace.dispose();
757 }
758 }
759 }
760 }
761
762 setErrorMessage(null);
763 return true;
764 }
765
766 private List<File> isolateTraces() {
767
768 List<File> traces = new ArrayList<File>();
769
770 // Get the selection
771 List<FileSystemElement> selectedResources = getSelectedResources();
772 Iterator<FileSystemElement> resources = selectedResources.iterator();
773
774 // Get the sorted list of unique entries
775 Map<String, File> fileSystemObjects = new HashMap<String, File>();
776 while (resources.hasNext()) {
777 File resource = (File) resources.next().getFileSystemObject();
778 String key = resource.getAbsolutePath();
779 fileSystemObjects.put(key, resource);
780 }
781 List<String> files = new ArrayList<String>(fileSystemObjects.keySet());
782 Collections.sort(files);
783
784 // After sorting, traces correspond to the unique prefixes
785 String prefix = null;
786 for (int i = 0; i < files.size(); i++) {
787 File file = fileSystemObjects.get(files.get(i));
788 String name = file.getAbsolutePath();
789 if (prefix == null || !name.startsWith(prefix)) {
790 prefix = name; // new prefix
791 traces.add(file);
792 }
793 }
794
795 return traces;
796 }
797
798 // ------------------------------------------------------------------------
799 // Import the trace(s)
800 // ------------------------------------------------------------------------
801
802 /**
803 * Finish the import.
804 * @return <code>true</code> if successful else false
805 */
806 public boolean finish() {
807 // Ensure source is valid
808 File sourceDir = new File(getSourceDirectoryName());
809 if (!sourceDir.isDirectory()) {
810 setErrorMessage(Messages.ImportTraceWizard_InvalidTraceDirectory);
811 return false;
812 }
813
814 try {
815 sourceDir.getCanonicalPath();
816 } catch (IOException e) {
817 MessageDialog.openInformation(getContainer().getShell(), Messages.ImportTraceWizard_Information,
818 Messages.ImportTraceWizard_InvalidTraceDirectory);
819 return false;
820 }
821
822 // Save directory for next import operation
823 fRootDirectory = getSourceDirectoryName();
824
825 List<FileSystemElement> selectedResources = getSelectedResources();
826 Iterator<FileSystemElement> resources = selectedResources.iterator();
827
828 // Use a map to end up with unique resources (getSelectedResources() can return duplicates)
829 Map<String, File> fileSystemObjects = new HashMap<String, File>();
830 while (resources.hasNext()) {
831 File file = (File) resources.next().getFileSystemObject();
832 String key = file.getAbsolutePath();
833 fileSystemObjects.put(key, file);
834 }
835
836 if (fileSystemObjects.size() > 0) {
837 boolean ok = importResources(fileSystemObjects);
838 String traceBundle = null;
839 String traceTypeId = null;
840 String traceIcon = null;
841 String traceType = fTraceTypes.getText();
842 boolean traceTypeOK = false;
843 if (traceType.startsWith(CUSTOM_TXT_CATEGORY)) {
844 for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) {
845 if (traceType.equals(CUSTOM_TXT_CATEGORY + " : " + def.definitionName)) { //$NON-NLS-1$
846 traceTypeOK = true;
847 traceBundle = Activator.getDefault().getBundle().getSymbolicName();
848 traceTypeId = CustomTxtTrace.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$
849 traceIcon = DEFAULT_TRACE_ICON_PATH;
850 break;
851 }
852 }
853 } else if (traceType.startsWith(CUSTOM_XML_CATEGORY)) {
854 for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) {
855 if (traceType.equals(CUSTOM_XML_CATEGORY + " : " + def.definitionName)) { //$NON-NLS-1$
856 traceTypeOK = true;
857 traceBundle = Activator.getDefault().getBundle().getSymbolicName();
858 traceTypeId = CustomXmlTrace.class.getCanonicalName() + ":" + def.definitionName; //$NON-NLS-1$
859 traceIcon = DEFAULT_TRACE_ICON_PATH;
860 break;
861 }
862 }
863 } else {
864 IConfigurationElement ce = fTraceAttributes.get(traceType);
865 if (ce != null) {
866 traceTypeOK = true;
867 traceBundle = ce.getContributor().getName();
868 traceTypeId = ce.getAttribute(TmfTraceType.ID_ATTR);
869 traceIcon = ce.getAttribute(TmfTraceType.ICON_ATTR);
870 }
871 }
872 if (ok && traceTypeOK && !traceType.equals("")) { //$NON-NLS-1$
873 // Tag the selected traces with their type
874 List<String> files = new ArrayList<String>(fileSystemObjects.keySet());
875 Collections.sort(files, new Comparator<String>() {
876 @Override
877 public int compare(String o1, String o2) {
878 String v1 = o1 + File.separatorChar;
879 String v2 = o2 + File.separatorChar;
880 return v1.compareTo(v2);
881 }
882 });
883 // After sorting, traces correspond to the unique prefixes
884 String prefix = null;
885 for (int i = 0; i < files.size(); i++) {
886 File file = fileSystemObjects.get(files.get(i));
887 String name = file.getAbsolutePath() + File.separatorChar;
888 if (fTargetFolder != null && (prefix == null || !name.startsWith(prefix))) {
889 prefix = name; // new prefix
890 IResource resource = fTargetFolder.findMember(file.getName());
891 if (resource != null) {
892 try {
893 // Set the trace properties for this resource
894 resource.setPersistentProperty(TmfCommonConstants.TRACEBUNDLE, traceBundle);
895 resource.setPersistentProperty(TmfCommonConstants.TRACETYPE, traceTypeId);
896 resource.setPersistentProperty(TmfCommonConstants.TRACEICON, traceIcon);
897 TmfProjectElement tmfProject = TmfProjectRegistry.getProject(resource.getProject());
898 if (tmfProject != null) {
899 for (TmfTraceElement traceElement : tmfProject.getTracesFolder().getTraces()) {
900 if (traceElement.getName().equals(resource.getName())) {
901 traceElement.refreshTraceType();
902 break;
903 }
904 }
905 }
906 } catch (CoreException e) {
907 Activator.getDefault().logError("Error importing trace resource " + resource.getName(), e); //$NON-NLS-1$
908 }
909 }
910 }
911 }
912 }
913 return ok;
914 }
915
916 MessageDialog.openInformation(getContainer().getShell(), Messages.ImportTraceWizard_Information,
917 Messages.ImportTraceWizard_SelectTraceNoneSelected);
918 return false;
919 }
920
921 private boolean importResources(Map<String, File> fileSystemObjects) {
922
923 // Determine the sorted canonical list of items to import
924 List<File> fileList = new ArrayList<File>();
925 for (Entry<String, File> entry : fileSystemObjects.entrySet()) {
926 fileList.add(entry.getValue());
927 }
928 Collections.sort(fileList, new Comparator<File>() {
929 @Override
930 public int compare(File o1, File o2) {
931 String v1 = o1.getAbsolutePath() + File.separatorChar;
932 String v2 = o2.getAbsolutePath() + File.separatorChar;
933 return v1.compareTo(v2);
934 }
935 });
936
937 // Perform a distinct import operation for everything that has the same prefix
938 // (distinct prefixes correspond to traces - we don't want to re-create parent structures)
939 boolean ok = true;
940 boolean isLinked = createLinksInWorkspaceButton.getSelection();
941 for (int i = 0; i < fileList.size(); i++) {
942 File resource = fileList.get(i);
943 File parentFolder = new File(resource.getParent());
944
945 List<File> subList = new ArrayList<File>();
946 subList.add(resource);
947 if (resource.isDirectory()) {
948 String prefix = resource.getAbsolutePath() + File.separatorChar;
949 boolean hasSamePrefix = true;
950 for (int j = i + 1; j < fileList.size() && hasSamePrefix; j++) {
951 File res = fileList.get(j);
952 hasSamePrefix = res.getAbsolutePath().startsWith(prefix);
953 if (hasSamePrefix) {
954 // Import children individually if not linked
955 if (!isLinked) {
956 subList.add(res);
957 }
958 i = j;
959 }
960 }
961 }
962
963 // Perform the import operation for this subset
964 FileSystemStructureProvider fileSystemStructureProvider = FileSystemStructureProvider.INSTANCE;
965 ImportOperation operation = new ImportOperation(getContainerFullPath(), parentFolder, fileSystemStructureProvider, this,
966 subList);
967 operation.setContext(getShell());
968 ok = executeImportOperation(operation);
969 }
970
971 return ok;
972 }
973
974 private boolean executeImportOperation(ImportOperation op) {
975 initializeOperation(op);
976
977 try {
978 getContainer().run(true, true, op);
979 } catch (InterruptedException e) {
980 return false;
981 } catch (InvocationTargetException e) {
982 displayErrorDialog(e.getTargetException());
983 return false;
984 }
985
986 IStatus status = op.getStatus();
987 if (!status.isOK()) {
988 ErrorDialog.openError(getContainer().getShell(), Messages.ImportTraceWizard_ImportProblem, null, status);
989 return false;
990 }
991
992 return true;
993 }
994
995 private void initializeOperation(ImportOperation op) {
996 op.setCreateContainerStructure(false);
997 op.setOverwriteResources(overwriteExistingResourcesCheckbox.getSelection());
998 op.setCreateLinks(createLinksInWorkspaceButton.getSelection());
999 op.setVirtualFolders(false);
1000 }
1001
1002 }
This page took 0.053817 seconds and 5 git commands to generate.