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