KickJava   Java API By Example, From Geeks To Geeks.

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


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.jdt.internal.junit.wizards;
12
13 import java.lang.reflect.InvocationTargetException JavaDoc;
14
15 import org.eclipse.core.runtime.Assert;
16 import org.eclipse.core.runtime.IProgressMonitor;
17 import org.eclipse.core.runtime.IStatus;
18 import org.eclipse.core.runtime.NullProgressMonitor;
19 import org.eclipse.core.runtime.SubProgressMonitor;
20
21 import org.eclipse.core.resources.IFile;
22
23 import org.eclipse.swt.widgets.Shell;
24
25 import org.eclipse.jface.action.IAction;
26 import org.eclipse.jface.dialogs.ErrorDialog;
27 import org.eclipse.jface.dialogs.MessageDialog;
28 import org.eclipse.jface.operation.IRunnableWithProgress;
29 import org.eclipse.jface.viewers.ILabelProvider;
30 import org.eclipse.jface.viewers.ISelection;
31 import org.eclipse.jface.viewers.IStructuredContentProvider;
32 import org.eclipse.jface.viewers.IStructuredSelection;
33 import org.eclipse.jface.window.Window;
34
35 import org.eclipse.jface.text.BadLocationException;
36 import org.eclipse.jface.text.Document;
37 import org.eclipse.jface.text.IDocument;
38
39 import org.eclipse.ui.IObjectActionDelegate;
40 import org.eclipse.ui.IWorkbenchPart;
41 import org.eclipse.ui.PlatformUI;
42 import org.eclipse.ui.dialogs.ISelectionStatusValidator;
43
44 import org.eclipse.jdt.core.IBuffer;
45 import org.eclipse.jdt.core.ICompilationUnit;
46 import org.eclipse.jdt.core.IJavaElement;
47 import org.eclipse.jdt.core.IMethod;
48 import org.eclipse.jdt.core.IPackageFragment;
49 import org.eclipse.jdt.core.ISourceRange;
50 import org.eclipse.jdt.core.IType;
51 import org.eclipse.jdt.core.JavaModelException;
52
53 import org.eclipse.jdt.ui.JavaElementLabelProvider;
54
55 import org.eclipse.jdt.junit.wizards.NewTestSuiteWizardPage;
56
57 import org.eclipse.jdt.internal.junit.Messages;
58 import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
59 import org.eclipse.jdt.internal.junit.util.CheckedTableSelectionDialog;
60 import org.eclipse.jdt.internal.junit.util.ExceptionHandler;
61 import org.eclipse.jdt.internal.junit.util.JUnitStatus;
62 import org.eclipse.jdt.internal.junit.util.JUnitStubUtility;
63 import org.eclipse.jdt.internal.junit.util.Resources;
64
65 /**
66  * An object contribution action that updates existing AllTests classes.
67  */

