KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > wizards > datatransfer > WizardArchiveFileResourceImportPage1


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * Red Hat, Inc - Extracted several methods to ArchiveFileManipulations
11  *******************************************************************************/

12 package org.eclipse.ui.internal.wizards.datatransfer;
13
14 import java.io.File JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.util.List JavaDoc;
17 import java.util.zip.ZipException JavaDoc;
18 import java.util.zip.ZipFile JavaDoc;
19
20 import org.eclipse.jface.dialogs.IDialogSettings;
21 import org.eclipse.jface.viewers.IStructuredSelection;
22 import org.eclipse.jface.viewers.ITreeContentProvider;
23 import org.eclipse.osgi.util.NLS;
24 import org.eclipse.swt.SWT;
25 import org.eclipse.swt.widgets.Button;
26 import org.eclipse.swt.widgets.Composite;
27 import org.eclipse.swt.widgets.FileDialog;
28 import org.eclipse.swt.widgets.Listener;
29 import org.eclipse.ui.IWorkbench;
30 import org.eclipse.ui.PlatformUI;
31 import org.eclipse.ui.model.AdaptableList;
32 import org.eclipse.ui.model.WorkbenchContentProvider;
33 import org.eclipse.ui.wizards.datatransfer.ImportOperation;
34
35
36 /**
37  * Page 1 of the base resource import-from-archive Wizard.
38  *
39  * Note that importing from .jar is identical to importing from .zip, so
40  * all references to .zip in this class are equally applicable to .jar
41  * references.
42  *
43  * @since 3.1
44  */

