KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 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.ant.internal.ui.datatransfer;
12
13 import java.io.File JavaDoc;
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Collections JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19
20 import org.apache.tools.ant.Task;
21 import org.apache.tools.ant.UnknownElement;
22 import org.apache.tools.ant.taskdefs.Javac;
23 import org.eclipse.ant.internal.ui.AntUIPlugin;
24 import org.eclipse.ant.internal.ui.AntUtil;
25 import org.eclipse.ant.internal.ui.model.AntElementNode;
26 import org.eclipse.ant.internal.ui.model.AntModelContentProvider;
27 import org.eclipse.ant.internal.ui.model.AntProjectNode;
28 import org.eclipse.ant.internal.ui.model.AntTargetNode;
29 import org.eclipse.ant.internal.ui.model.AntTaskNode;
30 import org.eclipse.ant.internal.ui.model.IAntModel;
31 import org.eclipse.core.resources.IFile;
32 import org.eclipse.core.resources.IProject;
33 import org.eclipse.core.resources.IResource;
34 import org.eclipse.core.resources.ResourcesPlugin;
35 import org.eclipse.core.runtime.CoreException;
36 import org.eclipse.core.runtime.IPath;
37 import org.eclipse.core.runtime.IProgressMonitor;
38 import org.eclipse.core.runtime.IStatus;
39 import org.eclipse.core.runtime.Path;
40 import org.eclipse.core.runtime.Status;
41 import org.eclipse.jdt.core.IJavaProject;
42 import org.eclipse.jface.dialogs.ErrorDialog;
43 import org.eclipse.jface.dialogs.IDialogConstants;
44 import org.eclipse.jface.viewers.IStructuredSelection;
45 import org.eclipse.jface.viewers.StructuredSelection;
46 import org.eclipse.jface.viewers.TableViewer;
47 import org.eclipse.jface.wizard.WizardPage;
48 import org.eclipse.osgi.util.NLS;
49 import org.eclipse.swt.SWT;
50 import org.eclipse.swt.events.ModifyEvent;
51 import org.eclipse.swt.events.ModifyListener;
52 import org.eclipse.swt.events.SelectionAdapter;
53 import org.eclipse.swt.events.SelectionEvent;
54 import org.eclipse.swt.graphics.Font;
55 import org.eclipse.swt.layout.GridData;
56 import org.eclipse.swt.layout.GridLayout;
57 import org.eclipse.swt.widgets.Button;
58 import org.eclipse.swt.widgets.Composite;
59 import org.eclipse.swt.widgets.FileDialog;
60 import org.eclipse.swt.widgets.Label;
61 import org.eclipse.swt.widgets.Table;
62 import org.eclipse.swt.widgets.Text;
63 import org.eclipse.ui.actions.WorkspaceModifyOperation;
64 import org.eclipse.ui.dialogs.IOverwriteQuery;
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 AntNewJavaProjectPage 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 Text fProjectNameField;
78     private Text fLocationPathField;
79     private Button fBrowseButton;
80     private Button fLinkButton;
81     
82     private IAntModel fAntModel;
83
84     private ModifyListener fLocationModifyListener = new ModifyListener() {
85         public void modifyText(ModifyEvent e) {
86             //no lexical or position, has task info
87
fAntModel= AntUtil.getAntModel(getProjectLocationFieldValue(), false, false, true);
88             AntProjectNode projectNode= fAntModel == null ? null : fAntModel.getProjectNode();
89             if (fAntModel != null && projectNode != null) {
90                 setProjectName(); // page will be validated on setting the project name
91
List JavaDoc javacNodes= new ArrayList JavaDoc();
92                 getJavacNodes(javacNodes, projectNode);
93                 fTableViewer.setInput(javacNodes.toArray());
94                 if (!javacNodes.isEmpty()) {
95                     fTableViewer.setSelection(new StructuredSelection(javacNodes.get(0)));
96                 }
97                 fTableViewer.getControl().setEnabled(true);
98             } else {
99                 fTableViewer.setInput(new Object JavaDoc[] {});
100                 fTableViewer.getControl().setEnabled(false);
101             }
102             setPageComplete(validatePage());
103         }
104     };
105     
106     private ModifyListener fNameModifyListener = new ModifyListener() {
107         public void modifyText(ModifyEvent e) {
108             setPageComplete(validatePage());
109         }
110     };
111
112     private static final int SIZING_TEXT_FIELD_WIDTH = 250;
113     private TableViewer fTableViewer;
114     
115     public AntNewJavaProjectPage() {
116         super("newPage"); //$NON-NLS-1$
117
setPageComplete(false);
118         setTitle(DataTransferMessages.AntNewJavaProjectPage_9);
119         setDescription(DataTransferMessages.AntNewJavaProjectPage_10);
120
121     }
122     
123     /* (non-Javadoc)
124      * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
125      */