68 public class UpdateTestSuite implements IObjectActionDelegate {
69     
70     private Shell fShell;
71     private IPackageFragment fPack;
72     private ICompilationUnit fTestSuite;
73     private IMethod fSuiteMethod;
74     private static boolean fEmptySelectionAllowed= false;
75     private Object JavaDoc[] fSelectedTestCases;
76
77     private class UpdateAllTestsValidator implements ISelectionStatusValidator {
78         /*
79          * @see ISelectionValidator#validate(Object[])
80          */

81         public IStatus validate(Object JavaDoc[] selection) {
82             int count= 0;
83             for (int i= 0; i < selection.length; i++) {
84                 if (selection[i] instanceof IType) {
85                     count++;
86                 }
87             }
88             if (count == 0 && !fEmptySelectionAllowed) {
89                 return new JUnitStatus(IStatus.ERROR, ""); //$NON-NLS-1$
90
}
91             
92             IStatus recursiveInclusionStatus= checkRecursiveSuiteInclusion(selection);
93             if (recursiveInclusionStatus != null && ! recursiveInclusionStatus.isOK())
94                 return recursiveInclusionStatus;
95                 
96             String JavaDoc message;
97             if (count == 1) {
98                 message= Messages.format(WizardMessages.UpdateAllTests_selected_methods_label_one, new Integer JavaDoc(count));
99             } else {
100                 message= Messages.format(WizardMessages.UpdateAllTests_selected_methods_label_many, new Integer JavaDoc(count));
101             }
102             return new JUnitStatus(IStatus.INFO, message);
103         }
104         
105         private IStatus checkRecursiveSuiteInclusion(Object JavaDoc[] selection){
106             IType suiteClass= fSuiteMethod.getDeclaringType();
107             for (int i= 0; i < selection.length; i++) {
108                 if (selection[i] instanceof IType){
109                     if (((IType)selection[i]).equals(suiteClass)){
110                         return new JUnitStatus(IStatus.WARNING, WizardMessages.UpdateTestSuite_infinite_recursion);
111                     }
112                 }
113             }
114             return null;
115         }
116     }
117
118     public UpdateTestSuite() {
119         super();
120     }
121
122     /*
123      * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
124      */

125     public void setActivePart(IAction action, IWorkbenchPart targetPart) {
126     }
127
128     /*
129      * @see IActionDelegate#run(IAction)
130      */

131     public void run(IAction action) {
132         ILabelProvider lprovider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
133         IStructuredContentProvider cprovider= new SuiteClassesContentProvider();
134     
135         /* find TestClasses already in Test Suite */
136         IType testSuiteType= fTestSuite.findPrimaryType();
137         fSuiteMethod= testSuiteType.getMethod("suite", new String JavaDoc[] {}); //$NON-NLS-1$
138
if (fSuiteMethod.exists()) {
139             try {
140             ISourceRange range= fSuiteMethod.getSourceRange();
141             IBuffer buf= fTestSuite.getBuffer();
142             String JavaDoc originalContent= buf.getText(range.getOffset(), range.getLength());
143             buf.close();
144             if (getTestSuiteClassListRange(originalContent) != null) {
145                 CheckedTableSelectionDialog dialog= new CheckedTableSelectionDialog(fShell, lprovider, cprovider);
146                 dialog.setValidator(new UpdateAllTestsValidator());
147                 dialog.setTitle(WizardMessages.UpdateAllTests_title);
148                 dialog.setMessage(WizardMessages.UpdateAllTests_message);
149                 dialog.setInitialSelections(cprovider.getElements(fPack));
150                 dialog.setSize(60, 25);
151                 dialog.setInput(fPack);
152                 if (dialog.open() == Window.OK) {
153                     fSelectedTestCases= dialog.getResult();
154                     try {
155                         PlatformUI.getWorkbench().getProgressService().busyCursorWhile(getRunnable());
156                     } catch (Exception JavaDoc e) {
157                         JUnitPlugin.log(e);
158                     }
159                 }
160             } else {
161                 cannotUpdateSuiteError();
162             }
163             } catch (JavaModelException e) {
164                 JUnitPlugin.log(e);
165             }
166         } else {
167             noSuiteError();
168         }
169     }
170
171     /*
172      * @see IActionDelegate#selectionChanged(IAction, ISelection)
173      */

174     public void selectionChanged(IAction action, ISelection selection) {
175         fShell= JUnitPlugin.getActiveWorkbenchShell();
176         if (selection instanceof IStructuredSelection) {
177             Object JavaDoc testSuiteObj= ((IStructuredSelection) selection).getFirstElement();
178             if (testSuiteObj != null && testSuiteObj instanceof ICompilationUnit) {
179                 fTestSuite= (ICompilationUnit) testSuiteObj;
180                 IJavaElement packIJE= fTestSuite.getParent();
181                 if (packIJE instanceof IPackageFragment) {
182                     fPack= (IPackageFragment) packIJE;
183                 }
184             }
185         }
186     }
187     
188     private void updateTestCasesInSuite(IProgressMonitor monitor) {
189         try {
190             monitor.beginTask(WizardMessages.UpdateAllTests_beginTask, 5);
191             if (! checkValidateEditStatus(fTestSuite, fShell))
192                 return;
193                 
194             ISourceRange range= fSuiteMethod.getSourceRange();
195             IDocument fullSource= new Document(fTestSuite.getBuffer().getContents());
196             String JavaDoc originalContent= fullSource.get(range.getOffset(), range.getLength());
197             StringBuffer JavaDoc source= new StringBuffer JavaDoc(originalContent);
198             TestSuiteClassListRange classRange = getTestSuiteClassListRange(source.toString());
199             if (classRange != null) {
200                 monitor.worked(1);
201                 // String updatableCode= source.substring(start,end+NewTestSuiteCreationWizardPage.endMarker.length());
202
source.replace(classRange.getStart(), classRange.getEnd(), getUpdatableString(fSelectedTestCases));
203                 fullSource.replace(range.getOffset(), range.getLength(), source.toString());
204                 monitor.worked(1);
205                 String JavaDoc formattedContent= JUnitStubUtility.formatCompilationUnit(fTestSuite.getJavaProject(), fullSource.get(), fTestSuite.findRecommendedLineSeparator());
206                 //buf.replace(range.getOffset(), range.getLength(), formattedContent);
207
IBuffer buf= fTestSuite.getBuffer();
208                 buf.replace(0, buf.getLength(), formattedContent);
209                 monitor.worked(1);
210                 fTestSuite.save(new SubProgressMonitor(monitor, 1), true);
211                 monitor.worked(1);
212             }
213         } catch (JavaModelException e) {
214             ExceptionHandler.handle(e, fShell, WizardMessages.UpdateTestSuite_update, WizardMessages.UpdateTestSuite_error);
215         } catch (BadLocationException e) {
216             Assert.isTrue(false, "Should never happen"); //$NON-NLS-1$
217
} finally{
218             monitor.done();
219         }
220     }
221     
222     public static TestSuiteClassListRange getTestSuiteClassListRange(String JavaDoc source) {
223         int start= source.indexOf(NewTestSuiteWizardPage.NON_COMMENT_START_MARKER);
224         if (start <= -1)
225             return null;
226         start = source.lastIndexOf(NewTestSuiteWizardPage.COMMENT_START, start);
227         if (start <= -1)
228             return null;
229         int end= source.indexOf(NewTestSuiteWizardPage.NON_COMMENT_END_MARKER, start);
230         if (end <= -1)
231             return null;
232         end += NewTestSuiteWizardPage.NON_COMMENT_END_MARKER.length();
233         return new TestSuiteClassListRange(start, end);
234     }
235
236     /*
237      * Returns the new code to be included in a new suite() or which replaces old code in an existing suite().
238      */

239     public static String JavaDoc getUpdatableString(Object JavaDoc[] selectedClasses) {
240         StringBuffer JavaDoc suite= new StringBuffer JavaDoc();
241         suite.append(NewTestSuiteWizardPage.START_MARKER+"\n"); //$NON-NLS-1$
242
for (int i= 0; i < selectedClasses.length; i++) {
243             if (selectedClasses[i] instanceof IType) {
244                 IType testType= (IType) selectedClasses[i];
245                 IMethod suiteMethod= testType.getMethod("suite", new String JavaDoc[] {}); //$NON-NLS-1$
246
if (!suiteMethod.exists()) {
247                     suite.append("suite.addTestSuite("+testType.getElementName()+".class);"); //$NON-NLS-1$ //$NON-NLS-2$
248
} else {
249                     suite.append("suite.addTest("+testType.getElementName()+".suite());"); //$NON-NLS-1$ //$NON-NLS-2$
250
}
251             }
252         }
253         suite.append("\n"+NewTestSuiteWizardPage.END_MARKER); //$NON-NLS-1$
254
return suite.toString();
255     }
256     
257     public static boolean checkValidateEditStatus(ICompilationUnit testSuiteCu, Shell shell){
258         IStatus status= validateModifiesFiles(getTestSuiteFile(testSuiteCu));
259         if (status.isOK())
260             return true;
261         ErrorDialog.openError(shell, WizardMessages.UpdateTestSuite_update, WizardMessages.UpdateTestSuite_could_not_update, status);
262         return false;
263     }
264     
265     private static IFile getTestSuiteFile(ICompilationUnit testSuiteCu) {
266         return (IFile) testSuiteCu.getResource();
267     }
268     
269     private static IStatus validateModifiesFiles(IFile fileToModify) {
270         IFile[] filesToModify= {fileToModify};
271         IStatus status= Resources.checkInSync(filesToModify);
272         if (! status.isOK())
273             return status;
274         status= Resources.makeCommittable(filesToModify, null);
275         if (! status.isOK())
276             return status;
277         return new JUnitStatus();
278     }
279
280     public IRunnableWithProgress getRunnable() {
281         return new IRunnableWithProgress() {
282             public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
283                 if (monitor == null) {
284                     monitor= new NullProgressMonitor();
285                 }
286                 updateTestCasesInSuite(monitor);
287             }
288         };
289     }
290
291     private void cannotUpdateSuiteError() {
292         MessageDialog.openError(fShell, WizardMessages.UpdateAllTests_cannotUpdate_errorDialog_title,
293             Messages.format(WizardMessages.UpdateAllTests_cannotUpdate_errorDialog_message, new String JavaDoc[] {NewTestSuiteWizardPage.START_MARKER, NewTestSuiteWizardPage.END_MARKER}));
294
295     }
296
297     private void noSuiteError() {
298         MessageDialog.openError(fShell, WizardMessages.UpdateAllTests_cannotFind_errorDialog_title, WizardMessages.UpdateAllTests_cannotFind_errorDialog_message);
299     }
300 }
301
Popular Tags