Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 134254 | Differences between
and this patch

Collapse All | Expand All

(-)src/org/eclipse/hyades/test/tools/core/internal/common/CommonPluginMessages.java (-1 / +29 lines)
Lines 23-37 Link Here
23
        NLS.initializeMessages(BUNDLE_NAME, CommonPluginMessages.class);
23
        NLS.initializeMessages(BUNDLE_NAME, CommonPluginMessages.class);
24
    }
24
    }
25
25
26
    public static String E_CODEGEN_PACK_DIAG;
26
    public static String ADJUST_CLASSPATH;
27
	public static String ASSOCIATE_TEST_TO_SOURCE;
28
	public static String CREATE_CONTAINER;
29
	public static String CREATE_PACKAGE;
30
	public static String DEFAULT_PACKAGE;
31
	public static String DEFINE_SOURCE_FOLDER;
32
	public static String DELETE_FILE;
33
	public static String DELETING_FILE;
34
	public static String E_CODEGEN_PACK_DIAG;
27
    public static String E_CODEGEN_CLASS_DIAG;
35
    public static String E_CODEGEN_CLASS_DIAG;
28
    public static String E_CODEGEN_CLOSED_PROJECT;
36
    public static String E_CODEGEN_CLOSED_PROJECT;
29
    public static String E_CODEGEN_NO_SRCFOLDER;
37
    public static String E_CODEGEN_NO_SRCFOLDER;
30
    
38
    
31
    public static String _ERROR_LAUNCH_VALIDATOR;
39
    public static String _ERROR_LAUNCH_VALIDATOR;
32
    public static String _WARNING_LAUNCH_VALIDATOR;
40
    public static String _WARNING_LAUNCH_VALIDATOR;
41
	public static String E_COMP_UNIT_READ_ONLY;
42
	public static String GENERATE_CODE;
43
	public static String GENERATE_FILE;
44
	public static String GENERATING_FILE;
45
	public static String GENERIC_GENERATOR;
46
	public static String JavaGenerator_W_COMP_UNIT_UNSAVED_CHANGES;
47
	public static String MOVE_COMPILATION_UNIT;
48
	public static String MOVE_RENAME_COMPILATION_UNIT;
49
	public static String NO_FILE;
50
	public static String NO_SOURCE_FOLDER;
51
	public static String NOT_A_SOURCE_FOLDER;
52
	public static String NOT_IN_JAVA_PROJECT;
53
	public static String PROJECT_NOT_ACCESSIBLE;
54
	public static String READ_ONLY_FILE;
55
	public static String RENAME_COMPILATION_UNIT;
56
	public static String RESOURCE_NOT_ACCESSIBLE;
57
	public static String SETUP_CONTEXT;
58
	public static String UNKNOWN_LOCATION;
59
	public static String UPDATE_CODE;
33
    public static String VALIDATION_NO_HOST_NAME_ERROR;
60
    public static String VALIDATION_NO_HOST_NAME_ERROR;
34
    public static String VALIDATION_BAD_ROOTDIR_ERROR_;
61
    public static String VALIDATION_BAD_ROOTDIR_ERROR_;
35
    public static String _WARNING_BUILD_PATH_PROBLEM;
62
    public static String _WARNING_BUILD_PATH_PROBLEM;
36
    public static String _WARNING_COMPILATION_PROBLEM;
63
    public static String _WARNING_COMPILATION_PROBLEM;
64
	public static String W_COMP_UNIT_OVERWRITE;
37
}
65
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/messages.properties (-1 / +29 lines)
Lines 14-19 Link Here
14
14
15
E_CODEGEN_PACK_DIAG		= A problem was found with the package name: {0}. The code for this test suite cannot be generated until you adjust the package name.
15
E_CODEGEN_PACK_DIAG		= A problem was found with the package name: {0}. The code for this test suite cannot be generated until you adjust the package name.
16
E_CODEGEN_CLASS_DIAG	= A problem was found with the class name: {0}. The code for this test suite cannot be generated until you adjust the class name.
16
E_CODEGEN_CLASS_DIAG	= A problem was found with the class name: {0}. The code for this test suite cannot be generated until you adjust the class name.
17
E_COMP_UNIT_READ_ONLY=Compilation unit {0} is read-only
17
E_CODEGEN_CLOSED_PROJECT= The source folder: {0} belongs to a closed project. The code for this test cannot be generated until the project is opened.
18
E_CODEGEN_CLOSED_PROJECT= The source folder: {0} belongs to a closed project. The code for this test cannot be generated until the project is opened.
18
E_CODEGEN_NO_SRCFOLDER	= The test suite does not specify a source folder.
19
E_CODEGEN_NO_SRCFOLDER	= The test suite does not specify a source folder.
19
20
Lines 22-25 Link Here
22
VALIDATION_NO_HOST_NAME_ERROR	= No host name found
23
VALIDATION_NO_HOST_NAME_ERROR	= No host name found
23
VALIDATION_BAD_ROOTDIR_ERROR_	= {0}\nThis value for ROOTDIR does not match existing directory on the specified host: {1}
24
VALIDATION_BAD_ROOTDIR_ERROR_	= {0}\nThis value for ROOTDIR does not match existing directory on the specified host: {1}
24
_WARNING_BUILD_PATH_PROBLEM		= Java build path errors exist in enclosing project: {0}.
25
_WARNING_BUILD_PATH_PROBLEM		= Java build path errors exist in enclosing project: {0}.
25
_WARNING_COMPILATION_PROBLEM	= Compilation errors exist in enclosing project: {0}.
26
_WARNING_COMPILATION_PROBLEM	= Compilation errors exist in enclosing project: {0}.
27
CREATE_PACKAGE=Create package {0}
28
CREATE_CONTAINER=Create container {0}
29
NO_SOURCE_FOLDER=Source folder doesn't exist
30
NOT_A_SOURCE_FOLDER=Package fragment root is not a source folder
31
NOT_IN_JAVA_PROJECT=Container {0} does not belong to a Java project
32
ASSOCIATE_TEST_TO_SOURCE=Associate test {0} to source {1}
33
NO_FILE=File does not exist
34
READ_ONLY_FILE=File is read-only
35
DELETING_FILE=Deleting file
36
DELETE_FILE=Delete file {0}
37
DEFINE_SOURCE_FOLDER=Define {0} as a source folder
38
RESOURCE_NOT_ACCESSIBLE=Resource {0} is not accessible
39
RENAME_COMPILATION_UNIT=Rename compilation unit {0} to {1}
40
ADJUST_CLASSPATH=Adjust classpath for project {0}
41
PROJECT_NOT_ACCESSIBLE=Project '{0}' is not accessible
42
GENERATE_FILE=Generate file {0}
43
GENERATE_CODE=Generate code
44
UNKNOWN_LOCATION=Unknown location for file 
45
GENERATING_FILE=Generating file
46
GENERIC_GENERATOR=Generic TPTP code generator
47
SETUP_CONTEXT=Setup context
48
UPDATE_CODE=Update code
49
MOVE_RENAME_COMPILATION_UNIT=Move compilation unit {0} to package {1} and rename it to {2}
50
MOVE_COMPILATION_UNIT=Move compilation unit {0} to package {1}
51
W_COMP_UNIT_OVERWRITE=Compilation unit {0} will be overwritten
52
DEFAULT_PACKAGE=(default package)
53
JavaGenerator_W_COMP_UNIT_UNSAVED_CHANGES=Compilation unit {0} has unsaved changes. Code update may be unaccurate.
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/JavaGenerator.java (-81 / +233 lines)
Lines 11-70 Link Here
11
 **********************************************************************/
11
 **********************************************************************/
12
package org.eclipse.hyades.test.tools.core.internal.common.codegen;
12
package org.eclipse.hyades.test.tools.core.internal.common.codegen;
13
13
14
import java.util.ArrayList;
15
import java.util.Arrays;
16
import java.util.Collection;
14
import java.util.Collection;
17
import java.util.Collections;
15
import java.util.Collections;
18
import java.util.HashSet;
16
import java.util.HashSet;
19
import java.util.Iterator;
17
import java.util.Iterator;
20
import java.util.List;
21
import java.util.Set;
18
import java.util.Set;
22
19
23
import org.eclipse.core.resources.IContainer;
20
import org.eclipse.core.resources.IContainer;
24
import org.eclipse.core.resources.IFile;
21
import org.eclipse.core.resources.IFile;
25
import org.eclipse.core.resources.IProject;
22
import org.eclipse.core.resources.IProject;
26
import org.eclipse.core.resources.IResource;
27
import org.eclipse.core.resources.ResourcesPlugin;
23
import org.eclipse.core.resources.ResourcesPlugin;
28
import org.eclipse.core.runtime.CoreException;
24
import org.eclipse.core.runtime.CoreException;
29
import org.eclipse.core.runtime.IPath;
25
import org.eclipse.core.runtime.IPath;
30
import org.eclipse.core.runtime.IProgressMonitor;
26
import org.eclipse.core.runtime.IProgressMonitor;
31
import org.eclipse.core.runtime.IStatus;
27
import org.eclipse.core.runtime.IStatus;
28
import org.eclipse.core.runtime.OperationCanceledException;
32
import org.eclipse.core.runtime.Path;
29
import org.eclipse.core.runtime.Path;
33
import org.eclipse.core.runtime.Status;
34
import org.eclipse.core.runtime.SubProgressMonitor;
30
import org.eclipse.core.runtime.SubProgressMonitor;
35
import org.eclipse.hyades.models.common.facades.behavioral.ITestCase;
31
import org.eclipse.hyades.models.common.facades.behavioral.ITestCase;
36
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
32
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
37
import org.eclipse.hyades.test.tools.core.CorePlugin;
38
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
33
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
39
import org.eclipse.jdt.core.IClasspathEntry;
34
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.AdjustSourceContainerChange;
35
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.CreatePackageFragmentChange;
36
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.MoveCompilationUnitChange;
37
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.PotentialChange;
38
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.ProjectAdjustChange;
39
import org.eclipse.jdt.core.ICompilationUnit;
40
import org.eclipse.jdt.core.IJavaElement;
40
import org.eclipse.jdt.core.IJavaProject;
41
import org.eclipse.jdt.core.IJavaProject;
42
import org.eclipse.jdt.core.IPackageFragment;
43
import org.eclipse.jdt.core.IPackageFragmentRoot;
41
import org.eclipse.jdt.core.JavaConventions;
44
import org.eclipse.jdt.core.JavaConventions;
42
import org.eclipse.jdt.core.JavaCore;
45
import org.eclipse.jdt.core.JavaCore;
46
import org.eclipse.ltk.core.refactoring.Change;
47
import org.eclipse.ltk.core.refactoring.CompositeChange;
48
import org.eclipse.ltk.core.refactoring.NullChange;
49
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
43
import org.eclipse.osgi.util.NLS;
50
import org.eclipse.osgi.util.NLS;
44
51
45
/**
52
/**
46
 * @author marcelop
53
 * Abstract Java code generator.
47
 * @author jcanches
54
 * <p>Although this abstract class does not implement any code generation
55
 * or code update, it provides additional features for generating java code, and also
56
 * makes additional assumptions about the test suite behavior model.</p>
57
 * <p>Sub-classes must implement {@link Generator#generateCode(IProgressMonitor)}, and
58
 * need to redefine {@link #createSourceUpdateChange(SubProgressMonitor)} if code update
59
 * is desired.</p>
60
 * <p>Sub-classes may also redefine {@link #computeTestMethodNames(ITestSuite, boolean, Helper)},
61
 * and extend {@link #createAdjustProjectClasspathChange(IProgressMonitor)},
62
 * {@link #createPreCodegenerationChange(IProgressMonitor)},
63
 * {@link Generator#createPostCodegenerationChange(IProgressMonitor)}, and all conditions
64
 * checking methods.</p>
65
 * @author marcelop, jcanches
48
 * @since 1.0.1
66
 * @since 1.0.1
49
 */
67
 */
50
abstract public class JavaGenerator extends Generator {
68
abstract public class JavaGenerator extends Generator {
51
	
69
	
52
	private IProjectDependencyUpdater projectDependencyUpdater;
70
	private IProjectDependencyUpdater projectDependencyUpdater;
53
	
71
	
54
	protected JavaGenerator(IProjectDependencyUpdater updater) {
72
	/**
73
	 * Creates a JavaGenerator for a Java test suite.
74
	 * @param testSuite
75
	 * @param updater A Project dependency updater that will perform project
76
	 * adjustment to comply with additional classpath requirements.
77
	 */
78
	protected JavaGenerator(ITestSuite testSuite, IProjectDependencyUpdater updater) {
79
		super(testSuite);
55
		this.projectDependencyUpdater = updater;
80
		this.projectDependencyUpdater = updater;
56
	}
81
	}
57
	
82
	
58
	protected void adjustProjectClasspath(ITestSuite testSuite, IProject project, IProgressMonitor monitor) throws CoreException {
83
	/**
59
		Collection dependentProjects = getDependentProjects(testSuite, project);
84
	 * Creates the change that adjusts the project classpath.
60
		for(Iterator it = dependentProjects.iterator(); it.hasNext(); ) {
85
	 * <p>This implementation creates a change that invokes the generator's project
61
			projectDependencyUpdater.addRequiredProject((IProject)it.next());
86
	 * dependency updater.</p>
87
	 * <p>Sub-classes may extend or redefine this implementation.</p> 
88
	 * @param monitor
89
	 * @return
90
	 * @throws CoreException
91
	 */
92
	protected Change createAdjustProjectClasspathChange(IProgressMonitor monitor) throws CoreException {
93
		monitor.beginTask("", 1); //$NON-NLS-1$
94
		try {
95
			IProject project = getFileHandle(getTestSuite()).getProject();
96
			Collection dependentProjects = getDependentProjects(getTestSuite(), project);
97
			for(Iterator it = dependentProjects.iterator(); it.hasNext(); ) {
98
				projectDependencyUpdater.addRequiredProject((IProject)it.next());
99
			}
100
			if (!projectDependencyUpdater.previewAdjustProject(project).isEmpty()) {
101
				monitor.worked(1);
102
				return new ProjectAdjustChange(projectDependencyUpdater, project);
103
			} else {
104
				monitor.worked(1);
105
				return null;
106
			}
107
		} finally {
108
			monitor.done();
109
		}
110
	}
111
	
112
	protected IPackageFragmentRoot getPackageFragmentRoot(ITestSuite ts) {
113
		IContainer container = getSourceContainerHandle(ts);
114
		IJavaElement javaElement = JavaCore.create(container);
115
		if (javaElement instanceof IJavaProject) {
116
			IJavaProject jproject = (IJavaProject)javaElement;
117
			return jproject.getPackageFragmentRoot(container);
118
		} else if (javaElement instanceof IPackageFragmentRoot) {
119
			return (IPackageFragmentRoot)javaElement;
120
		}
121
		return null;
122
	}
123
	
124
	protected IPackageFragment getPackageFragment(ITestSuite ts) {
125
		IPackageFragmentRoot root = getPackageFragmentRoot(ts);
126
		if (root == null) return null;
127
		return root.getPackageFragment(getPackageName(ts));
128
	}
129
	
130
	protected ICompilationUnit getCompilationUnit(ITestSuite ts) {
131
		IPackageFragment pack = getPackageFragment(ts);
132
		if (pack != null) {
133
			return pack.getCompilationUnit(getClassName(ts) + ".java"); //$NON-NLS-1$
62
		}
134
		}
63
		projectDependencyUpdater.adjustProject(project, monitor);
135
		return null;
64
	}
136
	}
65
	
137
	
66
	protected String getPackageName(ITestSuite testSuite) {
138
	/**
67
		String cls = testSuite.getImplementor().getResource();
139
	 * Returns the package name that the generated class must belong to.
140
	 * @return A Java package name.
141
	 */
142
	protected String getPackageName(ITestSuite ts) {
143
		String cls = ts.getImplementor().getResource();
68
		String packageName;
144
		String packageName;
69
		int index = cls.lastIndexOf('.');
145
		int index = cls.lastIndexOf('.');
70
		if (index == -1) {
146
		if (index == -1) {
Lines 75-82 Link Here
75
		return packageName;
151
		return packageName;
76
	}
152
	}
77
	
153
	
78
	protected String getClassName(ITestSuite testSuite) {
154
	/**
79
		String cls = testSuite.getImplementor().getResource();
155
	 * Returns the class name of the generated class.
156
	 * @return
157
	 */
158
	protected String getClassName(ITestSuite ts) {
159
		String cls = ts.getImplementor().getResource();
80
		String className;
160
		String className;
81
		int index = cls.lastIndexOf('.');
161
		int index = cls.lastIndexOf('.');
82
		if (index == -1) {
162
		if (index == -1) {
Lines 87-151 Link Here
87
		return className;
167
		return className;
88
	}
168
	}
89
	
169
	
90
	protected void doGenerateFile(ITestSuite testSuite, IContainer sourceContainer, IFile file, IProgressMonitor monitor)
170
	/**
91
	throws Exception
171
	 * In addition to its super implementation, this implementation creates a change that ensures 
172
	 * that the source container is a source folder, creates the package, and adjusts the project
173
	 * classpath if necessary.
174
	 */
175
	protected Change createPreCodegenerationChange(IProgressMonitor monitor) throws CoreException
92
	{
176
	{
93
		monitor.beginTask("", 10); //$NON-NLS-1$
177
		monitor.beginTask("", 10); //$NON-NLS-1$
94
		try {
178
		try {
95
			String packageName = getPackageName(testSuite);
179
			CompositeChange change = new CompositeChange(CommonPluginMessages.SETUP_CONTEXT);
96
			adjustSourceContainer(sourceContainer, packageName, new SubProgressMonitor(monitor, 1));
180
			addPotentialChange(super.createPreCodegenerationChange(monitor), change);
97
			adjustProjectClasspath(testSuite, file.getProject(), new SubProgressMonitor(monitor, 4));
181
			addPotentialChange(createAdjustSourceContainerChange(), change);
98
			generateFile(testSuite, file, new SubProgressMonitor(monitor, 5));
182
			addPotentialChange(createCreatePackageChange(), change);
183
			addPotentialChange(createAdjustProjectClasspathChange(new SubProgressMonitor(monitor, 1)), change);
184
			return packCompositeChange(change);
99
		} finally {
185
		} finally {
100
			monitor.done();
186
			monitor.done();
101
		}
187
		}
102
	}
188
	}
189
	
190
	/**
191
	 * Helper method to create a change that makes sure that the source container is a java
192
	 * source folder.
193
	 * @return
194
	 */
195
	final protected Change createAdjustSourceContainerChange() {
196
		PotentialChange change = new AdjustSourceContainerChange(getSourceContainerHandle(getTestSuite()));
197
		if (change.hasEffect()) return change;
198
		else return new NullChange();
199
	}
200
	
201
	/**
202
	 * Helper method to create a change that creates the package, if necessary.
203
	 */
204
	final protected Change createCreatePackageChange() {
205
		IJavaProject jproject = JavaCore.create(getSourceContainerHandle(getTestSuite()).getProject());
206
		IPackageFragmentRoot sourceFolder = jproject.getPackageFragmentRoot(getSourceContainerHandle(getTestSuite()));
207
		PotentialChange change = new CreatePackageFragmentChange(sourceFolder, getPackageName(getTestSuite()));
208
		if (change.hasEffect()) return change;
209
		else return new NullChange();
210
	}
103
211
104
	protected void doUpdateFile(ITestSuite testSuite, IContainer sourceContainer, IFile file, IProgressMonitor monitor) throws Exception {
212
	protected final Change createUpdateChange(IFile file, IProgressMonitor monitor) throws CoreException, UnsupportedOperationException {
105
		monitor.beginTask("", 2); //$NON-NLS-1$
213
		monitor.beginTask("", 2); //$NON-NLS-1$
106
		try {
214
		try {
107
			adjustProjectClasspath(testSuite, sourceContainer.getProject(), new SubProgressMonitor(monitor, 1));
215
			Change sourceUpdateChange = createSourceUpdateChange(file, new SubProgressMonitor(monitor, 1));
108
			updateFile(testSuite, file, new SubProgressMonitor(monitor, 1));
216
			CompositeChange change = new CompositeChange(CommonPluginMessages.UPDATE_CODE);
217
			addPotentialChange(createAdjustProjectClasspathChange(new SubProgressMonitor(monitor, 1)), change);
218
			addPotentialChange(sourceUpdateChange, change);
219
			addPotentialChange(createCreatePackageChange(), change);
220
			addPotentialChange(createMoveCompilationUnitChange(), change);
221
			addPotentialChange(createPostCodegenerationChange(new SubProgressMonitor(monitor, 1)), change);
222
			change.markAsSynthetic();
223
			return packCompositeChange(change);
109
		} finally {
224
		} finally {
110
			monitor.done();
225
			monitor.done();
111
		}
226
		}
112
	}
227
	}
228
	
229
	/**
230
	 * Creates a move compilation unit change, if necessary (i.e. if the classes in the
231
	 * previous and in the current versions of the model are different).
232
	 * @return
233
	 */
234
	private Change createMoveCompilationUnitChange() {
235
		ITestSuite previous = getRepositoryTestSuite();
236
		if (previous != null) {
237
			IFile file = getFileHandle(previous);
238
			IFile newFile = getFileHandle(getTestSuite());
239
			if (!newFile.equals(file)) {
240
				// Change destination
241
				if (file.exists()) {
242
					ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
243
					if (cu.exists()) {
244
						IPackageFragment newPackage = getPackageFragment(getTestSuite());
245
						return new MoveCompilationUnitChange(cu, newPackage, newFile.getName());
246
					}
247
				}
248
			}
249
		}
250
		return null;
251
	}
113
252
114
	public IStatus validate(ITestSuite testSuite) {
253
	/**
115
		IStatus status;
254
	 * Creates the source update change. This implementation throws a {@link UnsupportedOperationException}.
116
		
255
	 * Sub-classes need to redefine this method in order to be code-update-capable.
117
		// Super validation
256
	 * @file The file to update. This is not always equal to getFileHandle(), when there
118
		status = super.validate(testSuite);
257
	 * is a source file move involved during the generation.
119
		if (status.getSeverity() != IStatus.OK) return status;
258
	 * @param monitor A progress monitor
120
		
259
	 * @return
121
		// Package name
260
	 * @throws CoreException, UnsupportedOperationException
122
		String packageName = getPackageName(testSuite);
261
	 */
123
		if (packageName.length() > 0) {
262
	protected Change createSourceUpdateChange(IFile file, SubProgressMonitor monitor) throws CoreException, UnsupportedOperationException {
124
			status = JavaConventions.validatePackageName(packageName);
263
		throw new UnsupportedOperationException();
125
			if (status.getSeverity() != IStatus.OK) {
264
	}
126
				if (status.getSeverity() == IStatus.ERROR) {
265
266
	/**
267
	 * In addition to its super implementation, this implementation checks that the package name
268
	 * and class name are valid.
269
	 */
270
	public RefactoringStatus checkInitialConditions(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
271
		monitor.beginTask("", 4); //$NON-NLS-1$
272
		try {
273
			// Super validation
274
			RefactoringStatus status = super.checkInitialConditions(new SubProgressMonitor(monitor, 2));
275
			
276
			// Package name
277
			String packageName = getPackageName(getTestSuite());
278
			if (packageName.length() > 0) {
279
				IStatus st = JavaConventions.validatePackageName(packageName);
280
				if (st.getSeverity() != IStatus.OK) {
281
					if (st.getSeverity() == IStatus.ERROR) {
282
						// Replace the diagnosis of JDT with something more explicit
283
						status.addFatalError(NLS.bind(CommonPluginMessages.E_CODEGEN_PACK_DIAG, st.getMessage()));
284
					}
285
				}
286
			}
287
			monitor.worked(1);
288
			
289
			// Class name
290
			String className = getClassName(getTestSuite());
291
			IStatus st = JavaConventions.validateJavaTypeName(className);
292
			if (st.getSeverity() != IStatus.OK) {
293
				if (st.getSeverity() == IStatus.ERROR) {
127
					// Replace the diagnosis of JDT with something more explicit
294
					// Replace the diagnosis of JDT with something more explicit
128
					return new Status(status.getSeverity(), CorePlugin.PLUGIN_ID, 0, NLS.bind(CommonPluginMessages.E_CODEGEN_PACK_DIAG, status.getMessage()), null);
295
					status.addFatalError(NLS.bind(CommonPluginMessages.E_CODEGEN_CLASS_DIAG, st.getMessage()));
129
				}
296
				}
130
				return status;
131
			}
297
			}
132
		}
298
			monitor.worked(1);
133
		
299
			
134
		// Class name
300
			ITestSuite previous = getRepositoryTestSuite();
135
		String className = getClassName(testSuite);
301
			ICompilationUnit cu;
136
		status = JavaConventions.validateJavaTypeName(className);
302
			if (previous != null) {
137
		if (status.getSeverity() != IStatus.OK) {
303
				cu = getCompilationUnit(previous);
138
			if (status.getSeverity() == IStatus.ERROR) {
304
			} else {
139
				// Replace the diagnosis of JDT with something more explicit
305
				cu = getCompilationUnit(getTestSuite());
140
				return new Status(status.getSeverity(), CorePlugin.PLUGIN_ID, 0, NLS.bind(CommonPluginMessages.E_CODEGEN_CLASS_DIAG, status.getMessage()), null);
306
			}
307
			if (cu != null && cu.hasUnsavedChanges()) {
308
				status.addError(NLS.bind(CommonPluginMessages.JavaGenerator_W_COMP_UNIT_UNSAVED_CHANGES, cu.getElementName()));
141
			}
309
			}
142
			return status;
310
			return status;
311
		} finally {
312
			monitor.done();
143
		}
313
		}
144
		
145
		// Otherwise OK
146
		return Status.OK_STATUS;
147
	}
314
	}
148
	
315
	
316
	/**
317
	 * Computes the names of the test methods associated to the test cases of the specified test
318
	 * suite. Test methods names should be typically stored in the model.
319
	 * @param testSuite
320
	 * @param isExternalBehavior
321
	 * @param helper
322
	 * @see Helper#setTestMethodName(ITestCase, String)
323
	 */
149
	protected void computeTestMethodNames(ITestSuite testSuite, boolean isExternalBehavior, Helper helper) {
324
	protected void computeTestMethodNames(ITestSuite testSuite, boolean isExternalBehavior, Helper helper) {
150
		Iterator it = testSuite.getITestCases().iterator();
325
		Iterator it = testSuite.getITestCases().iterator();
151
		while (it.hasNext()) {
326
		while (it.hasNext()) {
Lines 155-184 Link Here
155
		}
330
		}
156
	}
331
	}
157
	
332
	
158
	public IFile getFileHandle(ITestSuite testSuite)
333
	public IFile getFileHandle(ITestSuite ts) {
159
	{
334
		IContainer sourceContainer = getSourceContainerHandle(ts);
160
		IContainer sourceContainer = getSourceContainerHandle(testSuite);
335
		return sourceContainer.getFile(new Path(ts.getImplementor().getResource().replace('.','/') + ".java")); //$NON-NLS-1$
161
		return sourceContainer.getFile(new Path(testSuite.getImplementor().getResource().replace('.','/') + ".java")); //$NON-NLS-1$
162
	}
336
	}
163
			
337
			
164
	protected void adjustSourceContainer(IContainer sourceContainer, String packageName, IProgressMonitor monitor)
165
	throws Exception
166
	{
167
		IJavaProject javaProject = JavaCore.create(sourceContainer.getProject());
168
		if(sourceContainer.getType() == IResource.FOLDER)
169
		{
170
			if(!javaProject.isOnClasspath(sourceContainer))
171
			{
172
				IClasspathEntry entry = JavaCore.newSourceEntry(sourceContainer.getFullPath());
173
				List entries = new ArrayList(Arrays.asList(javaProject.getRawClasspath()));
174
				entries.add(1, entry);
175
				javaProject.setRawClasspath((IClasspathEntry[])entries.toArray(new IClasspathEntry[entries.size()]), monitor);
176
			}
177
		}
178
		
179
		javaProject.getPackageFragmentRoot(sourceContainer).createPackageFragment(packageName, true, monitor);
180
	}
181
	
182
	protected static Collection getDependentProjects(ITestSuite testSuite, IProject project)
338
	protected static Collection getDependentProjects(ITestSuite testSuite, IProject project)
183
	{
339
	{
184
		if((testSuite.getIReferencedSuites() == null) || (testSuite.getIReferencedSuites().isEmpty()))
340
		if((testSuite.getIReferencedSuites() == null) || (testSuite.getIReferencedSuites().isEmpty()))
Lines 203-210 Link Here
203
		return entries;
359
		return entries;
204
	}
360
	}
205
361
206
	public IProjectDependencyUpdater getProjectDependencyUpdater() {
207
		return projectDependencyUpdater;
208
	}
209
	
210
}
362
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/Helper.java (+145 lines)
Lines 26-36 Link Here
26
import org.eclipse.hyades.test.core.util.EMFUtil;
26
import org.eclipse.hyades.test.core.util.EMFUtil;
27
import org.eclipse.hyades.test.core.util.JavaUtil;
27
import org.eclipse.hyades.test.core.util.JavaUtil;
28
import org.eclipse.hyades.test.tools.core.CorePlugin;
28
import org.eclipse.hyades.test.tools.core.CorePlugin;
29
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.CompilationUnitChange;
30
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.DeleteFileChange;
31
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.MoveCompilationUnitChange;
32
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.ProjectAdjustChange;
29
import org.eclipse.jdt.core.ICompilationUnit;
33
import org.eclipse.jdt.core.ICompilationUnit;
30
import org.eclipse.jdt.core.JavaModelException;
34
import org.eclipse.jdt.core.JavaModelException;
31
import org.eclipse.jdt.core.ToolFactory;
35
import org.eclipse.jdt.core.ToolFactory;
36
import org.eclipse.jdt.core.dom.CompilationUnit;
37
import org.eclipse.jdt.core.dom.ImportDeclaration;
32
import org.eclipse.jdt.core.formatter.CodeFormatter;
38
import org.eclipse.jdt.core.formatter.CodeFormatter;
33
import org.eclipse.jface.text.Document;
39
import org.eclipse.jface.text.Document;
40
import org.eclipse.ltk.core.refactoring.Change;
41
import org.eclipse.ltk.core.refactoring.CompositeChange;
34
import org.eclipse.text.edits.TextEdit;
42
import org.eclipse.text.edits.TextEdit;
35
43
36
/**
44
/**
Lines 353-358 Link Here
353
			cu.createImport(importName, /*sibling*/null, /*progressMonitor*/null);
361
			cu.createImport(importName, /*sibling*/null, /*progressMonitor*/null);
354
		}
362
		}
355
	}
363
	}
364
	
365
	public void emitSortedImports(CompilationUnit cu) {
366
		Iterator it = importManager.getImports().iterator();
367
		while (it.hasNext()) {
368
			String importName = (String) it.next();
369
			if (!ASTHelper.hasImport(cu, importName)) {
370
				ImportDeclaration id = cu.getAST().newImportDeclaration();
371
				id.setName(cu.getAST().newName(importName));
372
				cu.imports().add(id);
373
			}
374
		}
375
		// TODO Remove unused imports
376
	}