126     public void createControl(Composite parent) {
127         
128         initializeDialogUnits(parent);
129         Composite composite = new Composite(parent, SWT.NONE);
130         GridLayout layout = new GridLayout();
131         layout.marginHeight= IDialogConstants.VERTICAL_MARGIN;
132         layout.marginWidth= IDialogConstants.HORIZONTAL_MARGIN;
133         layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
134         layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
135         layout.numColumns= 3;
136         composite.setLayout(layout);
137         composite.setLayoutData(new GridData(GridData.FILL_BOTH));
138         composite.setFont(parent.getFont());
139         
140         createProjectNameGroup(composite);
141         createProjectLocationGroup(composite);
142         createTargetsTable(composite);
143         
144         fLinkButton = new Button(composite, SWT.CHECK);
145         fLinkButton.setText(DataTransferMessages.AntNewJavaProjectPage_24);
146         fLinkButton.setFont( parent.getFont());
147         GridData gd= new GridData();
148         gd.horizontalAlignment= GridData.FILL;
149         gd.grabExcessHorizontalSpace= false;
150         gd.horizontalSpan= 2;
151         fLinkButton.setLayoutData(gd);
152         
153         validatePage();
154         // Show description on opening
155
setErrorMessage(null);
156         setMessage(null);
157         setControl(composite);
158     }
159
160     /**
161      * Creates the project location specification controls.
162      *
163      * @param parent the parent composite
164      */

165     private final void createProjectLocationGroup(Composite parent) {
166         // new project label
167
Label projectContentsLabel = new Label(parent, SWT.NONE);
168         projectContentsLabel.setText(DataTransferMessages.AntNewJavaProjectPage_11);
169         projectContentsLabel.setFont(parent.getFont());
170
171         createUserSpecifiedProjectLocationGroup(parent);
172     }
173     /**
174      * Creates the project name specification controls.
175      *
176      * @param parent the parent composite
177      */

178     private final void createProjectNameGroup(Composite parent) {
179         
180         Font dialogFont = parent.getFont();
181
182         // new project label
183
Label projectLabel = new Label(parent, SWT.NONE);
184         projectLabel.setText(DataTransferMessages.AntNewJavaProjectPage_12);
185         projectLabel.setFont(dialogFont);
186         GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
187         projectLabel.setLayoutData(gd);
188
189         // new project name entry field
190
fProjectNameField = new Text(parent, SWT.BORDER);
191         gd= new GridData();
192         gd.horizontalAlignment= GridData.FILL;
193         gd.grabExcessHorizontalSpace= false;
194         gd.horizontalSpan= 2;
195         fProjectNameField.setLayoutData(gd);
196         fProjectNameField.setFont(dialogFont);
197         
198         fProjectNameField.addModifyListener(fNameModifyListener);
199     }
200     /**
201      * Creates the project location specification controls.
202      *
203      * @param projectGroup the parent composite
204      */

