KickJava   Java API By Example, From Geeks To Geeks.

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


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

11 package org.eclipse.ui.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.swt.SWT;
23 import org.eclipse.swt.widgets.*;
24 import org.eclipse.ui.IWorkbench;
25 import org.eclipse.ui.help.WorkbenchHelp;
26 import org.eclipse.ui.model.WorkbenchContentProvider;
27
28 /**
29  * Page 1 of the base resource import-from-zip Wizard.
30  *
31  * Note that importing from .jar is identical to importing from .zip, so
32  * all references to .zip in this class are equally applicable to .jar
33  * references.
34  */

35 /*package*/
36 class WizardZipFileResourceImportPage1
37     extends WizardFileSystemResourceImportPage1
38     implements Listener {
39     private ZipFileStructureProvider providerCache;
40     ZipFileStructureProvider currentProvider;
41
42     // constants
43
private static final String JavaDoc FILE_IMPORT_MASK = "*.jar;*.zip"; //$NON-NLS-1$
44

45     // dialog store id constants
46
private final static String JavaDoc STORE_SOURCE_NAMES_ID =
47         "WizardZipFileResourceImportPage1.STORE_SOURCE_NAMES_ID"; //$NON-NLS-1$
48
private final static String JavaDoc STORE_OVERWRITE_EXISTING_RESOURCES_ID =
49         "WizardZipFileResourceImportPage1.STORE_OVERWRITE_EXISTING_RESOURCES_ID"; //$NON-NLS-1$
50
private final static String JavaDoc STORE_SELECTED_TYPES_ID =
51         "WizardZipFileResourceImportPage1.STORE_SELECTED_TYPES_ID"; //$NON-NLS-1$
52
/**
53      * Creates an instance of this class
54      * @param aWorkbench IWorkbench
55      * @param selection IStructuredSelection
56      */

57     public WizardZipFileResourceImportPage1(
58         IWorkbench aWorkbench,
59         IStructuredSelection selection) {
60         super("zipFileImportPage1", aWorkbench, selection); //$NON-NLS-1$
61
setTitle(DataTransferMessages.getString("ZipExport.exportTitle")); //$NON-NLS-1$
62
setDescription(DataTransferMessages.getString("ZipImport.description")); //$NON-NLS-1$
63
}
64     /**
65      * Called when the user presses the Cancel button. Return a boolean
66      * indicating permission to close the wizard.
67      *
68      * @return boolean
69      */

70     public boolean cancel() {
71         clearProviderCache();
72         return true;
73     }
74     /**
75      * Clears the cached structure provider after first finalizing
76      * it properly.
77      */

78     protected void clearProviderCache() {
79         if (providerCache != null) {
80             closeZipFile(providerCache.getZipFile());
81             providerCache = null;
82         }
83     }
84     /**
85      * Attempts to close the passed zip file, and answers a boolean indicating success.
86      */

87     protected boolean closeZipFile(ZipFile JavaDoc file) {
88         try {
89             file.close();
90         } catch (IOException JavaDoc e) {
91             displayErrorDialog(DataTransferMessages.format("ZipImport.couldNotClose", new Object JavaDoc[] { file.getName()})); //$NON-NLS-1$
92
return false;
93         }
94
95         return true;
96     }
97     /** (non-Javadoc)
98      * Method declared on IDialogPage.
99      */

100     public void createControl(Composite parent) {
101         super.createControl(parent);
102         WorkbenchHelp.setHelp(
103             getControl(),
104             IDataTransferHelpContextIds.ZIP_FILE_IMPORT_WIZARD_PAGE);
105     }
106     /**
107      * Create the options specification widgets. There is only one
108      * in this case so create no group.
109      *
110      * @param parent org.eclipse.swt.widgets.Composite
111      */

112     protected void createOptionsGroup(Composite parent) {
113
114         // overwrite... checkbox
115
overwriteExistingResourcesCheckbox = new Button(parent, SWT.CHECK);
116         overwriteExistingResourcesCheckbox.setText(DataTransferMessages.getString("FileImport.overwriteExisting")); //$NON-NLS-1$
117
overwriteExistingResourcesCheckbox.setFont(parent.getFont());
118     }
119     /**
120      * Answer a boolean indicating whether the specified source currently exists
121      * and is valid (ie.- proper format)
122      */

123     protected boolean ensureSourceIsValid() {
124         ZipFile JavaDoc specifiedFile = getSpecifiedSourceFile();
125
126         if (specifiedFile == null)
127             return false;
128
129         return closeZipFile(specifiedFile);
130     }
131     /**
132      * The Finish button was pressed. Try to do the required work now and answer
133      * a boolean indicating success. If <code>false</code> is returned then the
134      * wizard will not close.
135      *
136      * @return boolean
137      */

138     public boolean finish() {
139         if (!super.finish())
140             return false;
141
142         clearProviderCache();
143         return true;
144     }
145     /**
146      * Returns a content provider for <code>FileSystemElement</code>s that returns
147      * only files as children.
148      */

149     protected ITreeContentProvider getFileProvider() {
150         return new WorkbenchContentProvider() {
151             public Object JavaDoc[] getChildren(Object JavaDoc o) {
152                 if (o instanceof MinimizedFileSystemElement) {
153                     MinimizedFileSystemElement element =
154                         (MinimizedFileSystemElement) o;
155                     return element.getFiles(currentProvider).getChildren(
156                         element);
157                 }
158                 return new Object JavaDoc[0];
159             }
160         };
161     }
162     /**
163      * Answer the root FileSystemElement that represents the contents of the
164      * currently-specified .zip file. If this FileSystemElement is not
165      * currently defined then create and return it.
166      */

167     protected MinimizedFileSystemElement getFileSystemTree() {
168
169         ZipFile JavaDoc sourceFile = getSpecifiedSourceFile();
170         if (sourceFile == null) {
171             //Clear out the provider as well
172
this.currentProvider = null;
173             return null;
174         }
175
176         ZipFileStructureProvider provider = getStructureProvider(sourceFile);
177         this.currentProvider = provider;
178         return selectFiles(provider.getRoot(), provider);
179     }
180     /**
181      * Returns a content provider for <code>FileSystemElement</code>s that returns
182      * only folders as children.
183      */

184     protected ITreeContentProvider getFolderProvider() {
185         return new WorkbenchContentProvider() {
186             public Object JavaDoc[] getChildren(Object JavaDoc o) {
187                 if (o instanceof MinimizedFileSystemElement) {
188                     MinimizedFileSystemElement element =
189                         (MinimizedFileSystemElement) o;
190                     return element.getFolders(currentProvider).getChildren(
191                         element);
192                 }
193                 return new Object JavaDoc[0];
194             }
195             public boolean hasChildren(Object JavaDoc o) {
196                 if (o instanceof MinimizedFileSystemElement) {
197                     MinimizedFileSystemElement element =
198                         (MinimizedFileSystemElement) o;
199                     if (element.isPopulated())
200                         return getChildren(element).length > 0;
201                     else {
202                         //If we have not populated then wait until asked
203
return true;
204                     }
205                 }
206                 return false;
207             }
208         };
209     }
210     /**
211      * Answer the string to display as the label for the source specification field
212      */

213     protected String JavaDoc getSourceLabel() {
214         return DataTransferMessages.getString("ZipImport.fromFile"); //$NON-NLS-1$
215
}
216     /**
217      * Answer a handle to the zip file currently specified as being the source.
218      * Return null if this file does not exist or is not of valid format.
219      */

220     protected ZipFile JavaDoc getSpecifiedSourceFile() {
221         return getSpecifiedSourceFile(sourceNameField.getText());
222     }
223     /**
224      * Answer a handle to the zip file currently specified as being the source.
225      * Return null if this file does not exist or is not of valid format.
226      */

227     private ZipFile JavaDoc getSpecifiedSourceFile(String JavaDoc fileName) {
228         if (fileName.length() == 0)
229             return null;
230
231         try {
232             return new ZipFile JavaDoc(fileName);
233         } catch (ZipException JavaDoc e) {
234             displayErrorDialog(DataTransferMessages.getString("ZipImport.badFormat")); //$NON-NLS-1$
235
} catch (IOException JavaDoc e) {
236             displayErrorDialog(DataTransferMessages.getString("ZipImport.couldNotRead")); //$NON-NLS-1$
237
}
238
239         sourceNameField.setFocus();
240         return null;
241     }
242     /**
243      * Returns a structure provider for the specified zip file.
244      */

245     protected ZipFileStructureProvider getStructureProvider(ZipFile JavaDoc targetZip) {
246         if (providerCache == null)
247             providerCache = new ZipFileStructureProvider(targetZip);
248         else if (
249             !providerCache.getZipFile().getName().equals(
250                 targetZip.getName())) {
251             clearProviderCache();
252             // ie.- new value, so finalize&remove old value
253
providerCache = new ZipFileStructureProvider(targetZip);
254         } else if (!providerCache.getZipFile().equals(targetZip))
255             closeZipFile(targetZip); // ie.- duplicate handle to same .zip
256

257         return providerCache;
258     }
259     /**
260      * Open a FileDialog so that the user can specify the source
261      * file to import from
262      */

263     protected void handleSourceBrowseButtonPressed() {
264         String JavaDoc selectedFile = queryZipFileToImport();
265
266         if (selectedFile != null) {
267             if (!selectedFile.equals(sourceNameField.getText())) {
268                 //Be sure it is valid before we go setting any names
269
ZipFile JavaDoc sourceFile = getSpecifiedSourceFile(selectedFile);
270                 if (sourceFile != null) {
271                     closeZipFile(sourceFile);
272                     setSourceName(selectedFile);
273                     selectionGroup.setFocus();
274                 }
275             }
276         }
277     }
278     /**
279      * Import the resources with extensions as specified by the user
280      */

281     protected boolean importResources(List JavaDoc fileSystemObjects) {
282         ZipFile JavaDoc zipFile = getSpecifiedSourceFile();
283         ZipFileStructureProvider structureProvider =
284             getStructureProvider(zipFile);
285         ImportOperation operation =
286             new ImportOperation(
287                 getContainerFullPath(),
288                 structureProvider.getRoot(),
289                 structureProvider,
290                 this,
291                 fileSystemObjects);
292
293         operation.setContext(getShell());
294         boolean result = executeImportOperation(operation);
295
296         closeZipFile(zipFile);
297
298         return result;
299     }
300     /**
301      * Initializes the specified operation appropriately.
302      */

303     protected void initializeOperation(ImportOperation op) {
304         op.setOverwriteResources(
305             overwriteExistingResourcesCheckbox.getSelection());
306     }
307     /**
308      * Opens a file selection dialog and returns a string representing the
309      * selected file, or <code>null</code> if the dialog was canceled.
310      */

311     protected String JavaDoc queryZipFileToImport() {
312         FileDialog dialog =
313             new FileDialog(sourceNameField.getShell(), SWT.OPEN);
314         dialog.setFilterExtensions(new String JavaDoc[] { FILE_IMPORT_MASK });
315         dialog.setText(DataTransferMessages.getString("ZipImportSource.title")); //$NON-NLS-1$
316

317         String JavaDoc currentSourceString = sourceNameField.getText();
318         int lastSeparatorIndex =
319             currentSourceString.lastIndexOf(File.separator);
320         if (lastSeparatorIndex != -1)
321             dialog.setFilterPath(
322                 currentSourceString.substring(0, lastSeparatorIndex));
323
324         return dialog.open();
325     }
326     /**
327      * Repopulate the view based on the currently entered directory.
328      */

329     protected void resetSelection() {
330
331         super.resetSelection();
332         setAllSelections(true);
333     }
334     /**
335      * Use the dialog store to restore widget values to the values that they held
336      * last time this wizard was used to completion
337      */

338     protected void restoreWidgetValues() {
339         IDialogSettings settings = getDialogSettings();
340         if (settings != null) {
341             String JavaDoc[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
342             if (sourceNames == null)
343                 return; // ie.- no settings stored
344

345             // set filenames history
346
for (int i = 0; i < sourceNames.length; i++)
347                 sourceNameField.add(sourceNames[i]);
348
349             // radio buttons and checkboxes
350
overwriteExistingResourcesCheckbox.setSelection(
351                 settings.getBoolean(STORE_OVERWRITE_EXISTING_RESOURCES_ID));
352         }
353     }
354     /**
355      * Since Finish was pressed, write widget values to the dialog store so that they
356      * will persist into the next invocation of this wizard page.
357      *
358      * Note that this method is identical to the one that appears in the superclass.
359      * This is necessary because proper overriding of instance variables is not occurring.
360      */

361     protected void saveWidgetValues() {
362         IDialogSettings settings = getDialogSettings();
363         if (settings != null) {
364             // update source names history
365
String JavaDoc[] sourceNames = settings.getArray(STORE_SOURCE_NAMES_ID);
366             if (sourceNames == null)
367                 sourceNames = new String JavaDoc[0];
368
369             sourceNames = addToHistory(sourceNames, sourceNameField.getText());
370             settings.put(STORE_SOURCE_NAMES_ID, sourceNames);
371
372             // update specific types to import history
373
String JavaDoc[] selectedTypesNames =
374                 settings.getArray(STORE_SELECTED_TYPES_ID);
375             if (selectedTypesNames == null)
376                 selectedTypesNames = new String JavaDoc[0];
377
378             settings.put(
379                 STORE_OVERWRITE_EXISTING_RESOURCES_ID,
380                 overwriteExistingResourcesCheckbox.getSelection());
381         }
382     }
383     /**
384      * Answer a boolean indicating whether self's source specification
385      * widgets currently all contain valid values.
386      */

387     protected boolean validateSourceGroup() {
388
389         //If there is nothing being provided to the input then there is a problem
390
if (this.currentProvider == null) {
391             setMessage(SOURCE_EMPTY_MESSAGE);
392             enableButtonGroup(false);
393             return false;
394         } else {
395             enableButtonGroup(true);
396             return true;
397         }
398     }
399 }
400
Popular Tags