356
377
357
	public String getImportedName(String qualifiedName)
378
	public String getImportedName(String qualifiedName)
358
	{
379
	{
Lines 424-427 Link Here
424
	public String getSuperclassName() {
445
	public String getSuperclassName() {
425
		return superClassName;
446
		return superClassName;
426
	}
447
	}
448
	
449
	/**
450
	 * Compares two strings appearing within a java comment/javadoc comment and return true
451
	 * if they contain the same strings, ignoring differences such as line breaks, tabs and
452
	 * space indentation.
453
	 * @param comment1
454
	 * @param comment2
455
	 * @return
456
	 */
457
	public static boolean compareJavaComments(CharSequence comment1, String comment2) {
458
		// Compare character by character, ignoring separating characters
459
		final String separators = "\n\r\t "; //$NON-NLS-1$
460
		StringIterator i1 = new StringIterator(comment1, separators);
461
		StringIterator i2 = new StringIterator(comment2, separators);
462
		while(i1.hasNextCharacter() && i2.hasNextCharacter()) {
463
			if (i1.getNextCharacter() != i2.getNextCharacter()) return false;
464
		}
465
		return !i1.hasNextCharacter() && !i2.hasNextCharacter();
466
	}
467
	
468
	/**
469
	 * String iterator that iterates character by character through a string. It has
470
	 * the ability to group a certain class of characters, replacing a sequence of one or 
471
	 * more of such characters by a single space. 
472
	 * @author jcanches
473
	 */
474
	public static class StringIterator {
475
		private int currentIndex;
476
		private int length;
477
		private CharSequence string;
478
		private String spaceCharacters;
479
		private boolean issueSpace;
480
		public StringIterator(CharSequence string, String spaceCharacters) {
481
			this.string = string;
482
			this.length = string.length();
483
			this.spaceCharacters = spaceCharacters;
484
			this.currentIndex = 0;
485
			this.issueSpace = false;
486
			skipIgnoredCharacters();
487
		}
488
		private void skipIgnoredCharacters() {
489
			while (currentIndex < length
490
				   && spaceCharacters.indexOf(string.charAt(currentIndex)) != -1) {
491
				issueSpace = true;
492
				currentIndex++;
493
			}
494
		}
495
		public boolean hasNextCharacter() {
496
			return issueSpace || currentIndex < length;
497
		}
498
		public char getNextCharacter() {
499
			if (issueSpace) {
500
				issueSpace = false;
501
				return ' ';
502
			}
503
			char ret = string.charAt(currentIndex++);
504
			skipIgnoredCharacters();
505
			return ret;
506
		}
507
	}
508
509
	public static class LineIterator {
510
		private final static String lineDelimiters = "\n\r"; //$NON-NLS-1$
511
		private StringIterator iterator;
512
		private String nextLine;
513
		public LineIterator(CharSequence string, String spaceCharacters) {
514
			this.iterator = new StringIterator(string, spaceCharacters);
515
			computeNextLine();
516
		}
517
		public boolean hasNextLine() {
518
			return nextLine != null;
519
		}
520
		public String getNextLine() {
521
			String ret = nextLine;
522
			computeNextLine();
523
			return ret;
524
		}
525
		private void computeNextLine() {
526
			StringBuffer line = new StringBuffer();
527
			boolean lineBegins = true;
528
			while (iterator.hasNextCharacter()) {
529
				char c = iterator.getNextCharacter();
530
				if (lineBegins) {
531
					if (c == ' ' || lineDelimiters.indexOf(c) != -1) {
532
						continue;
533
					}
534
					lineBegins = false;
535
				}
536
				if (lineDelimiters.indexOf(c) == -1) {
537
					line.append(c);
538
				} else {
539
					break;
540
				}
541
			}
542
			nextLine = line.toString().trim();
543
			if (nextLine.length() == 0) nextLine = null;
544
		}
545
	}
546
	
547
	public static boolean isDestructiveChange(Change change) {
548
		if (change instanceof ProjectAdjustChange) {
549
			return true;
550
		}
551
		if (change instanceof CompilationUnitChange) {
552
			return ((CompilationUnitChange)change).isDestructive();
553
		}
554
		if (change instanceof MoveCompilationUnitChange) {
555
			return true;
556
		}
557
		if (change instanceof DeleteFileChange) {
558
			return true;
559
		}
560
		if (change instanceof CompositeChange) {
561
			CompositeChange cchange = (CompositeChange)change;
562
			Change[] children = cchange.getChildren();
563
			for (int i = 0; i < children.length; i++) {
564
				Change c = children[i];
565
				if (isDestructiveChange(c)) return true;
566
			}
567
			return false;
568
		}
569
		return false;
570
	}
571
427
}
572
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/IProjectDependencyUpdater.java (-3 / +15 lines)
Lines 12-26 Link Here
12
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen;
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen;
14
14
15
import java.util.Collection;
16
15
import org.eclipse.core.resources.IProject;
17
import org.eclipse.core.resources.IProject;
16
import org.eclipse.core.runtime.CoreException;
18
import org.eclipse.core.runtime.CoreException;
17
import org.eclipse.core.runtime.IProgressMonitor;
19
import org.eclipse.core.runtime.IProgressMonitor;
18
20
19
/**
21
/**
20
 * Updates a project dependencies (usually for the purpose of updating the classpath
22
 * Updates a project dependencies (usually for the purpose of updating the classpath
21
 * available to this project).
23
 * available to this project). Implementations should not perform any modification until
24
 * {@link #adjustProject(IProject, IProgressMonitor)} is called.
22
 * @author jcanches
25
 * @author jcanches
23
 *
26
 * @since 4.2
24
 */
27
 */
25
public interface IProjectDependencyUpdater {
28
public interface IProjectDependencyUpdater {
26
29
Lines 28-34 Link Here
28
	 * Add to the project dependencies the specified plugin.
31
	 * Add to the project dependencies the specified plugin.
29
	 * @param pluginName The name of the required plugin.
32
	 * @param pluginName The name of the required plugin.
30
	 * @param jarName An optional jar name. This parameter may be used as a hint
33
	 * @param jarName An optional jar name. This parameter may be used as a hint
31
	 * by some implementations. <code>null</code> means that the complete
34
	 * by some implementations. <code>null</code> is valid and means that the complete
32
	 * libraries of the specified plugin should be taken into account.
35
	 * libraries of the specified plugin should be taken into account.
33
	 */
36
	 */
34
	void addRequiredPlugin(String pluginId, String jarName);
37
	void addRequiredPlugin(String pluginId, String jarName);
Lines 47-50 Link Here
47
	 */
50
	 */
48
	void adjustProject(IProject project, IProgressMonitor monitor) throws CoreException;
51
	void adjustProject(IProject project, IProgressMonitor monitor) throws CoreException;
49
	
52
	
53
	/**
54
	 * Determines which changes the call to adjustProject would make.
55
	 * @param project
56
	 * @return A collection of strings indicating the dependencies that need to be added to
57
	 * the project. An empty list indicates that the project is already up-to-date
58
	 * and does not need adjusting.
59
	 */
60
	Collection previewAdjustProject(IProject project);
61
	
50
}
62
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/JavaProjectDependencyUpdater.java (-14 / +58 lines)
Lines 18-45 Link Here
18
import java.util.ArrayList;
18
import java.util.ArrayList;
19
import java.util.Arrays;
19
import java.util.Arrays;
20
import java.util.Collection;
20
import java.util.Collection;
21
import java.util.Collections;
21
import java.util.HashSet;
22
import java.util.HashSet;
22
import java.util.Iterator;
23
import java.util.Iterator;
23
import java.util.List;
24
import java.util.List;
24
import java.util.Set;
25
25
26
import org.eclipse.core.resources.IProject;
26
import org.eclipse.core.resources.IProject;
27
import org.eclipse.core.resources.ResourcesPlugin;
27
import org.eclipse.core.runtime.FileLocator;
28
import org.eclipse.core.runtime.ILibrary;
29
import org.eclipse.core.runtime.IPath;
28
import org.eclipse.core.runtime.IPath;
30
import org.eclipse.core.runtime.IProgressMonitor;
29
import org.eclipse.core.runtime.IProgressMonitor;
31
import org.eclipse.core.runtime.Path;
30
import org.eclipse.core.runtime.Path;
32
import org.eclipse.core.runtime.Platform;
31
import org.eclipse.core.runtime.Platform;
33
import org.eclipse.core.runtime.Plugin;
32
import org.eclipse.core.runtime.Plugin;
34
import org.eclipse.emf.common.util.URI;
33
import org.eclipse.emf.common.util.URI;
35
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
36
import org.eclipse.hyades.models.common.util.IDisposable;
34
import org.eclipse.hyades.models.common.util.IDisposable;
37
import org.eclipse.hyades.test.tools.core.CorePlugin;
35
import org.eclipse.hyades.test.tools.core.CorePlugin;
38
import org.eclipse.jdt.core.IClasspathEntry;
36
import org.eclipse.jdt.core.IClasspathEntry;
39
import org.eclipse.jdt.core.IJavaProject;
37
import org.eclipse.jdt.core.IJavaProject;
40
import org.eclipse.jdt.core.JavaCore;
38
import org.eclipse.jdt.core.JavaCore;
41
import org.eclipse.jdt.core.JavaModelException;
39
import org.eclipse.jdt.core.JavaModelException;
40
import org.eclipse.osgi.util.ManifestElement;
42
import org.osgi.framework.Bundle;
41
import org.osgi.framework.Bundle;
42
import org.osgi.framework.BundleException;
43
import org.osgi.framework.Constants;
43
44
44
public class JavaProjectDependencyUpdater implements IProjectDependencyUpdater, IDisposable {
45
public class JavaProjectDependencyUpdater implements IProjectDependencyUpdater, IDisposable {
45
46
Lines 171-186 Link Here
171
		if(pluginId == null)
172
		if(pluginId == null)
172
			return new String[0];
173
			return new String[0];
173
174
174
		Plugin plugin = Platform.getPlugin(pluginId);
175
		Bundle bundle = Platform.getBundle(pluginId);
175
176
176
		ILibrary[] pluginLibraries = plugin.getDescriptor().getRuntimeLibraries();
177
		Plugin plugin;
177
		List libraries = new ArrayList(pluginLibraries.length);
178
		String requires = (String)bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH);
178
		for(int i = 0, maxi = pluginLibraries.length; i < maxi; i++)
179
		try {
179
		{
180
			ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_CLASSPATH, requires);
180
			String variablePluginLibrary = getVariablePluginLibrary(pluginId, pluginLibraries[i].getPath().toString());
181
			List libraries = new ArrayList(elements.length);
181
			libraries.add(variablePluginLibrary);
182
			for(int i = 0, maxi = elements.length; i < maxi; i++) {
183
				String variablePluginLibrary = getVariablePluginLibrary(pluginId, elements[i].getValue());
184
				libraries.add(variablePluginLibrary);
185
			}
186
			return (String[])libraries.toArray(new String[libraries.size()]);
187
		} catch (BundleException e) {
188
			CorePlugin.logError(e);
189
			return new String[0];
182
		}
190
		}
183
		return (String[])libraries.toArray(new String[libraries.size()]);
184
	}
191
	}
185
	
192
	
186
	protected static String getVariablePluginLibrary(String pluginId, String library)
193
	protected static String getVariablePluginLibrary(String pluginId, String library)
Lines 193-199 Link Here
193
			return ""; //$NON-NLS-1$
200
			return ""; //$NON-NLS-1$
194
201
195
		try {
202
		try {
196
			URL url = Platform.resolve(bundle.getEntry("")); //$NON-NLS-1$
203
			URL url = FileLocator.resolve(bundle.getEntry("")); //$NON-NLS-1$
197
			IPath pluginPath = new Path(url.getFile());
204
			IPath pluginPath = new Path(url.getFile());
198
			if (url.getProtocol().equals("jar"))  //jar in the plugin root //$NON-NLS-1$
205
			if (url.getProtocol().equals("jar"))  //jar in the plugin root //$NON-NLS-1$
199
			{
206
			{
Lines 208-214 Link Here
208
			
215
			
209
			IPath eclipseHomePath = JavaCore.getClasspathVariable(ECLIPSE_HOME);
216
			IPath eclipseHomePath = JavaCore.getClasspathVariable(ECLIPSE_HOME);
210
			
217
			
211
			
212
			// On Windows, sometimes the case of the device for the plugin does
218
			// On Windows, sometimes the case of the device for the plugin does
213
			// not match the case of the device for the eclipseHomePath.
219
			// not match the case of the device for the eclipseHomePath.
214
			// This would never happen on *nix, because it the cases were different,
220
			// This would never happen on *nix, because it the cases were different,
Lines 257-260 Link Here
257
263
258
	}
264
	}
259
265
266
	public Collection previewAdjustProject(IProject project) {
267
		if((requiredLibraries == null || requiredLibraries.isEmpty())
268
				&& (requiredProjects == null || requiredProjects.isEmpty())) return Collections.EMPTY_SET;
269
				
270
			IJavaProject javaProject = JavaCore.create(project);
271
			IClasspathEntry[] resolvedClasspath;
272
			List additionalClasspathEntries = new ArrayList();
273
			try {
274
				resolvedClasspath = javaProject.getResolvedClasspath(/*ignoreUnresolvedEntries*/true);
275
			} catch (JavaModelException e) {
276
				CorePlugin.logError(e);
277
				return Collections.EMPTY_SET;
278
			}
279
			
280
			HashSet result = new HashSet();
281
			
282
			if (requiredLibraries != null) {
283
				for (Iterator it = requiredLibraries.iterator(); it.hasNext();) {
284
					IClasspathEntry entry = getLibrariesEntry((String)it.next());
285
					if (!classpathContains(resolvedClasspath, entry)) {
286
						result.add(entry.getPath().toString());
287
					}
288
				}
289
			}
290
			
291
			if (requiredProjects != null) {
292
				for(Iterator it = requiredProjects.iterator(); it.hasNext();) {
293
					IProject dproject = (IProject)it.next();
294
					IClasspathEntry entry = getProjectEntry(dproject);
295
					if(!classpathContains(resolvedClasspath, entry)) {
296
						result.add(dproject.getName());
297
					}
298
				}
299
			}
300
			
301
			return result;
302
	}
303
260
}
304
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/Generator.java (-61 / +261 lines)
Lines 15-113 Link Here
15
import org.eclipse.core.resources.IFile;
15
import org.eclipse.core.resources.IFile;
16
import org.eclipse.core.resources.IProject;
16
import org.eclipse.core.resources.IProject;
17
import org.eclipse.core.resources.ResourcesPlugin;
17
import org.eclipse.core.resources.ResourcesPlugin;
18
import org.eclipse.core.runtime.CoreException;
18
import org.eclipse.core.runtime.IPath;
19
import org.eclipse.core.runtime.IPath;
19
import org.eclipse.core.runtime.IProgressMonitor;
20
import org.eclipse.core.runtime.IProgressMonitor;
20
import org.eclipse.core.runtime.IStatus;
21
import org.eclipse.core.runtime.OperationCanceledException;
21
import org.eclipse.core.runtime.Path;
22
import org.eclipse.core.runtime.Path;
22
import org.eclipse.core.runtime.Status;
23
import org.eclipse.core.runtime.SubProgressMonitor;
24
import org.eclipse.emf.common.util.URI;
25
import org.eclipse.emf.ecore.EObject;
26
import org.eclipse.emf.ecore.resource.Resource;
27
import org.eclipse.emf.ecore.resource.ResourceSet;
28
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
29
import org.eclipse.emf.ecore.util.EcoreUtil;
23
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
30
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
24
import org.eclipse.hyades.models.common.util.ResourceUtil;
31
import org.eclipse.hyades.models.common.testprofile.TPFTestSuite;
25
import org.eclipse.hyades.test.tools.core.CorePlugin;
26
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
32
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
33
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.CreateContainerChange;
34
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.CreateFileChange;
35
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.DeleteFileChange;
36
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.PotentialChange;
37
import org.eclipse.ltk.core.refactoring.Change;
38
import org.eclipse.ltk.core.refactoring.CompositeChange;
39
import org.eclipse.ltk.core.refactoring.NullChange;
40
import org.eclipse.ltk.core.refactoring.Refactoring;
41
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
27
import org.eclipse.osgi.util.NLS;
42
import org.eclipse.osgi.util.NLS;
28
43
29
/**
44
/**
30
 * @author marcelop
45
 * Abstract code generator / code updater.<br>
46
 * <p>The typical use of the generator to generate the code for a test suite is:
47
 * <pre>
48
 * Generator generator = new Generator(testSuite);
49
 * if (generator.checkAllConditions(new SubProgressMonitor(pm, 1)).isOk()) {
50
 *   Change change = generator.createChange(new SubProgressMonitor(pm, 1));
51
 *   change.perform(new SubProgressMonitor(pm, 1));
52
 * }
53
 * </pre>
54
 * Since this class implements Refactoring, it can also be used in the context of a refactor
55
 * wizard (see {@link org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation}).</p>
56
 * <p>As of release 4.3, the Generator class has been completely redesigned, and now extends
57
 * the Refactoring framework provided by Eclipse SDK. This allows the user to preview
58
 * the changes implied by code generation/code update, and also to revert these changes.</p>
59
 * <p>This class is abstract. Sub-classes must provide {@link #generateCode(IProgressMonitor)}.
60
 * Optionally, if specific actions are needed before and/or after code generation, they can
61
 * extend {@link #createPreCodegenerationChange(IProgressMonitor)} and
62
 * {@link #createPostCodegenerationChange(IProgressMonitor)}.
63
 * If code update is desired they must override {@link #createUpdateChange(IFile, IProgressMonitor)}.
64
 * If additional checkings are needed, sub-classes may extend {@link #checkInitialConditions(IProgressMonitor)},
65
 * {@link #checkFinalConditions(IProgressMonitor)} and {@link #checkAllConditions(IProgressMonitor)}.
66
 * </p>
67
 * <p>The location and name of the generated file may be customized by overriding the methods
68
 * {@link #getFileHandle(ITestSuite)} and {@link #getSourceContainerHandle(ITestSuite)}.</p>
69
 * <p>A couple of helper methods are available to sub-classes: to manipulate Changes, see 
70
 * {@link #addPotentialChange(Change, CompositeChange)} and {@link #packCompositeChange(CompositeChange)}.</p>
71
 * <p>The package {@link org.eclipse.hyades.test.tools.core.internal.common.codegen.changes} provides a
72
 * library of pre-defined Changes for achieving various actions related to code-generation.</p>
73
 * <p>For classes that generate java code, consider extending {@link JavaGenerator}.</p>
74
 * @author marcelop, jcanches
31
 * @since 1.0.1
75
 * @since 1.0.1
32
 */
76
 */
33
abstract public class Generator
77
abstract public class Generator extends Refactoring
34
{
78
{
35
	public static final String CHARSET_UTF8 = "UTF-8"; //$NON-NLS-1$
79
	public static final String CHARSET_UTF8 = "UTF-8"; //$NON-NLS-1$
36
	
80
	
81
	private ITestSuite testSuite;
82
	private ITestSuite cachedRepositoryTestSuite;
83
	private boolean cachedRepositoryComputed = false;
84
	
37
	/**
85
	/**
38
	 * Generates the code for the specified test suite, creating all the required
86
	 * Instantiates a generator for the specified test suite.
39
	 * folders, packages and adjusting the project's classpath.
40
	 * 
41
	 * <p>The location of the test suite's implementor must be equals to the source
42
	 * container (ie, project and source folder).  The implementor's resource must
43
	 * be equals to the full class name (ie, package and class name).
44
	 *  
45
	 * @param testSuite
87
	 * @param testSuite
46
	 * @param monitor
47
	 * @throws Exception
48
	 */
88
	 */
49
	public void generate(ITestSuite testSuite, IProgressMonitor monitor) throws Exception
89
	protected Generator(ITestSuite testSuite) {
50
	{
90
		this.testSuite = testSuite;
91
	}
92
	
93
	/**
94
	 * Returns the test suite for which this generator is generating or updating code.
95
	 * @return
96
	 */
97
	final public ITestSuite getTestSuite() {
98
		return testSuite;
99
	}
100
	
101
	/**
102
	 * Returns the test suite as it is currently persisted on disk. This allows
103
	 * to compare models before and after modification.
104
	 * @return A test suite model, or <code>null</code> if the test suite model is
105
	 * new and has never been persisted.
106
	 */
107
	final protected ITestSuite getRepositoryTestSuite() {
108
		if (!cachedRepositoryComputed) {
109
			TPFTestSuite ts = (TPFTestSuite)getTestSuite();
110
			Resource res = ts.eResource();
111
			if (res != null) {
112
				URI uri = EcoreUtil.getURI(ts);
113
				ResourceSet rs = new ResourceSetImpl();
114
				try {
115
					EObject object = rs.getEObject(uri, /*loadOnDemand*/true);
116
					if (object != null && object instanceof ITestSuite) {
117
						cachedRepositoryTestSuite = (ITestSuite)object;
118
					}
119
				} catch (Throwable t) {
120
					// In 99% this is because the resource does not exist.
121
					cachedRepositoryTestSuite = null;
122
				}
123
			}
124
			cachedRepositoryComputed = true;
125
		}
126
		return cachedRepositoryTestSuite;
127
	}
128
	
129
	/**
130
	 * Add a change to a composite change, if this change has a real effect.
131
	 * A change is considered to have an effect if it not <code>null</code>, if it is not
132
	 * an instance of {@link NullChange}, and if it is not an instance of {@link PotentialChange},
133
	 * unless this potential change reports to be required.
134
	 * @param change A change or <code>null</code>.
135
	 * @param composite The composite change that will receive the change if necessary.
136
	 */
137
	protected final void addPotentialChange(Change change, CompositeChange composite) {
138
		if (change != null) {
139
			if (change instanceof NullChange) return;
140
			if (change instanceof PotentialChange && !((PotentialChange)change).hasEffect()) return;
141
			composite.add(change);
142
		}
143
	}
144
	
145
	/**
146
	 * Pack a composite change. If the composite change
147
	 * has zero children, a {@link NullChange} is returned. Otherwise, the composite itself is
148
	 * returned.
149
	 * @param change
150
	 * @return
151
	 */
152
	protected final Change packCompositeChange(CompositeChange change) {
153
		if (change.getChildren().length > 0) return change;
154
		return new NullChange();
155
	}
156
	
157
	/**
158
	 * This implementation always return a OK status.
159
	 */
160
	public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
161
		pm.beginTask("", 1); //$NON-NLS-1$
162
		try {
163
			return new RefactoringStatus();
164
		} finally {
165
			pm.done();
166
		}
167
	}
168
169
	/**
170
	 * This implementation checks existence of the source container, and the accessibility of its project.
171
	 */
172
	public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
173
		pm.beginTask("", 2); //$NON-NLS-1$
174
		try {
175
			RefactoringStatus status = new RefactoringStatus();
176
			IContainer container = getSourceContainerHandle(testSuite);
177
			pm.worked(1);
178
			if (container == null) {
179
				status.addError(CommonPluginMessages.E_CODEGEN_NO_SRCFOLDER);
180
			} else {
181
				IProject project = container.getProject();
182
				if (project.exists() && !project.isOpen()) {
183
					status.addError(NLS.bind(CommonPluginMessages.E_CODEGEN_CLOSED_PROJECT, container.getFullPath().toString()));
184
				}
185
				pm.worked(1);
186
			}
187
			return status;
188
		} finally {
189
			pm.done();
190
		}
191
	}
192
193
	final public Change createChange(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
194
		Change change = null;
51
		IFile file = getFileHandle(testSuite);
195
		IFile file = getFileHandle(testSuite);
52
		IContainer sourceContainer = getSourceContainerHandle(testSuite);
196
		ITestSuite previous = getRepositoryTestSuite();
53
		
197
		if (previous != null) {
54
		boolean mustGenerate = true;
198
			file = getFileHandle(previous);
55
		if(file.exists()) {
199
		}
200
		if(file != null && file.exists()) {
56
			try {
201
			try {
57
				doUpdateFile(testSuite, sourceContainer, file, monitor);
202
				change = createUpdateChange(file, monitor);
58
				mustGenerate = false;
59
			} catch (UnsupportedOperationException e) {
203
			} catch (UnsupportedOperationException e) {
60
				file.delete(/*force*/true, null);
204
				//Fall back to code generation.
61
			}
205
			}
62
		}
206
		}
63
		
207
		if (change == null) {
64
		if (mustGenerate) {
208
			change = createGenerateChange(monitor);
65
			ResourceUtil.createContainer(sourceContainer, monitor);
209
		}
66
			doGenerateFile(testSuite, sourceContainer, file, monitor);
210
		return change;
211
	}
212
213
	public String getName() {
214
		return CommonPluginMessages.GENERIC_GENERATOR;
215
	}
216
217
	private Change createGenerateChange(IProgressMonitor monitor) throws CoreException {
218
		monitor.beginTask("", 6); //$NON-NLS-1$
219
		try {
220
			CompositeChange change = new CompositeChange(CommonPluginMessages.GENERATE_CODE);
221
			Change subChange = createPreCodegenerationChange(new SubProgressMonitor(monitor, 1));
222
			if (subChange != null) {
223
				change.add(subChange);
224
			}
225
			IFile file = getFileHandle(testSuite);
226
			if (file.exists()) {
227
				change.add(new DeleteFileChange(file));
228
			}
229
			monitor.worked(1);
230
			String code = generateCode(monitor);
231
			change.add(new CreateFileChange(file, code, CHARSET_UTF8));
232
			monitor.worked(3);
233
			subChange = createPostCodegenerationChange(new SubProgressMonitor(monitor, 1));
234
			if (subChange != null) {
235
				change.add(subChange);
236
			}
237
			return change;
238
		} finally {
239
			monitor.done();
67
		}
240
		}
68
	}
241
	}
69
	
242
	
70
	/**
243
	/**
71
	 * Validates whether code can be generated for the specified test suite.
244
	 * This implementation creates the source container, if it does not exist.
72
	 * The returned status may be either IStatus.OK, IStatus.WARNING or IStatus.ERROR.
245
	 * @param monitor
73
	 * In the two latter cases, a message describes the reason(s) why code cannot
74
	 * be generated. This method should typically be called prior to invoking
75
	 * generate(). generate() would typically throw an exception if this method returns
76
	 * an error status.
77
	 * @param testSuite
78
	 * @return
246
	 * @return
247
	 * @throws CoreException
79
	 */
248
	 */
80
	public IStatus validate(ITestSuite testSuite) {
249
	protected Change createPreCodegenerationChange(IProgressMonitor monitor) throws CoreException {
81
		IContainer container = getSourceContainerHandle(testSuite);
250
		monitor.beginTask("", 1); //$NON-NLS-1$
82
		if (container == null) {
251
		try {
83
			return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, 0, CommonPluginMessages.E_CODEGEN_NO_SRCFOLDER, null);
252
			IContainer sourceContainer = getSourceContainerHandle(testSuite);
84
		}
253
			if (!sourceContainer.exists()) {
85
		IProject project = container.getProject();
254
				return new CreateContainerChange(sourceContainer);
86
		if (project.exists() && !project.isOpen()) {
255
			}
87
			return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, 0, NLS.bind(CommonPluginMessages.E_CODEGEN_CLOSED_PROJECT, container.getFullPath().toString()), null);
256
			return new NullChange();
257
		} finally {
258
			monitor.done();
88
		}
259
		}
89
		return Status.OK_STATUS;
90
	}
260
	}
91
	
261
	
92
	protected void doGenerateFile(ITestSuite testSuite, IContainer sourceContainer, IFile file, IProgressMonitor monitor) throws Exception
262
	/**
93
	{
263
	 * This implementation does nothing.
94
		generateFile(testSuite, file, monitor);
264
	 * @param monitor
265
	 * @return
266
	 * @throws CoreException
267
	 */
268
	protected Change createPostCodegenerationChange(IProgressMonitor monitor) throws CoreException {
269
		monitor.beginTask("", 1); //$NON-NLS-1$
270
		try {
271
			return new NullChange();
272
		} finally {
273
			monitor.done();
274
		}
95
	}
275
	}
96
	
276
	
97
	protected void doUpdateFile(ITestSuite testSuite, IContainer sourceContainer, IFile file, IProgressMonitor monitor) throws Exception {
277
	/**
98
		updateFile(testSuite, file, monitor);		
278
	 * Creates the change that describes the update of the specified file.
279
	 * <p>This implementation throws a {@link UnsupportedOperationException}. If code update
280
	 * is desired, the sub-class must override this implementation.</p>
281
	 * @param file The file to update
282
	 * @param monitor A progress monitor
283
	 * @return A change describing the update.
284
	 * @throws CoreException if the update creation failed, UnsupportedOperationException if code
285
	 * update is not supported.
286
	 */
287
	protected Change createUpdateChange(IFile file, IProgressMonitor monitor) throws CoreException, UnsupportedOperationException {
288
		throw new UnsupportedOperationException();
99
	}
289
	}
100
		
290
		
101
	public IFile getFileHandle(ITestSuite testSuite)
291
	/**
102
	{
292
	 * Returns the generated file. This is handle-only method, i.e. the returned file is
103
		IContainer sourceContainer = getSourceContainerHandle(testSuite);
293
	 * not required to exist. 
104
		return sourceContainer.getFile(new Path(testSuite.getImplementor().getResource()));
294
	 * @return The generated file.
295
	 */
296
	public IFile getFileHandle(ITestSuite ts) {
297
		IContainer sourceContainer = getSourceContainerHandle(ts);
298
		return sourceContainer.getFile(new Path(ts.getImplementor().getResource()));
105
	}
299
	}
106
	
300
	
107
	protected IContainer getSourceContainerHandle(ITestSuite testSuite)
301
	/**
108
	{
302
	 * Returns the container that will receive the generated file.
303
	 * @return
304
	 */
305
	final protected IContainer getSourceContainerHandle(ITestSuite ts) {
109
		IContainer container = null;
306
		IContainer container = null;
110
		String location = testSuite.getImplementor().getLocation();
307
		String location = ts.getImplementor().getLocation();
111
		if (location != null) {
308
		if (location != null) {
112
			IPath path = new Path(location);
309
			IPath path = new Path(location);
113
			if(path.segmentCount() == 1) {
310
			if(path.segmentCount() == 1) {
Lines 119-128 Link Here
119
		return container;
316
		return container;
120
	}
317
	}
121
	
318
	
122
	abstract protected void generateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor) throws Exception;
319
	/**
123
	
320
	 * Generates the code for the test suite. The code will be placed in the file returned
124
	protected void updateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor) throws Exception {
321
	 * by {@link #getFileHandle()}.
125
		throw new UnsupportedOperationException();
322
	 * @param monitor A progress monitor
126
	}
323
	 * @return Source code.
324
	 * @throws CoreException
325
	 */
326
	abstract protected String generateCode(IProgressMonitor monitor) throws CoreException;
127
	
327
	
128
}
328
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/AutomaticDependencyUpdater.java (-2 / +14 lines)
Lines 13-18 Link Here
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen;
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen;
14
14
15
import java.util.Collection;
15
import java.util.Collection;
16
import java.util.Collections;
16
import java.util.HashSet;
17
import java.util.HashSet;
17
import java.util.Iterator;
18
import java.util.Iterator;
18
19
Lines 52-59 Link Here
52
		requiredProjects.add(project);
53
		requiredProjects.add(project);
53
	}
