KickJava   Java API By Example, From Geeks To Geeks.

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


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  *******************************************************************************/

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

42 public class WizardZipFileResourceImportPage1 extends
43         WizardFileSystemResourceImportPage1 implements Listener {
44     private ZipFileStructureProvider providerCache;
45
46     ZipFileStructureProvider currentProvider;
47
48     // constants
49
private static final String JavaDoc[] FILE_IMPORT_MASK = { "*.jar;*.zip", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
50

51     // dialog store id constants
52
private final static String JavaDoc STORE_SOURCE_NAMES_ID = "WizardZipFileResourceImportPage1.STORE_SOURCE_NAMES_ID"; //$NON-NLS-1$
53

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

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

58     /**
59      * Creates an instance of this class
60      * @param aWorkbench IWorkbench
61      * @param selection IStructuredSelection
62      */

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

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

85     protected void clearProviderCache() {
86         if (providerCache != null) {
87             closeZipFile(providerCache.getZipFile());
88             providerCache = null;
89         }
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     /**
130      * Answer a boolean indicating whether the specified source currently exists
131      * and is valid (ie.- proper format)
132      */

133     protected boolean ensureSourceIsValid() {
134         ZipFile JavaDoc specifiedFile = getSpecifiedSourceFile();
135
136         if (specifiedFile == null) {
137             return false;
138         }
139
140         return closeZipFile(specifiedFile);
141     }
142
143     /**
144      * The Finish button was pressed. Try to do the required work now and answer
145      * a boolean indicating success. If <code>false</code> is returned then the
146      * wizard will not close.
147      *
148      * @return boolean
149      */

150     public boolean finish() {
151         if (!super.finish()) {
152             return false;
153         }
154
155         clearProviderCache();
156         return true;
157     }
158
159     /**
160      * Returns a content provider for <code>FileSystemElement</code>s that returns
161      * only files as children.
162      */

163     protected ITreeContentProvider getFileProvider() {
164         return new WorkbenchContentProvider() {
165             public Object JavaDoc[] getChildren(Object JavaDoc o) {
166                 if (o instanceof MinimizedFileSystemElement) {
167                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
168                     return element.getFiles(currentProvider).getChildren(
169                             element);
170                 }
171                 return new Object JavaDoc[0];
172             }
173         };
174     }
175
176     /**
177      * Answer the root FileSystemElement that represents the contents of the
178      * currently-specified .zip file. If this FileSystemElement is not
179      * currently defined then create and return it.
180      */

181     protected MinimizedFileSystemElement getFileSystemTree() {
182
183         ZipFile JavaDoc sourceFile = getSpecifiedSourceFile();
184         if (sourceFile == null) {
185             //Clear out the provider as well
186
this.currentProvider = null;
187             return null;
188         }
189
190         ZipFileStructureProvider provider = getStructureProvider(sourceFile);
191         this.currentProvider = provider;
192         return selectFiles(provider.getRoot(), provider);
193     }
194
195     /**
196      * Returns a content provider for <code>FileSystemElement</code>s that returns
197      * only folders as children.
198      */

199     protected ITreeContentProvider getFolderProvider() {
200         return new WorkbenchContentProvider() {
201             public Object JavaDoc[] getChildren(Object JavaDoc o) {
202                 if (o instanceof MinimizedFileSystemElement) {
203                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
204                     return element.getFolders(currentProvider).getChildren(
205                             element);
206                 }
207                 return new Object JavaDoc[0];
208             }
209
210             public boolean hasChildren(Object JavaDoc o) {
211                 if (o instanceof MinimizedFileSystemElement) {
212                     MinimizedFileSystemElement element = (MinimizedFileSystemElement) o;
213                     if (element.isPopulated()) {
214                         return getChildren(element).length > 0;
215                     } else {
216                         //If we have not populated then wait until asked
217
return true;
218                     }
219                 }
220                 return false;
221             }
222         };
223     }
224
225     /**
226      * Answer the string to display as the label for the source specification field
227      */

228     protected String JavaDoc getSourceLabel() {
229         return DataTransferMessages.ZipImport_fromFile;
230     }
231
232     /**
233      * Answer a handle to the zip file currently specified as being the source.
234      * Return null if this file does not exist or is not of valid format.
235      */

236     protected ZipFile JavaDoc getSpecifiedSourceFile() {
237         return getSpecifiedSourceFile(sourceNameField.getText());
238     }
239
240     /**
241      * Answer a handle to the zip file currently specified as being the source.
242      * Return null if this file does not exist or is not of valid format.
243      */

244     private ZipFile JavaDoc getSpecifiedSourceFile(String JavaDoc fileName) {
245         if (fileName.length() == 0) {
246             return null;
247         }
248
249         try {
250             return new ZipFile JavaDoc(fileName);
251         } catch (ZipException JavaDoc e) {
252             displayErrorDialog(DataTransferMessages.ZipImport_badFormat);
253         } catch (IOException JavaDoc e) {
254             displayErrorDialog(DataTransferMessages.ZipImport_couldNotRead);
255         }
256
257         sourceNameField.setFocus();
258         return null;
259     }
260
261     /**
262      * Returns a structure provider for the specified zip file.
263      */

264     protected ZipFileStructureProvider getStructureProvider(ZipFile JavaDoc targetZip) {
265         if (providerCache == null) {
266             providerCache = new ZipFileStructureProvider(targetZip);
267         } else if (!providerCache.getZipFile().getName().equals(
268                 targetZip.getName())) {
269             clearProviderCache();
270             // ie.- new value, so finalize&remove old value
271
providerCache = new ZipFileStructureProvider(targetZip);
272         } else if (!providerCache.getZipFile().equals(targetZip)) {
273             closeZipFile(targetZip); // ie.- duplicate handle to same .zip
274
}
275
276         return providerCache;
277     }
278
279     /**
280      * Open a FileDialog so that the user can specify the source
281      * file to import from
282      */

283     protected void handleSourceBrowseButtonPressed() {
284         String JavaDoc selectedFile = queryZipFileToImport();
285
286         if (selectedFile != null) {
287             if (!selectedFile.equals(sourceNameField.getText())) {
288                 //Be sure it is valid before we go setting any names
289
ZipFile JavaDoc sourceFile = getSpecifiedSourceFile(selectedFile);
290                 if (sourceFile != null) {
291                     closeZipFile(sourceFile);
292                     setSourceName(selectedFile);
293                     selectionGroup.setFocus();
294                 }
295             }
296         }
297     }
298
299     /**
300      * Import the resources with extensions as specified by the user
301      */

302     protected boolean importResources(List JavaDoc fileSystemObjects) {
303         ZipFile JavaDoc zipFile = getSpecifiedSourceFile();
304         ZipFileStructureProvider structureProvider = getStructureProvider(zipFile);
305         ImportOperation operation = new ImportOperation(getContainerFullPath(),
306                 structureProvider.getRoot(), structureProvider, this,
307                 fileSystemObjects);
308
309         operation.setContext(getShell());
310         boolean result = executeImportOperation(operation);
311
312         closeZipFile(zipFile);
313
314         return result;
315     }
316
317     /**
318      * Initializes the specified operation appropriately.
319      */

320     protected void initializeOperation(ImportOperation op) {
321         op.setOverwriteResources(overwriteExistingResourcesCheckbox
322                 .getSelection());
323     }
324
325     /**
326      * Opens a file selection dialog and returns a string representing the
327      * selected file, or <code>null</code> if the dialog was canceled.
328      */

329     protected String JavaDoc queryZipFileToImport() {
330         FileDialog dialog = new FileDialog(sourceNameField.getShell(), SWT.OPEN);
331         dialog.setFilterExtensions(FILE_IMPORT_MASK);
332         dialog.setText(DataTransferMessages.ZipImportSource_title);
333
334         String JavaDoc currentSourceString = sourceNameField.getText();
335         int lastSeparatorIndex = currentSourceString
336                 .lastIndexOf(File.separator);
337         if (lastSeparatorIndex != -1) {
338             dialog.setFilterPath(currentSourceString.substring(0,
339                     lastSeparatorIndex));
340         }
341
342         return dialog.open();
343     }
344
345     /**
346      * Repopulate the view based on the currently entered directory.
347      */

348     protected void resetSelection() {
349
350         super.resetSelection();
351         setAllSelections(true);
352     }
353
354     /**
355      * Use the dialog store to restore widget values to the values that they held
356      * last time this wizard was used to completion
357      */

358     protected void restoreWidgetValues() {
359         IDialogSettings settings = getDialogSettings();
360         if (settings != null) {
361             String JavaDoc[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
362             if (sourceNames == null) {
363                 return; // ie.- no settings stored
364
}
365
366             // set filenames history
367
for (int i = 0; i < sourceNames.length; i++) {
368                 sourceNameField.add(sourceNames[i]);
369             }
370
371             // radio buttons and checkboxes
372
overwriteExistingResourcesCheckbox.setSelection(settings
373                     .getBoolean(STORE_OVERWRITE_EXISTING_RESOURCES_ID));
374         }
375     }
376
377     /**
378      * Since Finish was pressed, write widget values to the dialog store so that they
379      * will persist into the next invocation of this wizard page.
380      *
381      * Note that this method is identical to the one that appears in the superclass.
382      * This is necessary because proper overriding of instance variables is not occurring.
383      */

384     protected void saveWidgetValues() {
385         IDialogSettings settings = getDialogSettings();
386         if (settings != null) {
387             // update source names history
388
String JavaDoc[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
389             if (sourceNames == null) {
390                 sourceNames = new String JavaDoc[0];
391             }
392
393             sourceNames = addToHistory(sourceNames, sourceNameField.getText());
394             settings.put(STORE_SOURCE_NAMES_ID, sourceNames);
395
396             // update specific types to import history
397
String JavaDoc[] selectedTypesNames = settings
398                     .getArray(STORE_SELECTED_TYPES_ID);
399             if (selectedTypesNames == null) {
400                 selectedTypesNames = new String JavaDoc[0];
401             }
402
403             settings.put(STORE_OVERWRITE_EXISTING_RESOURCES_ID,
404                     overwriteExistingResourcesCheckbox.getSelection());
405         }
406     }
407
408     /**
409      * Answer a boolean indicating whether self's source specification
410      * widgets currently all contain valid values.
411      */

412     protected boolean validateSourceGroup() {
413
414         //If there is nothing being provided to the input then there is a problem
415
if (this.currentProvider == null) {
416             setMessage(SOURCE_EMPTY_MESSAGE);
417             enableButtonGroup(false);
418             return false;
419         } else {
420             enableButtonGroup(true);
421             return true;
422         }
423     }
424 }
425
Popular Tags