KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > junit > wizards > NewTestSuiteCreationWizardPage


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.jdt.internal.junit.wizards;
12
13 import java.lang.reflect.InvocationTargetException JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.List JavaDoc;
16 import org.eclipse.core.runtime.CoreException;
17 import org.eclipse.core.runtime.IProgressMonitor;
18 import org.eclipse.core.runtime.IStatus;
19 import org.eclipse.core.runtime.NullProgressMonitor;
20 import org.eclipse.core.runtime.SubProgressMonitor;
21 import org.eclipse.jdt.core.Flags;
22 import org.eclipse.jdt.core.IBuffer;
23 import org.eclipse.jdt.core.ICompilationUnit;
24 import org.eclipse.jdt.core.IJavaElement;
25 import org.eclipse.jdt.core.IMethod;
26 import org.eclipse.jdt.core.IPackageFragment;
27 import org.eclipse.jdt.core.IPackageFragmentRoot;
28 import org.eclipse.jdt.core.ISourceRange;
29 import org.eclipse.jdt.core.IType;
30 import org.eclipse.jdt.core.JavaConventions;
31 import org.eclipse.jdt.core.JavaModelException;
32 import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds;
33 import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
34 import org.eclipse.jdt.internal.junit.util.JUnitStatus;
35 import org.eclipse.jdt.internal.junit.util.JUnitStubUtility;
36 import org.eclipse.jdt.internal.junit.util.LayoutUtil;
37 import org.eclipse.jdt.internal.junit.util.SWTUtil;
38 import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
39 import org.eclipse.jdt.ui.JavaElementLabelProvider;
40 import org.eclipse.jdt.ui.wizards.NewTypeWizardPage;
41 import org.eclipse.jface.dialogs.Dialog;
42 import org.eclipse.jface.dialogs.IDialogSettings;
43 import org.eclipse.jface.dialogs.MessageDialog;
44 import org.eclipse.jface.operation.IRunnableWithProgress;
45 import org.eclipse.jface.viewers.CheckStateChangedEvent;
46 import org.eclipse.jface.viewers.CheckboxTableViewer;
47 import org.eclipse.jface.viewers.ICheckStateListener;
48 import org.eclipse.jface.viewers.IStructuredContentProvider;
49 import org.eclipse.jface.viewers.IStructuredSelection;
50 import org.eclipse.jface.viewers.Viewer;
51 import org.eclipse.swt.SWT;
52 import org.eclipse.swt.events.ModifyEvent;
53 import org.eclipse.swt.events.ModifyListener;
54 import org.eclipse.swt.events.SelectionAdapter;
55 import org.eclipse.swt.events.SelectionEvent;
56 import org.eclipse.swt.layout.GridData;
57 import org.eclipse.swt.layout.GridLayout;
58 import org.eclipse.swt.widgets.Button;
59 import org.eclipse.swt.widgets.Composite;
60 import org.eclipse.swt.widgets.Label;
61 import org.eclipse.swt.widgets.Text;
62 import org.eclipse.ui.help.WorkbenchHelp;
63
64 /**
65  * Wizard page to select the test classes to include
66  * in the test suite.
67  */

