KickJava   Java API By Example, From Geeks To Geeks.

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


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.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.List JavaDoc;
16
17 import org.eclipse.core.resources.IContainer;
18 import org.eclipse.core.resources.IProject;
19 import org.eclipse.core.resources.IWorkspaceRoot;
20 import org.eclipse.core.resources.ResourcesPlugin;
21 import org.eclipse.core.runtime.IPath;
22 import org.eclipse.core.runtime.IStatus;
23 import org.eclipse.core.runtime.Path;
24 import org.eclipse.jface.dialogs.ErrorDialog;
25 import org.eclipse.jface.dialogs.IDialogSettings;
26 import org.eclipse.jface.viewers.IStructuredSelection;
27 import org.eclipse.osgi.util.NLS;
28 import org.eclipse.swt.SWT;
29 import org.eclipse.swt.graphics.Font;
30 import org.eclipse.swt.layout.GridData;
31 import org.eclipse.swt.layout.GridLayout;
32 import org.eclipse.swt.widgets.Button;
33 import org.eclipse.swt.widgets.Combo;
34 import org.eclipse.swt.widgets.Composite;
35 import org.eclipse.swt.widgets.DirectoryDialog;
36 import org.eclipse.swt.widgets.Event;
37 import org.eclipse.swt.widgets.Group;
38 import org.eclipse.swt.widgets.Label;
39 import org.eclipse.swt.widgets.Listener;
40 import org.eclipse.swt.widgets.Widget;
41 import org.eclipse.ui.PlatformUI;
42 import org.eclipse.ui.dialogs.WizardExportResourcesPage;
43
44
45 /**
46  * Page 1 of the base resource export-to-file-system Wizard
47  */

48 public class WizardFileSystemResourceExportPage1 extends
49         WizardExportResourcesPage implements Listener {
50
51     // widgets
52
private Combo destinationNameField;
53
54     private Button destinationBrowseButton;
55
56     protected Button overwriteExistingFilesCheckbox;
57
58     protected Button createDirectoryStructureButton;
59
60     protected Button createSelectionOnlyButton;
61
62     // dialog store id constants
63
private static final String JavaDoc STORE_DESTINATION_NAMES_ID = "WizardFileSystemResourceExportPage1.STORE_DESTINATION_NAMES_ID"; //$NON-NLS-1$
64

65     private static final String JavaDoc STORE_OVERWRITE_EXISTING_FILES_ID = "WizardFileSystemResourceExportPage1.STORE_OVERWRITE_EXISTING_FILES_ID"; //$NON-NLS-1$
66

67     private static final String JavaDoc STORE_CREATE_STRUCTURE_ID = "WizardFileSystemResourceExportPage1.STORE_CREATE_STRUCTURE_ID"; //$NON-NLS-1$
68

69     //messages
70
private static final String JavaDoc SELECT_DESTINATION_MESSAGE = DataTransferMessages.FileExport_selectDestinationMessage;
71
72     private static final String JavaDoc SELECT_DESTINATION_TITLE = DataTransferMessages.FileExport_selectDestinationTitle;
73  
74
75     /**
76      * Create an instance of this class
77      */

78     protected WizardFileSystemResourceExportPage1(String JavaDoc name,
79             IStructuredSelection selection) {
80         super(name, selection);
81     }
82
83     /**
84      * Create an instance of this class.
85      *
86      * @param selection the selection
87      */

88     public WizardFileSystemResourceExportPage1(IStructuredSelection selection) {
89         this("fileSystemExportPage1", selection); //$NON-NLS-1$
90
setTitle(DataTransferMessages.DataTransfer_fileSystemTitle);
91         setDescription(DataTransferMessages.FileExport_exportLocalFileSystem);
92     }
93
94     /**
95      * Add the passed value to self's destination widget's history
96      *
97      * @param value java.lang.String
98      */

99     protected void addDestinationItem(String JavaDoc value) {
100         destinationNameField.add(value);
101     }
102
103     /** (non-Javadoc)
104      * Method declared on IDialogPage.
105      */

106     public void createControl(Composite parent) {
107         super.createControl(parent);
108         giveFocusToDestination();
109         PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(),
110                 IDataTransferHelpContextIds.FILE_SYSTEM_EXPORT_WIZARD_PAGE);
111     }
112
113     /**
114      * Create the export destination specification widgets
115      *
116      * @param parent org.eclipse.swt.widgets.Composite
117      */

