KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > ui > datatransfer > ExternalAntBuildfileImportPage


1 /*******************************************************************************
2  * Copyright (c) 2000, 2004 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.ant.internal.ui.datatransfer;
12
13 import java.io.BufferedReader JavaDoc;
14 import java.io.File JavaDoc;
15 import java.io.FileInputStream JavaDoc;
16 import java.io.FileNotFoundException JavaDoc;
17 import java.io.IOException JavaDoc;
18 import java.io.InputStream JavaDoc;
19 import java.io.InputStreamReader JavaDoc;
20 import java.io.UnsupportedEncodingException JavaDoc;
21 import java.lang.reflect.InvocationTargetException JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25
26 import org.apache.tools.ant.Task;
27 import org.apache.tools.ant.UnknownElement;
28 import org.apache.tools.ant.taskdefs.Javac;
29 import org.eclipse.ant.internal.ui.editor.model.AntElementNode;
30 import org.eclipse.ant.internal.ui.editor.model.AntProjectNode;
31 import org.eclipse.ant.internal.ui.editor.model.AntTargetNode;
32 import org.eclipse.ant.internal.ui.editor.model.AntTaskNode;
33 import org.eclipse.ant.internal.ui.editor.outline.AntModel;
34 import org.eclipse.ant.internal.ui.editor.outline.LocationProvider;
35 import org.eclipse.ant.internal.ui.editor.outline.XMLCore;
36 import org.eclipse.ant.internal.ui.model.AntUIPlugin;
37 import org.eclipse.core.resources.IProject;
38 import org.eclipse.core.resources.ResourcesPlugin;
39 import org.eclipse.core.runtime.CoreException;
40 import org.eclipse.core.runtime.IPath;
41 import org.eclipse.core.runtime.IProgressMonitor;
42 import org.eclipse.core.runtime.Path;
43 import org.eclipse.jdt.core.IJavaProject;
44 import org.eclipse.jface.dialogs.ErrorDialog;
45 import org.eclipse.jface.text.Document;
46 import org.eclipse.jface.text.IDocument;
47 import org.eclipse.jface.wizard.WizardPage;
48 import org.eclipse.swt.SWT;
49 import org.eclipse.swt.events.SelectionAdapter;
50 import org.eclipse.swt.events.SelectionEvent;
51 import org.eclipse.swt.graphics.Font;
52 import org.eclipse.swt.layout.GridData;
53 import org.eclipse.swt.layout.GridLayout;
54 import org.eclipse.swt.widgets.Button;
55 import org.eclipse.swt.widgets.Composite;
56 import org.eclipse.swt.widgets.Event;
57 import org.eclipse.swt.widgets.FileDialog;
58 import org.eclipse.swt.widgets.Label;
59 import org.eclipse.swt.widgets.Listener;
60 import org.eclipse.swt.widgets.Text;
61 import org.eclipse.ui.actions.WorkspaceModifyOperation;
62 import org.eclipse.ui.dialogs.IOverwriteQuery;
63 import org.eclipse.ui.help.WorkbenchHelp;
64 import org.eclipse.ui.internal.ide.IHelpContextIds;
65 import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
66 import org.eclipse.ui.wizards.datatransfer.IImportStructureProvider;
67 import org.eclipse.ui.wizards.datatransfer.ImportOperation;
68
69 public class ExternalAntBuildfileImportPage extends WizardPage {
70     
71     private static class ImportOverwriteQuery implements IOverwriteQuery {
72         public String JavaDoc queryOverwrite(String JavaDoc file) {
73             return ALL;
74         }
75     }
76
77     //private static String previouslyBrowsedDirectory = ""; //$NON-NLS-1$
78

79     private Text projectNameField;
80     private Text locationPathField;
81     private Button browseButton;
82     
83     private AntModel fAntModel;
84
85     private Listener locationModifyListener = new Listener() {
86         public void handleEvent(Event e) {
87             fAntModel= getAntModel(getBuildFile(getProjectLocationFieldValue()));
88             setProjectName();
89             setPageComplete(validatePage());
90         }
91     };
92     
93     private Listener nameModifyListener = new Listener() {
94         public void handleEvent(Event e) {
95             setPageComplete(validatePage());
96         }
97     };
98
99     private static final int SIZING_TEXT_FIELD_WIDTH = 250;
100     
101     public ExternalAntBuildfileImportPage() {
102         super("externalAntBuildfilePage"); //$NON-NLS-1$
103
setPageComplete(false);
104         setTitle(DataTransferMessages.getString("ExternalAntBuildfileImportPage.9")); //$NON-NLS-1$
105
setDescription(DataTransferMessages.getString("ExternalAntBuildfileImportPage.10")); //$NON-NLS-1$
106

107     }
108     /* (non-Javadoc)
109      * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
110      */

