tmf: Import from archive in the standard import wizard
[deliverable/tracecompass.git] / org.eclipse.linuxtools.tmf.ui / src / org / eclipse / linuxtools / internal / tmf / ui / project / wizards / importtrace / ImportTraceWizardPage.java
1 /*******************************************************************************
2 * Copyright (c) 2009, 2014 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 * Matthew Khouzam - Moved out some common functions
15 * Patrick Tasse - Add sorting of file system elements
16 * Bernd Hufmann - Re-design of trace selection and trace validation
17 * Marc-Andre Laperle - Preserve folder structure on import
18 *******************************************************************************/
19
20 package org.eclipse.linuxtools.internal.tmf.ui.project.wizards.importtrace;
21
22 import java.io.File;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.lang.reflect.InvocationTargetException;
26 import java.net.URI;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipException;
35 import java.util.zip.ZipFile;
36
37 import org.eclipse.core.resources.IContainer;
38 import org.eclipse.core.resources.IFolder;
39 import org.eclipse.core.resources.IProject;
40 import org.eclipse.core.resources.IResource;
41 import org.eclipse.core.resources.ResourcesPlugin;
42 import org.eclipse.core.runtime.CoreException;
43 import org.eclipse.core.runtime.IPath;
44 import org.eclipse.core.runtime.IProgressMonitor;
45 import org.eclipse.core.runtime.IStatus;
46 import org.eclipse.core.runtime.NullProgressMonitor;
47 import org.eclipse.core.runtime.Path;
48 import org.eclipse.core.runtime.Platform;
49 import org.eclipse.core.runtime.Status;
50 import org.eclipse.core.runtime.SubMonitor;
51 import org.eclipse.core.runtime.SubProgressMonitor;
52 import org.eclipse.core.runtime.URIUtil;
53 import org.eclipse.jface.dialogs.IDialogSettings;
54 import org.eclipse.jface.dialogs.MessageDialog;
55 import org.eclipse.jface.layout.PixelConverter;
56 import org.eclipse.jface.operation.IRunnableWithProgress;
57 import org.eclipse.jface.operation.ModalContext;
58 import org.eclipse.jface.viewers.CheckStateChangedEvent;
59 import org.eclipse.jface.viewers.ICheckStateListener;
60 import org.eclipse.jface.viewers.IStructuredSelection;
61 import org.eclipse.jface.viewers.ITreeContentProvider;
62 import org.eclipse.linuxtools.internal.tmf.ui.Activator;
63 import org.eclipse.linuxtools.tmf.core.TmfCommonConstants;
64 import org.eclipse.linuxtools.tmf.core.TmfProjectNature;
65 import org.eclipse.linuxtools.tmf.core.project.model.TmfTraceImportException;
66 import org.eclipse.linuxtools.tmf.core.project.model.TmfTraceType;
67 import org.eclipse.linuxtools.tmf.core.project.model.TraceTypeHelper;
68 import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectElement;
69 import org.eclipse.linuxtools.tmf.ui.project.model.TmfProjectRegistry;
70 import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceElement;
71 import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceFolder;
72 import org.eclipse.linuxtools.tmf.ui.project.model.TmfTraceTypeUIUtils;
73 import org.eclipse.linuxtools.tmf.ui.project.model.TmfTracesFolder;
74 import org.eclipse.osgi.util.NLS;
75 import org.eclipse.swt.SWT;
76 import org.eclipse.swt.custom.BusyIndicator;
77 import org.eclipse.swt.events.FocusAdapter;
78 import org.eclipse.swt.events.FocusEvent;
79 import org.eclipse.swt.events.ModifyEvent;
80 import org.eclipse.swt.events.ModifyListener;
81 import org.eclipse.swt.events.SelectionAdapter;
82 import org.eclipse.swt.events.SelectionEvent;
83 import org.eclipse.swt.events.TraverseEvent;
84 import org.eclipse.swt.events.TraverseListener;
85 import org.eclipse.swt.layout.GridData;
86 import org.eclipse.swt.layout.GridLayout;
87 import org.eclipse.swt.widgets.Button;
88 import org.eclipse.swt.widgets.Combo;
89 import org.eclipse.swt.widgets.Composite;
90 import org.eclipse.swt.widgets.DirectoryDialog;
91 import org.eclipse.swt.widgets.Event;
92 import org.eclipse.swt.widgets.FileDialog;
93 import org.eclipse.swt.widgets.Group;
94 import org.eclipse.swt.widgets.Label;
95 import org.eclipse.ui.IWorkbench;
96 import org.eclipse.ui.dialogs.FileSystemElement;
97 import org.eclipse.ui.dialogs.IOverwriteQuery;
98 import org.eclipse.ui.dialogs.WizardResourceImportPage;
99 import org.eclipse.ui.internal.ide.DialogUtil;
100 import org.eclipse.ui.internal.ide.dialogs.IElementFilter;
101 import org.eclipse.ui.internal.wizards.datatransfer.ArchiveFileManipulations;
102 import org.eclipse.ui.internal.wizards.datatransfer.DataTransferMessages;
103 import org.eclipse.ui.internal.wizards.datatransfer.ILeveledImportStructureProvider;
104 import org.eclipse.ui.internal.wizards.datatransfer.TarEntry;
105 import org.eclipse.ui.internal.wizards.datatransfer.TarException;
106 import org.eclipse.ui.internal.wizards.datatransfer.TarFile;
107 import org.eclipse.ui.internal.wizards.datatransfer.TarLeveledStructureProvider;
108 import org.eclipse.ui.internal.wizards.datatransfer.ZipLeveledStructureProvider;
109 import org.eclipse.ui.model.AdaptableList;
110 import org.eclipse.ui.model.WorkbenchContentProvider;
111 import org.eclipse.ui.model.WorkbenchLabelProvider;
112 import org.eclipse.ui.model.WorkbenchViewerComparator;
113 import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
114 import org.eclipse.ui.wizards.datatransfer.IImportStructureProvider;
115 import org.eclipse.ui.wizards.datatransfer.ImportOperation;
116
117 /**
118 * A variant of the standard resource import wizard for importing traces
119 * to given tracing project. If no project or tracing project was selected
120 * the wizard imports it to the default tracing project which is created
121 * if necessary.
122 *
123 * In our case traces could be files or a directory structure. This wizard
124 * supports both cases. It imports traces for a selected trace type or, if
125 * no trace type is selected, it tries to detect the trace type automatically.
126 * However, the automatic detection is a best-effort and cannot guarantee
127 * that the detection is successful. The reason for this is that there might
128 * be multiple trace types that can be assigned to a single trace.
129 *
130 *
131 * @author Francois Chouinard
132 * @since 2.0
133 */
134 @SuppressWarnings("restriction")
135 public class ImportTraceWizardPage extends WizardResourceImportPage {
136
137 // ------------------------------------------------------------------------
138 // Constants
139 // ------------------------------------------------------------------------
140 private static final String IMPORT_WIZARD_PAGE = "ImportTraceWizardPage"; //$NON-NLS-1$
141 private static final String IMPORT_WIZARD_ROOT_DIRECTORY_ID = IMPORT_WIZARD_PAGE + ".import_root_directory_id"; //$NON-NLS-1$
142 private static final String IMPORT_WIZARD_ARCHIVE_FILE_NAME_ID = IMPORT_WIZARD_PAGE + ".import_archive_file_name_id"; //$NON-NLS-1$
143 private static final String IMPORT_WIZARD_IMPORT_UNRECOGNIZED_ID = IMPORT_WIZARD_PAGE + ".import_unrecognized_traces_id"; //$NON-NLS-1$
144 private static final String IMPORT_WIZARD_PRESERVE_FOLDERS_ID = IMPORT_WIZARD_PAGE + ".import_preserve_folders_id"; //$NON-NLS-1$
145 private static final String IMPORT_WIZARD_IMPORT_FROM_DIRECTORY = IMPORT_WIZARD_PAGE + ".import_from_directory"; //$NON-NLS-1$
146 private static final String SEPARATOR = ":"; //$NON-NLS-1$
147 private static final String AUTO_DETECT = Messages.ImportTraceWizard_AutoDetection;
148
149 // constant from WizardArchiveFileResourceImportPage1
150 private static final String[] FILE_IMPORT_MASK = { "*.jar;*.zip;*.tar;*.tar.gz;*.tgz", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
151 private static final String TRACE_IMPORT_TEMP_FOLDER = ".traceImport"; //$NON-NLS-1$
152
153 // ------------------------------------------------------------------------
154 // Attributes
155 // ------------------------------------------------------------------------
156
157 // Target import directory ('Traces' folder)
158 private IFolder fTargetFolder;
159 // Target Trace folder element
160 private TmfTraceFolder fTraceFolderElement;
161 // Flag to handle destination folder change event
162 private Boolean fIsDestinationChanged = false;
163 // Combo box containing trace types
164 private Combo fTraceTypes;
165 // Button to ignore unrecognized traces or not
166 private Button fImportUnrecognizedButton;
167 // Button to overwrite existing resources or not
168 private Button fOverwriteExistingResourcesCheckbox;
169 // Button to link or copy traces to workspace
170 private Button fCreateLinksInWorkspaceButton;
171 // Button to preserve folder structure
172 private Button fPreserveFolderStructureButton;
173 private boolean entryChanged = false;
174 // The import from directory radio button
175 private Button fImportFromDirectoryRadio;
176 // The import from archive radio button
177 private Button fImportFromArchiveRadio;
178 // Flag to remember the "create links" checkbox when it gets disabled by
179 // the import from archive radio button
180 private Boolean fPreviousCreateLinksValue = true;
181 /** The archive name field */
182 private Combo fArchiveNameField;
183 /** The archive browse button. */
184 protected Button fArchiveBrowseButton;
185
186 /** The directory name field */
187 protected Combo directoryNameField;
188 /** The directory browse button. */
189 protected Button directoryBrowseButton;
190
191 /**
192 * ResourceTreeAndListGroup was internal in Kepler and we referenced it. It
193 * is now removed in Luna. To keep our builds compatible with Kepler, we
194 * need to have our own version of this class. Once we stop supporting
195 * Kepler, we can delete this class and use the public one from the
196 * platform.
197 */
198 private ResourceTreeAndListGroup fSelectionGroup;
199
200 // Keep trace of the selection root so that we can dispose its related
201 // resources
202 private TraceFileSystemElement fSelectionGroupRoot;
203
204 // ------------------------------------------------------------------------
205 // Constructors
206 // ------------------------------------------------------------------------
207
208 /**
209 * Constructor. Creates the trace wizard page.
210 *
211 * @param name
212 * The name of the page.
213 * @param selection
214 * The current selection
215 */
216 protected ImportTraceWizardPage(String name, IStructuredSelection selection) {
217 super(name, selection);
218 }
219
220 /**
221 * Create the import source selection widget. (Copied from WizardResourceImportPage
222 * but instead always uses the internal ResourceTreeAndListGroup to keep compatibility
223 * with Kepler)
224 */
225 @Override
226 protected void createFileSelectionGroup(Composite parent) {
227
228 //Just create with a dummy root.
229 fSelectionGroup = new ResourceTreeAndListGroup(parent,
230 new FileSystemElement("Dummy", null, true),//$NON-NLS-1$
231 getFolderProvider(), new WorkbenchLabelProvider(),
232 getFileProvider(), new WorkbenchLabelProvider(), SWT.NONE,
233 DialogUtil.inRegularFontMode(parent));
234
235 ICheckStateListener listener = new ICheckStateListener() {
236 @Override
237 public void checkStateChanged(CheckStateChangedEvent event) {
238 updateWidgetEnablements();
239 }
240 };
241
242 WorkbenchViewerComparator comparator = new WorkbenchViewerComparator();
243 fSelectionGroup.setTreeComparator(comparator);
244 fSelectionGroup.setListComparator(comparator);
245 fSelectionGroup.addCheckStateListener(listener);
246
247 }
248
249 /**
250 * Constructor
251 *
252 * @param workbench
253 * The workbench reference.
254 * @param selection
255 * The current selection
256 */
257 public ImportTraceWizardPage(IWorkbench workbench, IStructuredSelection selection) {
258 this(IMPORT_WIZARD_PAGE, selection);
259 setTitle(Messages.ImportTraceWizard_FileSystemTitle);
260 setDescription(Messages.ImportTraceWizard_ImportTrace);
261
262 // Locate the target trace folder
263 IFolder traceFolder = null;
264 Object element = selection.getFirstElement();
265
266 if (element instanceof TmfTraceFolder) {
267 fTraceFolderElement = (TmfTraceFolder) element;
268 traceFolder = fTraceFolderElement.getResource();
269 } else if (element instanceof IProject) {
270 IProject project = (IProject) element;
271 try {
272 if (project.hasNature(TmfProjectNature.ID)) {
273 TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true);
274 fTraceFolderElement = projectElement.getTracesFolder();
275 traceFolder = project.getFolder(TmfTracesFolder.TRACES_FOLDER_NAME);
276 }
277 } catch (CoreException e) {
278 }
279 }
280
281 // If no tracing project was selected or trace folder doesn't exist use
282 // default tracing project
283 if (traceFolder == null) {
284 IProject project = TmfProjectRegistry.createProject(
285 TmfCommonConstants.DEFAULT_TRACE_PROJECT_NAME, null, new NullProgressMonitor());
286 TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true);
287 fTraceFolderElement = projectElement.getTracesFolder();
288 traceFolder = project.getFolder(TmfTracesFolder.TRACES_FOLDER_NAME);
289 }
290
291 // Set the target trace folder
292 if (traceFolder != null) {
293 fTargetFolder = traceFolder;
294 String path = traceFolder.getFullPath().toString();
295 setContainerFieldValue(path);
296 }
297 }
298
299 // ------------------------------------------------------------------------
300 // WizardResourceImportPage
301 // ------------------------------------------------------------------------
302
303 @Override
304 protected void createSourceGroup(Composite parent) {
305 createSourceSelectionGroup(parent);
306 createFileSelectionGroup(parent);
307 createTraceTypeGroup(parent);
308 validateSourceGroup();
309 }
310
311 @Override
312 protected ITreeContentProvider getFileProvider() {
313 return new WorkbenchContentProvider() {
314 @Override
315 public Object[] getChildren(Object object) {
316 if (object instanceof TraceFileSystemElement) {
317 TraceFileSystemElement element = (TraceFileSystemElement) object;
318 return element.getFiles().getChildren(element);
319 }
320 return new Object[0];
321 }
322 };
323 }
324
325 @Override
326 protected ITreeContentProvider getFolderProvider() {
327 return new WorkbenchContentProvider() {
328 @Override
329 public Object[] getChildren(Object o) {
330 if (o instanceof TraceFileSystemElement) {
331 TraceFileSystemElement element = (TraceFileSystemElement) o;
332 return element.getFolders().getChildren();
333 }
334 return new Object[0];
335 }
336
337 @Override
338 public boolean hasChildren(Object o) {
339 if (o instanceof TraceFileSystemElement) {
340 TraceFileSystemElement element = (TraceFileSystemElement) o;
341 if (element.isPopulated()) {
342 return getChildren(element).length > 0;
343 }
344 //If we have not populated then wait until asked
345 return true;
346 }
347 return false;
348 }
349 };
350 }
351
352 // ------------------------------------------------------------------------
353 // Directory Selection Group (forked WizardFileSystemResourceImportPage1)
354 // ------------------------------------------------------------------------
355
356 /**
357 * creates the source selection group.
358 *
359 * @param parent
360 * the parent composite
361 */
362 private void createSourceSelectionGroup(Composite workArea) {
363
364 Composite sourceGroup = new Composite(workArea, SWT.NONE);
365 GridLayout layout = new GridLayout();
366 layout.numColumns = 3;
367 layout.makeColumnsEqualWidth = false;
368 layout.marginWidth = 0;
369 sourceGroup.setLayout(layout);
370 sourceGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
371
372 // import from directory radio button
373 fImportFromDirectoryRadio = new Button(sourceGroup, SWT.RADIO);
374 fImportFromDirectoryRadio
375 .setText(Messages.ImportTraceWizard_DirectoryLocation);
376
377 // import location entry combo
378 directoryNameField = new Combo(sourceGroup, SWT.BORDER);
379
380 GridData directoryPathData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
381 directoryPathData.widthHint = new PixelConverter(directoryNameField).convertWidthInCharsToPixels(25);
382 directoryNameField.setLayoutData(directoryPathData);
383
384 // browse button
385 directoryBrowseButton = new Button(sourceGroup, SWT.PUSH);
386 directoryBrowseButton
387 .setText(Messages.ImportTraceWizard_BrowseButton);
388 setButtonLayoutData(directoryBrowseButton);
389
390 // import from archive radio button
391 fImportFromArchiveRadio = new Button(sourceGroup, SWT.RADIO);
392 fImportFromArchiveRadio
393 .setText(Messages.ImportTraceWizard_ArchiveLocation);
394
395 // import location entry combo
396 fArchiveNameField = new Combo(sourceGroup, SWT.BORDER);
397
398 GridData archivePathData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
399 archivePathData.widthHint = new PixelConverter(fArchiveNameField).convertWidthInCharsToPixels(25);
400 fArchiveNameField.setLayoutData(archivePathData); // browse button
401 fArchiveBrowseButton = new Button(sourceGroup, SWT.PUSH);
402 fArchiveBrowseButton.setText(DataTransferMessages.DataTransfer_browse);
403 setButtonLayoutData(fArchiveBrowseButton);
404
405 fImportFromDirectoryRadio.setSelection(true);
406 fArchiveNameField.setEnabled(false);
407 fArchiveBrowseButton.setEnabled(false);
408
409 directoryBrowseButton.addSelectionListener(new SelectionAdapter() {
410 @Override
411 public void widgetSelected(SelectionEvent e) {
412 handleSourceDirectoryBrowseButtonPressed();
413 }
414
415 });
416
417 fArchiveBrowseButton.addSelectionListener(new SelectionAdapter() {
418 @Override
419 public void widgetSelected(SelectionEvent e) {
420 handleArchiveBrowseButtonPressed();
421 }
422 });
423
424 TraverseListener traverseListener = new TraverseListener() {
425 @Override
426 public void keyTraversed(TraverseEvent e) {
427 if (e.detail == SWT.TRAVERSE_RETURN) {
428 e.doit = false;
429 entryChanged = false;
430 updateFromSourceField();
431 }
432 }
433 };
434
435 FocusAdapter focusAdapter = new FocusAdapter() {
436 @Override
437 public void focusLost(FocusEvent e) {
438 // Clear the flag to prevent constant update
439 if (entryChanged) {
440 entryChanged = false;
441 updateFromSourceField();
442 }
443 }
444 };
445
446 SelectionAdapter selectionAdapter = new SelectionAdapter() {
447 @Override
448 public void widgetSelected(SelectionEvent e) {
449 entryChanged = false;
450 updateFromSourceField();
451 }
452 };
453
454 ModifyListener modifyListner = new ModifyListener() {
455 @Override
456 public void modifyText(ModifyEvent e) {
457 entryChanged = true;
458 }
459 };
460
461 directoryNameField.addModifyListener(modifyListner);
462 directoryNameField.addTraverseListener(traverseListener);
463 directoryNameField.addFocusListener(focusAdapter);
464 directoryNameField.addSelectionListener(selectionAdapter);
465 fArchiveNameField.addModifyListener(modifyListner);
466 fArchiveNameField.addTraverseListener(traverseListener);
467 fArchiveNameField.addFocusListener(focusAdapter);
468 fArchiveNameField.addSelectionListener(selectionAdapter);
469
470 fImportFromDirectoryRadio.addSelectionListener(new SelectionAdapter() {
471 @Override
472 public void widgetSelected(SelectionEvent e) {
473 directoryRadioSelected();
474 }
475 });
476
477 fImportFromArchiveRadio.addSelectionListener(new SelectionAdapter() {
478 @Override
479 public void widgetSelected(SelectionEvent e) {
480 archiveRadioSelected();
481 }
482 });
483 }
484
485 private void archiveRadioSelected() {
486 if (fImportFromArchiveRadio.getSelection()) {
487 directoryNameField.setEnabled(false);
488 directoryBrowseButton.setEnabled(false);
489 fArchiveNameField.setEnabled(true);
490 fArchiveBrowseButton.setEnabled(true);
491 updateFromSourceField();
492 fArchiveNameField.setFocus();
493 fPreviousCreateLinksValue = fCreateLinksInWorkspaceButton.getSelection();
494 fCreateLinksInWorkspaceButton.setSelection(false);
495 fCreateLinksInWorkspaceButton.setEnabled(false);
496 }
497 }
498
499 private void directoryRadioSelected() {
500 if (fImportFromDirectoryRadio.getSelection()) {
501 directoryNameField.setEnabled(true);
502 directoryBrowseButton.setEnabled(true);
503 fArchiveNameField.setEnabled(false);
504 fArchiveBrowseButton.setEnabled(false);
505 updateFromSourceField();
506 directoryNameField.setFocus();
507 fCreateLinksInWorkspaceButton.setSelection(fPreviousCreateLinksValue);
508 fCreateLinksInWorkspaceButton.setEnabled(true);
509 }
510 }
511
512 // ------------------------------------------------------------------------
513 // Browse for the source directory
514 // ------------------------------------------------------------------------
515
516 @Override
517 public void handleEvent(Event event) {
518 if (event.widget == directoryBrowseButton) {
519 handleSourceDirectoryBrowseButtonPressed();
520 }
521
522 // Avoid overwriting destination path without repeatedly trigger
523 // call of handleEvent();
524 synchronized (fIsDestinationChanged) {
525 if (fIsDestinationChanged == false) {
526 event.display.asyncExec(new Runnable() {
527 @Override
528 public void run() {
529 synchronized (fIsDestinationChanged) {
530 fIsDestinationChanged = true;
531 String path = fTargetFolder.getFullPath().toString();
532 setContainerFieldValue(path);
533 }
534 }
535 });
536 } else {
537 fIsDestinationChanged = false;
538 }
539 }
540 super.handleEvent(event);
541 }
542
543 @Override
544 protected void handleContainerBrowseButtonPressed() {
545 // Do nothing so that destination directory cannot be changed.
546 }
547
548 /**
549 * Handle the button pressed event
550 */
551 protected void handleSourceDirectoryBrowseButtonPressed() {
552 String currentSource = directoryNameField.getText();
553 DirectoryDialog dialog = new DirectoryDialog(directoryNameField.getShell(), SWT.SAVE | SWT.SHEET);
554 dialog.setText(Messages.ImportTraceWizard_SelectTraceDirectoryTitle);
555 dialog.setMessage(Messages.ImportTraceWizard_SelectTraceDirectoryMessage);
556 dialog.setFilterPath(getSourceDirectoryName(currentSource));
557
558 String selectedDirectory = dialog.open();
559 if (selectedDirectory != null) {
560 // Just quit if the directory is not valid
561 if ((getSourceDirectory(selectedDirectory) == null) || selectedDirectory.equals(currentSource)) {
562 return;
563 }
564 // If it is valid then proceed to populate
565 setErrorMessage(null);
566 setSourceName(selectedDirectory);
567 }
568 }
569
570 /**
571 * Handle the button pressed event
572 */
573 private void handleArchiveBrowseButtonPressed() {
574 FileDialog dialog = new FileDialog(fArchiveNameField.getShell(), SWT.SHEET);
575 dialog.setFilterExtensions(FILE_IMPORT_MASK);
576 dialog.setText(Messages.ImportTraceWizard_SelectTraceArchiveTitle);
577 String fileName = fArchiveNameField.getText().trim();
578 if (!fileName.isEmpty()) {
579 File path = new File(fileName).getParentFile();
580 if (path != null && path.exists()) {
581 dialog.setFilterPath(path.toString());
582 }
583 }
584
585 String selectedArchive = dialog.open();
586 if (selectedArchive != null) {
587 setErrorMessage(null);
588 setSourceName(selectedArchive);
589 updateWidgetEnablements();
590 }
591 }
592
593 private File getSourceDirectory() {
594 return getSourceDirectory(directoryNameField.getText());
595 }
596
597 private File getSourceArchiveFile() {
598 return getSourceArchiveFile(fArchiveNameField.getText());
599 }
600
601 private String getSourceContainerPath() {
602 if (fImportFromDirectoryRadio.getSelection()) {
603 File sourceDirectory = getSourceDirectory();
604 if (sourceDirectory != null) {
605 return sourceDirectory.getAbsolutePath();
606 }
607 }
608 File sourceArchiveFile = getSourceArchiveFile();
609 if (sourceArchiveFile != null) {
610 return sourceArchiveFile.getParent();
611 }
612 return null;
613 }
614
615 private static File getSourceDirectory(String path) {
616 File sourceDirectory = new File(getSourceDirectoryName(path));
617 if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
618 return null;
619 }
620
621 return sourceDirectory;
622 }
623
624 private static File getSourceArchiveFile(String path) {
625 File sourceArchiveFile = new File(path);
626 if (!sourceArchiveFile.exists() || sourceArchiveFile.isDirectory()) {
627 return null;
628 }
629
630 return sourceArchiveFile;
631 }
632
633 private static String getSourceDirectoryName(String sourceName) {
634 IPath result = new Path(sourceName.trim());
635 if (result.getDevice() != null && result.segmentCount() == 0) {
636 result = result.addTrailingSeparator();
637 } else {
638 result = result.removeTrailingSeparator();
639 }
640 return result.toOSString();
641 }
642
643 private void updateFromSourceField() {
644 setSourceName(getSourceField().getText());
645 updateWidgetEnablements();
646 }
647
648 private Combo getSourceField() {
649 return directoryNameField.isEnabled() ? directoryNameField : fArchiveNameField;
650 }
651
652 private void setSourceName(String path) {
653 Combo sourceField = getSourceField();
654 if (path.length() > 0) {
655 String[] currentItems = sourceField.getItems();
656 int selectionIndex = -1;
657 for (int i = 0; i < currentItems.length; i++) {
658 if (currentItems[i].equals(path)) {
659 selectionIndex = i;
660 }
661 }
662 if (selectionIndex < 0) {
663 int oldLength = currentItems.length;
664 String[] newItems = new String[oldLength + 1];
665 System.arraycopy(currentItems, 0, newItems, 0, oldLength);
666 newItems[oldLength] = path;
667 sourceField.setItems(newItems);
668 selectionIndex = oldLength;
669 }
670 sourceField.select(selectionIndex);
671 }
672 resetSelection();
673 }
674
675 // ------------------------------------------------------------------------
676 // File Selection Group (forked WizardFileSystemResourceImportPage1)
677 // ------------------------------------------------------------------------
678 private void resetSelection() {
679 if (fSelectionGroupRoot != null) {
680 disposeSelectionGroupRoot();
681 }
682 fSelectionGroupRoot = getFileSystemTree();
683 fSelectionGroup.setRoot(fSelectionGroupRoot);
684 }
685
686 private void disposeSelectionGroupRoot() {
687 if (fSelectionGroupRoot != null && fSelectionGroupRoot.getProvider() != null) {
688 FileSystemObjectImportStructureProvider provider = fSelectionGroupRoot.getProvider();
689 provider.dispose();
690 fSelectionGroupRoot = null;
691 }
692 }
693
694 private TraceFileSystemElement getFileSystemTree() {
695 IFileSystemObject rootElement = null;
696 FileSystemObjectImportStructureProvider importStructureProvider = null;
697
698 // Import from directory
699 if (fImportFromDirectoryRadio.getSelection()) {
700 importStructureProvider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
701 File sourceDirectory = getSourceDirectory();
702 if (sourceDirectory == null) {
703 return null;
704 }
705 rootElement = importStructureProvider.getIFileSystemObject(sourceDirectory);
706 } else {
707 // Import from archive
708 FileSystemObjectLeveledImportStructureProvider leveledImportStructureProvider = null;
709 String archivePath = getSourceArchiveFile() != null ? getSourceArchiveFile().getAbsolutePath() : ""; //$NON-NLS-1$
710 if (ArchiveFileManipulations.isTarFile(archivePath)) {
711 if (ensureTarSourceIsValid(archivePath)) {
712 // We close the file when we dispose the import provider, see disposeSelectionGroupRoot
713 TarFile tarFile = getSpecifiedTarSourceFile(archivePath);
714 leveledImportStructureProvider = new FileSystemObjectLeveledImportStructureProvider(new TarLeveledStructureProvider(tarFile), archivePath);
715 }
716 } else if (ensureZipSourceIsValid(archivePath)) {
717 // We close the file when we dispose the import provider, see disposeSelectionGroupRoot
718 @SuppressWarnings("resource")
719 ZipFile zipFile = getSpecifiedZipSourceFile(archivePath);
720 leveledImportStructureProvider = new FileSystemObjectLeveledImportStructureProvider(new ZipLeveledStructureProvider(zipFile), archivePath);
721 }
722 if (leveledImportStructureProvider == null) {
723 return null;
724 }
725 rootElement = leveledImportStructureProvider.getRoot();
726 importStructureProvider = leveledImportStructureProvider;
727 }
728
729 if (rootElement == null) {
730 return null;
731 }
732
733 return selectFiles(rootElement, importStructureProvider);
734 }
735
736 /**
737 * An import provider that makes use of the IFileSystemObject abstraction
738 * instead of using plain file system objects (File, TarEntry, ZipEntry)
739 */
740 private static class FileSystemObjectImportStructureProvider implements IImportStructureProvider {
741
742 private IImportStructureProvider fImportProvider;
743 private String fArchivePath;
744 private FileSystemObjectImportStructureProvider(IImportStructureProvider importStructureProvider, String archivePath) {
745 fImportProvider = importStructureProvider;
746 fArchivePath = archivePath;
747 }
748
749 @Override
750 public List<IFileSystemObject> getChildren(Object element) {
751 @SuppressWarnings("rawtypes")
752 List children = fImportProvider.getChildren(((IFileSystemObject)element).getRawFileSystemObject());
753 List<IFileSystemObject> adapted = new ArrayList<>(children.size());
754 for (Object o : children) {
755 adapted.add(getIFileSystemObject(o));
756 }
757 return adapted;
758 }
759
760 public IFileSystemObject getIFileSystemObject(Object o) {
761 if (o instanceof File) {
762 return new FileFileSystemObject((File)o);
763 } else if (o instanceof TarEntry) {
764 return new TarFileSystemObject((TarEntry) o, fArchivePath);
765 } else if (o instanceof ZipEntry) {
766 return new ZipFileSystemObject((ZipEntry) o, fArchivePath);
767 }
768
769 throw new IllegalArgumentException("Object type not handled"); //$NON-NLS-1$
770 }
771
772 @Override
773 public InputStream getContents(Object element) {
774 return fImportProvider.getContents(((IFileSystemObject)element).getRawFileSystemObject());
775 }
776
777 @Override
778 public String getFullPath(Object element) {
779 return fImportProvider.getFullPath(((IFileSystemObject)element).getRawFileSystemObject());
780 }
781
782 @Override
783 public String getLabel(Object element) {
784 return fImportProvider.getLabel(((IFileSystemObject)element).getRawFileSystemObject());
785 }
786
787 @Override
788 public boolean isFolder(Object element) {
789 return fImportProvider.isFolder(((IFileSystemObject)element).getRawFileSystemObject());
790 }
791
792 /**
793 * Disposes of the resources associated with the provider.
794 */
795 public void dispose() {
796 }
797 }
798
799 /**
800 * An import provider that both supports using IFileSystemObject and adds
801 * "archive functionality" by delegating to a leveled import provider
802 * (TarLeveledStructureProvider, ZipLeveledStructureProvider)
803 */
804 private static class FileSystemObjectLeveledImportStructureProvider extends FileSystemObjectImportStructureProvider implements ILeveledImportStructureProvider {
805
806 private ILeveledImportStructureProvider fLeveledImportProvider;
807
808 private FileSystemObjectLeveledImportStructureProvider(ILeveledImportStructureProvider importStructureProvider, String archivePath) {
809 super(importStructureProvider, archivePath);
810 fLeveledImportProvider = importStructureProvider;
811 }
812
813 @Override
814 public IFileSystemObject getRoot() {
815 return getIFileSystemObject(fLeveledImportProvider.getRoot());
816 }
817
818 @Override
819 public void setStrip(int level) {
820 fLeveledImportProvider.setStrip(level);
821 }
822
823 @Override
824 public int getStrip() {
825 return fLeveledImportProvider.getStrip();
826 }
827
828 @Override
829 public boolean closeArchive() {
830 return fLeveledImportProvider.closeArchive();
831 }
832 }
833
834 @SuppressWarnings("resource")
835 private boolean ensureZipSourceIsValid(String archivePath) {
836 ZipFile specifiedFile = getSpecifiedZipSourceFile(archivePath);
837 if (specifiedFile == null) {
838 return false;
839 }
840 return ArchiveFileManipulations.closeZipFile(specifiedFile, getShell());
841 }
842
843 private boolean ensureTarSourceIsValid(String archivePath) {
844 TarFile specifiedFile = getSpecifiedTarSourceFile(archivePath);
845 if (specifiedFile == null) {
846 return false;
847 }
848 return ArchiveFileManipulations.closeTarFile(specifiedFile, getShell());
849 }
850
851 private static ZipFile getSpecifiedZipSourceFile(String fileName) {
852 if (fileName.length() == 0) {
853 return null;
854 }
855
856 try {
857 return new ZipFile(fileName);
858 } catch (ZipException e) {
859 // ignore
860 } catch (IOException e) {
861 // ignore
862 }
863
864 return null;
865 }
866
867 private static TarFile getSpecifiedTarSourceFile(String fileName) {
868 if (fileName.length() == 0) {
869 return null;
870 }
871
872 try {
873 return new TarFile(fileName);
874 } catch (TarException e) {
875 // ignore
876 } catch (IOException e) {
877 // ignore
878 }
879
880 return null;
881 }
882
883 private TraceFileSystemElement selectFiles(final IFileSystemObject rootFileSystemObject,
884 final FileSystemObjectImportStructureProvider structureProvider) {
885 final TraceFileSystemElement[] results = new TraceFileSystemElement[1];
886 BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
887 @Override
888 public void run() {
889 // Create the root element from the supplied file system object
890 results[0] = createRootElement(rootFileSystemObject, structureProvider);
891 }
892 });
893 return results[0];
894 }
895
896 private static TraceFileSystemElement createRootElement(IFileSystemObject element,
897 FileSystemObjectImportStructureProvider provider) {
898 boolean isContainer = provider.isFolder(element);
899 String elementLabel = provider.getLabel(element);
900
901 // Use an empty label so that display of the element's full name
902 // doesn't include a confusing label
903 TraceFileSystemElement dummyParent = new TraceFileSystemElement("", null, true, provider);//$NON-NLS-1$
904 Object dummyParentFileSystemObject = element;
905 Object rawFileSystemObject = element.getRawFileSystemObject();
906 if (rawFileSystemObject instanceof File) {
907 dummyParentFileSystemObject = provider.getIFileSystemObject(((File) rawFileSystemObject).getParentFile());
908 }
909 dummyParent.setFileSystemObject(dummyParentFileSystemObject);
910 dummyParent.setPopulated();
911 TraceFileSystemElement result = new TraceFileSystemElement(
912 elementLabel, dummyParent, isContainer, provider);
913 result.setFileSystemObject(element);
914
915 //Get the files for the element so as to build the first level
916 result.getFiles();
917
918 return dummyParent;
919 }
920
921 // ------------------------------------------------------------------------
922 // Trace Type Group
923 // ------------------------------------------------------------------------
924 private final void createTraceTypeGroup(Composite parent) {
925 Composite composite = new Composite(parent, SWT.NONE);
926 GridLayout layout = new GridLayout();
927 layout.numColumns = 3;
928 layout.makeColumnsEqualWidth = false;
929 composite.setLayout(layout);
930 composite.setFont(parent.getFont());
931 GridData buttonData = new GridData(SWT.FILL, SWT.FILL, true, false);
932 composite.setLayoutData(buttonData);
933
934 // Trace type label ("Trace Type:")
935 Label typeLabel = new Label(composite, SWT.NONE);
936 typeLabel.setText(Messages.ImportTraceWizard_TraceType);
937 typeLabel.setFont(parent.getFont());
938
939 // Trace type combo
940 fTraceTypes = new Combo(composite, SWT.BORDER | SWT.READ_ONLY);
941 GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
942 fTraceTypes.setLayoutData(data);
943 fTraceTypes.setFont(parent.getFont());
944
945 String[] availableTraceTypes = TmfTraceType.getAvailableTraceTypes();
946 String[] traceTypeList = new String[availableTraceTypes.length + 1];
947 traceTypeList[0] = AUTO_DETECT;
948 for (int i = 0; i < availableTraceTypes.length; i++) {
949 traceTypeList[i + 1] = availableTraceTypes[i];
950 }
951 fTraceTypes.setItems(traceTypeList);
952 fTraceTypes.addSelectionListener(new SelectionAdapter() {
953 @Override
954 public void widgetSelected(SelectionEvent e) {
955 updateWidgetEnablements();
956 boolean enabled = fTraceTypes.getText().equals(AUTO_DETECT);
957 fImportUnrecognizedButton.setEnabled(enabled);
958 }
959 });
960 fTraceTypes.select(0);
961
962 // Unrecognized checkbox
963 fImportUnrecognizedButton = new Button(composite, SWT.CHECK);
964 fImportUnrecognizedButton.setSelection(true);
965 fImportUnrecognizedButton.setText(Messages.ImportTraceWizard_ImportUnrecognized);
966 }
967
968 // ------------------------------------------------------------------------
969 // Options
970 // ------------------------------------------------------------------------
971
972 @Override
973 protected void createOptionsGroupButtons(Group optionsGroup) {
974
975 // Overwrite checkbox
976 fOverwriteExistingResourcesCheckbox = new Button(optionsGroup, SWT.CHECK);
977 fOverwriteExistingResourcesCheckbox.setFont(optionsGroup.getFont());
978 fOverwriteExistingResourcesCheckbox.setText(Messages.ImportTraceWizard_OverwriteExistingTrace);
979 fOverwriteExistingResourcesCheckbox.setSelection(false);
980
981 // Create links checkbox
982 fCreateLinksInWorkspaceButton = new Button(optionsGroup, SWT.CHECK);
983 fCreateLinksInWorkspaceButton.setFont(optionsGroup.getFont());
984 fCreateLinksInWorkspaceButton.setText(Messages.ImportTraceWizard_CreateLinksInWorkspace);
985 fCreateLinksInWorkspaceButton.setSelection(true);
986
987 fCreateLinksInWorkspaceButton.addSelectionListener(new SelectionAdapter() {
988 @Override
989 public void widgetSelected(SelectionEvent e) {
990 updateWidgetEnablements();
991 }
992 });
993
994 fPreserveFolderStructureButton = new Button(optionsGroup, SWT.CHECK);
995 fPreserveFolderStructureButton.setFont(optionsGroup.getFont());
996 fPreserveFolderStructureButton.setText(Messages.ImportTraceWizard_PreserveFolderStructure);
997 fPreserveFolderStructureButton.setSelection(true);
998
999 updateWidgetEnablements();
1000 }
1001
1002 // ------------------------------------------------------------------------
1003 // Determine if the finish button can be enabled
1004 // ------------------------------------------------------------------------
1005 @Override
1006 public boolean validateSourceGroup() {
1007
1008 File source = fImportFromDirectoryRadio.getSelection() ? getSourceDirectory() : getSourceArchiveFile();
1009 if (source == null) {
1010 setMessage(Messages.ImportTraceWizard_SelectTraceSourceEmpty);
1011 setErrorMessage(null);
1012 return false;
1013 }
1014
1015 if (sourceConflictsWithDestination(new Path(source.getPath()))) {
1016 setMessage(null);
1017 setErrorMessage(getSourceConflictMessage());
1018 return false;
1019 }
1020
1021 if (!fImportFromDirectoryRadio.getSelection()) {
1022 if (!ensureTarSourceIsValid(source.getAbsolutePath()) && !ensureZipSourceIsValid(source.getAbsolutePath())) {
1023 setMessage(null);
1024 setErrorMessage(Messages.ImportTraceWizard_BadArchiveFormat);
1025 return false;
1026 }
1027 }
1028
1029 if (fSelectionGroup.getCheckedElementCount() == 0) {
1030 setMessage(null);
1031 setErrorMessage(Messages.ImportTraceWizard_SelectTraceNoneSelected);
1032 return false;
1033 }
1034
1035 IContainer container = getSpecifiedContainer();
1036 if (container != null && container.isVirtual()) {
1037 if (Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, ResourcesPlugin.PREF_DISABLE_LINKING, false, null)) {
1038 setMessage(null);
1039 setErrorMessage(Messages.ImportTraceWizard_CannotImportFilesUnderAVirtualFolder);
1040 return false;
1041 }
1042 if (fCreateLinksInWorkspaceButton == null || !fCreateLinksInWorkspaceButton.getSelection()) {
1043 setMessage(null);
1044 setErrorMessage(Messages.ImportTraceWizard_HaveToCreateLinksUnderAVirtualFolder);
1045 return false;
1046 }
1047 }
1048
1049 setErrorMessage(null);
1050 return true;
1051 }
1052
1053 @Override
1054 protected void restoreWidgetValues() {
1055 super.restoreWidgetValues();
1056
1057 IDialogSettings settings = getDialogSettings();
1058 boolean value;
1059 if (settings.get(IMPORT_WIZARD_IMPORT_UNRECOGNIZED_ID) == null) {
1060 value = true;
1061 } else {
1062 value = settings.getBoolean(IMPORT_WIZARD_IMPORT_UNRECOGNIZED_ID);
1063 }
1064 fImportUnrecognizedButton.setSelection(value);
1065
1066 if (settings.get(IMPORT_WIZARD_PRESERVE_FOLDERS_ID) == null) {
1067 value = true;
1068 } else {
1069 value = settings.getBoolean(IMPORT_WIZARD_PRESERVE_FOLDERS_ID);
1070 }
1071 fPreserveFolderStructureButton.setSelection(value);
1072
1073 if (settings.get(IMPORT_WIZARD_IMPORT_FROM_DIRECTORY) == null) {
1074 value = true;
1075 } else {
1076 value = settings.getBoolean(IMPORT_WIZARD_IMPORT_FROM_DIRECTORY);
1077 }
1078 restoreComboValues(directoryNameField, settings, IMPORT_WIZARD_ROOT_DIRECTORY_ID);
1079 restoreComboValues(fArchiveNameField, settings, IMPORT_WIZARD_ARCHIVE_FILE_NAME_ID);
1080
1081 fImportFromDirectoryRadio.setSelection(value);
1082 fImportFromArchiveRadio.setSelection(!value);
1083 if (value) {
1084 directoryRadioSelected();
1085 } else {
1086 archiveRadioSelected();
1087 }
1088 }
1089
1090 @Override
1091 protected void saveWidgetValues() {
1092 // Persist dialog settings
1093 IDialogSettings settings = getDialogSettings();
1094 settings.put(IMPORT_WIZARD_IMPORT_UNRECOGNIZED_ID, fImportUnrecognizedButton.getSelection());
1095 settings.put(IMPORT_WIZARD_PRESERVE_FOLDERS_ID, fPreserveFolderStructureButton.getSelection());
1096 settings.put(IMPORT_WIZARD_IMPORT_FROM_DIRECTORY, fImportFromDirectoryRadio.getSelection());
1097
1098 saveComboValues(directoryNameField, settings, IMPORT_WIZARD_ROOT_DIRECTORY_ID);
1099 saveComboValues(fArchiveNameField, settings, IMPORT_WIZARD_ARCHIVE_FILE_NAME_ID);
1100 }
1101
1102 private static void restoreComboValues(Combo combo, IDialogSettings settings, String key) {
1103 String[] directoryNames = settings.getArray(key);
1104 if ((directoryNames != null) && (directoryNames.length != 0)) {
1105 for (int i = 0; i < directoryNames.length; i++) {
1106 combo.add(directoryNames[i]);
1107 }
1108 }
1109 }
1110
1111 private void saveComboValues(Combo combo, IDialogSettings settings, String key) {
1112 // update names history
1113 String[] directoryNames = settings.getArray(key);
1114 if (directoryNames == null) {
1115 directoryNames = new String[0];
1116 }
1117
1118 String items[] = combo.getItems();
1119 for (int i = 0; i < items.length; i++) {
1120 directoryNames = addToHistory(directoryNames, items[i]);
1121 }
1122 settings.put(key, directoryNames);
1123 }
1124
1125 // ------------------------------------------------------------------------
1126 // Import the trace(s)
1127 // ------------------------------------------------------------------------
1128
1129 /**
1130 * Finish the import.
1131 *
1132 * @return <code>true</code> if successful else <code>false</code>
1133 */
1134 public boolean finish() {
1135 String traceTypeName = fTraceTypes.getText();
1136 String traceId = null;
1137 if (!AUTO_DETECT.equals(traceTypeName)) {
1138 String tokens[] = traceTypeName.split(SEPARATOR, 2);
1139 if (tokens.length < 2) {
1140 return false;
1141 }
1142 traceId = TmfTraceType.getTraceTypeId(tokens[0], tokens[1]);
1143 }
1144
1145 // Save dialog settings
1146 saveWidgetValues();
1147
1148 IPath baseSourceContainerPath = new Path(getSourceContainerPath());
1149 boolean importFromArchive = getSourceArchiveFile() != null;
1150 final TraceValidateAndImportOperation operation = new TraceValidateAndImportOperation(traceId, baseSourceContainerPath, getContainerFullPath(), importFromArchive,
1151 fImportUnrecognizedButton.getSelection(), fOverwriteExistingResourcesCheckbox.getSelection(), fCreateLinksInWorkspaceButton.getSelection(), fPreserveFolderStructureButton.getSelection());
1152
1153 IStatus status = Status.OK_STATUS;
1154 try {
1155 getContainer().run(true, true, new IRunnableWithProgress() {
1156 @Override
1157 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
1158 operation.run(monitor);
1159 monitor.done();
1160 }
1161 });
1162
1163 status = operation.getStatus();
1164 } catch (InvocationTargetException e) {
1165 status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.ImportTraceWizard_ImportProblem, e);
1166 } catch (InterruptedException e) {
1167 status = Status.CANCEL_STATUS;
1168 } finally {
1169 if (!status.isOK()) {
1170 if (status.getSeverity() == IStatus.CANCEL) {
1171 setMessage(Messages.ImportTraceWizard_ImportOperationCancelled);
1172 setErrorMessage(null);
1173 } else {
1174 if (status.getException() != null) {
1175 displayErrorDialog(status.getMessage() + ": " + status.getException()); //$NON-NLS-1$
1176 }
1177 setMessage(null);
1178 setErrorMessage(Messages.ImportTraceWizard_ImportProblem);
1179 }
1180 return false;
1181 }
1182 }
1183 setErrorMessage(null);
1184 return true;
1185 }
1186
1187 @Override
1188 public void dispose() {
1189 super.dispose();
1190 disposeSelectionGroupRoot();
1191 }
1192
1193 // ------------------------------------------------------------------------
1194 // Classes
1195 // ------------------------------------------------------------------------
1196
1197 private class TraceValidateAndImportOperation {
1198 private IStatus fStatus;
1199 private String fTraceType;
1200 private IPath fDestinationContainerPath;
1201 private IPath fBaseSourceContainerPath;
1202 private boolean fImportFromArchive;
1203 private boolean fImportUnrecognizedTraces;
1204 private boolean fLink;
1205 private boolean fPreserveFolderStructure;
1206 private ImportConfirmation fConfirmationMode = ImportConfirmation.SKIP;
1207
1208 private TraceValidateAndImportOperation(String traceId, IPath baseSourceContainerPath, IPath destinationContainerPath, boolean importFromArchive, boolean doImport, boolean overwrite, boolean link, boolean preserveFolderStructure) {
1209 fTraceType = traceId;
1210 fBaseSourceContainerPath = baseSourceContainerPath;
1211 fDestinationContainerPath = destinationContainerPath;
1212 fImportFromArchive = importFromArchive;
1213 fImportUnrecognizedTraces = doImport;
1214 if (overwrite) {
1215 fConfirmationMode = ImportConfirmation.OVERWRITE_ALL;
1216 }
1217 fLink = link;
1218 fPreserveFolderStructure = preserveFolderStructure;
1219 }
1220
1221 public void run(IProgressMonitor progressMonitor) {
1222 String currentPath = null;
1223 final Map<String, TraceFileSystemElement> folderElements = new HashMap<>();
1224 try {
1225
1226 final ArrayList<TraceFileSystemElement> fileSystemElements = new ArrayList<>();
1227 IElementFilter passThroughFilter = new IElementFilter() {
1228
1229 @Override
1230 public void filterElements(Collection elements, IProgressMonitor monitor) {
1231 fileSystemElements.addAll(elements);
1232 }
1233 @Override
1234 public void filterElements(Object[] elements, IProgressMonitor monitor) {
1235 for (int i = 0; i < elements.length; i++) {
1236 fileSystemElements.add((TraceFileSystemElement)elements[i]);
1237 }
1238 }
1239 };
1240
1241 // List fileSystemElements will be filled using the passThroughFilter
1242 SubMonitor subMonitor = SubMonitor.convert(progressMonitor, 1);
1243 fSelectionGroup.getAllCheckedListItems(passThroughFilter, subMonitor);
1244
1245 // Check if operation was cancelled.
1246 ModalContext.checkCanceled(subMonitor);
1247
1248 Iterator<TraceFileSystemElement> fileSystemElementsIter = fileSystemElements.iterator();
1249 IFolder destTempFolder = null;
1250 subMonitor = SubMonitor.convert(progressMonitor, fileSystemElements.size());
1251 if (fImportFromArchive) {
1252 // When importing from archive, we first extract the
1253 // *selected* files to a temporary folder then create a new
1254 // Iterator<TraceFileSystemElement> that points to the
1255 // extracted files. This way, the import operator can
1256 // continue as it normally would.
1257
1258 subMonitor = SubMonitor.convert(progressMonitor, fileSystemElements.size() * 2);
1259 destTempFolder = fTargetFolder.getProject().getFolder(TRACE_IMPORT_TEMP_FOLDER);
1260 if (destTempFolder.exists()) {
1261 SubProgressMonitor monitor = new SubProgressMonitor(subMonitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
1262 destTempFolder.delete(true, monitor);
1263 }
1264 SubProgressMonitor monitor = new SubProgressMonitor(subMonitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
1265 destTempFolder.create(IResource.HIDDEN, true, monitor);
1266
1267 fileSystemElementsIter = extractSelectedFiles(fileSystemElementsIter, destTempFolder, subMonitor);
1268 // We need to update the source container path because the
1269 // "preserve folder structure" option would create the
1270 // wrong folders otherwise.
1271 fBaseSourceContainerPath = destTempFolder.getLocation();
1272 }
1273
1274 while (fileSystemElementsIter.hasNext()) {
1275 ModalContext.checkCanceled(progressMonitor);
1276 currentPath = null;
1277 TraceFileSystemElement element = fileSystemElementsIter.next();
1278 IFileSystemObject fileSystemObject = element.getFileSystemObject();
1279 String resourcePath = element.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString());
1280 element.setDestinationContainerPath(computeDestinationContainerPath(new Path(resourcePath)));
1281
1282 currentPath = resourcePath;
1283 SubMonitor sub = subMonitor.newChild(1);
1284 if (element.isDirectory()) {
1285 if (!folderElements.containsKey(resourcePath)) {
1286 if (isDirectoryTrace(element)) {
1287 folderElements.put(resourcePath, element);
1288 validateAndImportTrace(element, sub);
1289 }
1290 }
1291 } else {
1292 TraceFileSystemElement parentElement = (TraceFileSystemElement)element.getParent();
1293 String parentPath = parentElement.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString());
1294 parentElement.setDestinationContainerPath(computeDestinationContainerPath(new Path(parentPath)));
1295 currentPath = parentPath;
1296 if (!folderElements.containsKey(parentPath)) {
1297 if (isDirectoryTrace(parentElement)) {
1298 folderElements.put(parentPath, parentElement);
1299 validateAndImportTrace(parentElement, sub);
1300 } else {
1301 if (fileSystemObject.exists()) {
1302 validateAndImportTrace(element, sub);
1303 }
1304 }
1305 }
1306 }
1307 }
1308
1309 if (destTempFolder != null && destTempFolder.exists()) {
1310 destTempFolder.delete(true, progressMonitor);
1311 }
1312
1313 setStatus(Status.OK_STATUS);
1314 } catch (InterruptedException e) {
1315 setStatus(Status.CANCEL_STATUS);
1316 } catch (Exception e) {
1317 String errorMessage = Messages.ImportTraceWizard_ImportProblem + ": " + //$NON-NLS-1$
1318 (currentPath != null ? currentPath : ""); //$NON-NLS-1$
1319 Activator.getDefault().logError(errorMessage, e);
1320 setStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, errorMessage , e));
1321 }
1322 }
1323
1324 private Iterator<TraceFileSystemElement> extractSelectedFiles(Iterator<TraceFileSystemElement> fileSystemElementsIter, IFolder tempFolder, IProgressMonitor progressMonitor) throws InterruptedException,
1325 InvocationTargetException {
1326 List<TraceFileSystemElement> subList = new ArrayList<>();
1327 // Collect all the elements
1328 while (fileSystemElementsIter.hasNext()) {
1329 ModalContext.checkCanceled(progressMonitor);
1330 TraceFileSystemElement element = fileSystemElementsIter.next();
1331 if (element.isDirectory()) {
1332 Object[] array = element.getFiles().getChildren();
1333 for (int i = 0; i < array.length; i++) {
1334 subList.add((TraceFileSystemElement)array[i]);
1335 }
1336 }
1337 subList.add(element);
1338 }
1339
1340 // Find a sensible root element
1341 TraceFileSystemElement root = subList.get(0);
1342 while (root.getParent() != null) {
1343 root = (TraceFileSystemElement) root.getParent();
1344 }
1345
1346 ImportProvider fileSystemStructureProvider = new ImportProvider();
1347
1348 IOverwriteQuery myQueryImpl = new IOverwriteQuery() {
1349 @Override
1350 public String queryOverwrite(String file) {
1351 return IOverwriteQuery.NO_ALL;
1352 }
1353 };
1354
1355 progressMonitor.setTaskName(Messages.ImportTraceWizard_ExtractImportOperationTaskName);
1356 IPath containerPath = tempFolder.getFullPath();
1357 ImportOperation operation = new ImportOperation(containerPath, root, fileSystemStructureProvider, myQueryImpl, subList);
1358 operation.setContext(getShell());
1359
1360 operation.setCreateContainerStructure(true);
1361 operation.setOverwriteResources(false);
1362 operation.setVirtualFolders(false);
1363
1364 operation.run(new SubProgressMonitor(progressMonitor, subList.size(), SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
1365
1366 // Create the new import provider and root element based on the extracted temp folder
1367 FileSystemObjectImportStructureProvider importStructureProvider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
1368 IFileSystemObject rootElement = importStructureProvider.getIFileSystemObject(new File(tempFolder.getLocation().toOSString()));
1369 TraceFileSystemElement createRootElement = createRootElement(rootElement, importStructureProvider);
1370 List<TraceFileSystemElement> list = new ArrayList<>();
1371 getAllChildren(list, createRootElement);
1372 Iterator<TraceFileSystemElement> extractedElementsIter = list.iterator();
1373 return extractedElementsIter;
1374 }
1375
1376 /**
1377 * Get all the TraceFileSystemElements recursively.
1378 *
1379 * @param result
1380 * the list accumulating the result
1381 * @param rootElement
1382 * the root element of the file system to be imported
1383 */
1384 private void getAllChildren(List<TraceFileSystemElement> result, TraceFileSystemElement rootElement) {
1385 AdaptableList files = rootElement.getFiles();
1386 for (Object file : files.getChildren()) {
1387 result.add((TraceFileSystemElement) file);
1388 }
1389
1390 AdaptableList folders = rootElement.getFolders();
1391 for (Object folder : folders.getChildren()) {
1392 getAllChildren(result, (TraceFileSystemElement)folder);
1393 }
1394 }
1395
1396 private IPath computeDestinationContainerPath(Path resourcePath) {
1397 IPath destinationContainerPath = fDestinationContainerPath;
1398
1399 // We need to figure out the new destination path relative to the selected "base" source directory.
1400 // Here for example, the selected source directory is /home/user
1401 if (fPreserveFolderStructure) {
1402 // /home/user/bar/foo/trace -> /home/user/bar/foo
1403 IPath sourceContainerPath = resourcePath.removeLastSegments(1);
1404 if (fBaseSourceContainerPath.equals(resourcePath)) {
1405 // Use resourcePath directory if fBaseSourceContainerPath points to a directory trace
1406 sourceContainerPath = resourcePath;
1407 }
1408 // /home/user/bar/foo, /home/user -> bar/foo
1409 IPath relativeContainerPath = sourceContainerPath.makeRelativeTo(fBaseSourceContainerPath);
1410 // project/Traces + bar/foo -> project/Traces/bar/foo
1411 destinationContainerPath = fDestinationContainerPath.append(relativeContainerPath);
1412 }
1413 return destinationContainerPath;
1414 }
1415
1416 private void validateAndImportTrace(TraceFileSystemElement fileSystemElement, IProgressMonitor monitor)
1417 throws TmfTraceImportException, CoreException, InvocationTargetException, InterruptedException {
1418 String parentContainerPath = fBaseSourceContainerPath.toOSString();
1419 String path = fileSystemElement.getFileSystemObject().getAbsolutePath(parentContainerPath);
1420 TraceTypeHelper traceTypeHelper = null;
1421
1422 if (fTraceType == null) {
1423 // Auto Detection
1424 try {
1425 traceTypeHelper = TmfTraceTypeUIUtils.selectTraceType(path, null, null);
1426 } catch (TmfTraceImportException e) {
1427 // the trace did not match any trace type
1428 }
1429 if (traceTypeHelper == null) {
1430 if (fImportUnrecognizedTraces) {
1431 importResource(fileSystemElement, monitor);
1432 }
1433 return;
1434 }
1435 } else {
1436 boolean isDirectoryTraceType = TmfTraceType.isDirectoryTraceType(fTraceType);
1437 if (fileSystemElement.isDirectory() != isDirectoryTraceType) {
1438 return;
1439 }
1440 traceTypeHelper = TmfTraceType.getTraceType(fTraceType);
1441
1442 if (traceTypeHelper == null) {
1443 // Trace type not found
1444 throw new TmfTraceImportException(Messages.ImportTraceWizard_TraceTypeNotFound);
1445 }
1446
1447 if (!traceTypeHelper.validate(path).isOK()) {
1448 // Trace type exist but doesn't validate for given trace.
1449 return;
1450 }
1451 }
1452
1453 // Finally import trace
1454 IResource importedResource = importResource(fileSystemElement, monitor);
1455 if (importedResource != null) {
1456 TmfTraceTypeUIUtils.setTraceType(importedResource, traceTypeHelper);
1457 }
1458
1459 }
1460
1461 /**
1462 * Imports a trace resource to project. In case of name collision the
1463 * user will be asked to confirm overwriting the existing trace,
1464 * overwriting or skipping the trace to be imported.
1465 *
1466 * @param fileSystemElement
1467 * trace file system object to import
1468 * @param monitor
1469 * a progress monitor
1470 * @return the imported resource or null if no resource was imported
1471 *
1472 * @throws InvocationTargetException
1473 * if problems during import operation
1474 * @throws InterruptedException
1475 * if cancelled
1476 * @throws CoreException
1477 * if problems with workspace
1478 */
1479 private IResource importResource(TraceFileSystemElement fileSystemElement, IProgressMonitor monitor)
1480 throws InvocationTargetException, InterruptedException, CoreException {
1481
1482 ImportConfirmation mode = checkForNameClashes(fileSystemElement);
1483 switch (mode) {
1484 case RENAME:
1485 case RENAME_ALL:
1486 rename(fileSystemElement);
1487 break;
1488 case OVERWRITE:
1489 case OVERWRITE_ALL:
1490 delete(fileSystemElement, monitor);
1491 break;
1492 case CONTINUE:
1493 break;
1494 case SKIP:
1495 case SKIP_ALL:
1496 default:
1497 return null;
1498 }
1499
1500 List<TraceFileSystemElement> subList = new ArrayList<>();
1501
1502 FileSystemElement parentFolder = fileSystemElement.getParent();
1503
1504 IPath containerPath = fileSystemElement.getDestinationContainerPath();
1505 IPath tracePath = containerPath.addTrailingSeparator().append(fileSystemElement.getLabel());
1506 if (fileSystemElement.isDirectory() && (!fLink)) {
1507 containerPath = tracePath;
1508
1509 Object[] array = fileSystemElement.getFiles().getChildren();
1510 for (int i = 0; i < array.length; i++) {
1511 subList.add((TraceFileSystemElement)array[i]);
1512 }
1513 parentFolder = fileSystemElement;
1514
1515 } else {
1516 subList.add(fileSystemElement);
1517 }
1518
1519
1520 ImportProvider fileSystemStructureProvider = new ImportProvider();
1521
1522 IOverwriteQuery myQueryImpl = new IOverwriteQuery() {
1523 @Override
1524 public String queryOverwrite(String file) {
1525 return IOverwriteQuery.NO_ALL;
1526 }
1527 };
1528
1529 monitor.setTaskName(Messages.ImportTraceWizard_ImportOperationTaskName + " " + fileSystemElement.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString())); //$NON-NLS-1$
1530 ImportOperation operation = new ImportOperation(containerPath, parentFolder, fileSystemStructureProvider, myQueryImpl, subList);
1531 operation.setContext(getShell());
1532
1533 operation.setCreateContainerStructure(false);
1534 operation.setOverwriteResources(false);
1535 operation.setCreateLinks(fLink);
1536 operation.setVirtualFolders(false);
1537
1538 operation.run(new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));
1539 String sourceLocation = fileSystemElement.getFileSystemObject().getSourceLocation();
1540 IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(tracePath);
1541 if (sourceLocation != null) {
1542 resource.setPersistentProperty(TmfCommonConstants.SOURCE_LOCATION, sourceLocation);
1543 }
1544
1545 return resource;
1546 }
1547
1548 private boolean isDirectoryTrace(TraceFileSystemElement fileSystemElement) {
1549 String path = fileSystemElement.getFileSystemObject().getAbsolutePath(fBaseSourceContainerPath.toOSString());
1550 if (TmfTraceType.isDirectoryTrace(path)) {
1551 return true;
1552 }
1553 return false;
1554 }
1555
1556 private ImportConfirmation checkForNameClashes(TraceFileSystemElement fileSystemElement) throws InterruptedException {
1557 IPath tracePath = getInitialDestinationPath(fileSystemElement);
1558
1559 // handle rename
1560 if (getExistingTrace(tracePath) != null) {
1561 if ((fConfirmationMode == ImportConfirmation.RENAME_ALL) ||
1562 (fConfirmationMode == ImportConfirmation.OVERWRITE_ALL) ||
1563 (fConfirmationMode == ImportConfirmation.SKIP_ALL)) {
1564 return fConfirmationMode;
1565 }
1566
1567 int returnCode = promptForOverwrite(tracePath);
1568 if (returnCode < 0) {
1569 // Cancel
1570 throw new InterruptedException();
1571 }
1572 fConfirmationMode = ImportConfirmation.values()[returnCode];
1573 return fConfirmationMode;
1574 }
1575 return ImportConfirmation.CONTINUE;
1576 }
1577
1578 private int promptForOverwrite(IPath tracePath) {
1579 final MessageDialog dialog = new MessageDialog(getContainer()
1580 .getShell(), null, null, NLS.bind(Messages.ImportTraceWizard_TraceAlreadyExists, tracePath.makeRelativeTo(fTraceFolderElement.getProject().getPath())),
1581 MessageDialog.QUESTION, new String[] {
1582 ImportConfirmation.RENAME.getInName(),
1583 ImportConfirmation.RENAME_ALL.getInName(),
1584 ImportConfirmation.OVERWRITE.getInName(),
1585 ImportConfirmation.OVERWRITE_ALL.getInName(),
1586 ImportConfirmation.SKIP.getInName(),
1587 ImportConfirmation.SKIP_ALL.getInName(),
1588 }, 4) {
1589 @Override
1590 protected int getShellStyle() {
1591 return super.getShellStyle() | SWT.SHEET;
1592 }
1593 };
1594
1595 final int[] returnValue = new int[1];
1596 getShell().getDisplay().syncExec(new Runnable() {
1597
1598 @Override
1599 public void run() {
1600 returnValue[0] = dialog.open();
1601 }
1602 });
1603 return returnValue[0];
1604 }
1605
1606 /**
1607 * @return the initial destination path, before rename, if any
1608 */
1609 private IPath getInitialDestinationPath(TraceFileSystemElement fileSystemElement) {
1610 IPath traceFolderPath = fileSystemElement.getDestinationContainerPath();
1611 return traceFolderPath.append(fileSystemElement.getFileSystemObject().getLabel());
1612 }
1613
1614 private void rename(TraceFileSystemElement fileSystemElement) {
1615 IPath tracePath = getInitialDestinationPath(fileSystemElement);
1616 TmfTraceElement trace = getExistingTrace(tracePath);
1617 if (trace == null) {
1618 return;
1619 }
1620
1621 // Not using IFolder on purpose to leave the door open to import directly into an IProject
1622 IContainer folder = (IContainer) trace.getParent().getResource();
1623 int i = 2;
1624 while (true) {
1625 String name = trace.getName() + '(' + Integer.toString(i++) + ')';
1626 IResource resource = folder.findMember(name);
1627 if (resource == null) {
1628 fileSystemElement.setLabel(name);
1629 return;
1630 }
1631 }
1632 }
1633
1634 private void delete(TraceFileSystemElement fileSystemElement, IProgressMonitor monitor) throws CoreException {
1635 IPath tracePath = getInitialDestinationPath(fileSystemElement);
1636 TmfTraceElement trace = getExistingTrace(tracePath);
1637 if (trace == null) {
1638 return;
1639 }
1640
1641 trace.delete(monitor);
1642 }
1643
1644 private TmfTraceElement getExistingTrace(IPath tracePath) {
1645 List<TmfTraceElement> traces = fTraceFolderElement.getTraces();
1646 for (TmfTraceElement t : traces) {
1647 if (t.getPath().equals(tracePath)) {
1648 return t;
1649 }
1650 }
1651 return null;
1652 }
1653
1654 /**
1655 * Set the status for this operation
1656 *
1657 * @param status
1658 * the status
1659 */
1660 protected void setStatus(IStatus status) {
1661 fStatus = status;
1662 }
1663
1664 public IStatus getStatus() {
1665 return fStatus;
1666 }
1667 }
1668
1669 /**
1670 * The <code>TraceFileSystemElement</code> is a <code>FileSystemElement</code> that knows
1671 * if it has been populated or not.
1672 */
1673 private static class TraceFileSystemElement extends FileSystemElement {
1674
1675 private boolean fIsPopulated = false;
1676 private String fLabel = null;
1677 private IPath fDestinationContainerPath;
1678 private FileSystemObjectImportStructureProvider fProvider;
1679
1680 public TraceFileSystemElement(String name, FileSystemElement parent, boolean isDirectory, FileSystemObjectImportStructureProvider provider) {
1681 super(name, parent, isDirectory);
1682 fProvider = provider;
1683 }
1684
1685 public void setDestinationContainerPath(IPath destinationContainerPath) {
1686 fDestinationContainerPath = destinationContainerPath;
1687 }
1688
1689 public void setPopulated() {
1690 fIsPopulated = true;
1691 }
1692
1693 public boolean isPopulated() {
1694 return fIsPopulated;
1695 }
1696
1697 @Override
1698 public AdaptableList getFiles() {
1699 if(!fIsPopulated) {
1700 populateElementChildren();
1701 }
1702 return super.getFiles();
1703 }
1704
1705 @Override
1706 public AdaptableList getFolders() {
1707 if(!fIsPopulated) {
1708 populateElementChildren();
1709 }
1710 return super.getFolders();
1711 }
1712
1713 /**
1714 * Sets the label for the trace to be used when importing at trace.
1715 * @param name
1716 * the label for the trace
1717 */
1718 public void setLabel(String name) {
1719 fLabel = name;
1720 }
1721
1722 /**
1723 * Returns the label for the trace to be used when importing at trace.
1724 *
1725 * @return the label of trace resource
1726 */
1727 public String getLabel() {
1728 if (fLabel == null) {
1729 return getFileSystemObject().getLabel();
1730 }
1731 return fLabel;
1732 }
1733
1734 /**
1735 * The full path to the container that will contain the trace
1736 *
1737 * @return the destination container path
1738 */
1739 public IPath getDestinationContainerPath() {
1740 return fDestinationContainerPath;
1741 }
1742
1743 /**
1744 * Populates the children of the specified parent <code>FileSystemElement</code>
1745 */
1746 private void populateElementChildren() {
1747 List<IFileSystemObject> allchildren = fProvider.getChildren(this.getFileSystemObject());
1748 Object child = null;
1749 TraceFileSystemElement newelement = null;
1750 Iterator<IFileSystemObject> iter = allchildren.iterator();
1751 while(iter.hasNext()) {
1752 child = iter.next();
1753 newelement = new TraceFileSystemElement(fProvider.getLabel(child), this, fProvider.isFolder(child), fProvider);
1754 newelement.setFileSystemObject(child);
1755 }
1756 setPopulated();
1757 }
1758
1759 public FileSystemObjectImportStructureProvider getProvider() {
1760 return fProvider;
1761 }
1762
1763 @Override
1764 public IFileSystemObject getFileSystemObject() {
1765 Object fileSystemObject = super.getFileSystemObject();
1766 return (IFileSystemObject) fileSystemObject;
1767 }
1768 }
1769
1770 /**
1771 * This interface abstracts the differences between different kinds of
1772 * FileSystemObjects such as File, TarEntry and ZipEntry. This allows
1773 * clients (TraceFileSystemElement, TraceValidateAndImportOperation) to
1774 * handle all the types transparently.
1775 */
1776 private interface IFileSystemObject {
1777 String getLabel();
1778 String getAbsolutePath(String parentContainerPath);
1779 String getSourceLocation();
1780 Object getRawFileSystemObject();
1781 boolean exists();
1782 }
1783
1784 /**
1785 * The "File" implementation of an IFileSystemObject
1786 */
1787 private static class FileFileSystemObject implements IFileSystemObject {
1788
1789 private File fFileSystemObject;
1790
1791 private FileFileSystemObject(File fileSystemObject) {
1792 fFileSystemObject = fileSystemObject;
1793 }
1794
1795 @Override
1796 public String getLabel() {
1797 String name = fFileSystemObject.getName();
1798 if (name.length() == 0) {
1799 return fFileSystemObject.getPath();
1800 }
1801 return name;
1802 }
1803
1804 @Override
1805 public String getAbsolutePath(String parentContainerPath) {
1806 return fFileSystemObject.getAbsolutePath();
1807 }
1808
1809 @Override
1810 public boolean exists() {
1811 return fFileSystemObject.exists();
1812 }
1813
1814 @Override
1815 public String getSourceLocation() {
1816 IResource sourceResource;
1817 String sourceLocation = null;
1818 if (fFileSystemObject.isDirectory()) {
1819 sourceResource = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
1820 } else {
1821 sourceResource = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
1822 }
1823 if (sourceResource != null && sourceResource.exists()) {
1824 try {
1825 sourceLocation = sourceResource.getPersistentProperty(TmfCommonConstants.SOURCE_LOCATION);
1826 } catch (CoreException e) {
1827 // Something went wrong with the already existing resource.
1828 // This is not a problem, we'll assign a new location below.
1829 }
1830 }
1831 if (sourceLocation == null) {
1832 sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.toURI());
1833 }
1834 return sourceLocation;
1835 }
1836
1837 @Override
1838 public Object getRawFileSystemObject() {
1839 return fFileSystemObject;
1840 }
1841 }
1842
1843 /**
1844 * The "Tar" implementation of an IFileSystemObject
1845 */
1846 private static class TarFileSystemObject implements IFileSystemObject {
1847
1848 private TarEntry fFileSystemObject;
1849 private String fArchivePath;
1850
1851 private TarFileSystemObject(TarEntry fileSystemObject, String archivePath) {
1852 fFileSystemObject = fileSystemObject;
1853 fArchivePath = archivePath;
1854 }
1855
1856 @Override
1857 public String getLabel() {
1858 return new Path(fFileSystemObject.getName()).lastSegment();
1859 }
1860
1861 @Override
1862 public String getAbsolutePath(String parentContainerPath) {
1863 return new Path(parentContainerPath).append(fFileSystemObject.getName()).toOSString();
1864 }
1865
1866 @Override
1867 public boolean exists() {
1868 return true;
1869 }
1870
1871 @Override
1872 public String getSourceLocation() {
1873 URI uri = new File(fArchivePath).toURI();
1874 IPath entryPath = new Path(fFileSystemObject.getName());
1875 return URIUtil.toUnencodedString(URIUtil.toJarURI(uri, entryPath));
1876 }
1877
1878 @Override
1879 public Object getRawFileSystemObject() {
1880 return fFileSystemObject;
1881 }
1882 }
1883
1884 /**
1885 * The "Zip" implementation of an IFileSystemObject
1886 */
1887 private static class ZipFileSystemObject implements IFileSystemObject {
1888
1889 private ZipEntry fFileSystemObject;
1890 private String fArchivePath;
1891
1892 private ZipFileSystemObject(ZipEntry fileSystemObject, String archivePath) {
1893 fFileSystemObject = fileSystemObject;
1894 fArchivePath = archivePath;
1895 }
1896
1897 @Override
1898 public String getLabel() {
1899 return new Path(fFileSystemObject.getName()).lastSegment();
1900 }
1901
1902 @Override
1903 public String getAbsolutePath(String parentContainerPath) {
1904 return new Path(parentContainerPath).append(fFileSystemObject.getName()).toOSString();
1905 }
1906
1907 @Override
1908 public boolean exists() {
1909 return true;
1910 }
1911
1912 @Override
1913 public String getSourceLocation() {
1914 URI uri = new File(fArchivePath).toURI();
1915 IPath entryPath = new Path(fFileSystemObject.getName());
1916 return URIUtil.toUnencodedString(URIUtil.toJarURI(uri, entryPath));
1917 }
1918
1919 @Override
1920 public Object getRawFileSystemObject() {
1921 return fFileSystemObject;
1922 }
1923 }
1924
1925 private class ImportProvider implements IImportStructureProvider {
1926
1927 ImportProvider() {
1928 }
1929
1930 @Override
1931 public String getLabel(Object element) {
1932 TraceFileSystemElement resource = (TraceFileSystemElement)element;
1933 return resource.getLabel();
1934 }
1935
1936 @Override
1937 public List getChildren(Object element) {
1938 TraceFileSystemElement resource = (TraceFileSystemElement)element;
1939 Object[] array = resource.getFiles().getChildren();
1940 List<Object> list = new ArrayList<>();
1941 for (int i = 0; i < array.length; i++) {
1942 list.add(array[i]);
1943 }
1944 return list;
1945 }
1946
1947 @Override
1948 public InputStream getContents(Object element) {
1949 TraceFileSystemElement resource = (TraceFileSystemElement)element;
1950 return resource.getProvider().getContents(resource.getFileSystemObject());
1951 }
1952
1953 @Override
1954 public String getFullPath(Object element) {
1955 TraceFileSystemElement resource = (TraceFileSystemElement)element;
1956 return resource.getProvider().getFullPath(resource.getFileSystemObject());
1957 }
1958
1959 @Override
1960 public boolean isFolder(Object element) {
1961 TraceFileSystemElement resource = (TraceFileSystemElement)element;
1962 return resource.isDirectory();
1963 }
1964 }
1965
1966 private enum ImportConfirmation {
1967 // ------------------------------------------------------------------------
1968 // Enum definition
1969 // ------------------------------------------------------------------------
1970 RENAME(Messages.ImportTraceWizard_ImportConfigurationRename),
1971 RENAME_ALL(Messages.ImportTraceWizard_ImportConfigurationRenameAll),
1972 OVERWRITE(Messages.ImportTraceWizard_ImportConfigurationOverwrite),
1973 OVERWRITE_ALL(Messages.ImportTraceWizard_ImportConfigurationOverwriteAll),
1974 SKIP(Messages.ImportTraceWizard_ImportConfigurationSkip),
1975 SKIP_ALL(Messages.ImportTraceWizard_ImportConfigurationSkipAll),
1976 CONTINUE("CONTINUE"); //$NON-NLS-1$
1977
1978 // ------------------------------------------------------------------------
1979 // Attributes
1980 // ------------------------------------------------------------------------
1981 /**
1982 * Name of enum
1983 */
1984 private final String fInName;
1985
1986 // ------------------------------------------------------------------------
1987 // Constuctors
1988 // ------------------------------------------------------------------------
1989
1990 /**
1991 * Private constructor
1992 * @param name the name of state
1993 */
1994 private ImportConfirmation(String name) {
1995 fInName = name;
1996 }
1997
1998 // ------------------------------------------------------------------------
1999 // Accessors
2000 // ------------------------------------------------------------------------
2001 /**
2002 * @return state name
2003 */
2004 public String getInName() {
2005 return fInName;
2006 }
2007 }
2008 }
This page took 0.079156 seconds and 5 git commands to generate.