68 public class NewTestSuiteCreationWizardPage extends NewTypeWizardPage {
69
70     private final static String JavaDoc PAGE_NAME= "NewTestSuiteCreationWizardPage"; //$NON-NLS-1$
71
private final static String JavaDoc CLASSES_IN_SUITE= PAGE_NAME + ".classesinsuite"; //$NON-NLS-1$
72
private final static String JavaDoc SUITE_NAME= PAGE_NAME + ".suitename"; //$NON-NLS-1$
73

74     protected final static String JavaDoc STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$
75
protected final static String JavaDoc STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$
76
protected final static String JavaDoc STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; //$NON-NLS-1$
77

78
79     public static final String JavaDoc START_MARKER= "//$JUnit-BEGIN$"; //$NON-NLS-1$
80
public static final String JavaDoc END_MARKER= "//$JUnit-END$"; //$NON-NLS-1$
81

82     private CheckboxTableViewer fClassesInSuiteTable;
83     private Button fSelectAllButton;
84     private Button fDeselectAllButton;
85     private Label fSelectedClassesLabel;
86
87     private Label fSuiteNameLabel;
88     private Text fSuiteNameText;
89     private String JavaDoc fSuiteNameTextInitialValue;
90     private MethodStubsSelectionButtonGroup fMethodStubsButtons;
91     
92     private boolean fUpdatedExistingClassButton;
93
94     protected IStatus fClassesInSuiteStatus;
95     protected IStatus fSuiteNameStatus;
96     
97     public NewTestSuiteCreationWizardPage() {
98         super(true, PAGE_NAME);
99
100         fSuiteNameStatus= new JUnitStatus();
101         fSuiteNameTextInitialValue= ""; //$NON-NLS-1$
102
setTitle(WizardMessages.getString("NewTestSuiteWizPage.title")); //$NON-NLS-1$
103
setDescription(WizardMessages.getString("NewTestSuiteWizPage.description")); //$NON-NLS-1$
104

105         String JavaDoc[] buttonNames= new String JavaDoc[] {
106             "public static void main(Strin&g[] args)", //$NON-NLS-1$
107
/* Add testrunner statement to main Method */
108             WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$
109
};
110         
111         fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1);
112         fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage2.method.Stub.label")); //$NON-NLS-1$
113
fMethodStubsButtons.setUseSuiteInMainForTextRunner(true);
114         fClassesInSuiteStatus= new JUnitStatus();
115     }
116
117     /**
118      * @see org.eclipse.jface.dialogs.IDialogPage#createControl(Composite)
119      */

120     public void createControl(Composite parent) {
121         initializeDialogUnits(parent);
122         
123         Composite composite= new Composite(parent, SWT.NONE);
124         int nColumns= 4;
125         
126         GridLayout layout= new GridLayout();
127         layout.numColumns= nColumns;
128         composite.setLayout(layout);
129     
130         createContainerControls(composite, nColumns);
131         createPackageControls(composite, nColumns);
132         createSeparator(composite, nColumns);
133         createSuiteNameControl(composite, nColumns);
134         setTypeName("AllTests", true); //$NON-NLS-1$
135
createSeparator(composite, nColumns);
136         createClassesInSuiteControl(composite, nColumns);
137         createMethodStubSelectionControls(composite, nColumns);
138         setControl(composite);
139         restoreWidgetValues();
140         Dialog.applyDialogFont(composite);
141         WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTSUITE_WIZARD_PAGE);
142     }
143
144     protected void createMethodStubSelectionControls(Composite composite, int nColumns) {
145         LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns);
146         LayoutUtil.createEmptySpace(composite,1);
147         LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1);
148     }
149
150     /**
151      * Should be called from the wizard with the initial selection.
152      */

153     public void init(IStructuredSelection selection) {
154         IJavaElement jelem= getInitialJavaElement(selection);
155         initContainerPage(jelem);
156         initTypePage(jelem);
157         doStatusUpdate();
158
159         fMethodStubsButtons.setSelection(0, false); //main
160
fMethodStubsButtons.setSelection(1, false); //add textrunner
161
fMethodStubsButtons.setEnabled(1, false); //add text
162
}
163     
164     /**
165      * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
166      */

167     protected void handleFieldChanged(String JavaDoc fieldName) {
168         super.handleFieldChanged(fieldName);
169         if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER)) {
170             if (fieldName.equals(PACKAGE))
171                 fPackageStatus= packageChanged();
172             updateClassesInSuiteTable();
173         } else if (fieldName.equals(CLASSES_IN_SUITE)) {
174             fClassesInSuiteStatus= classesInSuiteChanged();
175             fSuiteNameStatus= testSuiteChanged(); //must check this one too
176
updateSelectedClassesLabel();
177         } else if (fieldName.equals(SUITE_NAME)) {
178             fSuiteNameStatus= testSuiteChanged();
179         }
180
181         doStatusUpdate();
182     }
183
184     // ------ validation --------
185
private void doStatusUpdate() {
186         // status of all used components
187
IStatus[] status= new IStatus[] {
188             fContainerStatus,
189             fPackageStatus,
190             fSuiteNameStatus,
191             fClassesInSuiteStatus
192         };
193         
194         // the most severe status will be displayed and the ok button enabled/disabled.
195
updateStatus(status);
196     }
197
198     /**
199      * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean)
200      */