111     public void createControl(Composite parent) {
112         
113         initializeDialogUnits(parent);
114         
115         Composite composite = new Composite(parent, SWT.NULL);
116
117         WorkbenchHelp.setHelp(composite, IHelpContextIds.NEW_PROJECT_WIZARD_PAGE);
118
119         composite.setLayout(new GridLayout());
120         composite.setLayoutData(new GridData(GridData.FILL_BOTH));
121         composite.setFont(parent.getFont());
122
123         createProjectNameGroup(composite);
124         createProjectLocationGroup(composite);
125         validatePage();
126         // Show description on opening
127
setErrorMessage(null);
128         setMessage(null);
129         setControl(composite);
130     }
131
132     /**
133      * Creates the project location specification controls.
134      *
135      * @param parent the parent composite
136      */

137     private final void createProjectLocationGroup(Composite parent) {
138
139         // project specification group
140
Composite projectGroup = new Composite(parent, SWT.NONE);
141         GridLayout layout = new GridLayout();
142         layout.numColumns = 3;
143         projectGroup.setLayout(layout);
144         projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
145         projectGroup.setFont(parent.getFont());
146
147         // new project label
148
Label projectContentsLabel = new Label(projectGroup, SWT.NONE);
149         projectContentsLabel.setText(DataTransferMessages.getString("ExternalAntBuildfileImportPage.11")); //$NON-NLS-1$
150
projectContentsLabel.setFont(parent.getFont());
151
152         createUserSpecifiedProjectLocationGroup(projectGroup);
153     }
154     /**
155      * Creates the project name specification controls.
156      *
157      * @param parent the parent composite
158      */

159     private final void createProjectNameGroup(Composite parent) {
160         
161         Font dialogFont = parent.getFont();
162         
163         // project specification group
164
Composite projectGroup = new Composite(parent, SWT.NONE);
165         GridLayout layout = new GridLayout();
166         layout.numColumns = 2;
167         projectGroup.setFont(dialogFont);
168         projectGroup.setLayout(layout);
169         projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
170
171         // new project label
172
Label projectLabel = new Label(projectGroup, SWT.NONE);
173         projectLabel.setText(DataTransferMessages.getString("ExternalAntBuildfileImportPage.12")); //$NON-NLS-1$
174
projectLabel.setFont(dialogFont);
175
176         // new project name entry field
177
projectNameField = new Text(projectGroup, SWT.BORDER);
178         GridData data = new GridData(GridData.FILL_HORIZONTAL);
179         data.widthHint = SIZING_TEXT_FIELD_WIDTH;
180         projectNameField.setLayoutData(data);
181         projectNameField.setFont(dialogFont);
182         
183         projectNameField.addListener(SWT.Modify, nameModifyListener);
184     }
185     /**
186      * Creates the project location specification controls.
187      *
188      * @param projectGroup the parent composite
189      * @param boolean - the initial enabled state of the widgets created
190      */