205     private void createUserSpecifiedProjectLocationGroup(Composite projectGroup) {
206         
207         Font dialogFont = projectGroup.getFont();
208
209         // project location entry field
210
fLocationPathField = new Text(projectGroup, SWT.BORDER);
211         GridData data = new GridData(GridData.FILL_HORIZONTAL);
212         data.widthHint = SIZING_TEXT_FIELD_WIDTH;
213         fLocationPathField.setLayoutData(data);
214         fLocationPathField.setFont(dialogFont);
215
216         // browse button
217
fBrowseButton = new Button(projectGroup, SWT.PUSH);
218         fBrowseButton.setText(DataTransferMessages.AntNewJavaProjectPage_13);
219         fBrowseButton.setFont(dialogFont);
220         setButtonLayoutData(fBrowseButton);
221         
222         fBrowseButton.addSelectionListener(new SelectionAdapter() {
223             public void widgetSelected(SelectionEvent event) {
224                 handleBrowseButtonPressed();
225             }
226         });
227
228         fLocationPathField.addModifyListener(fLocationModifyListener);
229     }
230
231     /**
232      * Returns the current project name
233      *
234      * @return the project name
235      */

236     private String JavaDoc getProjectName(AntProjectNode projectNode) {
237         String JavaDoc projectName= projectNode.getLabel();
238         if (projectName == null) {
239             projectName= DataTransferMessages.AntNewJavaProjectPage_14;
240         }
241         return projectName;
242     }
243     /**
244      * Returns the value of the project name field
245      * with leading and trailing spaces removed.
246      *
247      * @return the project name in the field
248      */

249     private String JavaDoc getProjectNameFieldValue() {
250         if (fProjectNameField == null) {
251             return ""; //$NON-NLS-1$
252
}
253         return fProjectNameField.getText().trim();
254     }
255     /**
256      * Returns the value of the project location field
257      * with leading and trailing spaces removed.
258      *
259      * @return the project location directory in the field
260      */

261     private String JavaDoc getProjectLocationFieldValue() {
262         return fLocationPathField.getText().trim();
263     }
264     
265     /**
266      * Determine the buildfile the user wishes to operate from
267      */

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

293     private boolean validatePage() {
294
295         String JavaDoc locationFieldContents = getProjectLocationFieldValue();
296
297         if (locationFieldContents.equals("")) { //$NON-NLS-1$
298
setErrorMessage(null);
299             setMessage(DataTransferMessages.AntNewJavaProjectPage_15);
300             return false;
301         }
302
303         IPath path = new Path(""); //$NON-NLS-1$
304
if (!path.isValidPath(locationFieldContents)) {
305             setErrorMessage(DataTransferMessages.AntNewJavaProjectPage_16);
306             return false;
307         }
308
309         if (fAntModel == null) {
310             if (getBuildFile(locationFieldContents) == null) {
311                 setErrorMessage(DataTransferMessages.AntNewJavaProjectPage_0);
312                 return false;
313             }
314             setErrorMessage(DataTransferMessages.AntNewJavaProjectPage_17);
315             return false;
316         }
317         
318         if (fAntModel.getProjectNode() == null) {
319             setErrorMessage(DataTransferMessages.AntNewJavaProjectPage_2);
320             return false;
321         }
322         
323         if (getProjectNameFieldValue().length() == 0) {
324             setErrorMessage(DataTransferMessages.AntNewJavaProjectPage_18);
325             return false;
326         }
327         try {
328             IProject existingProject= ResourcesPlugin.getWorkspace().getRoot().getProject(getProjectNameFieldValue());
329             if (existingProject.exists()) {
330                 setErrorMessage(DataTransferMessages.AntNewJavaProjectPage_19);
331                 return false;
332             }
333         } catch (IllegalArgumentException JavaDoc e) {
334             setErrorMessage(NLS.bind(DataTransferMessages.AntNewJavaProjectPage_23, e.getLocalizedMessage()));
335             return false;
336         }
337         
338         
339         if (fTableViewer.getTable().getItemCount() == 0) {
340             setErrorMessage(DataTransferMessages.AntNewJavaProjectPage_1);
341             setPageComplete(false);
342             return false;
343         }
344        
345         setErrorMessage(null);
346         setMessage(null);
347         return true;
348     }
349
350     /**
351      * Set the project name using either the name of the
352      * parent of the file or the name entry in the xml for
353      * the file
354      */