118     protected void createDestinationGroup(Composite parent) {
119
120         Font font = parent.getFont();
121         // destination specification group
122
Composite destinationSelectionGroup = new Composite(parent, SWT.NONE);
123         GridLayout layout = new GridLayout();
124         layout.numColumns = 3;
125         destinationSelectionGroup.setLayout(layout);
126         destinationSelectionGroup.setLayoutData(new GridData(
127                 GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
128         destinationSelectionGroup.setFont(font);
129
130         Label destinationLabel = new Label(destinationSelectionGroup, SWT.NONE);
131         destinationLabel.setText(getDestinationLabel());
132         destinationLabel.setFont(font);
133
134         // destination name entry field
135
destinationNameField = new Combo(destinationSelectionGroup, SWT.SINGLE
136                 | SWT.BORDER);
137         destinationNameField.addListener(SWT.Modify, this);
138         destinationNameField.addListener(SWT.Selection, this);
139         GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
140                 | GridData.GRAB_HORIZONTAL);
141         data.widthHint = SIZING_TEXT_FIELD_WIDTH;
142         destinationNameField.setLayoutData(data);
143         destinationNameField.setFont(font);
144
145         // destination browse button
146
destinationBrowseButton = new Button(destinationSelectionGroup,
147                 SWT.PUSH);
148         destinationBrowseButton.setText(DataTransferMessages.DataTransfer_browse);
149         destinationBrowseButton.addListener(SWT.Selection, this);
150         destinationBrowseButton.setFont(font);
151         setButtonLayoutData(destinationBrowseButton);
152
153         new Label(parent, SWT.NONE); // vertical spacer
154
}
155
156     /**
157      * Create the buttons in the options group.
158      */

159
160     protected void createOptionsGroupButtons(Group optionsGroup) {
161
162         Font font = optionsGroup.getFont();
163         createOverwriteExisting(optionsGroup, font);
164
165         createDirectoryStructureOptions(optionsGroup, font);
166     }
167
168     /**
169      * Create the buttons for the group that determine if the entire or
170      * selected directory structure should be created.
171      * @param optionsGroup
172      * @param font
173      */

174     protected void createDirectoryStructureOptions(Composite optionsGroup, Font font) {
175         // create directory structure radios
176
createDirectoryStructureButton = new Button(optionsGroup, SWT.RADIO
177                 | SWT.LEFT);
178         createDirectoryStructureButton.setText(DataTransferMessages.FileExport_createDirectoryStructure);
179         createDirectoryStructureButton.setSelection(false);
180         createDirectoryStructureButton.setFont(font);
181
182         // create directory structure radios
183
createSelectionOnlyButton = new Button(optionsGroup, SWT.RADIO
184                 | SWT.LEFT);
185         createSelectionOnlyButton.setText(DataTransferMessages.FileExport_createSelectedDirectories);
186         createSelectionOnlyButton.setSelection(true);
187         createSelectionOnlyButton.setFont(font);
188     }
189
190     /**
191      * Create the button for checking if we should ask if we are going to
192      * overwrite existing files.
193      * @param optionsGroup
194      * @param font
195      */

196     protected void createOverwriteExisting(Group optionsGroup, Font font) {
197         // overwrite... checkbox
198
overwriteExistingFilesCheckbox = new Button(optionsGroup, SWT.CHECK
199                 | SWT.LEFT);
200         overwriteExistingFilesCheckbox.setText(DataTransferMessages.ExportFile_overwriteExisting);
201         overwriteExistingFilesCheckbox.setFont(font);
202     }
203
204     /**
205      * Attempts to ensure that the specified directory exists on the local file system.
206      * Answers a boolean indicating success.
207      *
208      * @return boolean
209      * @param directory java.io.File
210      */

211     protected boolean ensureDirectoryExists(File JavaDoc directory) {
212         if (!directory.exists()) {
213             if (!queryYesNoQuestion(DataTransferMessages.DataTransfer_createTargetDirectory)) {
214                 return false;
215             }
216
217             if (!directory.mkdirs()) {
218                 displayErrorDialog(DataTransferMessages.DataTransfer_directoryCreationError);
219                 giveFocusToDestination();
220                 return false;
221             }
222         }
223
224         return true;
225     }
226
227     /**
228      * If the target for export does not exist then attempt to create it.
229      * Answer a boolean indicating whether the target exists (ie.- if it
230      * either pre-existed or this method was able to create it)
231      *
232      * @return boolean
233      */

234     protected boolean ensureTargetIsValid(File JavaDoc targetDirectory) {
235         if (targetDirectory.exists() && !targetDirectory.isDirectory()) {
236             displayErrorDialog(DataTransferMessages.FileExport_directoryExists);
237             giveFocusToDestination();
238             return false;
239         }
240
241         return ensureDirectoryExists(targetDirectory);
242     }
243
244     /**
245      * Set up and execute the passed Operation. Answer a boolean indicating success.
246      *
247      * @return boolean
248      */

249     protected boolean executeExportOperation(FileSystemExportOperation op) {
250         op.setCreateLeadupStructure(createDirectoryStructureButton
251                 .getSelection());
252         op.setOverwriteFiles(overwriteExistingFilesCheckbox.getSelection());
253
254         try {
255             getContainer().run(true, true, op);
256         } catch (InterruptedException JavaDoc e) {
257             return false;
258         } catch (InvocationTargetException JavaDoc e) {
259             displayErrorDialog(e.getTargetException());
260             return false;
261         }
262
263         IStatus status = op.getStatus();
264         if (!status.isOK()) {
265             ErrorDialog.openError(getContainer().getShell(),
266                     DataTransferMessages.DataTransfer_exportProblems,
267                     null, // no special message
268
status);
269             return false;
270         }
271
272         return true;
273     }
274
275     /**
276      * The Finish button was pressed. Try to do the required work now and answer
277      * a boolean indicating success. If false is returned then the wizard will
278      * not close.
279      *
280      * @return boolean
281      */

282     public boolean finish() {
283         List JavaDoc resourcesToExport = getWhiteCheckedResources();
284         if (!ensureTargetIsValid(new File JavaDoc(getDestinationValue()))) {
285             return false;
286         }
287
288
289         //Save dirty editors if possible but do not stop if not all are saved
290
saveDirtyEditors();
291         // about to invoke the operation so save our state
292
saveWidgetValues();
293
294         return executeExportOperation(new FileSystemExportOperation(null,
295                 resourcesToExport, getDestinationValue(), this));
296     }
297
298     /**
299      * Answer the string to display in self as the destination type
300      *
301      * @return java.lang.String
302      */

303     protected String JavaDoc getDestinationLabel() {
304         return DataTransferMessages.FileExport_toDirectory;
305     }
306
307     /**
308      * Answer the contents of self's destination specification widget
309      *
310      * @return java.lang.String
311      */

312     protected String JavaDoc getDestinationValue() {
313         return destinationNameField.getText().trim();
314     }
315
316     /**
317      * Set the current input focus to self's destination entry field
318      */

319     protected void giveFocusToDestination() {
320         destinationNameField.setFocus();
321     }
322
323     /**
324      * Open an appropriate destination browser so that the user can specify a source
325      * to import from
326      */

327     protected void handleDestinationBrowseButtonPressed() {
328         DirectoryDialog dialog = new DirectoryDialog(getContainer().getShell(),
329                 SWT.SAVE);
330         dialog.setMessage(SELECT_DESTINATION_MESSAGE);
331         dialog.setText(SELECT_DESTINATION_TITLE);
332         dialog.setFilterPath(getDestinationValue());
333         String JavaDoc selectedDirectoryName = dialog.open();
334
335         if (selectedDirectoryName != null) {
336             setErrorMessage(null);
337             setDestinationValue(selectedDirectoryName);
338         }
339     }
340
341     /**
342      * Handle all events and enablements for widgets in this page
343      * @param e Event
344      */

345     public void handleEvent(Event e) {
346         Widget source = e.widget;
347
348         if (source == destinationBrowseButton) {
349             handleDestinationBrowseButtonPressed();
350         }
351
352         updatePageCompletion();
353     }
354
355     /**
356      * Hook method for saving widget values for restoration by the next instance
357      * of this class.
358      */

359     protected void internalSaveWidgetValues() {
360         // update directory names history
361
IDialogSettings settings = getDialogSettings();
362         if (settings != null) {
363             String JavaDoc[] directoryNames = settings
364                     .getArray(STORE_DESTINATION_NAMES_ID);
365             if (directoryNames == null) {
366                 directoryNames = new String JavaDoc[0];
367             }
368
369             directoryNames = addToHistory(directoryNames, getDestinationValue());
370             settings.put(STORE_DESTINATION_NAMES_ID, directoryNames);
371
372             // options
373
settings.put(STORE_OVERWRITE_EXISTING_FILES_ID,
374                     overwriteExistingFilesCheckbox.getSelection());
375
376             settings.put(STORE_CREATE_STRUCTURE_ID,
377                     createDirectoryStructureButton.getSelection());
378
379         }
380     }
381
382     /**
383      * Hook method for restoring widget values to the values that they held
384      * last time this wizard was used to completion.
385      */

386     protected void restoreWidgetValues() {
387         IDialogSettings settings = getDialogSettings();
388         if (settings != null) {
389             String JavaDoc[] directoryNames = settings
390                     .getArray(STORE_DESTINATION_NAMES_ID);
391             if (directoryNames == null) {
392                 return; // ie.- no settings stored
393
}
394
395             // destination
396
setDestinationValue(directoryNames[0]);
397             for (int i = 0; i < directoryNames.length; i++) {
398                 addDestinationItem(directoryNames[i]);
399             }
400
401             // options
402
overwriteExistingFilesCheckbox.setSelection(settings
403                     .getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID));
404
405             boolean createDirectories = settings
406                     .getBoolean(STORE_CREATE_STRUCTURE_ID);
407             createDirectoryStructureButton.setSelection(createDirectories);
408             createSelectionOnlyButton.setSelection(!createDirectories);
409         }
410     }
411
412     /**
413      * Set the contents of the receivers destination specification widget to
414      * the passed value
415      *
416      */