201     public void setVisible(boolean visible) {
202         super.setVisible(visible);
203         if (visible) {
204             setFocus();
205             updateClassesInSuiteTable();
206             handleAllFieldsChanged();
207         }
208     }
209
210     private void handleAllFieldsChanged() {
211         handleFieldChanged(PACKAGE);
212         handleFieldChanged(CONTAINER);
213         handleFieldChanged(CLASSES_IN_SUITE);
214         handleFieldChanged(SUITE_NAME);
215     }
216
217     protected void updateClassesInSuiteTable() {
218         if (fClassesInSuiteTable != null) {
219             IPackageFragment pack= getPackageFragment();
220             if (pack == null) {
221                 IPackageFragmentRoot root= getPackageFragmentRoot();
222                 if (root != null)
223                     pack= root.getPackageFragment(""); //$NON-NLS-1$
224
else
225                     return;
226             }
227             fClassesInSuiteTable.setInput(pack);
228             fClassesInSuiteTable.setAllChecked(true);
229             updateSelectedClassesLabel();
230         }
231     }
232     
233     protected void createClassesInSuiteControl(Composite parent, int nColumns) {
234         if (fClassesInSuiteTable == null) {
235
236             Label label = new Label(parent, SWT.LEFT);
237             label.setText(WizardMessages.getString("NewTestSuiteWizPage.classes_in_suite.label")); //$NON-NLS-1$
238
GridData gd= new GridData();
239             gd.horizontalAlignment = GridData.FILL;
240             gd.horizontalSpan= nColumns;
241             label.setLayoutData(gd);
242
243             fClassesInSuiteTable= CheckboxTableViewer.newCheckList(parent, SWT.BORDER);
244             gd= new GridData(GridData.FILL_BOTH);
245             gd.heightHint= 80;
246             gd.horizontalSpan= nColumns-1;
247
248             fClassesInSuiteTable.getTable().setLayoutData(gd);
249             fClassesInSuiteTable.setContentProvider(new ClassesInSuitContentProvider());
250             fClassesInSuiteTable.setLabelProvider(new JavaElementLabelProvider());
251             fClassesInSuiteTable.addCheckStateListener(new ICheckStateListener() {
252                 public void checkStateChanged(CheckStateChangedEvent event) {
253                     handleFieldChanged(CLASSES_IN_SUITE);
254                 }
255             });
256
257             Composite buttonContainer= new Composite(parent, SWT.NONE);
258             gd= new GridData(GridData.FILL_VERTICAL);
259             buttonContainer.setLayoutData(gd);
260             GridLayout buttonLayout= new GridLayout();
261             buttonLayout.marginWidth= 0;
262             buttonLayout.marginHeight= 0;
263             buttonContainer.setLayout(buttonLayout);
264     
265             fSelectAllButton= new Button(buttonContainer, SWT.PUSH);
266             fSelectAllButton.setText(WizardMessages.getString("NewTestSuiteWizPage.selectAll")); //$NON-NLS-1$
267
GridData bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
268             bgd.heightHint = SWTUtil.getButtonHeigthHint(fSelectAllButton);
269             bgd.widthHint = SWTUtil.getButtonWidthHint(fSelectAllButton);
270             fSelectAllButton.setLayoutData(bgd);
271             fSelectAllButton.addSelectionListener(new SelectionAdapter() {
272                 public void widgetSelected(SelectionEvent e) {
273                     fClassesInSuiteTable.setAllChecked(true);
274                     handleFieldChanged(CLASSES_IN_SUITE);
275                 }
276             });
277     
278             fDeselectAllButton= new Button(buttonContainer, SWT.PUSH);
279             fDeselectAllButton.setText(WizardMessages.getString("NewTestSuiteWizPage.deselectAll")); //$NON-NLS-1$
280
bgd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
281             bgd.heightHint = SWTUtil.getButtonHeigthHint(fDeselectAllButton);
282             bgd.widthHint = SWTUtil.getButtonWidthHint(fDeselectAllButton);
283             fDeselectAllButton.setLayoutData(bgd);
284             fDeselectAllButton.addSelectionListener(new SelectionAdapter() {
285                 public void widgetSelected(SelectionEvent e) {
286                     fClassesInSuiteTable.setAllChecked(false);
287                     handleFieldChanged(CLASSES_IN_SUITE);
288                 }
289             });
290
291             // No of selected classes label
292
fSelectedClassesLabel= new Label(parent, SWT.LEFT | SWT.WRAP);
293             fSelectedClassesLabel.setFont(parent.getFont());
294             updateSelectedClassesLabel();
295             gd = new GridData();
296             gd.horizontalSpan = 2;
297             fSelectedClassesLabel.setLayoutData(gd);
298         }
299     }
300
301     static class ClassesInSuitContentProvider implements IStructuredContentProvider {
302             
303         public Object JavaDoc[] getElements(Object JavaDoc parent) {
304             if (! (parent instanceof IPackageFragment))
305                 return new Object JavaDoc[0];
306             IPackageFragment pack= (IPackageFragment) parent;
307             if (! pack.exists())
308                 return new Object JavaDoc[0];
309             try {
310                 ICompilationUnit[] cuArray= pack.getCompilationUnits();
311                 List JavaDoc typesArrayList= new ArrayList JavaDoc();
312                 for (int i= 0; i < cuArray.length; i++) {
313                     ICompilationUnit cu= cuArray[i];
314                     IType[] types= cu.getTypes();
315                     for (int j= 0; j < types.length; j++) {
316                         IType type= types[j];
317                         if (type.isClass() && ! Flags.isAbstract(type.getFlags()) && TestSearchEngine.isTestImplementor(type))
318                             typesArrayList.add(types[j]);
319                     }
320                 }
321                 return typesArrayList.toArray();
322             } catch (JavaModelException e) {
323                 JUnitPlugin.log(e);
324                 return new Object JavaDoc[0];
325             }
326         }
327         
328         public void dispose() {
329         }
330         
331         public void inputChanged(Viewer viewer, Object JavaDoc oldInput, Object JavaDoc newInput) {
332         }
333     }
334
335     /*
336      * @see TypePage#evalMethods
337      */