54
	}
54
55
55
	public void adjustProject(IProject project, IProgressMonitor monitor) throws CoreException {
56
	private IProjectDependencyUpdater createDelegate(IProject project) {
56
		if (requiredPluginJars == null && requiredProjects == null) return;
57
		IProjectDependencyUpdater delegate;
57
		IProjectDependencyUpdater delegate;
58
		if (PDEProjectUtil.isStrictPluginProject(project)) {
58
		if (PDEProjectUtil.isStrictPluginProject(project)) {
59
			delegate = new PluginProjectDependencyUpdater();
59
			delegate = new PluginProjectDependencyUpdater();
Lines 71-77 Link Here
71
				delegate.addRequiredProject((IProject)it.next());
71
				delegate.addRequiredProject((IProject)it.next());
72
			}
72
			}
73
		}
73
		}
74
		return delegate;
75
	}
76
	
77
	public void adjustProject(IProject project, IProgressMonitor monitor) throws CoreException {
78
		if (requiredPluginJars == null && requiredProjects == null) return;
79
		IProjectDependencyUpdater delegate = createDelegate(project);
74
		delegate.adjustProject(project, monitor);
80
		delegate.adjustProject(project, monitor);
75
	}
81
	}
76
82
83
	public Collection previewAdjustProject(IProject project) {
84
		if (requiredPluginJars == null && requiredProjects == null) return Collections.EMPTY_SET;
85
		IProjectDependencyUpdater delegate = createDelegate(project);
86
		return delegate.previewAdjustProject(project);
87
	}
88
77
}
89
}
(-)src/org/eclipse/hyades/test/tools/core/internal/java/codegen/GenTestSuiteConstructor.java (-1 / +1 lines)
Lines 4-10 Link Here
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: GenTestSuiteConstructor.java,v 1.2 2006/07/29 01:57:42 sschneid Exp $
7
 * $Id$
8
 * 
8
 * 
9
 * Contributors: 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
10
 * IBM Corporation - initial API and implementation
(-)src/org/eclipse/hyades/test/tools/core/internal/java/codegen/GenSuiteMethod.java (-1 / +1 lines)
Lines 4-10 Link Here
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: GenSuiteMethod.java,v 1.10 2006/07/29 21:36:45 sschneid Exp $
7
 * $Id$
8
 * 
8
 * 
9
 * Contributors: 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
10
 * IBM Corporation - initial API and implementation
(-)src/org/eclipse/hyades/test/tools/core/internal/java/codegen/JUnitGenerator.java (-111 / +241 lines)
Lines 11-124 Link Here
11
 **********************************************************************/
11
 **********************************************************************/
12
package org.eclipse.hyades.test.tools.core.internal.java.codegen;
12
package org.eclipse.hyades.test.tools.core.internal.java.codegen;
13
13
14
import java.io.ByteArrayInputStream;
15
import java.util.ArrayList;
14
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.Iterator;
15
import java.util.Iterator;
18
import java.util.List;
16
import java.util.List;
19
17
20
import org.eclipse.core.resources.IFile;
18
import org.eclipse.core.resources.IFile;
19
import org.eclipse.core.runtime.CoreException;
21
import org.eclipse.core.runtime.IProgressMonitor;
20
import org.eclipse.core.runtime.IProgressMonitor;
22
import org.eclipse.core.runtime.NullProgressMonitor;
23
import org.eclipse.core.runtime.SubProgressMonitor;
21
import org.eclipse.core.runtime.SubProgressMonitor;
24
import org.eclipse.emf.ecore.EObject;
25
import org.eclipse.hyades.models.common.facades.behavioral.ITestCase;
22
import org.eclipse.hyades.models.common.facades.behavioral.ITestCase;
26
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
23
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
27
import org.eclipse.hyades.test.core.util.EMFUtil;
28
import org.eclipse.hyades.test.tools.core.CorePlugin;
24
import org.eclipse.hyades.test.tools.core.CorePlugin;
25
import org.eclipse.hyades.test.tools.core.internal.common.codegen.ASTHelper;
26
import org.eclipse.hyades.test.tools.core.internal.common.codegen.DelegateProjectDependencyUpdater;
29
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
27
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
30
import org.eclipse.hyades.test.tools.core.internal.common.codegen.IProjectDependencyUpdater;
28
import org.eclipse.hyades.test.tools.core.internal.common.codegen.IProjectDependencyUpdater;
31
import org.eclipse.hyades.test.tools.core.internal.common.codegen.ImportManager;
29
import org.eclipse.hyades.test.tools.core.internal.common.codegen.ImportManager;
32
import org.eclipse.hyades.test.tools.core.internal.common.codegen.JavaGenerator;
30
import org.eclipse.hyades.test.tools.core.internal.common.codegen.JavaGenerator;
33
import org.eclipse.hyades.test.tools.core.internal.java.modelsync.JUnitModelUpdater;
31
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.AssociateModelSourceChange;
34
import org.eclipse.hyades.test.tools.core.internal.java.modelsync.JUnitProjectBuilder;
32
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.CompilationUnitChange;
33
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.PotentialChange;
34
import org.eclipse.hyades.test.tools.core.internal.java.JavaMessages;
35
import org.eclipse.jdt.core.ICompilationUnit;
35
import org.eclipse.jdt.core.ICompilationUnit;
36
import org.eclipse.jdt.core.IMethod;
36
import org.eclipse.jdt.core.IMethod;
37
import org.eclipse.jdt.core.IType;
38
import org.eclipse.jdt.core.JavaCore;
37
import org.eclipse.jdt.core.JavaCore;
39
import org.eclipse.jdt.core.JavaModelException;
38
import org.eclipse.jdt.core.JavaModelException;
39
import org.eclipse.jdt.core.dom.AST;
40
import org.eclipse.jdt.core.dom.ASTParser;
41
import org.eclipse.jdt.core.dom.CompilationUnit;
42
import org.eclipse.jdt.core.dom.Javadoc;
43
import org.eclipse.jdt.core.dom.MethodDeclaration;
44
import org.eclipse.jdt.core.dom.Name;
45
import org.eclipse.jdt.core.dom.SimpleType;
46
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
47
import org.eclipse.jdt.core.dom.TagElement;
48
import org.eclipse.jdt.core.dom.Type;
49
import org.eclipse.jdt.core.dom.TypeDeclaration;
50
import org.eclipse.jface.text.Document;
51
import org.eclipse.ltk.core.refactoring.Change;
52
import org.eclipse.ltk.core.refactoring.NullChange;
53
import org.eclipse.text.edits.MalformedTreeException;
54
import org.eclipse.text.edits.TextEdit;
40
55
41
/**
56
/**
57
 * JUnit code generator and code updater. This generator synchronizes the model behavior with
58
 * the static suite() method, and matches each test case with a test method.
59
 * This concrete implementation handles code generation and code update for JUnit and
60
 * JUnit Plugin types.
61
 * <p>If you do not need code synchronization, consider implementing {@link JavaGenerator}.</p>
42
 * @author marcelop, jcanches
62
 * @author marcelop, jcanches
43
 * @since 1.0.2
63
 * @since 1.0.2
44
 */
64
 */
45
public class JUnitGenerator extends JavaGenerator {
65
public class JUnitGenerator extends JavaGenerator {
46
	
66
	
47
	private String superclassName;
67
	private String superclassName;
68
	private boolean destructiveChangeFound;
48
69
49
	public JUnitGenerator(IProjectDependencyUpdater updater) {
70
	public JUnitGenerator(ITestSuite testSuite, IProjectDependencyUpdater updater) {
50
		super(updater);
71
		super(testSuite, new JUnitProjectDependencyUpdater(updater, !testSuite.getImplementor().isExternalImplementor()));
51
	}
72
	}
52
	
73
	
53
	public JUnitGenerator(IProjectDependencyUpdater updater, String superclassName) {
74
	public JUnitGenerator(ITestSuite testSuite, IProjectDependencyUpdater updater, String superclassName) {
54
		this(updater);
75
		this(testSuite, updater);
55
		this.superclassName = superclassName;
76
		this.superclassName = superclassName;
56
	}
77
	}
57
	
78
	
58
	/**
79
	/**
59
	 * @see org.eclipse.hyades.test.common.internal.codegen.Generator#generateFile(org.eclipse.hyades.models.common.facades.behavioral.ITestSuite, org.eclipse.core.resources.IFile, org.eclipse.core.runtime.IProgressMonitor)
80
	 * @see org.eclipse.hyades.test.common.internal.codegen.Generator#generateFile(org.eclipse.hyades.models.common.facades.behavioral.ITestSuite, org.eclipse.core.resources.IFile, org.eclipse.core.runtime.IProgressMonitor)
60
	 */
81
	 */
61
	protected void generateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor)
82
	protected String generateCode(IProgressMonitor monitor) throws CoreException {
62
	throws Exception
63
	{
64
		Helper helper = new Helper();
83
		Helper helper = new Helper();
65
		if (this.superclassName != null) {
84
		try {
66
			helper.setSuperclassName(this.superclassName);
85
			if (this.superclassName != null) {
86
				helper.setSuperclassName(this.superclassName);
87
			}
88
			ITestSuite testSuite = getTestSuite();
89
			computeTestMethodNames(testSuite, testSuite.getImplementor().isExternalImplementor(), helper);
90
			GenTestSuite generator = new GenTestSuite();
91
			return Helper.formatContent(generator.generate(testSuite, helper));
92
		} finally {
93
			helper.dispose();
67
		}
94
		}
68
		computeTestMethodNames(testSuite, testSuite.getImplementor().isExternalImplementor(), helper);
69
		GenTestSuite generator = new GenTestSuite();
70
		String content = Helper.formatContent(generator.generate(testSuite, helper));
71
		// use UTF-8 encoding - bugzilla_88029 running test with non-ASCII characters.
72
		file.create(new ByteArrayInputStream(content.getBytes(CHARSET_UTF8)), true, monitor);
73
		file.setCharset(CHARSET_UTF8, monitor);
74
		helper.dispose();
75
		// Associate the java file to the testsuite file
76
		associateJavaFileToTestSuite(file, testSuite);
77
	}
95
	}
78
	
96
	
79
	protected void updateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor) {
97
	protected Change createPostCodegenerationChange(IProgressMonitor monitor) throws CoreException {
98
		PotentialChange change = new AssociateModelSourceChange(getFileHandle(getTestSuite()), getTestSuite());
99
		if (change.hasEffect()) {
100
			return change;
101
		}
102
		return new NullChange();
103
	}
104
105
	protected Change createSourceUpdateChange(IFile file, SubProgressMonitor monitor) throws CoreException {
80
		monitor.beginTask("", 4); //$NON-NLS-1$
106
		monitor.beginTask("", 4); //$NON-NLS-1$
81
		try {
107
		try {
82
			ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
108
			ASTParser parser = ASTParser.newParser(AST.JLS3); // TODO Compute the argument
109
			ITestSuite testSuite = getTestSuite();
110
			ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(file);
111
			
83
			Helper helper = new Helper();
112
			Helper helper = new Helper();
84
			String packageName = helper.getPackageName(testSuite);
113
			String packageName = helper.getPackageName(testSuite);
85
			helper.setImportManager(new ImportManager(packageName));
114
			helper.setImportManager(new ImportManager(packageName));
86
			try {
115
			try {
87
				if (cu == null || !cu.isStructureKnown()) {
116
				// Parse the source code
88
					// TODO ask the user whether to override the code or not modify it
117
				destructiveChangeFound = false;
89
					return;
118
				Document doc = new Document(compilationUnit.getBuffer().getContents());
90
				}
119
				parser.setSource(doc.get().toCharArray());
91
				IType mainClass = cu.findPrimaryType();
120
				CompilationUnit cu = (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1));
92
				cu.becomeWorkingCopy(null, new SubProgressMonitor(monitor, 1));
121
				cu.recordModifications();
93
				try {
122
				TypeDeclaration mainType = ASTHelper.getMainType(cu);
94
					updateTestMethods(testSuite, mainClass, helper,
123
				if (mainType == null) {
95
							new SubProgressMonitor(monitor, 1));
124
					// TODO Error
96
					// The generation of suite() must be performed after the test methods update
125
					return new NullChange();
97
					// because the methods names might change during the update.
126
				}
98
					if (!testSuite.getImplementor().isExternalImplementor()) {
127
				
99
						updateSuiteMethod(testSuite, mainClass, helper);
128
				// Modify the AST tree
100
						checkConstructor(mainClass, helper);
129
				updateTestMethods(testSuite, mainType, helper, new SubProgressMonitor(monitor, 1));
101
					}
130
				// The generation of suite() must be performed after the test methods update
102
					monitor.worked(1);
131
				// because the methods names might change during the update.
103
					helper.emitSortedImports(cu);
132
				if (!testSuite.getImplementor().isExternalImplementor()) {
104
133
					updateSuiteMethod(testSuite, mainType, helper);
105
					cu.commitWorkingCopy(/*force*/false,
134
					checkConstructor(mainType, helper);
106
							new SubProgressMonitor(monitor, 1));
135
					checkSuperType(mainType, helper);
107
					// Associate the java file to the testsuite file
136
				}
108
					associateJavaFileToTestSuite(file, testSuite);
137
				monitor.worked(1);
109
				} finally {
138
				// Emit to AST the imports that are newly required by the updated code
110
					cu.discardWorkingCopy();
139
				helper.emitSortedImports(cu);
140
				
141
				// Compute the resulting document and save it
142
				TextEdit edit = cu.rewrite(doc, /*options*/null);
143
				if (edit.getChildrenSize() != 0) {
144
					CompilationUnitChange change = new CompilationUnitChange(JavaMessages.UPDATE_JUNIT_CODE, compilationUnit, destructiveChangeFound);
145
					change.setEdit(edit);
146
					return change;
111
				}
147
				}
112
			} catch (JavaModelException e) {
148
			} catch (JavaModelException e) {
113
				CorePlugin.logError(e);
149
				CorePlugin.logError(e);
150
			} catch (MalformedTreeException e) {
151
				CorePlugin.logError(e);
114
			} finally {
152
			} finally {
115
				helper.dispose();
153
				helper.dispose();
116
			}
154
			}
117
		} finally {
155
		} finally {
118
			monitor.done();
156
			monitor.done();
119
		}
157
		}
158
		return new NullChange();
120
	}
159
	}
121
160
161
	protected void checkSuperType(TypeDeclaration mainType, Helper helper) {
162
		boolean doIt = false;
163
		Type superclassType = mainType.getSuperclassType();
164
		if (superclassType == null) {
165
			doIt = true;
166
		}
167
		
168
		if (superclassType.isSimpleType()) {
169
			SimpleType st = (SimpleType)superclassType;
170
			Name supertypeName = ASTHelper.resolveName((CompilationUnit)mainType.getParent(), st.getName());
171
			if (supertypeName != null && !Helper.HYADES_TEST_CASE_CLASS_NAME.equals(supertypeName.getFullyQualifiedName())) {
172
				doIt = true;
173
			}
174
		}
175
		if (doIt) {
176
			destructiveChangeFound = true;
177
			helper.addImport(Helper.HYADES_TEST_CASE_CLASS_NAME);
178
			Name newName = mainType.getAST().newName(helper.getImportedName(Helper.HYADES_TEST_CASE_CLASS_NAME));
179
			if (superclassType == null) {
180
				superclassType = mainType.getAST().newSimpleType(newName);
181
				mainType.setSuperclassType(superclassType);
182
			} else {
183
				((SimpleType)superclassType).setName(newName);
184
			}
185
		}
186
	}
187
	
122
	/**
188
	/**
123
	 * Update the content of the suite() method for the specified class,
189
	 * Update the content of the suite() method for the specified class,
124
	 * with the behavior of the specified test suite.
190
	 * with the behavior of the specified test suite.
Lines 126-152 Link Here
126
	 * the method if it does not exist.
192
	 * the method if it does not exist.
127
	 * @throws JavaModelException 
193
	 * @throws JavaModelException 
128
	 */
194
	 */
129
	protected void updateSuiteMethod(ITestSuite testSuite, IType mainClass, Helper helper) throws JavaModelException {
195
	protected void updateSuiteMethod(ITestSuite testSuite, TypeDeclaration mainType, Helper helper) throws JavaModelException {
130
		// Compute the suite() method body
196
		// Compute the suite() method body
131
		GenSuiteMethod generator = new GenSuiteMethod();
197
		GenSuiteMethod generator = new GenSuiteMethod();
132
		String content = generator.generate(testSuite, helper);
198
		String content = generator.generate(testSuite, helper);
133
		IMethod suiteMethod = mainClass.getMethod("suite", new String[0]); //$NON-NLS-1$
199
		MethodDeclaration newSuiteMethod = ASTHelper.parseMethod(mainType.getAST(), content);
134
		IMethod sibling = null; // The suite() method sits before this method
200
		
135
		if (suiteMethod.exists()) {
201
		// Compute the existing suite() method index and removes it if it exists
136
			IMethod[] methods = mainClass.getMethods();
202
		MethodDeclaration suiteMethod = ASTHelper.findMethodWithNoParameter(mainType, "suite"); //$NON-NLS-1$
137
			int index = Arrays.asList(methods).indexOf(suiteMethod);
203
		int index;
138
			suiteMethod.delete(/*force*/false, new NullProgressMonitor());
204
		if (suiteMethod == null) {
139
			methods = mainClass.getMethods();
205
			index = ASTHelper.getFirstMethodIndex(mainType);
140
			if (index < methods.length) {
141
				sibling = methods[index];
142
			}
143
		} else {
206
		} else {
144
			IMethod[] methods = mainClass.getMethods();
207
			ITestSuite previousVersion = getRepositoryTestSuite();
145
			if (methods.length > 0) {
208
			if (previousVersion != null && previousVersion.getImplementor().isExternalImplementor()) {
146
				sibling = methods[0];
209
				destructiveChangeFound = true;
147
			}
210
			}
211
			index = mainType.bodyDeclarations().indexOf(suiteMethod);
212
			mainType.bodyDeclarations().remove(index);
213
		}
214
		
215
		// Inserts the new MethodDeclaration at the right position
216
		if (index == -1) {
217
			mainType.bodyDeclarations().add(newSuiteMethod);
218
		} else {
219
			mainType.bodyDeclarations().add(index, newSuiteMethod);
148
		}
220
		}
149
		mainClass.createMethod(Helper.formatContent(content, 0), sibling, /*force*/true, new NullProgressMonitor());
150
	}
221
	}
151
	
222
	
152
	/**
223
	/**
Lines 156-168 Link Here
156
	 * @param helper
227
	 * @param helper
157
	 * @throws JavaModelException 
228
	 * @throws JavaModelException 
158
	 */
229
	 */
159
	protected void checkConstructor(IType mainClass, Helper helper) throws JavaModelException {
230
	protected void checkConstructor(TypeDeclaration mainType, Helper helper) throws JavaModelException {
160
		IMethod method = mainClass.getMethod(mainClass.getElementName(), new String[] { "QString;" }); //$NON-NLS-1$
231
		MethodDeclaration pattern = mainType.getAST().newMethodDeclaration();
161
		if (method.exists()) return;
232
		pattern.setName(mainType.getAST().newSimpleName(mainType.getName().getIdentifier()));
162
		GenTestSuiteConstructor generator = new GenTestSuiteConstructor();
233
		SingleVariableDeclaration svd = mainType.getAST().newSingleVariableDeclaration();
163
		String contents = generator.generate(mainClass.getElementName(), helper);
234
		svd.setType(mainType.getAST().newSimpleType(mainType.getAST().newSimpleName("String"))); //$NON-NLS-1$
164
		IMethod[] methods = mainClass.getMethods();
235
		pattern.parameters().add(svd);
165
		mainClass.createMethod(Helper.formatContent(contents, 0), methods.length == 0 ? null : methods[0], /*force*/true, new NullProgressMonitor());
236
		
237
		MethodDeclaration constructor = ASTHelper.findMethod(mainType, pattern);
238
		if (constructor == null) {
239
			GenTestSuiteConstructor generator = new GenTestSuiteConstructor();
240
			String contents = generator.generate(mainType.getName().getIdentifier(), helper);
241
			constructor = ASTHelper.parseMethod(mainType.getAST(), contents);
242
			int index = ASTHelper.getFirstMethodIndex(mainType);
243
			if (index == -1) {
244
				mainType.bodyDeclarations().add(constructor);
245
			} else {
246
				mainType.bodyDeclarations().add(index, constructor);
247
			}
248
		}
249
	}
250
	
251
	/**
252
	 * Returns whether a method is a test method.
253
	 * @param method
254
	 * @return
255
	 */
256
	public static boolean isTestMethod(MethodDeclaration method) {
257
		String name = method.getName().getIdentifier();
258
		return name.startsWith("test") && method.parameters().size() == 0; //$NON-NLS-1$
166
	}
259
	}
167
	
260
	
168
	/**
261
	/**
Lines 175-181 Link Here
175
		String[] types = method.getParameterTypes();
268
		String[] types = method.getParameterTypes();
176
		return name.startsWith("test") && types.length == 0; //$NON-NLS-1$
269
		return name.startsWith("test") && types.length == 0; //$NON-NLS-1$
177
	}
270
	}
178
	
271
179
	/**
272
	/**
180
	 * Update the list of test methods in the specified class, so that the list of
273
	 * Update the list of test methods in the specified class, so that the list of
181
	 * test methods matches the list of test cases of the specified test suite.
274
	 * test methods matches the list of test cases of the specified test suite.
Lines 184-191 Link Here
184
	 * @param helper
277
	 * @param helper
185
	 * @throws JavaModelException
278
	 * @throws JavaModelException
186
	 */
279
	 */
187
	protected void updateTestMethods(ITestSuite testSuite, IType mainClass, Helper helper, IProgressMonitor monitor) throws JavaModelException {
280
	protected void updateTestMethods(ITestSuite testSuite, TypeDeclaration mainType, Helper helper, IProgressMonitor monitor) throws JavaModelException {
188
		IMethod[] methods = mainClass.getMethods();
281
		MethodDeclaration[] methods = mainType.getMethods();
189
		monitor.beginTask("", methods.length + testSuite.getITestCases().size()); //$NON-NLS-1$
282
		monitor.beginTask("", methods.length + testSuite.getITestCases().size()); //$NON-NLS-1$
190
		try {
283
		try {
191
			List usedTestMethods = new ArrayList(methods.length);
284
			List usedTestMethods = new ArrayList(methods.length);
Lines 200-222 Link Here
200
					actualMethodName = computedMethodName;
293
					actualMethodName = computedMethodName;
201
					Helper.setTestMethodName(testCase, actualMethodName);
294
					Helper.setTestMethodName(testCase, actualMethodName);
202
				}
295
				}
203
				IMethod method = mainClass.getMethod(actualMethodName, new String[0]);
296
				MethodDeclaration method = ASTHelper.findMethodWithNoParameter(mainType, actualMethodName);
204
				if (!method.exists()) {
297
				if (method == null) {
205
					method = createTestMethod(mainClass, testCase, helper);
298
					method = createTestMethod(mainType, testCase, helper);
206
				} else {
299
				} else {
207
					// We still need to rename the method to conform to the computed name
300
					updateTestMethod(testCase, computedMethodName, method, helper);
208
					if (!computedMethodName.equals(actualMethodName)) {
209
						method.rename(computedMethodName, /*replace*/true, new SubProgressMonitor(monitor, 1));
210
						Helper.setTestMethodName(testCase, computedMethodName);
211
					}
212
				}
301
				}
213
				usedTestMethods.add(method);
302
				usedTestMethods.add(method);
214
				monitor.worked(1);
303
				monitor.worked(1);
215
			}
304
			}
216
			// 2) Remove unused test methods
305
			// 2) Remove unused test methods
217
			for (int i = 0; i< methods.length; i++) {
306
			for (int i = 0; i < methods.length; i++) {
218
				if (isTestMethod(methods[i]) && !usedTestMethods.contains(methods[i])) {
307
				if (isTestMethod(methods[i]) && !usedTestMethods.contains(methods[i])) {
219
					methods[i].delete(/*force*/false, new NullProgressMonitor());
308
					destructiveChangeFound = true;
309
					mainType.bodyDeclarations().remove(methods[i]);
220
				}
310
				}
221
				monitor.worked(1);
311
				monitor.worked(1);
222
			}
312
			}
Lines 224-263 Link Here
224
			monitor.done();
314
			monitor.done();
225
		}
315
		}
226
	}
316
	}
317
	
318
	protected void updateTestMethod(ITestCase testCase, String newName, MethodDeclaration method, Helper helper) {
319
		// Update method name if necessary
320
		if (!newName.equals(method.getName().getIdentifier())) {
321
			destructiveChangeFound = true;
322
			method.setName(method.getAST().newSimpleName(newName));
323
			Helper.setTestMethodName(testCase, newName);
324
		}
325
		// Update comments if necessary
326
		Javadoc javadoc = method.getJavadoc();
327
		if (javadoc == null) {
328
			javadoc = method.getAST().newJavadoc();
329
			method.setJavadoc(javadoc);
330
		}
331
		updateDescriptionTag(javadoc, testCase);
332
	}
333
	
334
	protected void updateDescriptionTag(Javadoc javadoc, ITestCase testCase) {
335
		TagElement oldtag = null;
336
		if (!javadoc.tags().isEmpty()) {
337
			TagElement tag = (TagElement) javadoc.tags().get(0);
338
			if (tag.getTagName() == null) {
339
				oldtag = tag;
340
			}
341
		}
342
		
343
		if (oldtag != null) {
344
			String sourceDescription = ASTHelper.extractDescription(oldtag);
345
			String modelDescription = makeJavadocDescription(testCase);
346
			if (!Helper.compareJavaComments(sourceDescription, modelDescription)) {
347
				destructiveChangeFound = true;
348
				javadoc.tags().remove(oldtag);
349
				ASTHelper.addDescriptionToJavadoc(javadoc, modelDescription);
350
			}
351
		} else {
352
			ASTHelper.addDescriptionToJavadoc(javadoc, makeJavadocDescription(testCase));
353
		}
354
	}
355
	
356
	public static String makeJavadocDescription(ITestCase testCase) {
357
		StringBuffer buf = new StringBuffer();
358
		buf.append(testCase.getName());
359
		if (testCase.getDescription() != null) {
360
			String descr = testCase.getDescription().trim();
361
			if (descr.length() > 0) {
362
				buf.append("\r\n"); //$NON-NLS-1$
363
				buf.append(descr);
364
			}
365
		}
366
		return buf.toString();
367
	}
227
368
228
	/**
369
	/**
229
	 * Creates a test method for the specified test case.
370
	 * Creates a test method for the specified test case.
230
	 * @param mainClass
231
	 * @param testCase
232
	 * @param helper
233
	 * @throws JavaModelException 
234
	 */
371
	 */
235
	protected IMethod createTestMethod(IType mainClass, ITestCase testCase, Helper helper) throws JavaModelException {
372
	protected MethodDeclaration createTestMethod(TypeDeclaration mainType, ITestCase testCase, Helper helper) throws JavaModelException {
236
		GenTestMethod generator = new GenTestMethod();
373
		GenTestMethod generator = new GenTestMethod();
237
		String content = generator.generate(testCase, helper);
374
		String content = generator.generate(testCase, helper);
238
		return mainClass.createMethod(content, null, /*force*/false, new NullProgressMonitor());
375
		MethodDeclaration method = ASTHelper.parseMethod(mainType.getAST(), content);
376
		mainType.bodyDeclarations().add(method);
377
		return method;
239
	}
378
	}
240
	
379
	
241
	private void associateJavaFileToTestSuite(IFile javaFile, ITestSuite testSuite) {
380
	public static class JUnitProjectDependencyUpdater extends DelegateProjectDependencyUpdater {
242
		try {
381
243
			if (testSuite instanceof EObject) {
382
		public JUnitProjectDependencyUpdater(IProjectDependencyUpdater delegate, boolean isModelBehavior) {
244
				EObject eObject = (EObject) testSuite;
383
			super(delegate);
245
				IFile testSuiteFile = EMFUtil.getWorkspaceFile(eObject);
384
			addRequiredPlugin("org.junit", "junit.jar"); //$NON-NLS-1$ //$NON-NLS-2$
246
				if (testSuiteFile != null && testSuiteFile.exists()) {
385
			if (isModelBehavior) {
247
					// Add the Junit builder to the file's project (if not already installed)
386
				addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
248
					JUnitProjectBuilder.installBuilder(javaFile.getProject());
387
				addRequiredPlugin(CorePlugin.getID(), "java.runner.jar"); //$NON-NLS-1$
249
					// Also add the JUnit builder to the test suite's project (the source file
250
					// and the test suite usually are under the same project, but this is not
251
					// mandatory).
252
					JUnitProjectBuilder.installBuilder(testSuiteFile.getProject());
253
					// Record the link from the java file to the testsuite file
254
					JUnitModelUpdater.associateTestSuiteToJUnitSourceFile(
255
							javaFile, testSuiteFile);
256
				}
257
			}
388
			}
258
		} catch (Throwable t) {
259
			CorePlugin.logError(t);
260
		}
389
		}
390
261
	}
391
	}
262
	
392
	
263
}
393
}
(-)src/org/eclipse/hyades/test/tools/core/internal/java/codegen/GenTestSuite.java (-1 / +1 lines)
Lines 4-10 Link Here
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: GenTestSuite.java,v 1.11 2006/07/29 01:57:42 sschneid Exp $
7
 * $Id$
8
 * 
8
 * 
9
 * Contributors: 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
10
 * IBM Corporation - initial API and implementation
(-)src/org/eclipse/hyades/test/tools/core/internal/java/codegen/GenTestMethod.java (-1 / +1 lines)
Lines 4-10 Link Here
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: GenTestMethod.java,v 1.9 2006/07/29 21:36:45 sschneid Exp $
7
 * $Id$
8
 * 
8
 * 
9
 * Contributors: 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
10
 * IBM Corporation - initial API and implementation
(-)src/org/eclipse/hyades/test/tools/core/internal/manual/codegen/ManualGenerator.java (-21 / +10 lines)
Lines 11-21 Link Here
11
 **********************************************************************/
11
 **********************************************************************/
12
package org.eclipse.hyades.test.tools.core.internal.manual.codegen;
12
package org.eclipse.hyades.test.tools.core.internal.manual.codegen;
13
13
14
import java.io.ByteArrayInputStream;
14
import org.eclipse.core.runtime.CoreException;
15
16
import org.eclipse.core.resources.IFile;
17
import org.eclipse.core.runtime.IProgressMonitor;
15
import org.eclipse.core.runtime.IProgressMonitor;
18
19
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
16
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
20
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Generator;
17
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Generator;
21
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
18
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
Lines 24-41 Link Here
24
 * @author marcelop