355     private void setProjectName() {
356         AntProjectNode node= fAntModel.getProjectNode();
357         String JavaDoc projectName= getProjectName(node);
358         
359         fProjectNameField.setText(projectName);
360     }
361
362     /**
363      * Return a .xml file from the specified location.
364      * If there isn't one return null.
365      */

366     private File JavaDoc getBuildFile(String JavaDoc locationFieldContents) {
367         File JavaDoc buildFile = new File JavaDoc(locationFieldContents);
368         if (!buildFile.isFile() || !buildFile.exists()) {
369             return null;
370         }
371
372         return buildFile;
373     }
374
375     /**
376      * Creates a new project resource based on the Ant buildfile.
377      * The classpath is configured based on the classpath of the javac declaration in the buildfile.
378      *
379      * @return the created project resource, or <code>null</code> if the project
380      * was not created
381      */

382     protected IJavaProject createProject() {
383         final IJavaProject[] result= new IJavaProject[1];
384         final String JavaDoc projectName= getProjectNameFieldValue();
385         final File JavaDoc buildFile= getBuildFile(getProjectLocationFieldValue());
386         final List JavaDoc selectedJavacs= ((IStructuredSelection)fTableViewer.getSelection()).toList();
387         final boolean link = fLinkButton.getSelection();
388         WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
389             protected void execute(IProgressMonitor monitor) throws CoreException {
390                 List JavaDoc javacTasks= resolveJavacTasks(selectedJavacs);
391                 ProjectCreator creator= new ProjectCreator();
392                 Iterator JavaDoc iter= javacTasks.iterator();
393                 while (iter.hasNext()) {
394                     Javac javacTask = (Javac) iter.next();
395                     IJavaProject javaProject= creator.createJavaProjectFromJavacNode(projectName, javacTask, monitor);
396                     importBuildFile(monitor, javaProject, buildFile, link);
397                     result[0]= javaProject;
398                 }
399             }
400         };
401         
402         //run the new project creation operation
403
try {
404             getContainer().run(true, true, op);
405         } catch (InterruptedException JavaDoc e) {
406             return null;
407         } catch (InvocationTargetException JavaDoc e) {
408             // ie.- one of the steps resulted in a core exception
409
Throwable JavaDoc t = e.getTargetException();
410             IStatus status= null;
411             if (t instanceof CoreException) {
412                 status= ((CoreException) t).getStatus();
413             } else {
414                 status= new Status(IStatus.ERROR, AntUIPlugin.PI_ANTUI, IStatus.OK, "Error occurred. Check log for details ", t); //$NON-NLS-1$
415
AntUIPlugin.log(t);
416             }
417             ErrorDialog.openError(getShell(), DataTransferMessages.AntNewJavaProjectPage_21,
418                     null, status);
419         }
420         
421         return result[0];
422     }
423     
424     protected void importBuildFile(IProgressMonitor monitor, IJavaProject javaProject, File JavaDoc buildFile, boolean link) {
425         if (link) {
426             IProject project= javaProject.getProject();
427             IFile iBuildFile = project.getFile(buildFile.getName());
428             if (!iBuildFile.exists()) {
429                 try {
430                     iBuildFile.createLink(new Path(buildFile.getAbsolutePath()), IResource.ALLOW_MISSING_LOCAL, monitor);
431                 } catch (CoreException e) {
432                     ErrorDialog.openError(getShell(), DataTransferMessages.AntNewJavaProjectPage_22, null, e.getStatus());
433                 }
434             }
435         } else {
436             IImportStructureProvider structureProvider = FileSystemStructureProvider.INSTANCE;
437             File JavaDoc rootDir= buildFile.getParentFile();
438             try {
439                 ImportOperation op= new ImportOperation(javaProject.getPath(), rootDir, structureProvider, new ImportOverwriteQuery(), Collections.singletonList(buildFile));
440                 op.setCreateContainerStructure(false);
441                 op.run(monitor);
442             } catch (InterruptedException JavaDoc e) {
443                 // should not happen
444
} catch (InvocationTargetException JavaDoc e) {
445                 Throwable JavaDoc t = e.getTargetException();
446                 if (t instanceof CoreException) {
447                     ErrorDialog.openError(getShell(), DataTransferMessages.AntNewJavaProjectPage_22,
448                             null, ((CoreException) t).getStatus());
449                 }
450             }
451         }
452     }
453
454     private List JavaDoc resolveJavacTasks(List JavaDoc javacNodes) {
455         List JavaDoc resolvedJavacTasks= new ArrayList JavaDoc(javacNodes.size());
456         Iterator JavaDoc nodes= javacNodes.iterator();
457         while (nodes.hasNext()) {
458             AntTaskNode taskNode = (AntTaskNode) nodes.next();
459             Task javacTask= taskNode.getTask();
460             if (javacTask instanceof UnknownElement) {
461                 if (((UnknownElement)javacTask).getRealThing() == null) {
462                     javacTask.maybeConfigure();
463                 }
464                 
465                 resolvedJavacTasks.add(((UnknownElement)javacTask).getRealThing());
466             } else {
467                 resolvedJavacTasks.add(javacTask);
468             }
469         }
470         return resolvedJavacTasks;
471     }
472     
473     private void getJavacNodes(List JavaDoc javacNodes, AntElementNode parent) {
474         if (!parent.hasChildren()) {
475             return;
476         }
477         List JavaDoc children= parent.getChildNodes();
478         for (Iterator JavaDoc iter = children.iterator(); iter.hasNext();) {
479             AntElementNode node = (AntElementNode) iter.next();
480             if (node instanceof AntTargetNode) {
481                 getJavacNodes(javacNodes, node);
482             } else if (node instanceof AntTaskNode) {
483                 AntTaskNode task= (AntTaskNode)node;
484                 if ("javac".equals(task.getName())) { //$NON-NLS-1$
485
javacNodes.add(task);
486                 }
487             }
488         }
489     }
490     
491     /* (non-Javadoc)
492      * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
493      */