338     protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
339         writeImports(imports);
340         if (fMethodStubsButtons.isEnabled() && fMethodStubsButtons.isSelected(0))
341             createMain(type);
342         type.createMethod(getSuiteMethodString(), null, false, null);
343     }
344
345     protected void createMain(IType type) throws JavaModelException {
346         type.createMethod(fMethodStubsButtons.getMainMethod(getTypeName()), null, false, null);
347     }
348
349     /**
350      * Returns the string content for creating a new suite() method.
351      */

352     public String JavaDoc getSuiteMethodString() {
353         IPackageFragment pack= getPackageFragment();
354         String JavaDoc packName= pack.getElementName();
355         StringBuffer JavaDoc suite= new StringBuffer JavaDoc("public static Test suite () {TestSuite suite= new TestSuite(\"Test for "+((packName.equals(""))?"default package":packName)+"\");\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
356
suite.append(getUpdatableString());
357         suite.append("\nreturn suite;}"); //$NON-NLS-1$
358
return suite.toString();
359     }
360     
361     /**
362      * Returns the new code to be included in a new suite() or which replaces old code in an existing suite().
363      */

364     public static String JavaDoc getUpdatableString(Object JavaDoc[] selectedClasses) {
365         StringBuffer JavaDoc suite= new StringBuffer JavaDoc();
366         suite.append(START_MARKER+"\n"); //$NON-NLS-1$
367
for (int i= 0; i < selectedClasses.length; i++) {
368             if (selectedClasses[i] instanceof IType) {
369                 IType testType= (IType) selectedClasses[i];
370                 IMethod suiteMethod= testType.getMethod("suite", new String JavaDoc[] {}); //$NON-NLS-1$
371
if (!suiteMethod.exists()) {
372                     suite.append("suite.addTestSuite("+testType.getElementName()+".class);"); //$NON-NLS-1$ //$NON-NLS-2$
373
} else {
374                     suite.append("suite.addTest("+testType.getElementName()+".suite());"); //$NON-NLS-1$ //$NON-NLS-2$
375
}
376             }
377         }
378         suite.append("\n"+END_MARKER); //$NON-NLS-1$
379
return suite.toString();
380     }
381     
382     private String JavaDoc getUpdatableString() {
383         return getUpdatableString(fClassesInSuiteTable.getCheckedElements());
384     }
385
386     /**
387      * Runnable for replacing an existing suite() method.
388      */

389     public IRunnableWithProgress getRunnable() {
390         return new IRunnableWithProgress() {
391             public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
392                 try {
393                     if (monitor == null) {
394                         monitor= new NullProgressMonitor();
395                     }
396                     updateExistingClass(monitor);
397                 } catch (CoreException e) {
398                     throw new InvocationTargetException JavaDoc(e);
399                 }
400             }
401         };
402     }
403     
404     protected void updateExistingClass(IProgressMonitor monitor) throws CoreException, InterruptedException JavaDoc {
405         IPackageFragment pack= getPackageFragment();
406         ICompilationUnit cu= pack.getCompilationUnit(getTypeName() + ".java"); //$NON-NLS-1$
407

408         if (!cu.exists()) {
409             createType(monitor);
410             fUpdatedExistingClassButton= false;
411             return;
412         }
413         
414         if (! UpdateTestSuite.checkValidateEditStatus(cu, getShell()))
415             return;
416
417         IType suiteType= cu.getType(getTypeName());
418         monitor.beginTask(WizardMessages.getString("NewTestSuiteWizPage.createType.beginTask"), 10); //$NON-NLS-1$
419
IMethod suiteMethod= suiteType.getMethod("suite", new String JavaDoc[] {}); //$NON-NLS-1$
420
monitor.worked(1);
421         
422         String JavaDoc lineDelimiter= JUnitStubUtility.getLineDelimiterUsed(cu);
423         if (suiteMethod.exists()) {
424             ISourceRange range= suiteMethod.getSourceRange();
425             if (range != null) {
426                 IBuffer buf= cu.getBuffer();
427                 String JavaDoc originalContent= buf.getText(range.getOffset(), range.getLength());
428                 StringBuffer JavaDoc source= new StringBuffer JavaDoc(originalContent);
429                 //using JDK 1.4
430
//int start= source.toString().indexOf(START_MARKER) --> int start= source.indexOf(START_MARKER);
431
int start= source.toString().indexOf(START_MARKER);
432                 if (start > -1) {
433                     //using JDK 1.4
434
//int end= source.toString().indexOf(END_MARKER, start) --> int end= source.indexOf(END_MARKER, start)
435
int end= source.toString().indexOf(END_MARKER, start);
436                     if (end > -1) {
437                         monitor.subTask(WizardMessages.getString("NewTestSuiteWizPage.createType.updating.suite_method")); //$NON-NLS-1$
438
monitor.worked(1);
439                         end += END_MARKER.length();
440                         source.replace(start, end, getUpdatableString());
441                         buf.replace(range.getOffset(), range.getLength(), source.toString());
442                         cu.reconcile();
443                         originalContent= buf.getText(0, buf.getLength());
444                         monitor.worked(1);
445                         String JavaDoc formattedContent=
446                             JUnitStubUtility.codeFormat(originalContent, 0, lineDelimiter);
447                         buf.replace(0, buf.getLength(), formattedContent);
448                         monitor.worked(1);
449                         cu.save(new SubProgressMonitor(monitor, 1), false);
450                     } else {
451                         cannotUpdateSuiteError();
452                     }
453                 } else {
454                     cannotUpdateSuiteError();
455                 }
456             } else {
457                 MessageDialog.openError(getShell(), WizardMessages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.title"), WizardMessages.getString("NewTestSuiteWizPage.createType.updateErrorDialog.message")); //$NON-NLS-1$ //$NON-NLS-2$
458
}
459         } else {
460             suiteType.createMethod(getSuiteMethodString(), null, true, monitor);
461             ISourceRange range= cu.getSourceRange();
462             IBuffer buf= cu.getBuffer();
463             String JavaDoc originalContent= buf.getText(range.getOffset(), range.getLength());
464             monitor.worked(2);
465             String JavaDoc formattedContent=
466                 JUnitStubUtility.codeFormat(originalContent, 0, lineDelimiter);
467             buf.replace(range.getOffset(), range.getLength(), formattedContent);
468             monitor.worked(1);
469             cu.save(new SubProgressMonitor(monitor, 1), false);
470         }
471         monitor.done();
472         fUpdatedExistingClassButton= true;
473     }
474
475     /**
476      * Returns true iff an existing suite() method has been replaced.
477      */

478     public boolean hasUpdatedExistingClass() {
479         return fUpdatedExistingClassButton;
480     }
481     
482     private IStatus classesInSuiteChanged() {
483         JUnitStatus status= new JUnitStatus();
484         if (fClassesInSuiteTable.getCheckedElements().length <= 0)
485             status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.classes_in_suite.error.no_testclasses_selected")); //$NON-NLS-1$
486
return status;
487     }
488     
489     private void updateSelectedClassesLabel() {
490         int noOfClassesChecked= fClassesInSuiteTable.getCheckedElements().length;
491         String JavaDoc key= (noOfClassesChecked==1) ? "NewTestClassWizPage.treeCaption.classSelected" : "NewTestClassWizPage.treeCaption.classesSelected"; //$NON-NLS-1$ //$NON-NLS-2$
492
fSelectedClassesLabel.setText(WizardMessages.getFormattedString(key, new Integer JavaDoc(noOfClassesChecked)));
493     }
494
495     protected void createSuiteNameControl(Composite composite, int nColumns) {
496         fSuiteNameLabel= new Label(composite, SWT.LEFT | SWT.WRAP);
497         fSuiteNameLabel.setFont(composite.getFont());
498         fSuiteNameLabel.setText(WizardMessages.getString("NewTestSuiteWizPage.suiteName.text")); //$NON-NLS-1$
499
GridData gd= new GridData();
500         gd.horizontalSpan= 1;
501         fSuiteNameLabel.setLayoutData(gd);
502
503         fSuiteNameText= new Text(composite, SWT.SINGLE | SWT.BORDER);
504         // moved up due to 1GEUNW2
505
fSuiteNameText.setEnabled(true);
506         fSuiteNameText.setFont(composite.getFont());
507         fSuiteNameText.addModifyListener(new ModifyListener() {
508             public void modifyText(ModifyEvent e) {
509                 handleFieldChanged(SUITE_NAME);
510             }
511         });
512         gd= new GridData();
513         gd.horizontalAlignment= GridData.FILL;
514         gd.grabExcessHorizontalSpace= true;
515         gd.horizontalSpan= nColumns - 2;
516         fSuiteNameText.setLayoutData(gd);
517         
518         Label space= new Label(composite, SWT.LEFT);
519         space.setText(" "); //$NON-NLS-1$
520
gd= new GridData();
521         gd.horizontalSpan= 1;
522         space.setLayoutData(gd);
523     }
524     
525     /**
526      * Gets the type name.
527      */

528     public String JavaDoc getTypeName() {
529         return (fSuiteNameText==null)?fSuiteNameTextInitialValue:fSuiteNameText.getText();
530     }
531     
532     /**
533      * Sets the type name.
534      * @param canBeModified Selects if the type name can be changed by the user
535      */

536     public void setTypeName(String JavaDoc name, boolean canBeModified) {
537         if (fSuiteNameText == null) {
538             fSuiteNameTextInitialValue= name;
539         } else {
540             fSuiteNameText.setText(name);
541             fSuiteNameText.setEnabled(canBeModified);
542         }
543     }
544
545     /**
546      * Called when the type name has changed.
547      * The method validates the type name and returns the status of the validation.
548      * Can be extended to add more validation
549      */

550     protected IStatus testSuiteChanged() {
551         JUnitStatus status= new JUnitStatus();
552         String JavaDoc typeName= getTypeName();
553         // must not be empty
554
if (typeName.length() == 0) {
555             status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_empty")); //$NON-NLS-1$
556
return status;
557         }
558         if (typeName.indexOf('.') != -1) {
559             status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_qualified")); //$NON-NLS-1$
560
return status;
561         }
562         IStatus val= JavaConventions.validateJavaTypeName(typeName);
563         if (val.getSeverity() == IStatus.ERROR) {
564             status.setError(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name_not_valid")+val.getMessage()); //$NON-NLS-1$
565
return status;
566         } else if (val.getSeverity() == IStatus.WARNING) {
567             status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.typeName.error.name.name_discouraged")+val.getMessage()); //$NON-NLS-1$
568
// continue checking
569
}
570
571         JUnitStatus recursiveSuiteInclusionStatus= checkRecursiveTestSuiteInclusion();
572         if (! recursiveSuiteInclusionStatus.isOK())
573             return recursiveSuiteInclusionStatus;
574             
575         IPackageFragment pack= getPackageFragment();
576         if (pack != null) {
577             ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
578
if (cu.exists()) {
579                 status.setWarning(WizardMessages.getString("NewTestSuiteWizPage.typeName.warning.already_exists")); //$NON-NLS-1$
580
fMethodStubsButtons.setEnabled(false);
581                 return status;
582             }
583         }
584         fMethodStubsButtons.setEnabled(true);
585         return status;
586     }
587
588     private JUnitStatus checkRecursiveTestSuiteInclusion(){
589         if (fClassesInSuiteTable == null)
590             return new JUnitStatus();
591         String JavaDoc typeName= getTypeName();
592         JUnitStatus status= new JUnitStatus();
593         Object JavaDoc[] checkedClasses= fClassesInSuiteTable.getCheckedElements();
594         for (int i= 0; i < checkedClasses.length; i++) {
595             IType checkedClass= (IType)checkedClasses[i];
596             if (checkedClass.getElementName().equals(typeName)){
597                 status.setWarning(WizardMessages.getString("NewTestSuiteCreationWizardPage.infinite_recursion")); //$NON-NLS-1$
598
return status;
599             }
600         }
601         return new JUnitStatus();
602     }
603
604     /**
605      * Sets the focus.
606      */

607     protected void setFocus() {
608         fSuiteNameText.setFocus();
609     }
610
611     /**
612      * Sets the classes in <code>elements</code> as checked.
613      */

614     public void setCheckedElements(Object JavaDoc[] elements) {
615         fClassesInSuiteTable.setCheckedElements(elements);
616     }
617     
618     protected void cannotUpdateSuiteError() {
619         MessageDialog.openError(getShell(), WizardMessages.getString("NewTestSuiteWizPage.cannotUpdateDialog.title"), //$NON-NLS-1$
620
WizardMessages.getFormattedString("NewTestSuiteWizPage.cannotUpdateDialog.message", new String JavaDoc[] {START_MARKER, END_MARKER})); //$NON-NLS-1$
621

622     }
623
624     private void writeImports(ImportsManager imports) {
625         imports.addImport("junit.framework.Test"); //$NON-NLS-1$
626
imports.addImport("junit.framework.TestSuite"); //$NON-NLS-1$
627
}
628
629     /**
630      * Use the dialog store to restore widget values to the values that they held
631      * last time this wizard was used to completion
632      */

633     private void restoreWidgetValues() {
634         IDialogSettings settings= getDialogSettings();
635         if (settings != null) {
636             boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN);
637             fMethodStubsButtons.setSelection(0, generateMain);
638             fMethodStubsButtons.setEnabled(1, generateMain);
639             fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER));
640             //The next 2 lines are necessary. Otherwise, if fMethodsStubsButtons is disabled, and USE_TESTRUNNER gets enabled,
641
//then the checkbox for USE_TESTRUNNER will be the only enabled component of fMethodsStubsButton
642
fMethodStubsButtons.setEnabled(!fMethodStubsButtons.isEnabled());
643             fMethodStubsButtons.setEnabled(!fMethodStubsButtons.isEnabled());
644             try {
645                 fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE));
646             } catch(NumberFormatException JavaDoc e) {}
647         }
648     }
649
650     /**
651      * Since Finish was pressed, write widget values to the dialog store so that they
652      * will persist into the next invocation of this wizard page
653      */

654     void saveWidgetValues() {
655         IDialogSettings settings= getDialogSettings();
656         if (settings != null) {
657             settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0));
658             settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1));
659             settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection());
660         }
661     }
662 }
663
Popular Tags