191     private void createUserSpecifiedProjectLocationGroup(Composite projectGroup) {
192         
193         Font dialogFont = projectGroup.getFont();
194
195         // project location entry field
196
this.locationPathField = new Text(projectGroup, SWT.BORDER);
197         GridData data = new GridData(GridData.FILL_HORIZONTAL);
198         data.widthHint = SIZING_TEXT_FIELD_WIDTH;
199         this.locationPathField.setLayoutData(data);
200         this.locationPathField.setFont(dialogFont);
201
202         // browse button
203
this.browseButton = new Button(projectGroup, SWT.PUSH);
204         this.browseButton.setText(DataTransferMessages.getString("ExternalAntBuildfileImportPage.13")); //$NON-NLS-1$
205
this.browseButton.setFont(dialogFont);
206         setButtonLayoutData(this.browseButton);
207         
208         this.browseButton.addSelectionListener(new SelectionAdapter() {
209             public void widgetSelected(SelectionEvent event) {
210                 handleBrowseButtonPressed();
211             }
212         });
213
214         locationPathField.addListener(SWT.Modify, locationModifyListener);
215     }
216
217     /**
218      * Returns the current project name as entered by the user, or its anticipated
219      * initial value.
220      *
221      * @return the project name, its anticipated initial value, or <code>null</code>
222      * if no project name is known
223      */

224     private String JavaDoc getProjectName(AntProjectNode projectNode) {
225         String JavaDoc userSpecifiedName= getProjectNameFieldValue();
226         if (userSpecifiedName.length() > 0) {
227             return userSpecifiedName;
228         }
229         String JavaDoc projectName= projectNode.getLabel();
230         if (projectName == null) {
231             projectName= DataTransferMessages.getString("ExternalAntBuildfileImportPage.14"); //$NON-NLS-1$
232
}
233         return projectName;
234     }
235     /**
236      * Returns the value of the project name field
237      * with leading and trailing spaces removed.
238      *
239      * @return the project name in the field
240      */

241     private String JavaDoc getProjectNameFieldValue() {
242         if (projectNameField == null) {
243             return ""; //$NON-NLS-1$
244
}
245         return projectNameField.getText().trim();
246     }
247     /**
248      * Returns the value of the project location field
249      * with leading and trailing spaces removed.
250      *
251      * @return the project location directory in the field
252      */

253     private String JavaDoc getProjectLocationFieldValue() {
254         return locationPathField.getText().trim();
255     }
256     
257     /**
258      * Determine the buildfile the user wishes to operate from
259      */

260     private void handleBrowseButtonPressed() {
261         
262             String JavaDoc lastUsedPath= null;
263             //lastUsedPath= dialogSettings.get(IAntUIConstants.DIALOGSTORE_LASTEXTFILE);
264
if (lastUsedPath == null) {
265                 lastUsedPath= ""; //$NON-NLS-1$
266
}
267             FileDialog dialog = new FileDialog(getShell(), SWT.SINGLE);
268             dialog.setFilterExtensions(new String JavaDoc[] { "*.xml" }); //$NON-NLS-1$;
269
dialog.setFilterPath(lastUsedPath);
270
271             String JavaDoc result = dialog.open();
272             if (result == null) {
273                 return;
274             }
275             IPath filterPath= new Path(dialog.getFilterPath());
276             String JavaDoc buildFileName= dialog.getFileName();
277             IPath path= filterPath.append(buildFileName).makeAbsolute();
278             
279 // previouslyBrowsedDirectory = selectedDirectory;
280
locationPathField.setText(path.toOSString());
281     }
282
283     /**
284      * Returns whether this page's controls currently all contain valid
285      * values.
286      *
287      * @return <code>true</code> if all controls are valid, and
288      * <code>false</code> if at least one is invalid
289      */

290     private boolean validatePage() {
291
292         String JavaDoc locationFieldContents = getProjectLocationFieldValue();
293
294         if (locationFieldContents.equals("")) { //$NON-NLS-1$
295
setErrorMessage(null);
296             setMessage(DataTransferMessages.getString("ExternalAntBuildfileImportPage.15")); //$NON-NLS-1$
297
return false;
298         }
299
300         IPath path = new Path(""); //$NON-NLS-1$
301
if (!path.isValidPath(locationFieldContents)) {
302             setErrorMessage(DataTransferMessages.getString("ExternalAntBuildfileImportPage.16")); //$NON-NLS-1$
303
return false;
304         }
305
306         if (fAntModel == null) {
307             setErrorMessage(DataTransferMessages.getString("ExternalAntBuildfileImportPage.17")); //$NON-NLS-1$
308
return false;
309         }
310         
311         if (getProjectNameFieldValue().length() == 0) {
312             setErrorMessage(DataTransferMessages.getString("ExternalAntBuildfileImportPage.18")); //$NON-NLS-1$
313
return false;
314         }
315         IProject existingProject= ResourcesPlugin.getWorkspace().getRoot().getProject(getProjectNameFieldValue());
316         if (existingProject.exists()) {
317             setErrorMessage(DataTransferMessages.getString("ExternalAntBuildfileImportPage.19")); //$NON-NLS-1$
318
return false;
319         }
320
321         setErrorMessage(null);
322         setMessage(null);
323         return true;
324     }
325
326     /**
327      * Set the project name using either the name of the
328      * parent of the file or the name entry in the xml for
329      * the file
330      */