45 public class WizardArchiveFileResourceImportPage1 extends
46         WizardFileSystemResourceImportPage1 implements Listener {
47
48     ZipLeveledStructureProvider zipCurrentProvider;
49     TarLeveledStructureProvider tarCurrentProvider;
50
51     // constants
52
private static final String JavaDoc[] FILE_IMPORT_MASK = { "*.jar;*.zip;*.tar;*.tar.gz;*.tgz", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
53

54     // dialog store id constants
55
private final static String JavaDoc STORE_SOURCE_NAMES_ID = "WizardZipFileResourceImportPage1.STORE_SOURCE_NAMES_ID"; //$NON-NLS-1$
56

57     private final static String JavaDoc STORE_OVERWRITE_EXISTING_RESOURCES_ID = "WizardZipFileResourceImportPage1.STORE_OVERWRITE_EXISTING_RESOURCES_ID"; //$NON-NLS-1$
58

59     private final static String JavaDoc STORE_SELECTED_TYPES_ID = "WizardZipFileResourceImportPage1.STORE_SELECTED_TYPES_ID"; //$NON-NLS-1$
60

61     /**
62      * Creates an instance of this class
63      * @param aWorkbench IWorkbench
64      * @param selection IStructuredSelection
65      */

66     public WizardArchiveFileResourceImportPage1(IWorkbench aWorkbench,
67             IStructuredSelection selection) {
68         super("zipFileImportPage1", aWorkbench, selection); //$NON-NLS-1$
69
setTitle(DataTransferMessages.ArchiveExport_exportTitle);
70         setDescription(DataTransferMessages.ArchiveImport_description);
71     }
72
73     /**
74      * Called when the user presses the Cancel button. Return a boolean
75      * indicating permission to close the wizard.
76      *
77      * @return boolean
78      */

79     public boolean cancel() {
80         clearProviderCache();
81         return true;
82     }
83
84     /**
85      * Clears the cached structure provider after first finalizing
86      * it properly.
87      */

88     protected void clearProviderCache() {
89         ArchiveFileManipulations.clearProviderCache(getContainer().getShell());
90     }
91
92     /**
93      * Attempts to close the passed zip file, and answers a boolean indicating success.
94      */

95     protected boolean closeZipFile(ZipFile JavaDoc file) {
96         try {
97             file.close();
98         } catch (IOException JavaDoc e) {
99             displayErrorDialog(NLS.bind(DataTransferMessages.ZipImport_couldNotClose, file.getName()));
100             return false;
101         }
102
103         return true;
104     }
105
106     /** (non-Javadoc)
107      * Method declared on IDialogPage.
108      */

109     public void createControl(Composite parent) {
110         super.createControl(parent);
111         PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(),
112                 IDataTransferHelpContextIds.ZIP_FILE_IMPORT_WIZARD_PAGE);
113     }
114
115     /**
116      * Create the options specification widgets. There is only one
117      * in this case so create no group.
118      *
119      * @param parent org.eclipse.swt.widgets.Composite
120      */

121     protected void createOptionsGroup(Composite parent) {
122
123         // overwrite... checkbox
124
overwriteExistingResourcesCheckbox = new Button(parent, SWT.CHECK);
125         overwriteExistingResourcesCheckbox.setText(DataTransferMessages.FileImport_overwriteExisting);
126         overwriteExistingResourcesCheckbox.setFont(parent.getFont());
127     }
128
129     private boolean validateSourceFile(String JavaDoc fileName) {
130         if(ArchiveFileManipulations.isTarFile(fileName)) {
131             TarFile tarFile = getSpecifiedTarSourceFile(fileName);
132             return (tarFile != null);
133         }
134         ZipFile JavaDoc zipFile = getSpecifiedZipSourceFile(fileName);
135         if(zipFile != null) {
136             ArchiveFileManipulations.closeZipFile(zipFile, getContainer()
137                     .getShell());
138             return true;
139         }
140         return false;
141     }
142
143     /**
144      * Answer a boolean indicating whether the specified source currently exists
145      * and is valid (ie.- proper format)
146      */

147     private boolean ensureZipSourceIsValid() {
148         ZipFile JavaDoc specifiedFile = getSpecifiedZipSourceFile();
149         if (specifiedFile == null) {
150             return false;
151         }
152         return ArchiveFileManipulations.closeZipFile(specifiedFile,
153                 getContainer().getShell());
154     }
155
156     private boolean ensureTarSourceIsValid() {
157         TarFile specifiedFile = getSpecifiedTarSourceFile();
158         if( specifiedFile == null ) {
159             return false;
160         }
161         return true;
162     }
163
164     /**
165      * Answer a boolean indicating whether the specified source currently exists
166      * and is valid (ie.- proper format)
167      */

168     protected boolean ensureSourceIsValid() {
169         if (ArchiveFileManipulations.isTarFile(sourceNameField.getText())) {
170             return ensureTarSourceIsValid();
171         }
172         return ensureZipSourceIsValid();
173     }
174     
175     /**
176      * The Finish button was pressed. Try to do the required work now and answer
177      * a boolean indicating success. If <code>false</code> is returned then the
178      * wizard will not close.
179      *
180      * @return boolean
181      */

182     public boolean finish() {
183         if (!super.finish()) {
184             return false;
185         }
186
187         ArchiveFileManipulations.clearProviderCache(getContainer().getShell());
188         return true;
189     }
190
191     /**
192      * Returns a content provider for <code>FileSystemElement</code>s that returns
193      * only files as children.
194      */

195     protected ITreeContentProvider getFileProvider() {
196         return new WorkbenchContentProvider() {
197             public Object JavaDoc[] getChildren(Object JavaDoc o) {
198                 if (o instanceof MinimizedFileSystemElement) {
199                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
200                     AdaptableList l;
201                     if(zipCurrentProvider != null) {
202                         l = element.getFiles(zipCurrentProvider);
203                     } else {
204                         l = element.getFiles(tarCurrentProvider);
205                     }
206                     return l.getChildren(element);
207                 }
208                 return new Object JavaDoc[0];
209             }
210         };
211     }
212
213     /**
214      * Answer the root FileSystemElement that represents the contents of the
215      * currently-specified .zip file. If this FileSystemElement is not
216      * currently defined then create and return it.
217      */

218     protected MinimizedFileSystemElement getFileSystemTree() {
219         if(ArchiveFileManipulations.isTarFile(sourceNameField.getText())) {
220             TarFile sourceTarFile = getSpecifiedTarSourceFile();
221             if (sourceTarFile == null) {
222                 //Clear out the provider as well
223
this.zipCurrentProvider = null;
224                 this.tarCurrentProvider = null;
225                 return null;
226             }
227     
228             TarLeveledStructureProvider provider = ArchiveFileManipulations
229                     .getTarStructureProvider(sourceTarFile, getContainer()
230                             .getShell());
231             this.tarCurrentProvider = provider;
232             this.zipCurrentProvider = null;
233             return selectFiles(provider.getRoot(), provider);
234         }
235
236         ZipFile JavaDoc sourceFile = getSpecifiedZipSourceFile();
237         if (sourceFile == null) {
238             //Clear out the provider as well
239
this.zipCurrentProvider = null;
240             this.tarCurrentProvider = null;
241             return null;
242         }
243
244         ZipLeveledStructureProvider provider = ArchiveFileManipulations
245                 .getZipStructureProvider(sourceFile, getContainer().getShell());
246         this.zipCurrentProvider = provider;
247         this.tarCurrentProvider = null;
248         return selectFiles(provider.getRoot(), provider);
249     }
250
251     /**
252      * Returns a content provider for <code>FileSystemElement</code>s that returns
253      * only folders as children.
254      */

255     protected ITreeContentProvider getFolderProvider() {
256         return new WorkbenchContentProvider() {
257             public Object JavaDoc[] getChildren(Object JavaDoc o) {
258                 if (o instanceof MinimizedFileSystemElement) {
259                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
260                     AdaptableList l;
261                     if(zipCurrentProvider != null) {
262                         l = element.getFolders(zipCurrentProvider);
263                     } else {
264                         l = element.getFolders(tarCurrentProvider);
265                     }
266                     return l.getChildren(element);
267                 }
268                 return new Object JavaDoc[0];
269             }
270
271             public boolean hasChildren(Object JavaDoc o) {
272                 if (o instanceof MinimizedFileSystemElement) {
273                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
274                     if (element.isPopulated()) {
275                         return getChildren(element).length > 0;
276                     }
277
278                     //If we have not populated then wait until asked
279
return true;
280                 }
281                 return false;
282             }
283         };
284     }
285
286     /**
287      * Answer the string to display as the label for the source specification field
288      */

289     protected String JavaDoc getSourceLabel() {
290         return DataTransferMessages.ArchiveImport_fromFile;
291     }
292
293     /**
294      * Answer a handle to the zip file currently specified as being the source.
295      * Return null if this file does not exist or is not of valid format.
296      */

297     protected ZipFile JavaDoc getSpecifiedZipSourceFile() {
298         return getSpecifiedZipSourceFile(sourceNameField.getText());
299     }
300
301     /**
302      * Answer a handle to the zip file currently specified as being the source.
303      * Return null if this file does not exist or is not of valid format.
304      */

305     private ZipFile JavaDoc getSpecifiedZipSourceFile(String JavaDoc fileName) {
306         if (fileName.length() == 0) {
307             return null;
308         }
309
310         try {
311             return new ZipFile JavaDoc(fileName);
312         } catch (ZipException JavaDoc e) {
313             displayErrorDialog(DataTransferMessages.ZipImport_badFormat);
314         } catch (IOException JavaDoc e) {
315             displayErrorDialog(DataTransferMessages.ZipImport_couldNotRead);
316         }
317
318         sourceNameField.setFocus();
319         return null;
320     }
321
322     /**
323      * Answer a handle to the zip file currently specified as being the source.
324      * Return null if this file does not exist or is not of valid format.
325      */

326     protected TarFile getSpecifiedTarSourceFile() {
327         return getSpecifiedTarSourceFile(sourceNameField.getText());
328     }
329
330     /**
331      * Answer a handle to the zip file currently specified as being the source.
332      * Return null if this file does not exist or is not of valid format.
333      */

334     private TarFile getSpecifiedTarSourceFile(String JavaDoc fileName) {
335         if (fileName.length() == 0) {
336             return null;
337         }
338
339         try {
340             return new TarFile(fileName);
341         } catch (TarException e) {
342             displayErrorDialog(DataTransferMessages.TarImport_badFormat);
343         } catch (IOException JavaDoc e) {
344             displayErrorDialog(DataTransferMessages.ZipImport_couldNotRead);
345         }
346
347         sourceNameField.setFocus();
348         return null;
349     }
350
351     /**
352      * Open a FileDialog so that the user can specify the source
353      * file to import from
354      */

355     protected void handleSourceBrowseButtonPressed() {
356         String JavaDoc selectedFile = queryZipFileToImport();
357
358         if (selectedFile != null) {
359             //Be sure it is valid before we go setting any names
360
if (!selectedFile.equals(sourceNameField.getText())
361                     && validateSourceFile(selectedFile)) {
362                 setSourceName(selectedFile);
363                 selectionGroup.setFocus();
364             }
365         }
366     }
367
368     /**
369      * Import the resources with extensions as specified by the user
370      */

371     protected boolean importResources(List JavaDoc fileSystemObjects) {
372         boolean result = false;
373
374         if (ArchiveFileManipulations.isTarFile(sourceNameField.getText())) {
375             if( ensureTarSourceIsValid()) {
376                 TarFile tarFile = getSpecifiedTarSourceFile();
377                 TarLeveledStructureProvider structureProvider = ArchiveFileManipulations
378                         .getTarStructureProvider(tarFile, getContainer()
379                                 .getShell());
380                 ImportOperation operation = new ImportOperation(getContainerFullPath(),
381                         structureProvider.getRoot(), structureProvider, this,
382                         fileSystemObjects);
383     
384                 operation.setContext(getShell());
385                 return executeImportOperation(operation);
386             }
387         }
388
389         if(ensureZipSourceIsValid()) {
390             ZipFile JavaDoc zipFile = getSpecifiedZipSourceFile();
391             ZipLeveledStructureProvider structureProvider = ArchiveFileManipulations
392                     .getZipStructureProvider(zipFile, getContainer().getShell());
393             ImportOperation operation = new ImportOperation(
394                     getContainerFullPath(), structureProvider.getRoot(),
395                     structureProvider, this, fileSystemObjects);
396
397             operation.setContext(getShell());
398             result = executeImportOperation(operation);
399
400             closeZipFile(zipFile);
401         }
402         return result;
403     }
404
405     /**
406      * Initializes the specified operation appropriately.
407      */

408     protected void initializeOperation(ImportOperation op) {
409         op.setOverwriteResources(overwriteExistingResourcesCheckbox
410                 .getSelection());
411     }
412
413     /**
414      * Opens a file selection dialog and returns a string representing the
415      * selected file, or <code>null</code> if the dialog was canceled.
416      */

417     protected String JavaDoc queryZipFileToImport() {
418         FileDialog dialog = new FileDialog(sourceNameField.getShell(), SWT.OPEN);
419         dialog.setFilterExtensions(FILE_IMPORT_MASK);
420         dialog.setText(DataTransferMessages.ArchiveImportSource_title);
421
422         String JavaDoc currentSourceString = sourceNameField.getText();
423         int lastSeparatorIndex = currentSourceString
424                 .lastIndexOf(File.separator);
425         if (lastSeparatorIndex != -1) {
426             dialog.setFilterPath(currentSourceString.substring(0,
427                     lastSeparatorIndex));
428         }
429
430         return dialog.open();
431     }
432
433     /**
434      * Repopulate the view based on the currently entered directory.
435      */

436     protected void resetSelection() {
437
438         super.resetSelection();
439         setAllSelections(true);
440     }
441
442     /**
443      * Use the dialog store to restore widget values to the values that they held
444      * last time this wizard was used to completion
445      */

446     protected void restoreWidgetValues() {
447         IDialogSettings settings = getDialogSettings();
448         if (settings != null) {
449             String JavaDoc[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
450             if (sourceNames == null) {
451                 return; // ie.- no settings stored
452
}
453
454             // set filenames history
455
for (int i = 0; i < sourceNames.length; i++) {
456                 sourceNameField.add(sourceNames[i]);
457             }
458
459             // radio buttons and checkboxes
460
overwriteExistingResourcesCheckbox.setSelection(settings
461                     .getBoolean(STORE_OVERWRITE_EXISTING_RESOURCES_ID));
462         }
463     }
464
465     /**
466      * Since Finish was pressed, write widget values to the dialog store so that they
467      * will persist into the next invocation of this wizard page.
468      *
469      * Note that this method is identical to the one that appears in the superclass.
470      * This is necessary because proper overriding of instance variables is not occurring.
471      */

472     protected void saveWidgetValues() {
473         IDialogSettings settings = getDialogSettings();
474         if (settings != null) {
475             // update source names history
476
String JavaDoc[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
477             if (sourceNames == null) {
478                 sourceNames = new String JavaDoc[0];
479             }
480
481             sourceNames = addToHistory(sourceNames, sourceNameField.getText());
482             settings.put(STORE_SOURCE_NAMES_ID, sourceNames);
483
484             // update specific types to import history
485
String JavaDoc[] selectedTypesNames = settings
486                     .getArray(STORE_SELECTED_TYPES_ID);
487             if (selectedTypesNames == null) {
488                 selectedTypesNames = new String JavaDoc[0];
489             }
490
491             settings.put(STORE_OVERWRITE_EXISTING_RESOURCES_ID,
492                     overwriteExistingResourcesCheckbox.getSelection());
493         }
494     }
495
496     /**
497      * Answer a boolean indicating whether self's source specification
498      * widgets currently all contain valid values.
499      */

500     protected boolean validateSourceGroup() {
501
502         //If there is nothing being provided to the input then there is a problem
503
if (this.zipCurrentProvider == null && this.tarCurrentProvider == null) {
504             setMessage(SOURCE_EMPTY_MESSAGE);
505             enableButtonGroup(false);
506             return false;
507         }
508         
509         List JavaDoc resourcesToExport = selectionGroup.getAllWhiteCheckedItems();
510         if (resourcesToExport.size() == 0){
511             setErrorMessage(DataTransferMessages.FileImport_noneSelected);
512             return false;
513         }
514         
515         enableButtonGroup(true);
516         setErrorMessage(null);
517         return true;
518     }
519 }
520
Popular Tags