494     public void setVisible(boolean visible) {
495         super.setVisible(visible);
496         if (visible) {
497             fLocationPathField.setFocus();
498         }
499     }
500     
501     /**
502      * Creates the table which displays the available targets
503      * @param parent the parent composite
504      */

505     private void createTargetsTable(Composite parent) {
506         Font font= parent.getFont();
507         Label label = new Label(parent, SWT.NONE);
508         label.setFont(font);
509         label.setText(DataTransferMessages.AntNewJavaProjectPage_3);
510         GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
511         gd.horizontalSpan= 3;
512         label.setLayoutData(gd);
513         
514         Table table= new Table(parent, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.RESIZE);
515         
516         GridData data= new GridData(GridData.FILL_BOTH);
517         int availableRows= availableRows(parent);
518         data.heightHint = table.getItemHeight() * (availableRows / 20);
519         data.widthHint= 250;
520         data.horizontalSpan= 3;
521         table.setLayoutData(data);
522         table.setFont(font);
523         
524         fTableViewer = new TableViewer(table);
525         fTableViewer.setLabelProvider(new JavacTableLabelProvider());
526         fTableViewer.setContentProvider(new AntModelContentProvider());
527         fTableViewer.getControl().setEnabled(false);
528     }
529     
530     /**
531      * Return the number of rows available in the current display using the
532      * current font.
533      * @param parent The Composite whose Font will be queried.
534      * @return int The result of the display size divided by the font size.
535      */

536     private int availableRows(Composite parent) {
537
538         int fontHeight = (parent.getFont().getFontData())[0].getHeight();
539         int displayHeight = parent.getDisplay().getClientArea().height;
540
541         return displayHeight / fontHeight;
542     }
543 }
544
Popular Tags