331     private void setProjectName() {
332
333         if (fAntModel == null) {
334             return;
335         }
336
337         AntProjectNode node= fAntModel.getProjectNode();
338         String JavaDoc projectName= getProjectName(node);
339         
340         projectNameField.setText(projectName);
341     }
342
343     /**
344      * Return a .xml file from the specified location.
345      * If there isn't one return null.
346      */

347     private File JavaDoc getBuildFile(String JavaDoc locationFieldContents) {
348         File JavaDoc buildFile = new File JavaDoc(locationFieldContents);
349         if (!buildFile.isFile() && buildFile.exists()) {
350             return null;
351         }
352
353         return buildFile;
354     }
355
356     /**
357      * Creates a new project resource based on the Ant buildfile.
358      *
359      * @return the created project resource, or <code>null</code> if the project
360      * was not created
361      */

362     protected IJavaProject createProject() {
363
364         AntProjectNode projectNode= fAntModel.getProjectNode();
365         
366         final List JavaDoc javacNodes= new ArrayList JavaDoc();
367         getJavacNodes(javacNodes, projectNode);
368         final IJavaProject[] result= new IJavaProject[1];
369         final String JavaDoc projectName= getProjectNameFieldValue();
370         final File JavaDoc buildFile= getBuildFile(getProjectLocationFieldValue());
371         if (javacNodes.size() > 1) {
372             setErrorMessage(DataTransferMessages.getString("ExternalAntBuildfileImportPage.20")); //$NON-NLS-1$
373
return null;
374         }
375         
376         WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
377             protected void execute(IProgressMonitor monitor) throws CoreException {
378                 List JavaDoc javacTasks= resolveJavacTasks(javacNodes);
379                 //TODO no javactasks...throw CoreException
380
ProjectCreator creator= new ProjectCreator();
381                 Iterator JavaDoc iter= javacTasks.iterator();
382                 while (iter.hasNext()) {
383                     Javac javacTask = (Javac) iter.next();
384                     IJavaProject javaProject= creator.createJavaProjectFromJavacNode(projectName, javacTask);
385                     importBuildFile(monitor, javaProject.getPath(), buildFile);
386                     result[0]= javaProject;
387                 }
388             }
389         };
390         
391         //run the new project creation operation
392
try {
393             getContainer().run(true, true, op);
394         } catch (InterruptedException JavaDoc e) {
395             return null;
396         } catch (InvocationTargetException JavaDoc e) {
397             // ie.- one of the steps resulted in a core exception
398
Throwable JavaDoc t = e.getTargetException();
399             if (t instanceof CoreException) {
400                 ErrorDialog.openError(getShell(), DataTransferMessages.getString("ExternalAntBuildfileImportPage.21"), //$NON-NLS-1$
401
null, ((CoreException) t).getStatus());
402             }
403         }
404         
405         return result[0];
406     }
407     
408     protected void importBuildFile(IProgressMonitor monitor, IPath destPath, File JavaDoc buildFile) {
409         IImportStructureProvider structureProvider = FileSystemStructureProvider.INSTANCE;
410         List JavaDoc files = new ArrayList JavaDoc(1);
411         
412         files.add(buildFile);
413         File JavaDoc rootDir= buildFile.getParentFile();
414         try {
415             ImportOperation op= new ImportOperation(destPath, rootDir, structureProvider, new ImportOverwriteQuery(), files);
416             op.setCreateContainerStructure(false);
417             op.run(monitor);
418         } catch (InterruptedException JavaDoc e) {
419             // should not happen
420
} catch (InvocationTargetException JavaDoc e) {
421             Throwable JavaDoc t = e.getTargetException();
422             if (t instanceof CoreException) {
423                 ErrorDialog.openError(getShell(), DataTransferMessages.getString("ExternalAntBuildfileImportPage.22"), //$NON-NLS-1$
424
null, ((CoreException) t).getStatus());
425             }
426         }
427     }
428
429     private List JavaDoc resolveJavacTasks(List JavaDoc javacNodes) {
430         List JavaDoc resolvedJavacTasks= new ArrayList JavaDoc(javacNodes.size());
431         Iterator JavaDoc nodes= javacNodes.iterator();
432         while (nodes.hasNext()) {
433             AntTaskNode taskNode = (AntTaskNode) nodes.next();
434             Task javacTask= taskNode.getTask();
435             if (javacTask instanceof UnknownElement) {
436                 if (((UnknownElement)javacTask).getRealThing() == null) {
437                     javacTask.maybeConfigure();
438                 }
439                 
440                 resolvedJavacTasks.add(((UnknownElement)javacTask).getRealThing());
441             } else {
442                 resolvedJavacTasks.add(javacTask);
443             }
444             
445         }
446         return resolvedJavacTasks;
447     }
448     
449     private AntModel getAntModel(final File JavaDoc buildFile) {
450         IDocument doc= getDocument(buildFile);
451         if (doc == null) {
452             return null;
453         }
454         AntModel model= new AntModel(XMLCore.getDefault(), doc, null, new LocationProvider(null) {
455             /* (non-Javadoc)
456              * @see org.eclipse.ant.internal.ui.editor.outline.ILocationProvider#getLocation()
457              */

458             public IPath getLocation() {
459                 return new Path(buildFile.getAbsolutePath());
460             }
461         });
462         model.reconcile(null);
463         return model;
464     }
465     
466     private IDocument getDocument(File JavaDoc buildFile) {
467         InputStream JavaDoc in;
468         try {
469             in = new FileInputStream JavaDoc(buildFile);
470         } catch (FileNotFoundException JavaDoc e) {
471             return null;
472         }
473         String JavaDoc initialContent= getStreamContentAsString(in);
474         return new Document(initialContent);
475     }
476     
477     private String JavaDoc getStreamContentAsString(InputStream JavaDoc inputStream) {
478         InputStreamReader JavaDoc reader;
479         try {
480             reader = new InputStreamReader JavaDoc(inputStream, ResourcesPlugin.getEncoding());
481         } catch (UnsupportedEncodingException JavaDoc e) {
482             AntUIPlugin.log(e);
483             return ""; //$NON-NLS-1$
484
}
485
486         return getReaderContentAsString( new BufferedReader JavaDoc(reader));
487     }
488     
489     private String JavaDoc getReaderContentAsString(BufferedReader JavaDoc bufferedReader) {
490         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
491         try {
492             String JavaDoc line= bufferedReader.readLine();
493
494             while(line != null) {
495                 if(result.length() != 0) {
496                     result.append("\n"); //$NON-NLS-1$
497
}
498                 result.append(line);
499                 line = bufferedReader.readLine();
500             }
501         } catch (IOException JavaDoc e) {
502             AntUIPlugin.log(e);
503             return null;
504         }
505
506         return result.toString();
507     }
508     
509     private void getJavacNodes(List JavaDoc javacNodes, AntElementNode parent) {
510         if (!parent.hasChildren()) {
511             return;
512         }
513         List JavaDoc children= parent.getChildNodes();
514         for (Iterator JavaDoc iter = children.iterator(); iter.hasNext();) {
515             AntElementNode node = (AntElementNode) iter.next();
516             if (node instanceof AntTargetNode) {
517                 getJavacNodes(javacNodes, node);
518             } else if (node instanceof AntTaskNode) {
519                 AntTaskNode task= (AntTaskNode)node;
520                 if (task.getName() == "javac") { //$NON-NLS-1$
521
javacNodes.add(task);
522                 }
523             }
524         }
525     }
526     
527     /* (non-Javadoc)
528      * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
529      */

530     public void setVisible(boolean visible) {
531         super.setVisible(visible);
532         if(visible)
533             this.locationPathField.setFocus();
534     }
535 }
536
Popular Tags