21
 * @author marcelop
25
 * @since 1.0.2
22
 * @since 1.0.2
26
 */
23
 */
27
public class ManualGenerator 
24
public class ManualGenerator extends Generator
28
extends Generator
29
{
25
{
26
27
	public ManualGenerator(ITestSuite testSuite) {
28
		super(testSuite);
29
	}
30
30
	/**
31
	/**
31
	 * @see org.eclipse.hyades.test.common.internal.codegen.Generator#generateFile(org.eclipse.hyades.models.common.facades.behavioral.ITestSuite, org.eclipse.core.resources.IFile, org.eclipse.core.runtime.IProgressMonitor)
32
	 * @see org.eclipse.hyades.test.common.internal.codegen.Generator#generateFile(org.eclipse.hyades.models.common.facades.behavioral.ITestSuite, org.eclipse.core.resources.IFile, org.eclipse.core.runtime.IProgressMonitor)
32
	 */
33
	 */
33
	protected void generateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor)
34
	protected String generateCode(IProgressMonitor monitor) throws CoreException {
34
	throws Exception
35
		return generateScript(getTestSuite());
35
	{
36
		// bugzilla_93098 specifically use UTF-8 when generating test file to work for multi-byte characters. 
37
		file.create(new ByteArrayInputStream(generateScript(testSuite).getBytes(CHARSET_UTF8)), true, monitor);
38
		file.setCharset(CHARSET_UTF8, monitor);
39
	}
36
	}
40
	
37
	
41
	public static String generateScript(ITestSuite testSuite)
38
	public static String generateScript(ITestSuite testSuite)
Lines 43-61 Link Here
43
		GenTestSuite genTestSuite = new GenTestSuite();
40
		GenTestSuite genTestSuite = new GenTestSuite();
44
		String script = genTestSuite.generate(testSuite, new Helper());
41
		String script = genTestSuite.generate(testSuite, new Helper());
45
		
42
		
46
		String extraChars = "\t\t" + genTestSuite.NL;
43
		String extraChars = "\t\t" + genTestSuite.NL; //$NON-NLS-1$
47
		if(script.startsWith(extraChars))
44
		if(script.startsWith(extraChars))
48
			script = script.substring(extraChars.length());
45
			script = script.substring(extraChars.length());
49
		
46
		
50
		return script;
47
		return script;
51
	}
48
	}
52
49
53
	/* (non-Javadoc)
54
	 * @see org.eclipse.hyades.test.tools.ui.common.internal.codegen.Generator#updateFile(org.eclipse.hyades.models.common.facades.behavioral.ITestSuite, org.eclipse.core.resources.IFile, org.eclipse.core.runtime.IProgressMonitor)
55
	 */
56
	protected void updateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor) throws Exception {
57
		// The script is not expected to be edited: update = generate
58
		generateFile(testSuite, file, monitor);
59
		
60
	}
61
}
50
}
(-)src/org/eclipse/hyades/test/tools/core/internal/manual/codegen/GenTestSuite.java (-1 / +1 lines)
Lines 4-10 Link Here
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: GenTestSuite.java,v 1.11 2006/07/29 01:57:42 sschneid Exp $
7
 * $Id$
8
 * 
8
 * 
9
 * Contributors: 
9
 * Contributors: 
10
 * IBM - Initial API and implementation
10
 * IBM - Initial API and implementation
(-)src/org/eclipse/hyades/test/tools/core/internal/java/modelsync/JUnitModelUpdater.java (-10 / +49 lines)
Lines 45-50 Link Here
45
import org.eclipse.hyades.test.tools.core.CorePlugin;
45
import org.eclipse.hyades.test.tools.core.CorePlugin;
46
import org.eclipse.hyades.test.tools.core.common.TestCommon;
46
import org.eclipse.hyades.test.tools.core.common.TestCommon;
47
import org.eclipse.hyades.test.tools.core.common.util.TestCommonUtil;
47
import org.eclipse.hyades.test.tools.core.common.util.TestCommonUtil;
48
import org.eclipse.hyades.test.tools.core.internal.common.codegen.ASTHelper;
48
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
49
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
49
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
50
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
50
import org.eclipse.hyades.test.tools.core.java.JUnitTestSuiteFacade;
51
import org.eclipse.hyades.test.tools.core.java.JUnitTestSuiteFacade;
Lines 52-57 Link Here
52
import org.eclipse.jdt.core.IMethod;
53
import org.eclipse.jdt.core.IMethod;
53
import org.eclipse.jdt.core.IType;
54
import org.eclipse.jdt.core.IType;
54
import org.eclipse.jdt.core.JavaCore;
55
import org.eclipse.jdt.core.JavaCore;
56
import org.eclipse.jdt.core.JavaModelException;
57
import org.eclipse.jdt.core.dom.TagElement;
55
58
56
/**
59
/**
57
 * This class provides methods for creating/updating a JUnit TestSuite model
60
 * This class provides methods for creating/updating a JUnit TestSuite model
Lines 61-67 Link Here
61
 */
64
 */
62
public class JUnitModelUpdater {
65
public class JUnitModelUpdater {
63
66
64
	private final static String TPTP_JUNIT_TEST_MARKER = "org.eclipse.hyades.test.tools.junit"; //$NON-NLS-1$
67
	private final static String TPTP_JUNIT_TEST_MARKER = "org.eclipse.hyades.test.tools.core.junit"; //$NON-NLS-1$
65
	private final static String TPTP_JUNIT_DEFINITION_ATTRIBUTE = "definition"; //$NON-NLS-1$
68
	private final static String TPTP_JUNIT_DEFINITION_ATTRIBUTE = "definition"; //$NON-NLS-1$
66
	
69
	
67
	/**
70
	/**
Lines 106-111 Link Here
106
						changed = true;
109
						changed = true;
107
					}
110
					}
108
					usedTestCases.add(testCase);
111
					usedTestCases.add(testCase);
112
					if (updateTestCaseDescription(methods[i], testCase)) {
113
						changed = true;
114
					}
109
    			}
115
    			}
110
			}
116
			}
111
			// Search for Test Cases that do not have a matching test method
117
			// Search for Test Cases that do not have a matching test method
Lines 134-139 Link Here
134
		return changed;
140
		return changed;
135
	}
141
	}
136
	
142
	
143
	private static boolean updateTestCaseDescription(IMethod method, ITestCase testCase) throws JavaModelException {
144
		TagElement sourceTag = ASTHelper.getJavadocDescription(method);
145
		if (sourceTag == null) {
146
			if (testCase.getDescription() != null && testCase.getDescription().length() > 0) {
147
				testCase.setDescription(null);
148
				return true;
149
			}
150
			return false;
151
		}
152
		
153
		String sourceDescription = ASTHelper.extractDescription(sourceTag);
154
		if (sourceDescription.startsWith(testCase.getName())) {
155
			sourceDescription = sourceDescription.substring(testCase.getName().length());
156
			if (sourceDescription.startsWith("\n")) sourceDescription = sourceDescription.substring("\n".length());  //$NON-NLS-1$//$NON-NLS-2$
157
		}
158
		
159
		String tcDescription = testCase.getDescription();
160
		if (tcDescription == null) tcDescription = ""; //$NON-NLS-1$
161
		if (!Helper.compareJavaComments(sourceDescription, tcDescription)) {
162
			testCase.setDescription(sourceDescription.trim());
163
			return true;
164
		}
165
		return false;
166
	}
167
	
137
	private static ITestCase findTestCase(ITestSuite testSuite, IMethod testMethod) {
168
	private static ITestCase findTestCase(ITestSuite testSuite, IMethod testMethod) {
138
		Iterator it = testSuite.getITestCases().iterator();
169
		Iterator it = testSuite.getITestCases().iterator();
139
		Helper helper = new Helper();
170
		Helper helper = new Helper();
Lines 241-255 Link Here
241
	
272
	
242
	private static IFile findTestSuiteFile(IFile javaFile) throws CoreException {
273
	private static IFile findTestSuiteFile(IFile javaFile) throws CoreException {
243
		// First method (typical): use the marker to find the test suite definition
274
		// First method (typical): use the marker to find the test suite definition
244
		IMarker[] markers = javaFile.findMarkers(TPTP_JUNIT_TEST_MARKER, /*includeSubTypes*/false, 0);
275
		IFile file = getRegisteredTestSuiteFile(javaFile);
245
		if (markers.length > 0) {
276
		if (file != null) {
246
			String testSuiteDefinition = markers[0].getAttribute(TPTP_JUNIT_DEFINITION_ATTRIBUTE, null);
277
			return file;
247
			if (testSuiteDefinition != null) {
248
				IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(testSuiteDefinition));
249
				if (res instanceof IFile && res.exists()) {
250
					return (IFile)res;
251
				}
252
			}
253
		}
278
		}
254
		// Second method: find a test suite file in the same directory, with the same name
279
		// Second method: find a test suite file in the same directory, with the same name
255
		IContainer container = javaFile.getParent();
280
		IContainer container = javaFile.getParent();
Lines 266-271 Link Here
266
		return null;
291
		return null;
267
	}
292
	}
268
	
293
	
294
	public static IFile getRegisteredTestSuiteFile(IFile javaFile) throws CoreException {
295
		IMarker[] markers = javaFile.findMarkers(TPTP_JUNIT_TEST_MARKER, /*includeSubTypes*/false, 0);
296
		if (markers.length > 0) {
297
			String testSuiteDefinition = markers[0].getAttribute(TPTP_JUNIT_DEFINITION_ATTRIBUTE, null);
298
			if (testSuiteDefinition != null) {
299
				IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(testSuiteDefinition));
300
				if (res instanceof IFile && res.exists()) {
301
					return (IFile)res;
302
				}
303
			}
304
		}
305
		return null;
306
	}
307
	
269
	/**
308
	/**
270
	 * Marks the specified junit source file as being associated to a TPTP JUnit test. This method
309
	 * Marks the specified junit source file as being associated to a TPTP JUnit test. This method
271
	 * does not perform any workspace operation if the association is already up-to-date.
310
	 * does not perform any workspace operation if the association is already up-to-date.
(-)src/org/eclipse/hyades/test/tools/core/internal/java/modelsync/JUnitProjectBuilder.java (+12 lines)
Lines 227-231 Link Here
227
		d.setBuildSpec(newCommands); 
227
		d.setBuildSpec(newCommands); 
228
		project.setDescription(d, null);
228
		project.setDescription(d, null);
229
	}
229
	}
230
	
231
	public static boolean isBuilderInstalled(IProject project) throws CoreException {
232
		IProjectDescription d = project.getDescription();
233
		ICommand[] buildSpec = d.getBuildSpec();
234
		int found = 0;
235
		for (int i = 0; i < buildSpec.length; i++) {
236
			if (buildSpec[i].getBuilderName().equals(BUILDER_ID)) {
237
				return true;
238
			}
239
		}
240
		return false;
241
	}
230
242
231
}
243
}
(-)src/org/eclipse/hyades/test/tools/core/internal/java/JavaMessages.java (+1 lines)
Lines 26-29 Link Here
26
	}
26
	}
27
27
28
	public static String BUILDER_LINK_TASK;
28
	public static String BUILDER_LINK_TASK;
29
	public static String UPDATE_JUNIT_CODE;
29
}
30
}
(-)src/org/eclipse/hyades/test/tools/core/internal/java/messages.properties (+1 lines)
Lines 14-16 Link Here
14
# NLS_ENCODING=UTF-8
14
# NLS_ENCODING=UTF-8
15
15
16
BUILDER_LINK_TASK=Linking Test Suites to source code
16
BUILDER_LINK_TASK=Linking Test Suites to source code
17
UPDATE_JUNIT_CODE=Update JUnit code
(-)META-INF/MANIFEST.MF (-4 / +5 lines)
Lines 65-79 Link Here
65
 org.eclipse.tptp.test.manual.runner.ui.internal.util
65
 org.eclipse.tptp.test.manual.runner.ui.internal.util
66
Require-Bundle: org.eclipse.hyades.test.core;bundle-version="[4.2.0,5.0.0)",
66
Require-Bundle: org.eclipse.hyades.test.core;bundle-version="[4.2.0,5.0.0)",
67
 org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
67
 org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
68
 org.eclipse.core.resources;resolution:=optional;bundle-version="[3.2.0,4.0.0)",
68
 org.eclipse.core.resources;bundle-version="[3.2.0,4.0.0)";resolution:=optional,
69
 org.eclipse.jface.text;bundle-version="[3.2.0,4.0.0)",
69
 org.eclipse.jface.text;bundle-version="[3.2.0,4.0.0)",
70
 org.eclipse.jdt.core;resolution:=optional;bundle-version="[3.2.0,4.0.0)",
70
 org.eclipse.jdt.core;bundle-version="[3.2.0,4.0.0)";resolution:=optional,
71
 org.eclipse.tptp.platform.models;bundle-version="[4.2.0,5.0.0)",
71
 org.eclipse.tptp.platform.models;bundle-version="[4.2.0,5.0.0)",
72
 org.eclipse.hyades.execution;bundle-version="[4.2.0,5.0.0)",
72
 org.eclipse.hyades.execution;bundle-version="[4.2.0,5.0.0)",
73
 org.eclipse.hyades.logging.core;bundle-version="[4.2.0,5.0.0)",
73
 org.eclipse.hyades.logging.core;bundle-version="[4.2.0,5.0.0)",
74
 com.ibm.icu;bundle-version="[3.4.3,4.0.0)",
74
 com.ibm.icu;bundle-version="[3.4.3,4.0.0)",
75
 org.eclipse.debug.core;resolution:=optional;bundle-version="[3.2.0,4.0.0)",
75
 org.eclipse.debug.core;bundle-version="[3.2.0,4.0.0)";resolution:=optional,
76
 org.eclipse.pde.core;bundle-version="[3.2.0,4.0.0)",
76
 org.eclipse.pde.core;bundle-version="[3.2.0,4.0.0)",
77
 org.eclipse.ui;resolution:=optional;bundle-version="[3.2.0,4.0.0)",
77
 org.eclipse.ltk.core.refactoring;bundle-version="[3.2.0,4.0.0)";visibility:=reexport,
78
 org.eclipse.ui;bundle-version="[3.2.0,4.0.0)";resolution:=optional,
78
 org.junit;bundle-version="[3.8.1,4.0.0)"
79
 org.junit;bundle-version="[3.8.1,4.0.0)"
79
Eclipse-LazyStart: true
80
Eclipse-LazyStart: true
(-)src/org/eclipse/hyades/test/tools/core/internal/manual/launch/RunHandler.java (-2 / +2 lines)
Lines 63-70 Link Here
63
		if(testScript == null)
63
		if(testScript == null)
64
			return null;
64
			return null;
65
			
65
			
66
		testScript = StringUtil.replace(testScript, "\r", "");
66
		testScript = StringUtil.replace(testScript, "\r", ""); //$NON-NLS-1$ //$NON-NLS-2$
67
		return StringUtil.replace(testScript, "\n", "");
67
		return StringUtil.replace(testScript, "\n", ""); //$NON-NLS-1$ //$NON-NLS-2$
68
	}
68
	}
69
69
70
	/* (non-Javadoc)
70
	/* (non-Javadoc)
(-)src/org/eclipse/hyades/test/tools/core/internal/plugin/codegen/PluginProjectDependencyUpdater.java (+19 lines)
Lines 14-19 Link Here
14
14
15
import java.io.File;
15
import java.io.File;
16
import java.util.Collection;
16
import java.util.Collection;
17
import java.util.Collections;
17
import java.util.HashSet;
18
import java.util.HashSet;
18
import java.util.Iterator;
19
import java.util.Iterator;
19
import java.util.jar.JarFile;
20
import java.util.jar.JarFile;
Lines 119-123 Link Here
119
		}
120
		}
120
	}
121
	}
121
122
123
	public Collection previewAdjustProject(IProject project) {
124
		IPluginModelBase pluginModel = findProjectPluginModel(project);
125
		if (pluginModel != null) {
126
			HashSet result = new HashSet();
127
			IPluginBase plugin = pluginModel.getPluginBase(/*CreateIfMissing*/false);
128
			Iterator it = requiredPlugins.iterator();
129
			boolean changed = false;
130
			while (it.hasNext()) {
131
				String pluginId = (String) it.next();
132
				if (findPluginImport(plugin, pluginId) == null) {
133
					result.add(pluginId);
134
				}
135
			}
136
			return result;
137
		}
138
		return Collections.EMPTY_SET;
139
	}
140
122
141
123
}
142
}
(-)plugin.xml (+7 lines)
Lines 284-288 Link Here
284
		point="org.eclipse.hyades.execution.service">
284
		point="org.eclipse.hyades.execution.service">
285
		<service class="org.eclipse.hyades.test.tools.core.services.AgentControllerVerificationService"/>
285
		<service class="org.eclipse.hyades.test.tools.core.services.AgentControllerVerificationService"/>
286
	</extension>
286
	</extension>
287
 <extension
288
       id="junit"
289
       name="TPTP JUnit source metadata"
290
       point="org.eclipse.core.resources.markers">
291
    <persistent value="true"/>
292
    <attribute name="definition"/>
293
 </extension>
287
   
294
   
