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