417     protected void setDestinationValue(String JavaDoc value) {
418         destinationNameField.setText(value);
419     }
420
421     /**
422      * Answer a boolean indicating whether the receivers destination specification
423      * widgets currently all contain valid values.
424      */

425     protected boolean validateDestinationGroup() {
426         String JavaDoc destinationValue = getDestinationValue();
427         if (destinationValue.length() == 0) {
428             setMessage(destinationEmptyMessage());
429             return false;
430         }
431
432         String JavaDoc conflictingContainer = getConflictingContainerNameFor(destinationValue);
433         if (conflictingContainer == null) {
434             // no error message, but warning may exists
435
String JavaDoc threatenedContainer = getOverlappingProjectName(destinationValue);
436             if(threatenedContainer == null)
437                 setMessage(null);
438             else
439                 setMessage(
440                     NLS.bind(DataTransferMessages.FileExport_conflictingContainer, threatenedContainer),
441                     WARNING);
442             
443         } else {
444             setErrorMessage(NLS.bind(DataTransferMessages.FileExport_conflictingContainer, conflictingContainer));
445             giveFocusToDestination();
446             return false;
447         }
448
449         return true;
450     }
451
452     /*
453      * (non-Javadoc)
454      * @see org.eclipse.ui.dialogs.WizardDataTransferPage#validateSourceGroup()
455      */