288
</plugin>
295
</plugin>
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/MoveCompilationUnitChange.java (+130 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2005 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.hyades.test.tools.core.internal.common.codegen.changes;
12
13
import org.eclipse.core.resources.IResource;
14
import org.eclipse.core.runtime.CoreException;
15
import org.eclipse.core.runtime.IProgressMonitor;
16
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
17
import org.eclipse.jdt.core.ICompilationUnit;
18
import org.eclipse.jdt.core.IPackageFragment;
19
import org.eclipse.ltk.core.refactoring.Change;
20
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
21
import org.eclipse.osgi.util.NLS;
22
23
/**
24
 * Changes that moves a compilation unit (to a new package and/or a new name).
25
 * @author jcanches
26
 * @since 4.3
27
 */
28
public class MoveCompilationUnitChange extends Change {
29
30
	private boolean fUndoable;
31
	private long fStampToRestore;
32
	private ICompilationUnit compilationUnit;
33
	private IPackageFragment newPackage;
34
	private String newName;
35
	private boolean isPackageChanged;
36
	private boolean isClassnameChanged;
37
	
38
	public MoveCompilationUnitChange(ICompilationUnit cu, IPackageFragment newPackage, String newName){
39
		this(cu, newPackage, newName, IResource.NULL_STAMP);
40
	}
41
	
42
	private MoveCompilationUnitChange(ICompilationUnit cu, IPackageFragment newPackage, String newName, long stampToRestore) {
43
		this.compilationUnit = cu;
44
		if (newPackage == null) {
45
			newPackage = (IPackageFragment)compilationUnit.getParent();
46
		} else {
47
			this.newPackage = newPackage;
48
		}
49
		if (newName == null) {
50
			this.newName = compilationUnit.getElementName();
51
		} else {
52
			this.newName = newName;
53
		}
54
		fStampToRestore= stampToRestore;
55
		isPackageChanged = !compilationUnit.getParent().equals(newPackage);
56
		isClassnameChanged = !this.newName.equals(compilationUnit.getElementName());
57
	}
58
	
59
	public String getName() {
60
		if (isPackageChanged && isClassnameChanged) {
61
			return NLS.bind(CommonPluginMessages.MOVE_RENAME_COMPILATION_UNIT,
62
					new Object[] { compilationUnit.getElementName(), getPackageName(newPackage), newName });
63
		}
64
		if (isPackageChanged) {
65
			return NLS.bind(CommonPluginMessages.MOVE_COMPILATION_UNIT,
66
					new Object[] { compilationUnit.getElementName(), getPackageName(newPackage) });
67
		}
68
		if (isClassnameChanged) {
69
			return NLS.bind(CommonPluginMessages.RENAME_COMPILATION_UNIT,
70
					new Object[] { compilationUnit.getElementName(), newName});
71
		}
72
		return "Invalid change"; //$NON-NLS-1$
73
	}
74
75
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
76
		RefactoringStatus status = new RefactoringStatus();
77
		if (compilationUnit.isReadOnly()) {
78
			status.addFatalError(NLS.bind(CommonPluginMessages.E_COMP_UNIT_READ_ONLY, compilationUnit.getElementName()));
79
		}
80
		if (newPackage.getCompilationUnit(newName).exists()) {
81
			status.addWarning(NLS.bind(CommonPluginMessages.W_COMP_UNIT_OVERWRITE, compilationUnit.getElementName()));
82
		}
83
		return status;
84
	}
85
	
86
	public Change perform(IProgressMonitor pm) throws CoreException {
87
		// get current modification stamp
88
		long currentStamp= IResource.NULL_STAMP;
89
		IResource resource= compilationUnit.getResource();
90
		if (resource != null) {
91
			currentStamp= resource.getModificationStamp();
92
		}
93
		
94
		fUndoable= ! newPackage.getCompilationUnit(newName).exists();
95
		String oldName = compilationUnit.getElementName();
96
		IPackageFragment oldPackage = (IPackageFragment) compilationUnit.getParent();
97
		
98
		// perform the move and restore modification stamp
99
		compilationUnit.move(newPackage, null, newName, true, pm);
100
		ICompilationUnit moved= newPackage.getCompilationUnit(newName);
101
		if (fStampToRestore != IResource.NULL_STAMP) {
102
			IResource movedResource= moved.getResource();
103
			if (movedResource != null) {
104
				movedResource.revertModificationStamp(fStampToRestore);
105
			}
106
		}
107
		
108
		if (fUndoable) {
109
			return new MoveCompilationUnitChange(moved, oldPackage, oldName, currentStamp);
110
		} else {
111
			return null;
112
		}
113
	}
114
	
115
	static String getPackageName(IPackageFragment pack) {
116
		if (pack.isDefaultPackage())
117
			return CommonPluginMessages.DEFAULT_PACKAGE; 
118
		else
119
			return pack.getElementName();
120
	}
121
122
	public Object getModifiedElement() {
123
		return compilationUnit;
124
	}
125
126
	public void initializeValidationData(IProgressMonitor pm) {
127
		// NOP
128
	}
129
130
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/CompilationUnitChange.java (+125 lines)
Added Link Here
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.hyades.test.tools.core.internal.common.codegen.changes;
12
13
import org.eclipse.core.resources.IFile;
14
import org.eclipse.core.runtime.Assert;
15
import org.eclipse.core.runtime.CoreException;
16
import org.eclipse.core.runtime.IProgressMonitor;
17
import org.eclipse.core.runtime.SubProgressMonitor;
18
import org.eclipse.jdt.core.ICompilationUnit;
19
import org.eclipse.jface.text.IDocument;
20
import org.eclipse.ltk.core.refactoring.TextFileChange;
21
22
/**
23
 * Change that modifies the content of a compilation unit.
24
 * Copied from org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange.
25
 * @author jcanches
26
 * @since 4.3
27
 */
28
public class CompilationUnitChange extends TextFileChange {
29
30
	private ICompilationUnit fCUnit;
31
	private boolean destructive;
32
	
33
	/**
34
	 * Creates a new <code>CompilationUnitChange</code>.
35
	 * 
36
	 * @param name the change's name mainly used to render the change in the UI
37
	 * @param cunit the compilation unit this text change works on
38
	 * @param destructive Whether this change contains destructive changes (i.e. applying it
39
	 * will delete some existing code)
40
	 */
41
	public CompilationUnitChange(String name, ICompilationUnit cunit, boolean destructive) {
42
		super(name, getFile(cunit));
43
		Assert.isNotNull(cunit);
44
		fCUnit= cunit;
45
		setTextType("java"); //$NON-NLS-1$
46
		this.destructive = destructive;
47
	}
48
	
49
	private static IFile getFile(ICompilationUnit cunit) {
50
		return (IFile) cunit.getResource();
51
	}
52
	
53
	/* non java-doc
54
	 * Method declared in IChange.
55
	 */
56
	public Object getModifiedElement(){
57
		return fCUnit;
58
	}
59
	
60
	/**
61
	 * Returns the compilation unit this change works on.
62
	 * 
63
	 * @return the compilation unit this change works on
64
	 */
65
	public ICompilationUnit getCompilationUnit() {
66
		return fCUnit;
67
	}
68
	
69
	/**
70
	 * {@inheritDoc}
71
	 */
72
	protected IDocument acquireDocument(IProgressMonitor pm) throws CoreException {
73
		pm.beginTask("", 2); //$NON-NLS-1$
74
		fCUnit.becomeWorkingCopy(null, new SubProgressMonitor(pm, 1));
75
		return super.acquireDocument(new SubProgressMonitor(pm, 1));
76
	}
77
	
78
	/**
79
	 * {@inheritDoc}
80
	 */
81
	protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException {
82
		super.releaseDocument(document, pm);
83
		try {
84
			fCUnit.discardWorkingCopy();
85
		} finally {
86
			if (!isDocumentAcquired()) {
87
				if (fCUnit.isWorkingCopy())
88
					fCUnit.reconcile(
89
							ICompilationUnit.NO_AST, 
90
							false /* don't force problem detection */, 
91
							null /* use primary owner */, 
92
							null /* no progress monitor */);
93
94
				else
95
					fCUnit.makeConsistent(pm);
96
			}
97
		}
98
	}
99
	
100
//	/**
101
//	 * {@inheritDoc}
102
//	 */
103
//	protected Change createUndoChange(UndoEdit edit, ContentStamp stampToRestore) {
104
//		try {
105
//			return new UndoCompilationUnitChange(getName(), fCUnit, edit, stampToRestore, getSaveMode());
106
//		} catch (CoreException e) {
107
//			JavaPlugin.log(e);
108
//			return null;
109
//		}
110
//	}
111
	
112
	/**
113
	 * {@inheritDoc}
114
	 */
115
	public Object getAdapter(Class adapter) {
116
		if (ICompilationUnit.class.equals(adapter))
117
			return fCUnit;
118
		return super.getAdapter(adapter);
119
	}
120
	
121
	public boolean isDestructive() {
122
		return destructive;
123
	}
124
}
125
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/AdjustSourceContainerChange.java (+100 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen.changes;
14
15
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.List;
18
19
import org.eclipse.core.resources.IContainer;
20
import org.eclipse.core.resources.IResource;
21
import org.eclipse.core.runtime.CoreException;
22
import org.eclipse.core.runtime.IProgressMonitor;
23
import org.eclipse.core.runtime.OperationCanceledException;
24
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
25
import org.eclipse.jdt.core.IClasspathEntry;
26
import org.eclipse.jdt.core.IJavaProject;
27
import org.eclipse.jdt.core.JavaCore;
28
import org.eclipse.ltk.core.refactoring.Change;
29
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
30
import org.eclipse.osgi.util.NLS;
31
32
/**
33
 * Change that transforms a folder into a source folder.
34
 * @author jcanches
35
 * @since 4.3
36
 */
37
public class AdjustSourceContainerChange extends PotentialChange {
38
39
	private IContainer container;
40
41
	public AdjustSourceContainerChange(IContainer container) {
42
		this.container = container;
43
	}
44
	
45
	public Object getModifiedElement() {
46
		return container;
47
	}
48
49
	public String getName() {
50
		return NLS.bind(CommonPluginMessages.DEFINE_SOURCE_FOLDER, container.getFullPath().toString());
51
	}
52
53
	public void initializeValidationData(IProgressMonitor pm) {
54
		// NOP
55
	}
56
57
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException,	OperationCanceledException {
58
		pm.beginTask("", 2); //$NON-NLS-1$
59
		try {
60
			RefactoringStatus status = new RefactoringStatus();
61
			if (!container.isAccessible()) {
62
				status.addFatalError(NLS.bind(CommonPluginMessages.RESOURCE_NOT_ACCESSIBLE, container.getFullPath().toString()));
63
			}
64
			pm.worked(1);
65
			IJavaProject javaProject = JavaCore.create(container.getProject());
66
			if (!javaProject.exists()) {
67
				status.addFatalError(NLS.bind(CommonPluginMessages.NOT_IN_JAVA_PROJECT, container.getFullPath().toString()));
68
			}
69
			pm.worked(1);
70
			return status;
71
		} finally {
72
			pm.done();
73
		}
74
	}
75
76
	public Change perform(IProgressMonitor monitor) throws CoreException {
77
		IJavaProject javaProject = JavaCore.create(container.getProject());
78
		if(container.getType() == IResource.FOLDER)
79
		{
80
			if(!javaProject.isOnClasspath(container))
81
			{
82
				IClasspathEntry entry = JavaCore.newSourceEntry(container.getFullPath());
83
				List entries = new ArrayList(Arrays.asList(javaProject.getRawClasspath()));
84
				entries.add(1, entry);
85
				javaProject.setRawClasspath((IClasspathEntry[])entries.toArray(new IClasspathEntry[entries.size()]), monitor);
86
			}
87
		}
88
		return null;
89
	}
90
91
	public boolean hasEffect() {
92
		IJavaProject javaProject = JavaCore.create(container.getProject());
93
		if(container.getType() == IResource.FOLDER)
94
		{
95
			return !javaProject.isOnClasspath(container);
96
		}
97
		return true;
98
	}
99
100
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/DelegateProjectDependencyUpdater.java (+52 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen;
14
15
import java.util.Collection;
16
17
import org.eclipse.core.resources.IProject;
18
import org.eclipse.core.runtime.CoreException;
19
import org.eclipse.core.runtime.IProgressMonitor;
20
21
/**
22
 * Utility dependency updater that delegates the update to a user-provided updater. Typically, a specific
23
 * type provider will implement this class and use it to wrap the user-provided dependency updater.
24
 * Mandatory dependencies can be registered in the constructor.
25
 * @author jcanches
26
 * @since 4.3
27
 */
28
public abstract class DelegateProjectDependencyUpdater implements IProjectDependencyUpdater {
29
30
	private IProjectDependencyUpdater delegate;
31
	
32
	public DelegateProjectDependencyUpdater(IProjectDependencyUpdater delegate) {
33
		this.delegate = delegate;
34
	}
35
36
	public void addRequiredPlugin(String pluginId, String jarName) {
37
		delegate.addRequiredPlugin(pluginId, jarName);
38
	}
39
40
	public void addRequiredProject(IProject project) {
41
		delegate.addRequiredProject(project);
42
	}
43
44
	public void adjustProject(IProject project, IProgressMonitor monitor) throws CoreException {
45
		delegate.adjustProject(project, monitor);
46
	}
47
48
	public Collection previewAdjustProject(IProject project) {
49
		return delegate.previewAdjustProject(project);
50
	}
51
	
52
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/ProjectAdjustChange.java (+65 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen.changes;
14
15
import org.eclipse.core.resources.IProject;
16
import org.eclipse.core.runtime.CoreException;
17
import org.eclipse.core.runtime.IProgressMonitor;
18
import org.eclipse.core.runtime.OperationCanceledException;
19
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
20
import org.eclipse.hyades.test.tools.core.internal.common.codegen.IProjectDependencyUpdater;
21
import org.eclipse.ltk.core.refactoring.Change;
22
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
23
import org.eclipse.osgi.util.NLS;
24
25
/**
26
 * Change that applies a project dependency updater on a project.
27
 * @author jcanches
28
 * @since 4.3
29
 */
30
public class ProjectAdjustChange extends Change {
31
32
	private IProject project;
33
	private IProjectDependencyUpdater updater;
34
	
35
	public ProjectAdjustChange(IProjectDependencyUpdater updater, IProject project) {
36
		this.updater = updater;
37
		this.project = project;
38
	}
39
	
40
	public Object getModifiedElement() {
41
		return project;
42
	}
43
44
	public String getName() {
45
		return NLS.bind(CommonPluginMessages.ADJUST_CLASSPATH, project.getName());
46
	}
47
48
	public void initializeValidationData(IProgressMonitor pm) {
49
		// NOP
50
	}
51
52
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException {
53
		RefactoringStatus status = new RefactoringStatus();
54
		if (!project.isAccessible()) {
55
			status.addFatalError(NLS.bind(CommonPluginMessages.PROJECT_NOT_ACCESSIBLE, project.getName()));
56
		}
57
		return status;
58
	}
59
60
	public Change perform(IProgressMonitor monitor) throws CoreException {
61
		updater.adjustProject(project, monitor);
62
		return null;
63
	}
64
65
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/CreatePackageFragmentChange.java (+71 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen.changes;
14
15
import org.eclipse.core.resources.IResource;
16
import org.eclipse.core.runtime.CoreException;
17
import org.eclipse.core.runtime.IProgressMonitor;
18
import org.eclipse.core.runtime.OperationCanceledException;
19
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
20
import org.eclipse.jdt.core.IPackageFragmentRoot;
21
import org.eclipse.ltk.core.refactoring.Change;
22
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
23
import org.eclipse.osgi.util.NLS;
24
25
/**
26
 * Change that creates a java package.
27
 * @author jcanches
28
 * @since 4.3
29
 */
30
public class CreatePackageFragmentChange extends PotentialChange {
31
32
	private IPackageFragmentRoot sourceFolder;
33
	private String packageName;
34
35
	public CreatePackageFragmentChange(IPackageFragmentRoot sourceFolder, String packageName) {
36
		this.sourceFolder = sourceFolder;
37
		this.packageName = packageName;
38
	}
39
	
40
	public boolean hasEffect() {
41
		return !sourceFolder.getPackageFragment(packageName).exists();
42
	}
43
44
	public Object getModifiedElement() {
45
		return sourceFolder;
46
	}
47
48
	public String getName() {
49
		return NLS.bind(CommonPluginMessages.CREATE_PACKAGE, packageName); 
50
	}
51
52
	public void initializeValidationData(IProgressMonitor monitor) {
53
		// NOP
54
	}
55
56
	public RefactoringStatus isValid(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
57
		RefactoringStatus status = new RefactoringStatus();
58
		if (!sourceFolder.exists()) {
59
			status.addFatalError(CommonPluginMessages.NO_SOURCE_FOLDER);
60
		} else if (sourceFolder.getResource().getType() != IResource.FOLDER) {
61
			status.addFatalError(CommonPluginMessages.NOT_A_SOURCE_FOLDER);
62
		}
63
		return status;
64
	}
65
66
	public Change perform(IProgressMonitor monitor) throws CoreException {
67
		sourceFolder.createPackageFragment(packageName, true, monitor);
68
		return null;
69
	}
70
71
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/ASTHelper.java (+326 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen;
14
15
import java.util.Iterator;
16
17
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper.LineIterator;
18
import org.eclipse.jdt.core.IMethod;
19
import org.eclipse.jdt.core.JavaModelException;
20
import org.eclipse.jdt.core.dom.AST;
21
import org.eclipse.jdt.core.dom.ASTMatcher;
22
import org.eclipse.jdt.core.dom.ASTNode;
23
import org.eclipse.jdt.core.dom.ASTParser;
24
import org.eclipse.jdt.core.dom.ASTVisitor;
25
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
26
import org.eclipse.jdt.core.dom.BodyDeclaration;
27
import org.eclipse.jdt.core.dom.CompilationUnit;
28
import org.eclipse.jdt.core.dom.ImportDeclaration;
29
import org.eclipse.jdt.core.dom.Javadoc;
30
import org.eclipse.jdt.core.dom.MemberRef;
31
import org.eclipse.jdt.core.dom.MethodDeclaration;
32
import org.eclipse.jdt.core.dom.MethodRef;
33
import org.eclipse.jdt.core.dom.MethodRefParameter;
34
import org.eclipse.jdt.core.dom.Modifier;
35
import org.eclipse.jdt.core.dom.Name;
36
import org.eclipse.jdt.core.dom.QualifiedName;
37
import org.eclipse.jdt.core.dom.SimpleName;
38
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
39
import org.eclipse.jdt.core.dom.TagElement;
40
import org.eclipse.jdt.core.dom.TextElement;
41
import org.eclipse.jdt.core.dom.TypeDeclaration;
42
43
/**
44
 * Utilities for manipulating AST trees.
45
 * @author jcanches
46
 * @since 4.3
47
 */
48
public class ASTHelper {
49
50
	/**
51
	 * Resolves a name to a qualified name, in the context of a given compilation unit,
52
	 * by looking at the imports.
53
	 */
54
	public static Name resolveName(CompilationUnit cu, Name name) {
55
		if (name.isSimpleName()) {
56
			SimpleName simpleName = (SimpleName)name;
57
			Iterator it = cu.imports().iterator();
58
			while (it.hasNext()) {
59
				ImportDeclaration id = (ImportDeclaration) it.next();
60
				if (matchName(simpleName, id.getName())) return id.getName(); 
61
			}
62
			return null;
63
		}
64
		return name;
65
	}
66
67
	private static boolean matchName(SimpleName simple, Name complete) {
68
		SimpleName unqualifiedName = null;
69
		if (complete.isSimpleName()) {
70
			unqualifiedName = (SimpleName)complete;
71
		}
72
		if (complete.isQualifiedName()) {
73
			QualifiedName qn = (QualifiedName) complete;
74
			unqualifiedName = qn.getName();
75
		}
76
		if (unqualifiedName != null) {
77
			return simple.getIdentifier().equals(unqualifiedName.getIdentifier());
78
		}
79
		return false;
80
	}
81
	
82
	/**
83
	 * Determines whether a compilation unit has a given import.
84
	 */
85
	public static boolean hasImport(CompilationUnit cu, String qualifiedName) {
86
		for (Iterator it = cu.imports().iterator(); it.hasNext();) {
87
			ImportDeclaration id = (ImportDeclaration)it.next();
88
			if (qualifiedName.equals(id.getName().getFullyQualifiedName())) {
89
				return true;
90
			}
91
		}
92
		return false;
93
	}
94
	
95
	/**
96
	 * Parses a method declaration and returns the resulting AST element.
97
	 * @param ast The AST that the result must belong to.
98
	 * @param methodDeclaration A method declaration (as a string).
99
	 * @return An AST MethodDeclaration object.
100
	 */
101
	public static MethodDeclaration parseMethod(AST ast, String methodDeclaration) {
102
		ASTParser parser = ASTParser.newParser(ast.apiLevel());
103
		parser.setSource(methodDeclaration.toCharArray());
104
		parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
105
		TypeDeclaration localType = (TypeDeclaration) parser.createAST(/*progress monitor*/null);
106
		MethodDeclaration method = (MethodDeclaration) localType.bodyDeclarations().get(0);
107
		// The resulting method must be cloned to the proper AST owner
108
		return (MethodDeclaration) ASTNode.copySubtree(ast, method);
109
	}
110
	
111
	/**
112
	 * Returns the method with 0 parameters matching the given name in the given type.
113
	 * @param type
114
	 * @param name
115
	 * @return
116
	 */
117
	public static MethodDeclaration findMethodWithNoParameter(TypeDeclaration type, String name) {
118
		MethodDeclaration[] methods = type.getMethods();
119
		for (int i = 0; i < methods.length; i++) {
120
			if (name.equals(methods[i].getName().getIdentifier()) && methods[i].parameters().isEmpty()) {
121
				return methods[i];
122
			}
123
		}
124
		return null;
125
	}
126
	
127
	/**
128
	 * Returns the method matching the name and the parameter types of a pattern.
129
	 * Return type, nor parameter names are taken into account.
130
	 * @param type The type where method is searched
131
	 * @param pattern A pattern. Only method name, and parameters types are taken into account.
132
	 * @return The method within <code>type</code> that matches pattern, or <code>null</code>
133
	 * if not found.
134
	 */
135
	public static MethodDeclaration findMethod(TypeDeclaration type, MethodDeclaration pattern) {
136
		MethodDeclaration[] methods = type.getMethods();
137
		for (int i = 0; i < methods.length; i++) {
138
			if (pattern.getName().getIdentifier().equals(methods[i].getName().getIdentifier()) && pattern.parameters().size() == methods[i].parameters().size()) {
139
				// Same name, same number of formal parameters:
140
				for (Iterator it1 = pattern.parameters().iterator(),
141
					          it2 = methods[i].parameters().iterator(); it1.hasNext();) {
142
					SingleVariableDeclaration patDecl = (SingleVariableDeclaration)it1.next();
143
					SingleVariableDeclaration matDecl = (SingleVariableDeclaration)it2.next();
144
					if (!patDecl.getType().subtreeMatch(new ASTMatcher(), matDecl.getType())) {
145
						break;
146
					}
147
				}
148
				return methods[i];
149
			}
150
		}
151
		return null;
152
	}
153
	
154
	/**
155
	 * Returns the index, among all the type members, of the first method within a
156
	 * type declaration.
157
	 * @param type A type declaration.
158
	 * @return The index of the first method, or -1 if there is no method within <code>type</code>.
159
	 */
160
	public static int getFirstMethodIndex(TypeDeclaration type) {
161
		int cpt;
162
		Iterator it;
163
		for (cpt = 0, it = type.bodyDeclarations().iterator(); it.hasNext(); cpt++) {
164
			BodyDeclaration bd = (BodyDeclaration)it.next();
165
			if (bd instanceof MethodDeclaration) {
166
				return cpt;
167
			}
168
		}
169
		return -1;
170
	}
171
	
172
	/**
173
	 * Returns the only public, first-level type declaration found in a compilation unit.
174
	 * @param cu A Compilation Unit.
175
	 * @return The "main" type, or <code>null</code> if no such type exists.
176
	 */
177
	public static TypeDeclaration getMainType(CompilationUnit cu) {
178
		for (Iterator it = cu.types().iterator(); it.hasNext(); ) {
179
			AbstractTypeDeclaration atd = (AbstractTypeDeclaration)it.next();
180
			if (atd.isPackageMemberTypeDeclaration()
181
				&& (atd.getModifiers() & Modifier.PUBLIC) != 0
182
				&& atd instanceof TypeDeclaration) {
183
				return (TypeDeclaration)atd;
184
			}
185
		}
186
		return null;
187
	}
188
	
189
	private static TagElement getJavadocDescription (String methodSource) {
190
		ASTParser parser = ASTParser.newParser(AST.JLS3);
191
		parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
192
		parser.setSource(methodSource.toCharArray());
193
		TypeDeclaration type = (TypeDeclaration) parser.createAST(null);
194
		MethodDeclaration md = (MethodDeclaration) type.bodyDeclarations().get(0);
195
		Javadoc javadoc = md.getJavadoc();
196
		if (javadoc != null && javadoc.tags().size() > 0) {
197
			TagElement tag = (TagElement) javadoc.tags().get(0);
198
			if (tag.getTagName() == null) {
199
				return tag;
200
			}
201
		}
202
		return null;
203
	}
204
	
205
	public static TagElement getJavadocDescription(IMethod method) throws JavaModelException {
206
		return getJavadocDescription(method.getSource());
207
	}
208
	
209
	public static TagElement parseJavadocDescription(AST ast, String javadoc) {
210
		String input = "/**" + javadoc + "*/void f(){}"; //$NON-NLS-1$ //$NON-NLS-2$
211
		TagElement tag = getJavadocDescription(input);
212
		return (TagElement)ASTNode.copySubtree(ast, tag);
213
	}
214
	
215
	public static boolean compareJavadocDescriptions(TagElement tag1, TagElement tag2) {
216
		return (tag1 == null && tag2 == null)
217
			|| (tag1 != null && tag1.subtreeMatch(new ASTMatcher(true), tag2));
218
	}
219
	
220
	public static String extractDescription(TagElement tag) {
221
		JavatagFlattener flattener = new JavatagFlattener();
222
		tag.accept(flattener);
223
		return flattener.getResult();
224
	}
225
	
226
	static class JavatagFlattener extends ASTVisitor {
227
228
		private StringBuffer buf = new StringBuffer();
229
		
230
		public String getResult() {
231
			return buf.toString();
232
		}
233
		
234
		public boolean visit(MemberRef node) {
235
			if (node.getQualifier() != null) {
236
				node.getQualifier().accept(this);
237
			}
238
			buf.append("#");//$NON-NLS-1$
239
			node.getName().accept(this);
240
			return false;
241
		}
242
243
		public boolean visit(MethodRef node) {
244
			if (node.getQualifier() != null) {
245
				node.getQualifier().accept(this);
246
			}
247
			buf.append("#");//$NON-NLS-1$
248
			node.getName().accept(this);
249
			buf.append("(");//$NON-NLS-1$
250
			for (Iterator it = node.parameters().iterator(); it.hasNext(); ) {
251
				MethodRefParameter e = (MethodRefParameter) it.next();
252
				e.accept(this);
253
				if (it.hasNext()) {
254
					buf.append(",");//$NON-NLS-1$
255
				}
256
			}
257
			buf.append(")");//$NON-NLS-1$
258
			return false;
259
		}
260
261
		public boolean visit(SimpleName node) {
262
			buf.append(node.getIdentifier());
263
			return false;
264
		}
265
		
266
		public boolean visit(QualifiedName node) {
267
			node.getQualifier().accept(this);
268
			buf.append(".");//$NON-NLS-1$
269
			node.getName().accept(this);
270
			return false;
271
		}
272
273
		public boolean visit(TagElement node) {
274
			if (node.isNested()) {
275
				// nested tags are always enclosed in braces
276
				buf.append("{");//$NON-NLS-1$
277
			}
278
			boolean previousRequiresWhiteSpace = false;
279
			if (node.getTagName() != null) {
280
				buf.append(node.getTagName());
281
				previousRequiresWhiteSpace = true;
282
			}
283
			boolean previousRequiresNewLine = false;
284
			for (Iterator it = node.fragments().iterator(); it.hasNext(); ) {
285
				ASTNode e = (ASTNode) it.next();
286
				// assume text elements include necessary leading and trailing whitespace
287
				// but Name, MemberRef, MethodRef, and nested TagElement do not include white space
288
				boolean currentIncludesWhiteSpace = (e instanceof TextElement);
289
				if (previousRequiresNewLine && currentIncludesWhiteSpace) {
290
					buf.append("\n");//$NON-NLS-1$
291
				}
292
				previousRequiresNewLine = currentIncludesWhiteSpace;
293
				// add space if required to separate
294
				if (previousRequiresWhiteSpace && !currentIncludesWhiteSpace) {
295
					buf.append(" "); //$NON-NLS-1$
296
				}
297
				e.accept(this);
298
				previousRequiresWhiteSpace = !currentIncludesWhiteSpace && !(e instanceof TagElement);
299
			}
300
			if (node.isNested()) {
301
				buf.append("}");//$NON-NLS-1$
302
			}
303
			return false;
304
		}
305
306
		public boolean visit(TextElement node) {
307
			buf.append(node.getText());
308
			return false;
309
		}
310
		
311
	}
312
313
	public static void addDescriptionToJavadoc(Javadoc javadoc, String string) {
314
		LineIterator it = new Helper.LineIterator(string, " \t"); //$NON-NLS-1$
315
		int idx = 0;
316
		while(it.hasNextLine()) {
317
			TagElement tag = javadoc.getAST().newTagElement();
318
			TextElement text = javadoc.getAST().newTextElement();
319
			text.setText(it.getNextLine());
320
			tag.fragments().add(text);
321
			javadoc.tags().add(idx++, tag);
322
		}
323
		
324
	}
325
	
326
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/PotentialChange.java (+33 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen.changes;
14
15
import org.eclipse.ltk.core.refactoring.Change;
16
import org.eclipse.ltk.core.refactoring.NullChange;
17
18
/**
19
 * Change that may be a NO-OP.
20
 * @author jcanches
21
 * @since 4.3
22
 */
23
public abstract class PotentialChange extends Change {
24
25
	/**
26
	 * Determines if the change would have any real effect, if it was applied.
27
	 * If the method returns <code>false</code>, then the effect of the change is
28
	 * equivalent to {@link NullChange}.
29
	 * @return <code>true</code> if and only if applying the change have a real effect.
30
	 */
31
	public abstract boolean hasEffect();
32
	
33
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/AssociateModelSourceChange.java (+114 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen.changes;
14
15
import org.eclipse.core.resources.IFile;
16
import org.eclipse.core.runtime.CoreException;
17
import org.eclipse.core.runtime.IProgressMonitor;
18
import org.eclipse.core.runtime.OperationCanceledException;
19
import org.eclipse.emf.ecore.EObject;
20
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
21
import org.eclipse.hyades.test.core.util.EMFUtil;
22
import org.eclipse.hyades.test.tools.core.CorePlugin;
23
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
24
import org.eclipse.hyades.test.tools.core.internal.java.modelsync.JUnitModelUpdater;
25
import org.eclipse.hyades.test.tools.core.internal.java.modelsync.JUnitProjectBuilder;
26
import org.eclipse.ltk.core.refactoring.Change;
27
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
28
import org.eclipse.osgi.util.NLS;
29
30
/**
31
 * Change that adds a JUnit association from a java file to a test suite model.
32
 * @author jcanches
33
 * @since 4.3
34
 */
35
public class AssociateModelSourceChange extends PotentialChange {
36
	
37
	private IFile javaFile;
38
	private ITestSuite testSuite;
39
	
40
	/**
41
	 * @param javaFile
42
	 * @param testSuite
43
	 */
44
	public AssociateModelSourceChange(IFile javaFile, ITestSuite testSuite) {
45
		this.javaFile = javaFile;
46
		this.testSuite = testSuite;
47
	}
48
49
	public Object getModifiedElement() {
50
		return javaFile;
51
	}
52
53
	public String getName() {
54
		return NLS.bind(CommonPluginMessages.ASSOCIATE_TEST_TO_SOURCE, new Object[] { testSuite.getName(), javaFile.getFullPath().toString() });
55
	}
56
57
	public void initializeValidationData(IProgressMonitor pm) {
58
		// NOP
59
	}
60
61
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException,	OperationCanceledException {
62
		return new RefactoringStatus();
63
	}
64
65
	public Change perform(IProgressMonitor pm) throws CoreException {
66
		pm.beginTask("", 3); //$NON-NLS-1$
67
		try {
68
			if (testSuite instanceof EObject) {
69
				EObject eObject = (EObject) testSuite;
70
				IFile testSuiteFile = EMFUtil.getWorkspaceFile(eObject);
71
				if (testSuiteFile != null && testSuiteFile.exists()) {
72
					// Add the Junit builder to the file's project (if not already installed)
73
					JUnitProjectBuilder.installBuilder(javaFile.getProject());
74
					pm.worked(1);
75
					// Also add the JUnit builder to the test suite's project (the source file
76
					// and the test suite usually are under the same project, but this is not
77
					// mandatory).
78
					JUnitProjectBuilder.installBuilder(testSuiteFile.getProject());
79
					pm.worked(1);
80
					// Record the link from the java file to the testsuite file
81
					JUnitModelUpdater.associateTestSuiteToJUnitSourceFile(javaFile, testSuiteFile);
82
					pm.worked(1);
83
				}
84
			}
85
		} catch (Throwable t) {
86
			CorePlugin.logError(t);
87
		} finally {
88
			pm.done();
89
		}
90
		return null;
91
	}
92
93
	public boolean hasEffect() {
94
		if (!javaFile.exists()) return true;
95
		try {
96
			if (!JUnitProjectBuilder.isBuilderInstalled(javaFile.getProject())) return true;
97
			if (testSuite instanceof EObject) {
98
				EObject eObject = (EObject) testSuite;
99
				IFile testSuiteFile = EMFUtil.getWorkspaceFile(eObject);
100
				if (testSuiteFile != null && testSuiteFile.exists()) {
101
					if (!JUnitProjectBuilder.isBuilderInstalled(testSuiteFile.getProject())) return true;
102
				}
103
				IFile registeredTestSuiteFile = JUnitModelUpdater.getRegisteredTestSuiteFile(javaFile);
104
				if (registeredTestSuiteFile == null || !registeredTestSuiteFile.equals(testSuiteFile)) return true;
105
				return false;
106
			}
107
			return true;
108
		} catch (CoreException e) {
109
			CorePlugin.logError(e);
110
			return false;
111
		}
112
	}
113
114
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/DeleteFileChange.java (+124 lines)
Added Link Here
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.hyades.test.tools.core.internal.common.codegen.changes;
12
import java.io.BufferedReader;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.InputStreamReader;
16
17
import org.eclipse.core.resources.IFile;
18
import org.eclipse.core.runtime.Assert;
19
import org.eclipse.core.runtime.CoreException;
20
import org.eclipse.core.runtime.IProgressMonitor;
21
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
22
import org.eclipse.jdt.core.IJavaModelStatusConstants;
23
import org.eclipse.jdt.core.JavaModelException;
24
import org.eclipse.ltk.core.refactoring.Change;
25
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
26
import org.eclipse.osgi.util.NLS;
27
28
/**
29
 * Change that deletes an existing file.
30
 * @author jcanches
31
 * @since 4.3
32
 */
33
public class DeleteFileChange extends Change {
34
35
	private IFile file;
36
	private String fSource;
37
	
38
	public DeleteFileChange(IFile file){
39
		Assert.isNotNull(file, "file"); //$NON-NLS-1$
40
		this.file = file;
41
	}
42
	
43
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
44
		RefactoringStatus status = new RefactoringStatus();
45
		if (!file.exists()) {
46
			status.addError(CommonPluginMessages.NO_FILE);
47
		}
48
		if (file.isReadOnly()) {
49
			status.addWarning(CommonPluginMessages.READ_ONLY_FILE);
50
		}
51
		return status;
52
	}
53
	
54
	public Change perform(IProgressMonitor pm) throws CoreException {
55
		try {
56
			pm.beginTask(CommonPluginMessages.DELETING_FILE, 1); 
57
			Assert.isNotNull(file);
58
			Assert.isTrue(file.exists());
59
			fSource= getSource(file);
60
			CreateFileChange undo= createUndoChange(file, file.getModificationStamp(), fSource);
61
			file.delete(true, true, pm);
62
			return undo;
63
		} finally {
64
			pm.done();
65
		}
66
	}
67
	
68
	private String getSource(IFile file) throws CoreException {
69
		String encoding= null;
70
		try {
71
			encoding= file.getCharset();
72
		} catch (CoreException ex) {
73
			// fall through. Take default encoding.
74
		}
75
		
76
		StringBuffer sb= new StringBuffer();
77
		BufferedReader br= null;
78
		InputStream in= null;
79
		try {
80
			in= file.getContents();
81
		    if (encoding != null)
82
		        br= new BufferedReader(new InputStreamReader(in, encoding));	
83
		    else
84
		        br= new BufferedReader(new InputStreamReader(in));	
85
			int read= 0;
86
			while ((read= br.read()) != -1)
87
				sb.append((char) read);
88
		} catch (IOException e){
89
			throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
90
		} finally {
91
			try{
92
				if (br != null) br.close();
93
				if (in != null) in.close();
94
			} catch (IOException e){
95
				throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
96
			}	
97
		}
98
		return sb.toString();
99
	}
100
	
101
	private static CreateFileChange createUndoChange(IFile file, long stampToRestore, String source) {
102
		String encoding;
103
		try {
104
			encoding= file.getCharset(false);
105
		} catch (CoreException e) {
106
			encoding= null;
107
		}
108
		return new CreateFileChange(file, source, encoding, stampToRestore);
109
	}
110
111
	public String getName() {
112
		return NLS.bind(CommonPluginMessages.DELETE_FILE, file.getFullPath().toString()); 
113
	}
114
115
	public Object getModifiedElement() {
116
		return file;
117
	}
118
119
	public void initializeValidationData(IProgressMonitor pm) {
120
		// TODO Auto-generated method stub
121
		
122
	}
123
}
124
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/CreateFileChange.java (+178 lines)
Added Link Here
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.hyades.test.tools.core.internal.common.codegen.changes;
12
13
import java.io.ByteArrayInputStream;
14
import java.io.IOException;
15
import java.io.InputStream;
16
import java.io.UnsupportedEncodingException;
17
import java.net.URI;
18
19
import org.eclipse.core.resources.IFile;
20
import org.eclipse.core.resources.IResource;
21
import org.eclipse.core.resources.ResourcesPlugin;
22
import org.eclipse.core.runtime.Assert;
23
import org.eclipse.core.runtime.CoreException;
24
import org.eclipse.core.runtime.IProgressMonitor;
25
import org.eclipse.core.runtime.SubProgressMonitor;
26
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
27
import org.eclipse.jdt.core.IJavaModelStatusConstants;
28
import org.eclipse.jdt.core.JavaModelException;
29
import org.eclipse.ltk.core.refactoring.Change;
30
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
31
import org.eclipse.osgi.util.NLS;
32
33
/**
34
 * Change that creates a text file and fills it in with an initial content.
35
 * @author jcanches
36
 * @since 4.3
37
 */
38
public class CreateFileChange extends Change {
39
40
	private IFile fFile;
41
	private String fSource;
42
	private String fEncoding;
43
	private boolean fExplicitEncoding;
44
	private long fStampToRestore;
45
46
	public CreateFileChange(IFile file, String source, String encoding) {
47
		this(file, source, encoding, IResource.NULL_STAMP);
48
	}
49
50
	public CreateFileChange(IFile file, String source, String encoding, long stampToRestore) {
51
		Assert.isNotNull(file, "file"); //$NON-NLS-1$
52
		Assert.isNotNull(source, "source"); //$NON-NLS-1$
53
		fFile = file;
54
		fSource= source;
55
		fEncoding= encoding;
56
		fExplicitEncoding= fEncoding != null;
57
		fStampToRestore= stampToRestore;
58
	}
59
60
	protected void setEncoding(String encoding, boolean explicit) {
61
		Assert.isNotNull(encoding, "encoding"); //$NON-NLS-1$
62
		fEncoding= encoding;
63
		fExplicitEncoding= explicit;
64
	}
65
66
	public String getName() {
67
		return NLS.bind(CommonPluginMessages.GENERATE_FILE, fFile.getFullPath().toString());
68
	}
69
70
	protected void setSource(String source) {
71
		fSource= source;
72
	}
73
74
	protected String getSource() {
75
		return fSource;
76
	}
77
78
	protected IFile getFile() {
79
		return fFile;
80
	}
81
82
	public Object getModifiedElement() {
83
		return fFile;
84
	}
85
86
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
87
		RefactoringStatus status = new RefactoringStatus();
88
		
89
		URI location = fFile.getLocationURI();
90
		if (location == null) {
91
			status.addFatalError(NLS.bind(CommonPluginMessages.UNKNOWN_LOCATION, fFile.getFullPath().toString()));
92
			return status;
93
		}
94
		
95
//		IFileInfo jFile= EFS.getStore(location).fetchInfo();
96
//		if (jFile.exists()) {
97
//			status.addFatalError(Messages.format(
98
//				NLSChangesMessages.CreateFileChange_error_exists, 
99
//				file.getFullPath().toString()));
100
//			return status;
101
//		}
102
		return status;
103
	}
104
105
	public Change perform(IProgressMonitor pm) throws CoreException {
106
107
		InputStream is= null;
108
		try {
109
			pm.beginTask(CommonPluginMessages.GENERATING_FILE, 2); 
110
111
			initializeEncoding();
112
			/*
113
			if (file.exists()) {
114
				CompositeChange composite= new CompositeChange(getName());
115
				composite.add(new DeleteFileChange(file));
116
				composite.add(new CreateFileChange(fPath, fSource, fEncoding, fStampToRestore, fExplicitEncoding));
117
				pm.worked(1);
118
				return composite.perform(new SubProgressMonitor(pm, 1));
119
			} else { */
120
			try {
121
				is= new ByteArrayInputStream(fSource.getBytes(fEncoding));
122
				fFile.create(is, false, new SubProgressMonitor(pm, 1));
123
				if (fStampToRestore != IResource.NULL_STAMP) {
124
					fFile.revertModificationStamp(fStampToRestore);
125
				}
126
				if (fExplicitEncoding) {
127
					fFile.setCharset(fEncoding, new SubProgressMonitor(pm, 1));
128
				} else {
129
					pm.worked(1);
130
				}
131
				return new DeleteFileChange(fFile);
132
			} catch (UnsupportedEncodingException e) {
133
				throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
134
			}
135
		} finally {
136
			try {
137
				if (is != null)
138
					is.close();
139
			} catch (IOException ioe) {
140
				throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
141
			} finally {
142
				pm.done();
143
			}
144
		}
145
	}
146
147
	private void initializeEncoding() {
148
		if (fEncoding == null) {
149
			fExplicitEncoding= false;
150
			if (fFile != null) {
151
				try {
152
					if (fFile.exists()) {
153
						fEncoding= fFile .getCharset(false);
154
						if (fEncoding == null) {
155
							fEncoding= fFile.getCharset(true);
156
						} else {
157
							fExplicitEncoding= true;
158
						}
159
					} else {
160
						fEncoding= fFile.getCharset(true);
161
					}
162
				} catch (CoreException e) {
163
					fEncoding= ResourcesPlugin.getEncoding();
164
					fExplicitEncoding= true;
165
				}
166
			} else {
167
				fEncoding= ResourcesPlugin.getEncoding();
168
				fExplicitEncoding= true;
169
			}
170
		}
171
		Assert.isNotNull(fEncoding);
172
	}
173
174
	public void initializeValidationData(IProgressMonitor pm) {
175
		// TODO Auto-generated method stub
176
		
177
	}
178
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/CreateContainerChange.java (+63 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.core.internal.common.codegen.changes;
14
15
import org.eclipse.core.resources.IContainer;
16
import org.eclipse.core.runtime.CoreException;
17
import org.eclipse.core.runtime.IProgressMonitor;
18
import org.eclipse.core.runtime.OperationCanceledException;
19
import org.eclipse.hyades.models.common.util.ResourceUtil;
20
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
21
import org.eclipse.ltk.core.refactoring.Change;
22
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
23
import org.eclipse.osgi.util.NLS;
24
25
/**
26
 * Change that creates a container.
27
 * @author jcanches
28
 * @since 4.3
29
 */
30
public class CreateContainerChange extends PotentialChange {
31
32
	private IContainer container;
33
34
	public CreateContainerChange(IContainer container) {
35
		this.container = container;
36
	}
37
	
38
	public Object getModifiedElement() {
39
		return container;
40
	}
41
42
	public String getName() {
43
		return NLS.bind(CommonPluginMessages.CREATE_CONTAINER, container.getFullPath().toString());
44
	}
45
46
	public void initializeValidationData(IProgressMonitor pm) {
47
		// NOP
48
	}
49
50
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException,	OperationCanceledException {
51
		return new RefactoringStatus();
52
	}
53
54
	public Change perform(IProgressMonitor monitor) throws CoreException {
55
		ResourceUtil.createContainer(container, monitor);
56
		return null;
57
	}
58
59
	public boolean hasEffect() {
60
		return !container.isAccessible();
61
	}
62
63
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/editor/JUnitEditorExtension.java (-16 / +72 lines)
Lines 13-30 Link Here
13
13
14
import org.eclipse.core.resources.IResource;
14
import org.eclipse.core.resources.IResource;
15
import org.eclipse.core.resources.ResourcesPlugin;
15
import org.eclipse.core.resources.ResourcesPlugin;
16
import org.eclipse.core.runtime.CoreException;
16
import org.eclipse.core.runtime.IProgressMonitor;
17
import org.eclipse.core.runtime.IProgressMonitor;
17
import org.eclipse.core.runtime.IStatus;
18
import org.eclipse.core.runtime.IStatus;
19
import org.eclipse.core.runtime.NullProgressMonitor;
20
import org.eclipse.core.runtime.OperationCanceledException;
18
import org.eclipse.core.runtime.Path;
21
import org.eclipse.core.runtime.Path;
22
import org.eclipse.core.runtime.Preferences;
19
import org.eclipse.core.runtime.SubProgressMonitor;
23
import org.eclipse.core.runtime.SubProgressMonitor;
20
import org.eclipse.hyades.test.tools.core.CorePlugin;
24
import org.eclipse.hyades.test.tools.core.CorePlugin;
21
import org.eclipse.hyades.test.tools.core.internal.common.codegen.AutomaticDependencyUpdater;
25
import org.eclipse.hyades.test.tools.core.internal.common.codegen.AutomaticDependencyUpdater;
26
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
22
import org.eclipse.hyades.test.tools.core.internal.common.codegen.IProjectDependencyUpdater;
27
import org.eclipse.hyades.test.tools.core.internal.common.codegen.IProjectDependencyUpdater;
23
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
28
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
24
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
29
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
25
import org.eclipse.hyades.test.tools.ui.common.internal.editor.TestSuiteEditorExtension;
30
import org.eclipse.hyades.test.tools.ui.common.internal.editor.TestSuiteEditorExtension;
31
import org.eclipse.hyades.test.tools.ui.java.internal.junit.preferences.JUnitPreferences;
32
import org.eclipse.hyades.test.tools.ui.java.internal.junit.wizard.UpdateCodeWizard;
26
import org.eclipse.hyades.test.ui.editor.form.util.WidgetFactory;
33
import org.eclipse.hyades.test.ui.editor.form.util.WidgetFactory;
27
import org.eclipse.hyades.ui.editor.IHyadesEditorPart;
34
import org.eclipse.hyades.ui.editor.IHyadesEditorPart;
35
import org.eclipse.jface.dialogs.IDialogConstants;
36
import org.eclipse.ltk.core.refactoring.Change;
37
import org.eclipse.ltk.core.refactoring.Refactoring;
38
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
39
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
40
import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
28
import org.eclipse.swt.widgets.MessageBox;
41
import org.eclipse.swt.widgets.MessageBox;
29
42
30
/**
43
/**
Lines 86-92 Link Here
86
	protected void displayCodeGenerationProblem(String message) {
99
	protected void displayCodeGenerationProblem(String message) {
87
		MessageBox box = new MessageBox(
100
		MessageBox box = new MessageBox(
88
				getHyadesEditorPart().getEditorPart().getSite().getShell());
101
				getHyadesEditorPart().getEditorPart().getSite().getShell());
89
		box.setText("Code Generator");
102
		box.setText(ToolsUiPlugin.getString("CODE_UPDATE")); //$NON-NLS-1$
90
		box.setMessage(message);
103
		box.setMessage(message);
91
		box.open();
104
		box.open();
92
	}
105
	}
Lines 99-105 Link Here
99
		try {
112
		try {
100
			// Instantiate our generator
113
			// Instantiate our generator
101
			IProjectDependencyUpdater pUpdater = new AutomaticDependencyUpdater();
114
			IProjectDependencyUpdater pUpdater = new AutomaticDependencyUpdater();
102
			JUnitGenerator generator = new JUnitGenerator(pUpdater);
115
			JUnitGenerator generator = new JUnitGenerator(getTestSuite(), pUpdater);
103
			// bugzilla 104343: Evaluate whether the project/source folder of the
116
			// bugzilla 104343: Evaluate whether the project/source folder of the
104
			// test suite exist. We never force a project or source folder creation.
117
			// test suite exist. We never force a project or source folder creation.
105
			IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(
118
			IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(
Lines 111-131 Link Here
111
				// (e.g. importing or checking out the project from CVS).
124
				// (e.g. importing or checking out the project from CVS).
112
				displayCodeGenerationProblem(ToolsUiPlugin.getString("EDT_JUNIT_MSSING_SRCFOLDER", getTestSuite().getImplementor().getLocation())); //$NON-NLS-1$
125
				displayCodeGenerationProblem(ToolsUiPlugin.getString("EDT_JUNIT_MSSING_SRCFOLDER", getTestSuite().getImplementor().getLocation())); //$NON-NLS-1$
113
			} else {
126
			} else {
114
				// Before generating, check that everything is OK
127
				// Generate the code (this operation may modify the test suite model)
115
				IStatus status = generator.validate(getTestSuite());
128
				if (!performChange(generator)) {
116
				if (status.getSeverity() == IStatus.ERROR) {
129
					throw new OperationCanceledException();
117
					// Something wrong: display a message and don't generate
118
					displayCodeGenerationProblem(status.getMessage());
119
				} else {
120
					// Make sure the classpath contains the required libraries
121
					if (!getTestSuite().getImplementor().isExternalImplementor()) {
122
						pUpdater.addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
123
						pUpdater.addRequiredPlugin(CorePlugin.getID(), "java.runner.jar"); //$NON-NLS-1$
124
					}
125
					pUpdater.addRequiredPlugin("org.junit", "junit.jar"); //$NON-NLS-1$ //$NON-NLS-2$
126
					// Generate the code (this operation may modify the test suite model)
127
					generator.generate(getTestSuite(), new SubProgressMonitor(monitor, 1));
128
				}
130
				}
131
				((JUnitForm)getTestSuiteForm()).reloadSourceInfo();
129
			}
132
			}
130
			// Perform the save
133
			// Perform the save
131
			super.save(new SubProgressMonitor(monitor, 1));
134
			super.save(new SubProgressMonitor(monitor, 1));
Lines 133-136 Link Here
133
			monitor.done();
136
			monitor.done();
134
		}
137
		}
135
	}
138
	}
139
140
	private boolean performBatchChange(Change change) {
141
		try {
142
			change.initializeValidationData(new NullProgressMonitor());
143
			if (change.isValid(new NullProgressMonitor()).isOK()) {
144
				change.perform(new NullProgressMonitor());
145
				return true;
146
			}
147
			return false;
148
		} catch (OperationCanceledException e) {
149
			return false;
150
		} catch (CoreException e) {
151
			ToolsUiPlugin.logError(e);
152
			return false;
153
		}
154
	}
155
	
156
	protected boolean performChange(Refactoring refactoring) {
157
		Preferences prefs = ToolsUiPlugin.getDefault().getPluginPreferences();
158
		int previewPref = prefs.getInt(JUnitPreferences.UPDATE_PREVIEW_MODE);
159
		boolean showWizard = previewPref != JUnitPreferences.PREVIEW_NEVER;
160
		Change change = null;
161
		try {
162
			RefactoringStatus status = refactoring.checkAllConditions(new NullProgressMonitor());
163
			if (status.hasEntries()) {
164
				// If there's something that the user should be aware of, always show the
165
				// preview.
166
				showWizard = true;
167
			} else {
168
				change = refactoring.createChange(new NullProgressMonitor());
169
				if (previewPref == JUnitPreferences.PREVIEW_IF_DESTRUCTIVE && !Helper.isDestructiveChange(change)) {
170
					showWizard = false;
171
				}
172
			}
173
		} catch (OperationCanceledException e1) {
174
			return false;
175
		} catch (CoreException e1) {
176
			ToolsUiPlugin.logError(e1);
177
			return false;
178
		}
179
		if (showWizard || (change != null && !performBatchChange(change))) {
180
			UpdateCodeWizard wizard = new UpdateCodeWizard(refactoring, showWizard);
181
			wizard.setDefaultPageTitle(ToolsUiPlugin.getString("CODE_UPDATE_PREVIEW")); //$NON-NLS-1$
182
			RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
183
			try {
184
				return op.run(this.getHyadesEditorPart().getEditorPart().getEditorSite().getShell(), ToolsUiPlugin.getString("CODE_UPDATE")) == IDialogConstants.OK_ID; //$NON-NLS-1$
185
			} catch (InterruptedException e) {
186
				ToolsUiPlugin.logError(e);
187
				return false;
188
			}
189
		}
190
		return true;
191
	}
136
}
192
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/editor/JUnitForm.java (+4 lines)
Lines 117-120 Link Here
117
		super.load();
117
		super.load();
118
		sourceInfoSection.setInput(getTestSuite());
118
		sourceInfoSection.setInput(getTestSuite());
119
	}
119
	}
120
	
121
	public void reloadSourceInfo() {
122
		sourceInfoSection.setInput(getTestSuite());
123
	}
120
}
124
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/editor/JUnitTestCasesForm.java (-1 / +6 lines)
Lines 11-22 Link Here
11
 *******************************************************************************/
11
 *******************************************************************************/
12
package org.eclipse.hyades.test.tools.ui.java.internal.junit.editor;
12
package org.eclipse.hyades.test.tools.ui.java.internal.junit.editor;
13
13
14
import org.eclipse.emf.ecore.EStructuralFeature;
15
import org.eclipse.hyades.models.common.testprofile.Common_TestprofilePackage;
14
import org.eclipse.hyades.test.tools.core.common.TestCommon;
16
import org.eclipse.hyades.test.tools.core.common.TestCommon;
15
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
17
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
16
import org.eclipse.hyades.test.tools.ui.common.internal.editor.TestCasesForm;
18
import org.eclipse.hyades.test.tools.ui.common.internal.editor.TestCasesForm;
17
import org.eclipse.hyades.test.tools.ui.common.internal.editor.action.AddTestCase;
19
import org.eclipse.hyades.test.tools.ui.common.internal.editor.action.AddTestCase;
18
import org.eclipse.hyades.test.tools.ui.java.internal.util.ContextIds;
20
import org.eclipse.hyades.test.tools.ui.java.internal.util.ContextIds;
21
import org.eclipse.hyades.test.ui.editor.form.util.EditorForm;
19
import org.eclipse.hyades.test.ui.editor.form.util.WidgetFactory;
22
import org.eclipse.hyades.test.ui.editor.form.util.WidgetFactory;
23
import org.eclipse.hyades.test.ui.internal.editor.form.util.EObjectTreeSection;
20
import org.eclipse.jface.action.IAction;
24
import org.eclipse.jface.action.IAction;
21
import org.eclipse.swt.widgets.Control;
25
import org.eclipse.swt.widgets.Control;
22
import org.eclipse.ui.help.WorkbenchHelp;
26
import org.eclipse.ui.help.WorkbenchHelp;
Lines 41-47 Link Here
41
     * @see org.eclipse.hyades.test.java.internal.junit.editor.TestCasesForm#getAddTestCaseAction()
45
     * @see org.eclipse.hyades.test.java.internal.junit.editor.TestCasesForm#getAddTestCaseAction()
42
     */
46
     */
43
    protected IAction getAddTestCaseAction() {
47
    protected IAction getAddTestCaseAction() {
44
        return new AddTestCase(this, TestCommon.JUNIT_TEST_CASE_TYPE, ToolsUiPlugin.getString("W_TEST").toLowerCase());
48
        return new AddTestCase(this, TestCommon.JUNIT_TEST_CASE_TYPE, ToolsUiPlugin.getString("W_TEST").toLowerCase()); //$NON-NLS-1$
45
    }
49
    }
46
50
47
    /**
51
    /**
Lines 70-73 Link Here
70
                break;
74
                break;
71
        }
75
        }
72
    }
76
    }
77
    
73
}
78
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/editor/SourceInfoViewer.java (-38 / +106 lines)
Lines 14-23 Link Here
14
14
15
import java.util.Iterator;
15
import java.util.Iterator;
16
16
17
import org.eclipse.core.resources.IFile;
17
import org.eclipse.core.resources.IResource;
18
import org.eclipse.core.resources.IResource;
18
import org.eclipse.core.resources.ResourcesPlugin;
19
import org.eclipse.core.resources.ResourcesPlugin;
19
import org.eclipse.core.runtime.CoreException;
20
import org.eclipse.core.runtime.CoreException;
20
import org.eclipse.core.runtime.Path;
21
import org.eclipse.core.runtime.Path;
22
import org.eclipse.emf.ecore.EObject;
21
import org.eclipse.hyades.models.common.configuration.CFGClass;
23
import org.eclipse.hyades.models.common.configuration.CFGClass;
22
import org.eclipse.hyades.models.common.configuration.impl.CFGInstanceImpl;
24
import org.eclipse.hyades.models.common.configuration.impl.CFGInstanceImpl;
23
import org.eclipse.hyades.models.common.configuration.impl.Common_ConfigurationFactoryImpl;
25
import org.eclipse.hyades.models.common.configuration.impl.Common_ConfigurationFactoryImpl;
Lines 31-36 Link Here
31
import org.eclipse.hyades.models.common.interactions.impl.Common_Behavior_InteractionsFactoryImpl;
33
import org.eclipse.hyades.models.common.interactions.impl.Common_Behavior_InteractionsFactoryImpl;
32
import org.eclipse.hyades.models.common.testprofile.TPFBehavior;
34
import org.eclipse.hyades.models.common.testprofile.TPFBehavior;
33
import org.eclipse.hyades.models.common.testprofile.TPFTest;
35
import org.eclipse.hyades.models.common.testprofile.TPFTest;
36
import org.eclipse.hyades.test.core.util.EMFUtil;
34
import org.eclipse.hyades.test.tools.core.CorePlugin;
37
import org.eclipse.hyades.test.tools.core.CorePlugin;
35
import org.eclipse.hyades.test.tools.core.internal.java.modelsync.JUnitModelUpdater;
38
import org.eclipse.hyades.test.tools.core.internal.java.modelsync.JUnitModelUpdater;
36
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
39
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
Lines 39-44 Link Here
39
import org.eclipse.hyades.test.ui.editor.form.util.WidgetFactory;
42
import org.eclipse.hyades.test.ui.editor.form.util.WidgetFactory;
40
import org.eclipse.hyades.test.ui.internal.util.SpecialFieldsBidiListener;
43
import org.eclipse.hyades.test.ui.internal.util.SpecialFieldsBidiListener;
41
import org.eclipse.hyades.ui.internal.util.GridDataUtil;
44
import org.eclipse.hyades.ui.internal.util.GridDataUtil;
45
import org.eclipse.jdt.core.ICompilationUnit;
42
import org.eclipse.jdt.core.IJavaElement;
46
import org.eclipse.jdt.core.IJavaElement;
43
import org.eclipse.jdt.core.IJavaProject;
47
import org.eclipse.jdt.core.IJavaProject;
44
import org.eclipse.jdt.core.IPackageFragment;
48
import org.eclipse.jdt.core.IPackageFragment;
Lines 62-67 Link Here
62
import org.eclipse.swt.widgets.Button;
66
import org.eclipse.swt.widgets.Button;
63
import org.eclipse.swt.widgets.Composite;
67
import org.eclipse.swt.widgets.Composite;
64
import org.eclipse.swt.widgets.Label;
68
import org.eclipse.swt.widgets.Label;
69
import org.eclipse.ui.PartInitException;
65
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
70
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
66
import org.eclipse.ui.dialogs.SelectionDialog;
71
import org.eclipse.ui.dialogs.SelectionDialog;
67
72
Lines 80-85 Link Here
80
	private Button sourceFolderButton;
85
	private Button sourceFolderButton;
81
	private Button packageButton;
86
	private Button packageButton;
82
	private Button updateFromCodeButton;
87
	private Button updateFromCodeButton;
88
	private Button openClassButton;
83
	
89
	
84
	private IImplementor implementor;
90
	private IImplementor implementor;
85
	private VerifyKeyListener verifyKeyListener;
91
	private VerifyKeyListener verifyKeyListener;
Lines 154-160 Link Here
154
160
155
		if(widgetFactory != null)
161
		if(widgetFactory != null)
156
			sourceFolderText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT,
162
			sourceFolderText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT,
157
					ToolsUiPlugin.getString("STR_WB_SRCFOLD"));
163
					ToolsUiPlugin.getString("STR_WB_SRCFOLD")); //$NON-NLS-1$
158
		else
164
		else
159
			sourceFolderText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT | SWT.BORDER);
165
			sourceFolderText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT | SWT.BORDER);
160
		sourceFolderText.setLayoutData(GridDataUtil.createHorizontalFill());
166
		sourceFolderText.setLayoutData(GridDataUtil.createHorizontalFill());
Lines 170-176 Link Here
170
			sourceFolderButton = new Button(composite, SWT.PUSH);
176
			sourceFolderButton = new Button(composite, SWT.PUSH);
171
			sourceFolderButton.setText(ToolsUiPlugin.getString("STR_WB_SRCFOLD_BTN")); //$NON-NLS-1$
177
			sourceFolderButton.setText(ToolsUiPlugin.getString("STR_WB_SRCFOLD_BTN")); //$NON-NLS-1$
172
		}
178
		}
173
		sourceFolderButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
179
		sourceFolderButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
174
		sourceFolderButton.addSelectionListener(this);
180
		sourceFolderButton.addSelectionListener(this);
175
		
181
		
176
		if(widgetFactory != null) {
182
		if(widgetFactory != null) {
Lines 183-189 Link Here
183
189
184
		if(widgetFactory != null)
190
		if(widgetFactory != null)
185
			packageText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT,
191
			packageText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT,
186
					ToolsUiPlugin.getString("STR_WB_PACK"));
192
					ToolsUiPlugin.getString("STR_WB_PACK")); //$NON-NLS-1$
187
		else
193
		else
188
			packageText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT | SWT.BORDER);
194
			packageText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT | SWT.BORDER);
189
		packageText.setLayoutData(GridDataUtil.createHorizontalFill());
195
		packageText.setLayoutData(GridDataUtil.createHorizontalFill());
Lines 200-206 Link Here
200
			packageButton.setText(ToolsUiPlugin.getString("STR_WB_PACK_BTN")); //$NON-NLS-1$
206
			packageButton.setText(ToolsUiPlugin.getString("STR_WB_PACK_BTN")); //$NON-NLS-1$
201
		}
207
		}
202
		
208
		
203
		packageButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
209
		packageButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
204
		packageButton.addSelectionListener(this);
210
		packageButton.addSelectionListener(this);
205
211
206
		if(widgetFactory != null) {
212
		if(widgetFactory != null) {
Lines 213-227 Link Here
213
219
214
		if(widgetFactory != null)
220
		if(widgetFactory != null)
215
			classNameText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE,
221
			classNameText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE,
216
					ToolsUiPlugin.getString("STR_WB_CLASS"));
222
					ToolsUiPlugin.getString("STR_WB_CLASS")); //$NON-NLS-1$
217
		else
223
		else
218
			classNameText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
224
			classNameText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
219
		classNameText.setEditable(false);
225
		classNameText.setEditable(false);
220
		classNameText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false, 2, 1));
226
		
221
			
227
		if(widgetFactory != null) {
228
			classNameText.setLayoutData(GridDataUtil.createHorizontalFill());
229
			openClassButton = widgetFactory.createButton(composite, ToolsUiPlugin.getString("SOURCE_INFO_VIEWER_OPEN_CLASS"), SWT.PUSH); //$NON-NLS-1$
230
			openClassButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
231
			openClassButton.addSelectionListener(this);
232
		} else {
233
			classNameText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false, 2, 1));
234
		}
235
		
222
		if (advanced) {
236
		if (advanced) {
223
			if (showExternalBehavior) {
237
			if (showExternalBehavior) {
224
				updateFromCodeButton = widgetFactory.createButton(composite, "Refresh test methods from code", SWT.PUSH);
238
				updateFromCodeButton = widgetFactory.createButton(composite, "Refresh test methods from code", SWT.PUSH); //$NON-NLS-1$
225
				updateFromCodeButton.setLayoutData(new GridData(SWT.END, SWT.BEGINNING, false, false, 2, 1));
239
				updateFromCodeButton.setLayoutData(new GridData(SWT.END, SWT.BEGINNING, false, false, 2, 1));
226
				updateFromCodeButton.addSelectionListener(this);
240
				updateFromCodeButton.addSelectionListener(this);
227
			}
241
			}
Lines 264-269 Link Here
264
			packageText.setEditable(false);
278
			packageText.setEditable(false);
265
			classNameText.setEditable(false);
279
			classNameText.setEditable(false);
266
		}
280
		}
281
		
282
		updateButtonsState();
267
	}
283
	}
268
	
284
	
269
	protected void adjustTexts() {
285
	protected void adjustTexts() {
Lines 357-364 Link Here
357
			else
373
			else
358
				getImplementor().setResource(pack + cls);
374
				getImplementor().setResource(pack + cls);
359
			
375
			
360
			markDirty();
361
		}
376
		}
377
		updateButtonsState();
378
		markDirty();
379
	}
380
	
381
	private void updateButtonsState() {
382
		packageButton.setEnabled(findSourceFolder() != null);
383
		openClassButton.setEnabled(findCompilationUnit() != null);
362
	}
384
	}
363
	
385
	
364
	/**
386
	/**
Lines 380-385 Link Here
380
				dialog.setTitle(ToolsUiPlugin.getString("TITLE_SRC_SELECT")); //$NON-NLS-1$
402
				dialog.setTitle(ToolsUiPlugin.getString("TITLE_SRC_SELECT")); //$NON-NLS-1$
381
				dialog.setMessage(ToolsUiPlugin.getString("STR_SRC_SELECT")); //$NON-NLS-1$
403
				dialog.setMessage(ToolsUiPlugin.getString("STR_SRC_SELECT")); //$NON-NLS-1$
382
				dialog.setEmptyListMessage(ToolsUiPlugin.getString("NO_SRC")); //$NON-NLS-1$
404
				dialog.setEmptyListMessage(ToolsUiPlugin.getString("NO_SRC")); //$NON-NLS-1$
405
				dialog.setInitialSelection(findSourceFolder());
383
				if (dialog.open() == IDialogConstants.OK_ID) {
406
				if (dialog.open() == IDialogConstants.OK_ID) {
384
					Object result = dialog.getFirstResult();
407
					Object result = dialog.getFirstResult();
385
					String text = ""; //$NON-NLS-1$
408
					String text = ""; //$NON-NLS-1$
Lines 396-434 Link Here
396
					markDirty();
419
					markDirty();
397
				}
420
				}
398
			} else if (e.widget == packageButton) {
421
			} else if (e.widget == packageButton) {
399
				IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(getImplementor().getLocation());
422
				try {
400
				if (res == null) {
423
					IPackageFragmentRoot srcFolder = findSourceFolder();
401
					e.doit = false;
424
					if (srcFolder != null) {
402
				} else {
403
					IJavaElement element = JavaCore.create(res);
404
					try {
405
						IPackageFragmentRoot srcFolder = null;
406
						String initialPackageName = getPackage();
425
						String initialPackageName = getPackage();
407
						if (element instanceof IJavaProject) {
426
						SelectionDialog dialog = JavaUI.createPackageDialog(packageButton.getShell(), srcFolder);
408
							srcFolder = ((IJavaProject)element).findPackageFragmentRoot(res.getFullPath());
427
						IPackageFragment initialPackage = null;
409
						} else if (element instanceof IPackageFragmentRoot) {
428
						if (initialPackageName != null) {
410
							srcFolder = (IPackageFragmentRoot)element;
429
							initialPackage = srcFolder.getPackageFragment(initialPackageName);
411
						}
430
						}
412
						if (srcFolder != null) {
431
						if (initialPackage != null && initialPackage.exists()) {
413
							SelectionDialog dialog = JavaUI.createPackageDialog(packageButton.getShell(), srcFolder);
432
							dialog.setInitialSelections(new Object[] {initialPackage});
414
							IPackageFragment initialPackage = null;
433
						}
415
							if (initialPackageName != null) {
434
						dialog.setTitle(ToolsUiPlugin.getString("TITLE_PACK_SELECT")); //$NON-NLS-1$
416
								initialPackage = srcFolder.getPackageFragment(initialPackageName);
435
						dialog.setMessage(ToolsUiPlugin.getString("STR_PACK_SELECT")); //$NON-NLS-1$
417
							}
436
						if (dialog.open() == IDialogConstants.OK_ID) {
418
							if (initialPackage != null && initialPackage.exists()) {
437
							IPackageFragment packageFragment = (IPackageFragment)dialog.getResult()[0];
419
								dialog.setInitialSelections(new Object[] {initialPackage});
438
							setPackage(packageFragment.getElementName());
420
							}
439
							markDirty();
421
							dialog.setTitle(ToolsUiPlugin.getString("TITLE_PACK_SELECT")); //$NON-NLS-1$
422
							dialog.setMessage(ToolsUiPlugin.getString("STR_PACK_SELECT")); //$NON-NLS-1$
423
							if (dialog.open() == IDialogConstants.OK_ID) {
424
								IPackageFragment packageFragment = (IPackageFragment)dialog.getResult()[0];
425
								setPackage(packageFragment.getElementName());
426
								markDirty();
427
							}
428
						}
440
						}
429
					} catch (JavaModelException e1) {
430
						e.doit = false;
431
					}
441
					}
442
				} catch (JavaModelException e1) {
443
					e.doit = false;
432
				}
444
				}
433
			} else if (e.widget == externalBehavior) {
445
			} else if (e.widget == externalBehavior) {
434
				if (externalBehavior.getSelection()) {
446
				if (externalBehavior.getSelection()) {
Lines 460-467 Link Here
460
				} catch (CoreException e1) {
472
				} catch (CoreException e1) {
461
					CorePlugin.logError(e1);
473
					CorePlugin.logError(e1);
462
				}
474
				}
475
			} else if (e.widget == openClassButton) {
476
				ICompilationUnit cu = findCompilationUnit();
477
				if (cu != null) {
478
					try {
479
						JavaUI.openInEditor(cu);
480
					} catch (PartInitException e1) {
481
						ToolsUiPlugin.logError(e1);
482
						e.doit = false;
483
					} catch (JavaModelException e1) {
484
						ToolsUiPlugin.logError(e1);
485
						e.doit = false;
486
					}
487
				}
488
			}
489
		}
490
	}
491
	
492
	protected IPackageFragmentRoot findSourceFolder() {
493
		IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(getSourceFolder());
494
		if (res == null) {
495
			return null;
496
		}
497
		IJavaElement element = JavaCore.create(res);
498
		if (element == null) return null;
499
		try {
500
			IPackageFragmentRoot srcFolder = null;
501
			if (element instanceof IJavaProject) {
502
				srcFolder = ((IJavaProject)element).findPackageFragmentRoot(res.getFullPath());
503
			} else if (element instanceof IPackageFragmentRoot) {
504
				srcFolder = (IPackageFragmentRoot)element;
505
			}
506
			return srcFolder;
507
		} catch (JavaModelException e) {
508
			ToolsUiPlugin.logError(e);
509
			return null;
510
		}
511
	}
512
	
513
	protected IPackageFragment findPackage() {
514
		IPackageFragmentRoot srcFolder = findSourceFolder();
515
		if (srcFolder != null) {
516
			IPackageFragment pack = srcFolder.getPackageFragment(getPackage());
517
			if (pack.exists()) {
518
				return pack;
519
			}
520
		}
521
		return null;
522
	}
523
	
524
	protected ICompilationUnit findCompilationUnit() {
525
		IPackageFragment pack = findPackage();
526
		if (pack != null) {
527
			ICompilationUnit cu = pack.getCompilationUnit(getClassName() + ".java"); //$NON-NLS-1$
528
			if (cu.exists()) {
529
				return cu;
463
			}
530
			}
464
		}
531
		}
532
		return null;
465
	}
533
	}
466
	
534
	
467
	static IBlock createBlock(IImplementor implementor) {
535
	static IBlock createBlock(IImplementor implementor) {
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/SourcePage.java (-58 / +10 lines)
Lines 11-29 Link Here
11
 *******************************************************************************/
11
 *******************************************************************************/
12
package org.eclipse.hyades.test.tools.ui.java.internal.junit.wizard;
12
package org.eclipse.hyades.test.tools.ui.java.internal.junit.wizard;
13
13
14
import java.util.ArrayList;
14
import java.util.Collection;
15
import java.util.Iterator;
15
import java.util.Iterator;
16
import java.util.List;
17
16
18
import org.eclipse.core.resources.IResource;
17
import org.eclipse.core.resources.IResource;
19
import org.eclipse.core.runtime.CoreException;
18
import org.eclipse.core.runtime.CoreException;
20
import org.eclipse.core.runtime.IStatus;
19
import org.eclipse.core.runtime.IStatus;
21
import org.eclipse.core.runtime.NullProgressMonitor;
20
import org.eclipse.core.runtime.NullProgressMonitor;
22
import org.eclipse.core.runtime.Status;
21
import org.eclipse.core.runtime.Status;
23
import org.eclipse.hyades.test.tools.core.CorePlugin;
24
import org.eclipse.hyades.test.tools.core.internal.common.codegen.AutomaticDependencyUpdater;
22
import org.eclipse.hyades.test.tools.core.internal.common.codegen.AutomaticDependencyUpdater;
25
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
23
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
26
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
24
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator.JUnitProjectDependencyUpdater;
27
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
25
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
28
import org.eclipse.hyades.test.tools.ui.java.internal.util.ContextIds;
26
import org.eclipse.hyades.test.tools.ui.java.internal.util.ContextIds;
29
import org.eclipse.hyades.ui.internal.util.GridDataUtil;
27
import org.eclipse.hyades.ui.internal.util.GridDataUtil;
Lines 296-330 Link Here
296
	 * @return the status of the validation
294
	 * @return the status of the validation
297
	 */
295
	 */
298
	protected IStatus validateProjectClasspath() {
296
	protected IStatus validateProjectClasspath() {
299
		Status status= new Status(IStatus.OK, ToolsUiPlugin.getID(), 1, "", null);
297
		Status status= new Status(IStatus.OK, ToolsUiPlugin.getID(), 1, "", null); //$NON-NLS-1$
300
		IPackageFragmentRoot root= getPackageFragmentRoot();
298
		IPackageFragmentRoot root= getPackageFragmentRoot();
301
		if (root == null)
299
		if (root == null)
302
			return status;
300
			return status;
303
		
301
		
304
		IJavaProject jp= root.getJavaProject();
302
		IJavaProject jp= root.getJavaProject();
305
		
303
		
306
		List missingLibraries = new ArrayList(3);
304
		JUnitProjectDependencyUpdater updater = new JUnitProjectDependencyUpdater(
307
		List requiredLibraries = getRequiredLibraries();
305
				new AutomaticDependencyUpdater(), isModelBehavior());
308
		Iterator it = requiredLibraries.iterator();
306
		Collection missingLibraries = updater.previewAdjustProject(jp.getProject());
309
		while (it.hasNext()) {
310
			RequiredLibrary lib = (RequiredLibrary) it.next();
311
			try {
312
				if (jp.findType(lib.testClass) == null)
313
					missingLibraries.add(lib);
314
			} catch (JavaModelException e) {
315
				// Let's keep quiet
316
			}
317
		}
318
		if (missingLibraries.isEmpty()) return status;
307
		if (missingLibraries.isEmpty()) return status;
319
		
308
		
320
		StringBuffer librariesAsText = new StringBuffer();
309
		StringBuffer librariesAsText = new StringBuffer();
321
		it = missingLibraries.iterator();
310
		Iterator it = missingLibraries.iterator();
322
		while (it.hasNext()) {
311
		while (it.hasNext()) {
323
			RequiredLibrary lib = (RequiredLibrary) it.next();
324
			if (librariesAsText.length() > 0) {
312
			if (librariesAsText.length() > 0) {
325
				librariesAsText.append(", ");
313
				librariesAsText.append(", "); //$NON-NLS-1$
326
			}
314
			}
327
			librariesAsText.append(lib.jarName);
315
			librariesAsText.append((String)it.next());
328
		}
316
		}
329
		
317
		
330
		if (!dontAskMissingLibsAgain) {
318
		if (!dontAskMissingLibsAgain) {
Lines 335-356 Link Here
335
				message = ToolsUiPlugin.getString("SourcePage.jars_not_on_buildpath.message", librariesAsText.toString()); //$NON-NLS-1$
323
				message = ToolsUiPlugin.getString("SourcePage.jars_not_on_buildpath.message", librariesAsText.toString()); //$NON-NLS-1$
336
			}
324
			}
337
			if (MessageDialog.openQuestion(getShell(), ToolsUiPlugin.getString("SourcePage.not_on_buildpath.title"), message)) { //$NON-NLS-1$
325
			if (MessageDialog.openQuestion(getShell(), ToolsUiPlugin.getString("SourcePage.not_on_buildpath.title"), message)) { //$NON-NLS-1$
338
				JUnitGenerator generator;
339
				IWizard theWizard = getWizard();
340
				if (theWizard instanceof JUnitTestSuiteNewWizard) {
341
					generator = ((JUnitTestSuiteNewWizard)theWizard).createGenerator();
342
				} else {
343
					// If the current page is used outside of JUnit wizard, use the default
344
					// generator
345
					generator = new JUnitGenerator(new AutomaticDependencyUpdater());
346
				}
347
				it = missingLibraries.iterator();
348
				while (it.hasNext()) {
349
					RequiredLibrary lib = (RequiredLibrary) it.next();
350
					generator.getProjectDependencyUpdater().addRequiredPlugin(lib.plugin, lib.jarName);
351
				}
352
				try {
326
				try {
353
					generator.getProjectDependencyUpdater().adjustProject(jp.getProject(), new NullProgressMonitor());
327
					updater.adjustProject(jp.getProject(), new NullProgressMonitor());
354
				} catch (CoreException e) {
328
				} catch (CoreException e) {
355
					ToolsUiPlugin.logError(e);
329
					ToolsUiPlugin.logError(e);
356
				}
330
				}
Lines 365-392 Link Here
365
		} else {
339
		} else {
366
			return new Status(IStatus.WARNING, ToolsUiPlugin.getID(), 1, ToolsUiPlugin.getString("SourcePage.error.jarsNotOnbuildpath", librariesAsText.toString()), null); //$NON-NLS-1$
340
			return new Status(IStatus.WARNING, ToolsUiPlugin.getID(), 1, ToolsUiPlugin.getString("SourcePage.error.jarsNotOnbuildpath", librariesAsText.toString()), null); //$NON-NLS-1$
367
		}
341
		}
368
				
369
	}
342
	}
370
343
371
	protected class RequiredLibrary {
372
		public String testClass;
373
		public String plugin;
374
		public String jarName;
375
		public RequiredLibrary(String testClass, String plugin, String jarName) {
376
			this.testClass = testClass;
377
			this.plugin = plugin;
378
			this.jarName = jarName;
379
		}
380
	}
381
	
382
	protected List getRequiredLibraries() {
383
		List result = new ArrayList(3);
384
		if (isModelBehavior()) {
385
			result.add(new RequiredLibrary(Helper.HYADES_TEST_SUITE_CLASS_NAME, CorePlugin.getID(), "common.runner.jar")); //$NON-NLS-1$
386
			result.add(new RequiredLibrary(Helper.HYADES_JUNIT_RUNNER, CorePlugin.getID(), "java.runner.jar")); //$NON-NLS-1$ //$NON-NLS-2$
387
		}
388
		result.add(new RequiredLibrary(Helper.JUNIT_TEST_CLASS_NAME, "org.junit", "junit.jar")); //$NON-NLS-1$ //$NON-NLS-2$
389
		return result;
390
	}
391
	
392
}
344
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/AdjustSourceInfoPage.java (-5 / +5 lines)
Lines 36-44 Link Here
36
	 */
36
	 */
37
	public AdjustSourceInfoPage(IImplementor implementor)
37
	public AdjustSourceInfoPage(IImplementor implementor)
38
	{
38
	{
39
		super("AdjustSourceInfoPage");
39
		super("AdjustSourceInfoPage"); //$NON-NLS-1$
40
		setTitle(ToolsUiPlugin.getString("JAVA_GEN_WTITLE"));
40
		setTitle(ToolsUiPlugin.getString("JAVA_GEN_WTITLE")); //$NON-NLS-1$
41
		setDescription(ToolsUiPlugin.getString("ADJ_PG_DSC"));
41
		setDescription(ToolsUiPlugin.getString("ADJ_PG_DSC")); //$NON-NLS-1$
42
42
43
		this.implementor = implementor;
43
		this.implementor = implementor;
44
	}
44
	}
Lines 78-90 Link Here
78
	{
78
	{
79
		if(!JavaConventions.validateIdentifier(sourceInfoViewer.getClassName()).isOK())
79
		if(!JavaConventions.validateIdentifier(sourceInfoViewer.getClassName()).isOK())
80
		{
80
		{
81
			setErrorMessage(ToolsUiPlugin.getString("_ERROR_INV_CLS_NAME"));
81
			setErrorMessage(ToolsUiPlugin.getString("_ERROR_INV_CLS_NAME")); //$NON-NLS-1$
82
			return false;
82
			return false;
83
		}
83
		}
84
84
85
		if(!JavaConventions.validatePackageName(sourceInfoViewer.getPackage()).isOK())
85
		if(!JavaConventions.validatePackageName(sourceInfoViewer.getPackage()).isOK())
86
		{
86
		{
87
			setErrorMessage(ToolsUiPlugin.getString("_ERROR_INV_PCK_NAME"));
87
			setErrorMessage(ToolsUiPlugin.getString("_ERROR_INV_PCK_NAME")); //$NON-NLS-1$
88
			return false;
88
			return false;
89
		}
89
		}
90
		
90
		
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/JUnitTestSuiteNewWizard.java (-35 / +24 lines)
Lines 16-23 Link Here
16
import org.eclipse.core.runtime.IProgressMonitor;
16
import org.eclipse.core.runtime.IProgressMonitor;
17
import org.eclipse.core.runtime.IStatus;
17
import org.eclipse.core.runtime.IStatus;
18
import org.eclipse.core.runtime.NullProgressMonitor;
18
import org.eclipse.core.runtime.NullProgressMonitor;
19
import org.eclipse.core.runtime.SubProgressMonitor;
19
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
20
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
20
import org.eclipse.hyades.test.tools.core.CorePlugin;
21
import org.eclipse.hyades.test.tools.core.common.TestCommon;
21
import org.eclipse.hyades.test.tools.core.common.TestCommon;
22
import org.eclipse.hyades.test.tools.core.internal.common.codegen.AutomaticDependencyUpdater;
22
import org.eclipse.hyades.test.tools.core.internal.common.codegen.AutomaticDependencyUpdater;
23
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
23
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
Lines 32-37 Link Here
32
import org.eclipse.jdt.core.JavaModelException;
32
import org.eclipse.jdt.core.JavaModelException;
33
import org.eclipse.jface.dialogs.IDialogSettings;
33
import org.eclipse.jface.dialogs.IDialogSettings;
34
import org.eclipse.jface.viewers.IStructuredSelection;
34
import org.eclipse.jface.viewers.IStructuredSelection;
35
import org.eclipse.ltk.core.refactoring.Change;
36
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
35
37
36
/**
38
/**
37
 * Extends the HyadesNewWizard to create the JUnit Test Suite.
39
 * Extends the HyadesNewWizard to create the JUnit Test Suite.
Lines 42-48 Link Here
42
public class JUnitTestSuiteNewWizard extends TestSuiteNewWizard2 {
44
public class JUnitTestSuiteNewWizard extends TestSuiteNewWizard2 {
43
	
45
	
44
	private SourcePage sourcePage;
46
	private SourcePage sourcePage;
45
	private ITestSuite generatedTestSuite;
46
	
47
	
47
    /**
48
    /**
48
     * Constructor for TestSuiteNewWizard
49
     * Constructor for TestSuiteNewWizard
Lines 166-191 Link Here
166
    	sourcePage_.init(structuredSelection, locationPage);
167
    	sourcePage_.init(structuredSelection, locationPage);
167
	}
168
	}
168
    
169
    
169
	/* (non-Javadoc)
170
	 * @see org.eclipse.jface.wizard.IWizard#performFinish()
171
	 */
172
	public boolean performFinish() {
173
		// Generate the Test Suite
174
		if (super.performFinish()) {
175
			if (this.generatedTestSuite != null) {
176
				try {
177
					// Generate the source code
178
					generateCode(this.generatedTestSuite, new NullProgressMonitor());
179
				} catch (Exception e) {
180
					ToolsUiPlugin.logError(e);
181
					return false;
182
				}
183
			}
184
			return true;
185
		}
186
		return false;
187
	}
188
189
	protected void adjustTestSuite(ITestSuite testSuite) {
170
	protected void adjustTestSuite(ITestSuite testSuite) {
190
	    // Set the name of the implementor class
171
	    // Set the name of the implementor class
191
		String qualifiedName = this.sourcePage.getQualifiedTypeName();
172
		String qualifiedName = this.sourcePage.getQualifiedTypeName();
Lines 204-231 Link Here
204
		if (!this.sourcePage.isModelBehavior()) {
185
		if (!this.sourcePage.isModelBehavior()) {
205
			JUnitModelUpdater.setImplementorBlock(testSuite.getImplementor(), null);
186
			JUnitModelUpdater.setImplementorBlock(testSuite.getImplementor(), null);
206
		}
187
		}
207
		this.generatedTestSuite = testSuite;
188
		try {
208
		// Don't invoke super.registerResource().
189
			// Generate the source code
190
			generateCode(testSuite, new NullProgressMonitor());
191
		} catch (Exception e) {
192
			ToolsUiPlugin.logError(e);
193
		}
194
		// Don't invoke super.adjustTestSuite().
209
	}
195
	}
210
	
196
	
211
	protected SourcePage getSourcePage() {
197
	protected SourcePage getSourcePage() {
212
		return this.sourcePage;
198
		return this.sourcePage;
213
	}
199
	}
214
	
200
	
215
	protected ITestSuite getGeneratedTestSuite() {
201
	protected JUnitGenerator createGenerator(ITestSuite testSuite) {
216
		return this.generatedTestSuite;
202
		return new JUnitGenerator(testSuite, new AutomaticDependencyUpdater(), getSourcePage().getSuperClass());
217
	}
218
	
219
	protected JUnitGenerator createGenerator() {
220
		return new JUnitGenerator(new AutomaticDependencyUpdater(), getSourcePage().getSuperClass());
221
	}
203
	}
222
	
204
	
223
	private void generateCode(ITestSuite testSuite, IProgressMonitor monitor) throws Exception {
205
	private void generateCode(ITestSuite testSuite, IProgressMonitor monitor) throws Exception {
224
		JUnitGenerator generator = createGenerator();
206
		monitor.beginTask("", 4); //$NON-NLS-1$
225
		generator.getProjectDependencyUpdater().addRequiredPlugin("org.junit", null); //$NON-NLS-1$
207
		try {
226
		generator.getProjectDependencyUpdater().addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
208
			JUnitGenerator generator = createGenerator(testSuite);
227
		generator.getProjectDependencyUpdater().addRequiredPlugin(CorePlugin.getID(), "java.runner.jar"); //$NON-NLS-1$
209
			RefactoringStatus status = generator.checkAllConditions(new SubProgressMonitor(monitor, 1));
228
		generator.generate(getGeneratedTestSuite(), monitor);
210
			if (status.hasFatalError()) {
211
				throw new IllegalStateException("Refactor conditions not met"); // TODO Treat this appropriately //$NON-NLS-1$
212
			}
213
			Change change = generator.createChange(new SubProgressMonitor(monitor, 1));
214
			change.perform(new SubProgressMonitor(monitor, 2));
215
		} finally {
216
			monitor.done();
217
		}
229
	}
218
	}
230
	
219
	
231
	protected void setSourcePage(SourcePage page) {
220
	protected void setSourcePage(SourcePage page) {
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/ProjectAndSourcePage.java (-21 / +21 lines)
Lines 52-59 Link Here
52
public class ProjectAndSourcePage 
52
public class ProjectAndSourcePage 
53
extends WizardPage implements ModifyListener, SelectionListener
53
extends WizardPage implements ModifyListener, SelectionListener
54
{
54
{
55
	protected static final String SET_PROJECT = "PROJECT_NAME";
55
	protected static final String SET_PROJECT = "PROJECT_NAME"; //$NON-NLS-1$
56
	protected static final String SET_SOURCE = "SOURCE_FOLDER_NAME";
56
	protected static final String SET_SOURCE = "SOURCE_FOLDER_NAME"; //$NON-NLS-1$
57
57
58
	private IImplementor implementor;
58
	private IImplementor implementor;
59
	private IJavaProject[] javaProjects;
59
	private IJavaProject[] javaProjects;
Lines 69-77 Link Here
69
	 */
69
	 */
70
	public ProjectAndSourcePage(IImplementor implementor, IJavaProject[] javaProjects)
70
	public ProjectAndSourcePage(IImplementor implementor, IJavaProject[] javaProjects)
71
	{
71
	{
72
		super("ProjectAndSourcePage");
72
		super("ProjectAndSourcePage"); //$NON-NLS-1$
73
		setTitle(ToolsUiPlugin.getString("JAVA_GEN_WTITLE"));
73
		setTitle(ToolsUiPlugin.getString("JAVA_GEN_WTITLE")); //$NON-NLS-1$
74
		setDescription(ToolsUiPlugin.getString("JAVA_GEN_LDESC"));
74
		setDescription(ToolsUiPlugin.getString("JAVA_GEN_LDESC")); //$NON-NLS-1$
75
		
75
		
76
		this.implementor = implementor;
76
		this.implementor = implementor;
77
		this.javaProjects = javaProjects;
77
		this.javaProjects = javaProjects;
Lines 103-109 Link Here
103
		composite.setLayoutData(GridDataUtil.createFill());
103
		composite.setLayoutData(GridDataUtil.createFill());
104
		
104
		
105
		Label label = new Label(composite, SWT.NONE);
105
		Label label = new Label(composite, SWT.NONE);
106
		label.setText(ToolsUiPlugin.getString("STR_WB_PROJECT"));
106
		label.setText(ToolsUiPlugin.getString("STR_WB_PROJECT")); //$NON-NLS-1$
107
		
107
		
108
		javaProjectText = new Text(composite, SWT.BORDER | SWT.SINGLE);
108
		javaProjectText = new Text(composite, SWT.BORDER | SWT.SINGLE);
109
		javaProjectText.setLayoutData(GridDataUtil.createHorizontalFill());
109
		javaProjectText.setLayoutData(GridDataUtil.createHorizontalFill());
Lines 112-123 Link Here
112
		GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
112
		GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
113
		gridData.horizontalSpan = 2;
113
		gridData.horizontalSpan = 2;
114
		selectJavaProjectButton.setLayoutData(gridData);
114
		selectJavaProjectButton.setLayoutData(gridData);
115
		selectJavaProjectButton.setText(ToolsUiPlugin.getString("STR_WB_BROWSE_BTN"));
115
		selectJavaProjectButton.setText(ToolsUiPlugin.getString("STR_WB_BROWSE_BTN")); //$NON-NLS-1$
116
		selectJavaProjectButton.addSelectionListener(this);
116
		selectJavaProjectButton.addSelectionListener(this);
117
		selectJavaProjectButton.setEnabled(javaProjects.length > 0);
117
		selectJavaProjectButton.setEnabled(javaProjects.length > 0);
118
		
118
		
119
		label = new Label(composite, SWT.NONE);
119
		label = new Label(composite, SWT.NONE);
120
		label.setText(ToolsUiPlugin.getString("STR_WB_SRC_FOLDER"));
120
		label.setText(ToolsUiPlugin.getString("STR_WB_SRC_FOLDER")); //$NON-NLS-1$
121
121
122
		sourceFolderText = new Text(composite, SWT.BORDER | SWT.SINGLE);
122
		sourceFolderText = new Text(composite, SWT.BORDER | SWT.SINGLE);
123
		sourceFolderText.setLayoutData(GridDataUtil.createHorizontalFill());
123
		sourceFolderText.setLayoutData(GridDataUtil.createHorizontalFill());
Lines 127-133 Link Here
127
		gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
127
		gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
128
		gridData.horizontalSpan = 2;
128
		gridData.horizontalSpan = 2;
129
		selectSourceFolderButton.setLayoutData(gridData);
129
		selectSourceFolderButton.setLayoutData(gridData);
130
		selectSourceFolderButton.setText(ToolsUiPlugin.getString("STR_WB_SOURCE_BTN"));
130
		selectSourceFolderButton.setText(ToolsUiPlugin.getString("STR_WB_SOURCE_BTN")); //$NON-NLS-1$
131
		selectSourceFolderButton.addSelectionListener(this);
131
		selectSourceFolderButton.addSelectionListener(this);
132
		
132
		
133
		
133
		
Lines 173-179 Link Here
173
			setPageComplete(false);
173
			setPageComplete(false);
174
			selectSourceFolderButton.setEnabled(false); 
174
			selectSourceFolderButton.setEnabled(false); 
175
			javaProjectText.setEditable(false);
175
			javaProjectText.setEditable(false);
176
			setErrorMessage(ToolsUiPlugin.getString("NO_JAVA_PRJ"));
176
			setErrorMessage(ToolsUiPlugin.getString("NO_JAVA_PRJ")); //$NON-NLS-1$
177
			composite.setFocus();
177
			composite.setFocus();
178
		}
178
		}
179
			
179
			
Lines 229-242 Link Here
229
		String value = javaProjectText.getText();
229
		String value = javaProjectText.getText();
230
		if(value.trim().length() == 0)
230
		if(value.trim().length() == 0)
231
		{
231
		{
232
			setErrorMessage(ToolsUiPlugin.getString("_ERROR_WIZ_EMPTY_PROJECT"));
232
			setErrorMessage(ToolsUiPlugin.getString("_ERROR_WIZ_EMPTY_PROJECT")); //$NON-NLS-1$
233
			return false;
233
			return false;
234
		}
234
		}
235
		
235
		
236
		IJavaProject javaProject = getJavaProject(value);
236
		IJavaProject javaProject = getJavaProject(value);
237
		if(javaProject == null)
237
		if(javaProject == null)
238
		{
238
		{
239
			setErrorMessage(ToolsUiPlugin.getString("_ERROR_WIZ_NOT_EXIST_PROJECT"));
239
			setErrorMessage(ToolsUiPlugin.getString("_ERROR_WIZ_NOT_EXIST_PROJECT")); //$NON-NLS-1$
240
			return false;
240
			return false;
241
		}
241
		}
242
		
242
		
Lines 254-266 Link Here
254
			value = sourceFolderText.getText();
254
			value = sourceFolderText.getText();
255
			if(value.trim().length() == 0)
255
			if(value.trim().length() == 0)
256
			{
256
			{
257
				setErrorMessage(ToolsUiPlugin.getString("_ERROR_WIZ_EMPTY_FOLDER"));
257
				setErrorMessage(ToolsUiPlugin.getString("_ERROR_WIZ_EMPTY_FOLDER")); //$NON-NLS-1$
258
				return false;
258
				return false;
259
			}
259
			}
260
			
260
			
261
			if(!isValidFolderName())
261
			if(!isValidFolderName())
262
			{
262
			{
263
				setErrorMessage(ToolsUiPlugin.getString("_ERROR_INV_FLD_NME"));
263
				setErrorMessage(ToolsUiPlugin.getString("_ERROR_INV_FLD_NME")); //$NON-NLS-1$
264
				return false;
264
				return false;
265
			}
265
			}
266
		}
266
		}
Lines 272-281 Link Here
272
	protected boolean isValidFolderName()
272
	protected boolean isValidFolderName()
273
	{
273
	{
274
		String folder = getSourceFolder();
274
		String folder = getSourceFolder();
275
		if(folder.startsWith("/"))
275
		if(folder.startsWith("/")) //$NON-NLS-1$
276
			return false;
276
			return false;
277
277
278
		if(folder.endsWith("/"))
278
		if(folder.endsWith("/")) //$NON-NLS-1$
279
			return false;
279
			return false;
280
			
280
			
281
		return true;
281
		return true;
Lines 286-292 Link Here
286
		if(sourceFolderText.getEditable())
286
		if(sourceFolderText.getEditable())
287
			return sourceFolderText.getText().trim().replace('\\', '/');
287
			return sourceFolderText.getText().trim().replace('\\', '/');
288
			
288
			
289
		return "";
289
		return ""; //$NON-NLS-1$
290
	}
290
	}
291
291
292
	protected IJavaProject getJavaProject()
292
	protected IJavaProject getJavaProject()
Lines 313-320 Link Here
313
	{
313
	{
314
		ILabelProvider labelProvider = new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
314
		ILabelProvider labelProvider = new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
315
		ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
315
		ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
316
		dialog.setTitle(ToolsUiPlugin.getString("TITLE_PROJECT_SELECT"));
316
		dialog.setTitle(ToolsUiPlugin.getString("TITLE_PROJECT_SELECT")); //$NON-NLS-1$
317
		dialog.setMessage(ToolsUiPlugin.getString("STR_PROJECT_SELECT"));
317
		dialog.setMessage(ToolsUiPlugin.getString("STR_PROJECT_SELECT")); //$NON-NLS-1$
318
		dialog.setElements(javaProjects);
318
		dialog.setElements(javaProjects);
319
319
320
		IJavaProject javaProject = getJavaProject(javaProjectText.getText());
320
		IJavaProject javaProject = getJavaProject(javaProjectText.getText());
Lines 330-337 Link Here
330
	protected Object chooseSourceFolder()
330
	protected Object chooseSourceFolder()
331
	{
331
	{
332
		ElementTreeSelectionDialog dialog = TestJavaUtil.createSourceFolderDialog(getShell(), null);
332
		ElementTreeSelectionDialog dialog = TestJavaUtil.createSourceFolderDialog(getShell(), null);
333
		dialog.setTitle(ToolsUiPlugin.getString("TITLE_SRC_SELECT"));
333
		dialog.setTitle(ToolsUiPlugin.getString("TITLE_SRC_SELECT")); //$NON-NLS-1$
334
		dialog.setMessage(ToolsUiPlugin.getString("STR_SRC_SELECT"));
334
		dialog.setMessage(ToolsUiPlugin.getString("STR_SRC_SELECT")); //$NON-NLS-1$
335
335
336
		IJavaProject javaProject = getJavaProject(javaProjectText.getText());
336
		IJavaProject javaProject = getJavaProject(javaProjectText.getText());
337
		if (javaProject != null)
337
		if (javaProject != null)
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/GenerateWizard.java (-12 / +15 lines)
Lines 15-22 Link Here
15
import java.lang.reflect.InvocationTargetException;
15
import java.lang.reflect.InvocationTargetException;
16
16
17
import org.eclipse.core.resources.IContainer;
17
import org.eclipse.core.resources.IContainer;
18
import org.eclipse.core.runtime.CoreException;
18
import org.eclipse.core.runtime.IProgressMonitor;
19
import org.eclipse.core.runtime.IProgressMonitor;
19
import org.eclipse.core.runtime.IStatus;
20
import org.eclipse.core.runtime.NullProgressMonitor;
20
import org.eclipse.core.runtime.Path;
21
import org.eclipse.core.runtime.Path;
21
import org.eclipse.emf.ecore.EObject;
22
import org.eclipse.emf.ecore.EObject;
22
import org.eclipse.emf.ecore.resource.Resource;
23
import org.eclipse.emf.ecore.resource.Resource;
Lines 39-44 Link Here
39
import org.eclipse.jface.operation.IRunnableWithProgress;
40
import org.eclipse.jface.operation.IRunnableWithProgress;
40
import org.eclipse.jface.viewers.IStructuredSelection;
41
import org.eclipse.jface.viewers.IStructuredSelection;
41
import org.eclipse.jface.wizard.Wizard;
42
import org.eclipse.jface.wizard.Wizard;
43
import org.eclipse.ltk.core.refactoring.Change;
44
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
42
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
45
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
43
46
44
/**
47
/**
Lines 100-106 Link Here
100
		IImplementor implementor = getTestSuite().getImplementor();
103
		IImplementor implementor = getTestSuite().getImplementor();
101
		this.generator = createGenerator();
104
		this.generator = createGenerator();
102
		
105
		
103
		if (generator.validate(testSuite).getSeverity() == IStatus.OK) {
106
		boolean isOk = false;
107
		try {
108
			RefactoringStatus status = generator.checkAllConditions(new NullProgressMonitor());
109
			isOk = status.isOK();
110
		} catch (CoreException e) {
111
			ToolsUiPlugin.logError(e);
112
		}
113
		if (isOk) {
104
			// Show only the project and source page
114
			// Show only the project and source page
105
			IJavaProject[] javaProjects = TestJavaUtil.getJavaProjects();
115
			IJavaProject[] javaProjects = TestJavaUtil.getJavaProjects();
106
			projectAndSourcePage = new ProjectAndSourcePage(implementor, javaProjects);
116
			projectAndSourcePage = new ProjectAndSourcePage(implementor, javaProjects);
Lines 162-171 Link Here
162
				}
172
				}
163
			}
173
			}
164
				
174
				
165
			addRequiredLibraries(generator);		
166
			try
175
			try
167
			{
176
			{
168
				generator.generate(getTestSuite(), mon);
177
				Change change = generator.createChange(new NullProgressMonitor());
178
				change.perform(new NullProgressMonitor());
169
			}
179
			}
170
			catch(Exception e)
180
			catch(Exception e)
171
			{
181
			{
Lines 226-239 Link Here
226
	
236
	
227
	protected Generator createGenerator()
237
	protected Generator createGenerator()
228
	{
238
	{
229
		return new JUnitGenerator(new AutomaticDependencyUpdater());
239
		return new JUnitGenerator(getTestSuite(), new AutomaticDependencyUpdater());
230
	}
240
	}
231
	
241
	
232
	protected void addRequiredLibraries(Generator generator)
233
	{
234
		JUnitGenerator junitGenerator = (JUnitGenerator)generator;
235
		junitGenerator.getProjectDependencyUpdater().addRequiredPlugin(PLUGIN_ID_JUNIT, null);
236
		junitGenerator.getProjectDependencyUpdater().addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
237
		junitGenerator.getProjectDependencyUpdater().addRequiredPlugin(CorePlugin.getID(), "java.runner.jar"); //$NON-NLS-1$
238
	}
239
}
242
}
(-)src/org/eclipse/hyades/test/tools/ui/http/internal/junit/wizard/HttpGenerateWizard.java (-20 / +4 lines)
Lines 12-26 Link Here
12
12
13
package org.eclipse.hyades.test.tools.ui.http.internal.junit.wizard;
13
package org.eclipse.hyades.test.tools.ui.http.internal.junit.wizard;
14
14
15
import org.eclipse.hyades.test.tools.core.CorePlugin;
15
import org.eclipse.hyades.test.tools.core.internal.common.codegen.AutomaticDependencyUpdater;
16
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Generator;
16
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Generator;
17
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
17
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
18
import org.eclipse.hyades.test.tools.ui.http.internal.codegen.HttpGenerator;
18
import org.eclipse.hyades.test.tools.ui.http.internal.codegen.HttpGenerator;
19
import org.eclipse.hyades.test.tools.ui.java.internal.junit.wizard.GenerateWizard;
19
import org.eclipse.hyades.test.tools.ui.java.internal.junit.wizard.GenerateWizard;
20
20
21
public class HttpGenerateWizard 
21
public class HttpGenerateWizard extends GenerateWizard {
22
extends GenerateWizard
22
	
23
{
24
    public HttpGenerateWizard() {
23
    public HttpGenerateWizard() {
25
        super();
24
        super();
26
        setWindowTitle(ToolsUiPlugin.getString("GEN_WTITLE")); //$NON-NLS-1$
25
        setWindowTitle(ToolsUiPlugin.getString("GEN_WTITLE")); //$NON-NLS-1$
Lines 31-52 Link Here
31
	 */
30
	 */
32
	protected Generator createGenerator()
31
	protected Generator createGenerator()
33
	{
32
	{
34
		return new HttpGenerator();
33
		return new HttpGenerator(getTestSuite(), new AutomaticDependencyUpdater());
35
	}
34
	}
36
	
35
	
37
	/**
38
	 * @see org.eclipse.hyades.test.java.internal.junit.wizard.GenerateWizard#addRequiredLibraries(org.eclipse.hyades.test.common.internal.codegen.Generator)
39
	 */
40
	protected void addRequiredLibraries(Generator generator)
41
	{
42
		HttpGenerator httpGenerator = (HttpGenerator)generator;
43
		httpGenerator.getProjectDependencyUpdater().addRequiredPlugin(PLUGIN_ID_JUNIT, null);
44
		httpGenerator.getProjectDependencyUpdater().addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
45
		httpGenerator.getProjectDependencyUpdater().addRequiredPlugin(CorePlugin.getID(), "http.runner.jar"); //$NON-NLS-1$
46
47
		//add additional libraries in order to run as a JUnit - bugzilla_98741  jn
48
		httpGenerator.getProjectDependencyUpdater().addRequiredPlugin("org.eclipse.hyades.logging.core", null); //$NON-NLS-1$
49
		httpGenerator.getProjectDependencyUpdater().addRequiredPlugin("org.eclipse.emf.ecore", null); //$NON-NLS-1$
50
		httpGenerator.getProjectDependencyUpdater().addRequiredPlugin("org.eclipse.emf.common", null); //$NON-NLS-1$
51
	}
52
}
36
}
(-)plugin.xml (+26 lines)
Lines 441-446 Link Here
441
               id="org.eclipse.hyades.test.tools.ui.JUnitTestSuiteOpenCode"/>
441
               id="org.eclipse.hyades.test.tools.ui.JUnitTestSuiteOpenCode"/>
442
      </objectContribution>
442
      </objectContribution>
443
   </extension>   
443
   </extension>   
444
   <extension
445
         point="org.eclipse.ui.popupMenus">
446
      <objectContribution
447
            adaptable="false"
448
            objectClass="org.eclipse.hyades.test.ui.internal.navigator.proxy.DefaultTestCaseProxyNode"
449
            id="org.eclipse.hyades.test.tools.ui.JUnitTestCaseContribution">
450
         <action
451
               enablesFor="1"
452
               label="%OPEN_JUNIT_TEST_SUITE_CODE"
453
               class="org.eclipse.hyades.test.tools.ui.java.internal.junit.navigator.actions.OpenJUnitTestSuiteCodeAction"
454
               menubarPath="org.eclipse.ui.OpenWithSubMenu"
455
               id="org.eclipse.hyades.test.tools.ui.JUnitTestCaseOpenCode"/>
456
      </objectContribution>
457
   </extension>   
444
   
458
   
445
<!-- #######################################################################  -->
459
<!-- #######################################################################  -->
446
<!--    Plugin JUnit extensions                                                       -->
460
<!--    Plugin JUnit extensions                                                       -->
Lines 566-570 Link Here
566
            recorderMessageHandlers="org.eclipse.hyades.execution.recorder.http.local.HttpRecorderDataProcessor"
580
            recorderMessageHandlers="org.eclipse.hyades.execution.recorder.http.local.HttpRecorderDataProcessor"
567
            wizardPageProvider="org.eclipse.tptp.test.tools.internal.recorder.http.providers.HttpRecorderWizardProvider"/>
581
            wizardPageProvider="org.eclipse.tptp.test.tools.internal.recorder.http.providers.HttpRecorderWizardProvider"/>
568
   </extension>
582
   </extension>
583
      <extension
584
            point="org.eclipse.ui.preferencePages">
585
         <page
586
               category="org.eclipse.hyades.test.ui.internal.preference.TestPreferencePage"
587
               class="org.eclipse.hyades.test.tools.ui.java.internal.junit.preferences.JUnitPreferencesPage"
588
               id="junit"
589
               name="%JUNIT_PREFS_PAGE_TITLE"/>
590
      </extension>
591
      <extension
592
            point="org.eclipse.core.runtime.preferences">
593
         <initializer class="org.eclipse.hyades.test.tools.ui.java.internal.junit.preferences.JUnitPreferences"/>
594
      </extension>
569
   
595
   
570
</plugin>
596
</plugin>
(-)plugin.properties (-1 / +15 lines)
Lines 110-115 Link Here
110
STR_WB_PROJECT                     = &Java Project:
110
STR_WB_PROJECT                     = &Java Project:
111
STR_WB_SRC_FOLDER                  = Source &Folder:
111
STR_WB_SRC_FOLDER                  = Source &Folder:
112
STR_WB_SOURCE_BTN                  = B&rowse...
112
STR_WB_SOURCE_BTN                  = B&rowse...
113
SOURCE_INFO_VIEWER_OPEN_CLASS      = Open
113
_ERROR_WIZ_EMPTY_PROJECT           = Java project name cannot be empty.
114
_ERROR_WIZ_EMPTY_PROJECT           = Java project name cannot be empty.
114
_ERROR_WIZ_EMPTY_FOLDER            = Source folder name cannot be empty.
115
_ERROR_WIZ_EMPTY_FOLDER            = Source folder name cannot be empty.
115
_ERROR_WIZ_NOT_EXIST_PROJECT       = Java project does not exist.
116
_ERROR_WIZ_NOT_EXIST_PROJECT       = Java project does not exist.
Lines 130-135 Link Here
130
NO_PACK                            = There is no packages in the workspace.
131
NO_PACK                            = There is no packages in the workspace.
131
NO_SRC                             = There are no source folders in the workspace.
132
NO_SRC                             = There are no source folders in the workspace.
132
STR_BTN_CREATE                     = &Create...
133
STR_BTN_CREATE                     = &Create...
134
CODE_UPDATE                        = Code Update
135
CODE_UPDATE_PREVIEW                = Code Update Preview
133
136
134
WIZ_ERR_NOT_EXIST_FOLDER           = Selected location is not a source folder.
137
WIZ_ERR_NOT_EXIST_FOLDER           = Selected location is not a source folder.
135
138
Lines 153-159 Link Here
153
W_LWR_INV                          = invocation
156
W_LWR_INV                          = invocation
154
Q_OVR_FILE                         = This test has been previously generated.\nIf you have made manual changes to the existing files they will be lost.\n\nWould you like to continue?
157
Q_OVR_FILE                         = This test has been previously generated.\nIf you have made manual changes to the existing files they will be lost.\n\nWould you like to continue?
155
158
156
159
#Code Update wizard
160
CODE_UPDATE_OPTIONS=JUnit Code Update Preview Options
161
UPDATE_CODE_PAGE_DESCR=Define the options related to code update preview.
162
ALWAYS_SKIP_TO_PREVIEW=Always skip to the preview page
163
SHOW_PREVIEW=Show the preview page
164
ALWAYS=Always
165
ONLY_IF_DESTRUCTIVE=Only when there are destructive changes
166
NEVER=Never
167
168
#JUnit preferences
169
CODE_UPDATE_GROUP=Code update
170
JUNIT_PREFS_PAGE_TITLE=TPTP JUnit 
157
171
158
###############################################################################
172
###############################################################################
159
#  HTTP properties
173
#  HTTP properties
(-)src/org/eclipse/hyades/test/tools/ui/plugin/internal/junit/wizard/PluginJUnitTestSuiteNewWizard.java (-2 / +3 lines)
Lines 12-17 Link Here
12
12
13
package org.eclipse.hyades.test.tools.ui.plugin.internal.junit.wizard;
13
package org.eclipse.hyades.test.tools.ui.plugin.internal.junit.wizard;
14
14
15
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
15
import org.eclipse.hyades.test.tools.core.common.TestCommon;
16
import org.eclipse.hyades.test.tools.core.common.TestCommon;
16
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
17
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator;
17
import org.eclipse.hyades.test.tools.core.internal.plugin.codegen.PluginProjectDependencyUpdater;
18
import org.eclipse.hyades.test.tools.core.internal.plugin.codegen.PluginProjectDependencyUpdater;
Lines 53-60 Link Here
53
		return TestCommon.PLUGIN_JUNIT_TEST_SUITE_TYPE;
54
		return TestCommon.PLUGIN_JUNIT_TEST_SUITE_TYPE;
54
	}
55
	}
55
56
56
	protected JUnitGenerator createGenerator() {
57
	protected JUnitGenerator createGenerator(ITestSuite testSuite) {
57
		return new JUnitGenerator(new PluginProjectDependencyUpdater(), getSourcePage().getSuperClass());
58
		return new JUnitGenerator(testSuite, new PluginProjectDependencyUpdater(), getSourcePage().getSuperClass());
58
	}
59
	}
59
60
60
	protected void initSourcePage(IStructuredSelection structuredSelection, LocationPage locationPage) {
61
	protected void initSourcePage(IStructuredSelection structuredSelection, LocationPage locationPage) {
(-)src/org/eclipse/hyades/test/tools/ui/http/internal/codegen/HttpGenerator.java (-15 / +33 lines)
Lines 11-51 Link Here
11
 **********************************************************************/
11
 **********************************************************************/
12
package org.eclipse.hyades.test.tools.ui.http.internal.codegen;
12
package org.eclipse.hyades.test.tools.ui.http.internal.codegen;
13
13
14
import java.io.ByteArrayInputStream;
14
import java.util.Collection;
15
15
16
import org.eclipse.core.resources.IFile;
16
import org.eclipse.core.resources.IProject;
17
import org.eclipse.core.runtime.CoreException;
17
import org.eclipse.core.runtime.IProgressMonitor;
18
import org.eclipse.core.runtime.IProgressMonitor;
18
19
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
19
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
20
import org.eclipse.hyades.test.tools.core.internal.common.codegen.AutomaticDependencyUpdater;
20
import org.eclipse.hyades.test.tools.core.CorePlugin;
21
import org.eclipse.hyades.test.tools.core.internal.common.codegen.DelegateProjectDependencyUpdater;
21
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
22
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
23
import org.eclipse.hyades.test.tools.core.internal.common.codegen.IProjectDependencyUpdater;
22
import org.eclipse.hyades.test.tools.core.internal.common.codegen.JavaGenerator;
24
import org.eclipse.hyades.test.tools.core.internal.common.codegen.JavaGenerator;
25
import org.eclipse.hyades.test.tools.core.internal.java.codegen.JUnitGenerator.JUnitProjectDependencyUpdater;
23
26
24
/**
27
/**
25
 * @author marcelop
28
 * @author marcelop
26
 * @since 1.0.2
29
 * @since 1.0.2
27
 */
30
 */
28
public class HttpGenerator extends JavaGenerator
31
public class HttpGenerator extends JavaGenerator {
29
{
30
	
32
	
31
	public HttpGenerator() {
33
	public final static String PLUGIN_ID_JUNIT = "org.junit"; //$NON-NLS-1$
32
		super(new AutomaticDependencyUpdater());
34
	public final static String PLUGIN_ID_EXECUTION_CORE = "org.eclipse.hyades.execution.core"; //$NON-NLS-1$
35
	public final static String PLUGIN_ID_EXECUTION_REMOTE = "org.eclipse.hyades.execution.remote"; //$NON-NLS-1$
36
37
	public HttpGenerator(ITestSuite testSuite, IProjectDependencyUpdater updater) {
38
		super(testSuite, new HttpProjectDependencyUpdater(updater));
33
	}
39
	}
34
	
40
	
35
	/**
41
	/**
36
	 * @see org.eclipse.hyades.test.common.internal.codegen.Generator#generateFile(org.eclipse.hyades.models.common.facades.behavioral.ITestSuite, org.eclipse.core.resources.IFile, org.eclipse.core.runtime.IProgressMonitor)
42
	 * @see org.eclipse.hyades.test.common.internal.codegen.Generator#generateFile(org.eclipse.hyades.models.common.facades.behavioral.ITestSuite, org.eclipse.core.resources.IFile, org.eclipse.core.runtime.IProgressMonitor)
37
	 */
43
	 */
38
	protected void generateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor)
44
	protected String generateCode(IProgressMonitor monitor) throws CoreException
39
	throws Exception
40
	{
45
	{
41
		GenTestSuite genTestSuite = new GenTestSuite();
46
		GenTestSuite genTestSuite = new GenTestSuite();
42
		Helper helper = new Helper();
47
		Helper helper = new Helper();
43
		computeTestMethodNames(testSuite, false, helper);
48
		computeTestMethodNames(getTestSuite(), false, helper);
44
		String content = Helper.formatContent(genTestSuite.generate(testSuite, helper));
49
		String content = Helper.formatContent(genTestSuite.generate(getTestSuite(), helper));
45
		helper.dispose();
50
		helper.dispose();
46
		// use UTF-8 encoding - bugzilla_88029 running test with non-ASCII characters.
51
		return content;
47
		file.create(new ByteArrayInputStream(content.getBytes(CHARSET_UTF8)), true, monitor);
52
	}
48
		file.setCharset(CHARSET_UTF8, monitor);
53
54
	static class HttpProjectDependencyUpdater extends DelegateProjectDependencyUpdater {
55
56
		public HttpProjectDependencyUpdater(IProjectDependencyUpdater delegate) {
57
			super(delegate);
58
			addRequiredPlugin(PLUGIN_ID_JUNIT, null);
59
			addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
60
			addRequiredPlugin(CorePlugin.getID(), "http.runner.jar"); //$NON-NLS-1$
61
			//add additional libraries in order to run as a JUnit - bugzilla_98741  jn
62
			addRequiredPlugin("org.eclipse.hyades.logging.core", null); //$NON-NLS-1$
63
			addRequiredPlugin("org.eclipse.emf.ecore", null); //$NON-NLS-1$
64
			addRequiredPlugin("org.eclipse.emf.common", null); //$NON-NLS-1$
65
		}
66
		
49
	}
67
	}
50
68
51
}
69
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/navigator/actions/OpenJUnitTestSuiteCodeAction.java (-8 / +61 lines)
Lines 12-25 Link Here
12
package org.eclipse.hyades.test.tools.ui.java.internal.junit.navigator.actions;
12
package org.eclipse.hyades.test.tools.ui.java.internal.junit.navigator.actions;
13
13
14
import org.eclipse.core.resources.IFile;
14
import org.eclipse.core.resources.IFile;
15
import org.eclipse.hyades.models.common.testprofile.TPFTestCase;
15
import org.eclipse.hyades.models.common.testprofile.TPFTestSuite;
16
import org.eclipse.hyades.models.common.testprofile.TPFTestSuite;
17
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
16
import org.eclipse.hyades.test.tools.core.java.JUnitTestSuiteFacade;
18
import org.eclipse.hyades.test.tools.core.java.JUnitTestSuiteFacade;
19
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
17
import org.eclipse.hyades.test.tools.ui.java.internal.junit.navigator.JUnitTestSuiteProxyNode;
20
import org.eclipse.hyades.test.tools.ui.java.internal.junit.navigator.JUnitTestSuiteProxyNode;
21
import org.eclipse.hyades.test.ui.internal.navigator.proxy.DefaultTestCaseProxyNode;
22
import org.eclipse.hyades.test.ui.navigator.IProxyNode;
18
import org.eclipse.hyades.ui.internal.util.UIUtil;
23
import org.eclipse.hyades.ui.internal.util.UIUtil;
24
import org.eclipse.jdt.core.ICompilationUnit;
25
import org.eclipse.jdt.core.IJavaElement;
26
import org.eclipse.jdt.core.IMethod;
27
import org.eclipse.jdt.core.IType;
28
import org.eclipse.jdt.core.JavaCore;
29
import org.eclipse.jdt.core.JavaModelException;
30
import org.eclipse.jdt.ui.JavaUI;
19
import org.eclipse.jface.action.IAction;
31
import org.eclipse.jface.action.IAction;
20
import org.eclipse.jface.viewers.ISelection;
32
import org.eclipse.jface.viewers.ISelection;
21
import org.eclipse.jface.viewers.IStructuredSelection;
33
import org.eclipse.jface.viewers.IStructuredSelection;
22
import org.eclipse.ui.IActionDelegate;
34
import org.eclipse.ui.IActionDelegate;
35
import org.eclipse.ui.IEditorPart;
36
import org.eclipse.ui.PartInitException;
23
37
24
/**
38
/**
25
 * Action to open the source code of a JUnit test suite.
39
 * Action to open the source code of a JUnit test suite.
Lines 34-47 Link Here
34
     * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
48
     * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
35
     */
49
     */
36
    public void run(IAction action) {
50
    public void run(IAction action) {
37
        TPFTestSuite ts = ((JUnitTestSuiteProxyNode)selection.getFirstElement()).getTestSuite();
51
    	IProxyNode proxy = (IProxyNode) selection.getFirstElement();
38
		IFile javaFile = JUnitTestSuiteFacade.getJUnitSourceFile(ts);
52
    	if (proxy instanceof JUnitTestSuiteProxyNode) {
39
        if(javaFile != null) {
53
    		TPFTestSuite ts = ((JUnitTestSuiteProxyNode)proxy).getTestSuite();
40
            UIUtil.openEditor(javaFile, null, false);
54
    		IFile javaFile = JUnitTestSuiteFacade.getJUnitSourceFile(ts);
41
        }
55
	        if(javaFile != null) {
42
        if(ts.eResource() != null) {
56
	            UIUtil.openEditor(javaFile, null, false);
43
            ts.eResource().unload();
57
	        }
44
        }
58
	        if(ts.eResource() != null) {
59
	            ts.eResource().unload();
60
	        }
61
    	} else if (proxy instanceof DefaultTestCaseProxyNode) {
62
    		DefaultTestCaseProxyNode tcpn = (DefaultTestCaseProxyNode)proxy;
63
    		if (tcpn.getParent() instanceof JUnitTestSuiteProxyNode) {
64
    			TPFTestCase tc = tcpn.getTestCase();
65
    			IFile javaFile = JUnitTestSuiteFacade.getJUnitSourceFile(tc.getTestSuite());
66
    			ICompilationUnit cu = JavaCore.createCompilationUnitFrom(javaFile);
67
    			try {
68
	    			if (cu.exists() && cu.isStructureKnown()) {
69
	    				String methodName = Helper.getTestMethodName(tc);
70
	    				IType primaryType = cu.findPrimaryType();
71
	    				if (primaryType != null && tc != null) {
72
	    					IMethod m = findMethodWithNoParameter(primaryType, methodName);
73
	    					if (m != null) {
74
	    						IEditorPart part = JavaUI.openInEditor(m);
75
	    						JavaUI.revealInEditor(part, (IJavaElement)m);
76
	    					}
77
	    				}
78
	    			}
79
    			} catch (JavaModelException e) {
80
    				ToolsUiPlugin.logError(e);
81
    			} catch (PartInitException e) {
82
    				ToolsUiPlugin.logError(e);
83
				}
84
    		}
85
    	}
86
    }
87
    
88
    private IMethod findMethodWithNoParameter(IType type, String name) throws JavaModelException {
89
    	IMethod[] methods = type.getMethods();
90
    	for (int i = 0; i < methods.length; i++) {
91
			if (name.equals(methods[i].getElementName())) {
92
				if (methods[i].getParameterTypes().length == 0) {
93
					return methods[i];
94
				}
95
			}
96
		}
97
    	return null;
45
    }
98
    }
46
99
47
    /* (non-Javadoc)
100
    /* (non-Javadoc)
(-)META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 69-73 Link Here
69
 org.eclipse.tptp.platform.report.core;bundle-version="[4.1.100,5.0.0)",
69
 org.eclipse.tptp.platform.report.core;bundle-version="[4.1.100,5.0.0)",
70
 org.eclipse.ui.forms;bundle-version="[3.2.0,4.0.0)",
70
 org.eclipse.ui.forms;bundle-version="[3.2.0,4.0.0)",
71
 org.eclipse.pde.core;bundle-version="[3.2.0,4.0.0)",
71
 org.eclipse.pde.core;bundle-version="[3.2.0,4.0.0)",
72
 org.eclipse.pde.ui;bundle-version="[3.2.0,4.0.0)"
72
 org.eclipse.pde.ui;bundle-version="[3.2.0,4.0.0)",
73
 org.eclipse.ltk.ui.refactoring;bundle-version="[3.2.0,4.0.0)"
73
Eclipse-LazyStart: true
74
Eclipse-LazyStart: true
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/preferences/JUnitCodeUpdatePreviewOptionsControl.java (+120 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.ui.java.internal.junit.preferences;
14
15
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
16
import org.eclipse.jface.preference.IPreferenceStore;
17
import org.eclipse.swt.SWT;
18
import org.eclipse.swt.layout.GridData;
19
import org.eclipse.swt.layout.GridLayout;
20
import org.eclipse.swt.layout.RowLayout;
21
import org.eclipse.swt.widgets.Button;
22
import org.eclipse.swt.widgets.Composite;
23
import org.eclipse.swt.widgets.Control;
24
import org.eclipse.swt.widgets.Group;
25
26
public class JUnitCodeUpdatePreviewOptionsControl extends Composite {
27
28
	private Button skipPage;
29
	private Button alwaysPreview;
30
	private Button onlyDestructive;
31
	private Button neverPreview;
32
	
33
	public JUnitCodeUpdatePreviewOptionsControl(Composite parent, int style) {
34
		super(parent, style);
35
		GridLayout layout = new GridLayout(1, false);
36
		layout.verticalSpacing = 15;
37
		setLayout(layout);
38
		
39
		Control group = createPreviewGroup();
40
		group.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
41
		
42
		skipPage = new Button(this, SWT.CHECK);
43
		skipPage.setText(ToolsUiPlugin.getString("ALWAYS_SKIP_TO_PREVIEW")); //$NON-NLS-1$
44
	}
45
46
	/**
47
	 * @param parent
48
	 */
49
	private Control createPreviewGroup() {
50
		Group composite = new Group(this, SWT.NONE);
51
		composite.setText(ToolsUiPlugin.getString("SHOW_PREVIEW")); //$NON-NLS-1$
52
		RowLayout layout = new RowLayout(SWT.VERTICAL);
53
		layout.spacing = 6;
54
		layout.marginWidth = 5;
55
		layout.marginHeight = 6;
56
		composite.setLayout(layout);
57
		
58
		alwaysPreview = new Button(composite, SWT.RADIO);
59
		alwaysPreview.setText(ToolsUiPlugin.getString("ALWAYS")); //$NON-NLS-1$
60
		
61
		onlyDestructive = new Button(composite, SWT.RADIO);
62
		onlyDestructive.setText(ToolsUiPlugin.getString("ONLY_IF_DESTRUCTIVE")); //$NON-NLS-1$
63
		
64
		neverPreview = new Button(composite, SWT.RADIO);
65
		neverPreview.setText(ToolsUiPlugin.getString("NEVER")); //$NON-NLS-1$
66
		return composite;
67
	}
68
	
69
	private void resetPreview() {
70
		alwaysPreview.setSelection(false);
71
		onlyDestructive.setSelection(false);
72
		neverPreview.setSelection(false);
73
	}
74
	
75
	public void initialize(IPreferenceStore prefs) {
76
		resetPreview();
77
		switch (prefs.getInt(JUnitPreferences.UPDATE_PREVIEW_MODE)) {
78
		case JUnitPreferences.PREVIEW_ALWAYS:
79
			alwaysPreview.setSelection(true);
80
			break;
81
		case JUnitPreferences.PREVIEW_IF_DESTRUCTIVE:
82
			onlyDestructive.setSelection(true);
83
			break;
84
		case JUnitPreferences.PREVIEW_NEVER:
85
			neverPreview.setSelection(true);
86
			break;
87
		}
88
		skipPage.setSelection(prefs.getBoolean(JUnitPreferences.SKIP_TO_PREVIEW_PAGE));
89
	}
90
	
91
	public void save(IPreferenceStore prefs) {
92
		int value;
93
		if (alwaysPreview.getSelection()) {
94
			value = JUnitPreferences.PREVIEW_ALWAYS;
95
		} else if (onlyDestructive.getSelection()) {
96
			value = JUnitPreferences.PREVIEW_IF_DESTRUCTIVE;
97
		} else {
98
			value = JUnitPreferences.PREVIEW_NEVER;
99
		}
100
		prefs.setValue(JUnitPreferences.UPDATE_PREVIEW_MODE, value);
101
		prefs.setValue(JUnitPreferences.SKIP_TO_PREVIEW_PAGE, skipPage.getSelection());
102
	}
103
104
	public void resetToDefaults(IPreferenceStore prefs) {
105
		resetPreview();
106
		switch (prefs.getDefaultInt(JUnitPreferences.UPDATE_PREVIEW_MODE)) {
107
		case JUnitPreferences.PREVIEW_ALWAYS:
108
			alwaysPreview.setSelection(true);
109
			break;
110
		case JUnitPreferences.PREVIEW_IF_DESTRUCTIVE:
111
			onlyDestructive.setSelection(true);
112
			break;
113
		case JUnitPreferences.PREVIEW_NEVER:
114
			neverPreview.setSelection(true);
115
			break;
116
		}
117
		skipPage.setSelection(prefs.getDefaultBoolean(JUnitPreferences.SKIP_TO_PREVIEW_PAGE));
118
	}
119
120
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/preferences/JUnitPreferencesPage.java (+69 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.ui.java.internal.junit.preferences;
14
15
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
16
import org.eclipse.jface.preference.PreferencePage;
17
import org.eclipse.swt.SWT;
18
import org.eclipse.swt.layout.GridData;
19
import org.eclipse.swt.layout.GridLayout;
20
import org.eclipse.swt.layout.RowLayout;
21
import org.eclipse.swt.widgets.Composite;
22
import org.eclipse.swt.widgets.Control;
23
import org.eclipse.swt.widgets.Group;
24
import org.eclipse.ui.IWorkbench;
25
import org.eclipse.ui.IWorkbenchPreferencePage;
26
27
public class JUnitPreferencesPage extends PreferencePage implements IWorkbenchPreferencePage {
28
29
	private JUnitCodeUpdatePreviewOptionsControl previewOptions;
30
	
31
	public JUnitPreferencesPage() {
32
		setPreferenceStore(ToolsUiPlugin.getDefault().getPreferenceStore());
33
	}
34
	
35
	protected Control createContents(Composite parent) {
36
		Composite composite = new Composite(parent, SWT.NONE);
37
		GridLayout layout = new GridLayout(1, true);
38
		composite.setLayout(layout);
39
		Control codeupdate = createCodeUpdateGroup(composite);
40
		codeupdate.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
41
		return composite;
42
	}
43
	
44
	private Control createCodeUpdateGroup(Composite parent) {
45
		Group previewGroup = new Group(parent, SWT.None);
46
		previewGroup.setText(ToolsUiPlugin.getString("CODE_UPDATE_GROUP")); //$NON-NLS-1$
47
		previewGroup.setLayout(new RowLayout(SWT.VERTICAL));
48
		
49
		previewOptions = new JUnitCodeUpdatePreviewOptionsControl(previewGroup, SWT.NONE);
50
		previewOptions.initialize(getPreferenceStore());
51
		
52
		return previewGroup;
53
	}
54
55
	public boolean performOk() {
56
		previewOptions.save(getPreferenceStore());
57
		return true;
58
	}
59
	
60
	protected void performDefaults() {
61
		previewOptions.resetToDefaults(getPreferenceStore());
62
		super.performDefaults();
63
	}
64
65
	public void init(IWorkbench workbench) {
66
		// NOP
67
	}
68
69
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/preferences/JUnitPreferences.java (+42 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.ui.java.internal.junit.preferences;
14
15
import org.eclipse.core.runtime.Preferences;
16
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
17
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
18
19
20
/**
21
 * Preferences constants for JUnit preferences.
22
 * @author jcanches
23
 * @since 4.3
24
 */
25
public class JUnitPreferences extends AbstractPreferenceInitializer {
26
27
	public final static String UPDATE_PREVIEW_MODE = "junit.previewMode"; //$NON-NLS-1$
28
	public final static int PREVIEW_ALWAYS = 0;
29
	public final static int PREVIEW_IF_DESTRUCTIVE = 1;
30
	public final static int PREVIEW_NEVER = 2;
31
	public final static int DEFAULT_UPDATE_PREVIEW_MODE = PREVIEW_ALWAYS;
32
	
33
	public final static String SKIP_TO_PREVIEW_PAGE = "junit.skipToPreviewPage"; //$NON-NLS-1$
34
	public final static boolean DEFAULT_SKIP_TO_PREVIEW_PAGE = false;
35
	
36
	public void initializeDefaultPreferences() {
37
		Preferences prefs = ToolsUiPlugin.getDefault().getPluginPreferences();
38
		prefs.setDefault(UPDATE_PREVIEW_MODE, DEFAULT_UPDATE_PREVIEW_MODE);
39
		prefs.setDefault(SKIP_TO_PREVIEW_PAGE, DEFAULT_SKIP_TO_PREVIEW_PAGE);
40
	}
41
42
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/UpdateCodeWizardPage.java (+42 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.ui.java.internal.junit.wizard;
14
15
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
16
import org.eclipse.hyades.test.tools.ui.java.internal.junit.preferences.JUnitCodeUpdatePreviewOptionsControl;
17
import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
18
import org.eclipse.swt.SWT;
19
import org.eclipse.swt.widgets.Composite;
20
21
public class UpdateCodeWizardPage extends UserInputWizardPage {
22
23
	private JUnitCodeUpdatePreviewOptionsControl control;
24
	
25
	protected UpdateCodeWizardPage() {
26
		super("UpdateCodeWizardPage"); //$NON-NLS-1$
27
		setTitle(ToolsUiPlugin.getString("CODE_UPDATE_OPTIONS")); //$NON-NLS-1$
28
		setDescription(ToolsUiPlugin.getString("UPDATE_CODE_PAGE_DESCR")); //$NON-NLS-1$
29
	}
30
31
	public void createControl(Composite parent) {
32
		initializeDialogUnits(parent);
33
		control = new JUnitCodeUpdatePreviewOptionsControl(parent, SWT.NONE);
34
		control.initialize(ToolsUiPlugin.getDefault().getPreferenceStore());
35
		setControl(control);
36
	}
37
	
38
	/* package */ void saveContent() {
39
		control.save(ToolsUiPlugin.getDefault().getPreferenceStore());
40
	}
41
	
42
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/UpdateCodeWizard.java (+56 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 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
 * $Id: $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
13
package org.eclipse.hyades.test.tools.ui.java.internal.junit.wizard;
14
15
import org.eclipse.core.runtime.Preferences;
16
import org.eclipse.hyades.test.tools.ui.ToolsUiPlugin;
17
import org.eclipse.hyades.test.tools.ui.java.internal.junit.preferences.JUnitPreferences;
18
import org.eclipse.jface.wizard.IWizardPage;
19
import org.eclipse.ltk.core.refactoring.Refactoring;
20
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
21
22
public class UpdateCodeWizard extends RefactoringWizard {
23
24
	UpdateCodeWizardPage previewOptionsPage;
25
	
26
	public UpdateCodeWizard(Refactoring refactoring, boolean showPreview) {
27
		super(refactoring, computeFlags(showPreview));
28
	}
29
	
30
	private static int computeFlags(boolean showPreview) {
31
		int flags = RefactoringWizard.WIZARD_BASED_USER_INTERFACE;
32
		if (!showPreview) flags |= RefactoringWizard.NO_PREVIEW_PAGE;
33
		return flags;
34
	}
35
	
36
	protected void addUserInputPages() {
37
		previewOptionsPage = new UpdateCodeWizardPage();
38
		addPage(previewOptionsPage);
39
	}
40
41
	public IWizardPage getStartingPage() {
42
		Preferences prefs = ToolsUiPlugin.getDefault().getPluginPreferences();
43
		boolean skipFirstPage = prefs.getBoolean(JUnitPreferences.SKIP_TO_PREVIEW_PAGE);
44
		if (skipFirstPage) {
45
			return super.getStartingPage().getNextPage();
46
		} else {
47
			return super.getStartingPage();
48
		}
49
	}
50
51
	public boolean performFinish() {
52
		previewOptionsPage.saveContent();
53
		return super.performFinish();
54
	}
55
	
56
}

Return to bug 134254