456     protected boolean validateSourceGroup() {
457         // there must be some resources selected for Export
458
boolean isValid = true;
459         List JavaDoc resourcesToExport = getWhiteCheckedResources();
460         if (resourcesToExport.size() == 0){
461             setErrorMessage(DataTransferMessages.FileExport_noneSelected);
462             isValid = false;
463         } else {
464             setErrorMessage(null);
465         }
466         return super.validateSourceGroup() && isValid;
467     }
468
469     /**
470      * Get the message used to denote an empty destination.
471      */

472     protected String JavaDoc destinationEmptyMessage() {
473         return DataTransferMessages.FileExport_destinationEmpty;
474     }
475
476     /**
477      * Returns the name of a container with a location that encompasses targetDirectory.
478      * Returns null if there is no conflict.
479      *
480      * @param targetDirectory the path of the directory to check.
481      * @return the conflicting container name or <code>null</code>
482      */

483     protected String JavaDoc getConflictingContainerNameFor(String JavaDoc targetDirectory) {
484
485         IPath rootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
486         IPath testPath = new Path(targetDirectory);
487         // cannot export into workspace root
488
if(testPath.equals(rootPath))
489             return rootPath.lastSegment();
490         
491         //Are they the same?
492
if(testPath.matchingFirstSegments(rootPath) == rootPath.segmentCount()){
493             String JavaDoc firstSegment = testPath.removeFirstSegments(rootPath.segmentCount()).segment(0);
494             if(!Character.isLetterOrDigit(firstSegment.charAt(0)))
495                 return firstSegment;
496         }
497
498         return null;
499
500     }
501     
502     /**
503      * Returns the name of a {@link IProject} with a location that includes
504      * targetDirectory. Returns null if there is no such {@link IProject}.
505      *
506      * @param targetDirectory
507      * the path of the directory to check.
508      * @return the overlapping project name or <code>null</code>
509      */

510     private String JavaDoc getOverlappingProjectName(String JavaDoc targetDirectory){
511         IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
512         IPath testPath = new Path(targetDirectory);
513         IContainer[] containers = root.findContainersForLocation(testPath);
514         if(containers.length > 0){
515             return containers[0].getProject().getName();
516         }
517         return null;
518     }
519     
520
521 }
522
Popular Tags