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

(-)plugin.xml (+14 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                                                       -->
(-).project (-1 / +1 lines)
Lines 1-6 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
2
<projectDescription>
3
	<name>org.eclipse.hyades.test.tools.ui</name>
3
	<name>org.eclipse.hyades.test.tools.ui_134254</name>
4
	<comment></comment>
4
	<comment></comment>
5
	<projects>
5
	<projects>
6
	</projects>
6
	</projects>
(-)plugin.properties (+1 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.
(-)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
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/editor/JUnitEditorExtension.java (-15 / +70 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.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 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-130 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
				}
129
			}
131
			}
130
			// Perform the save
132
			// Perform the save
Lines 133-136 Link Here
133
			monitor.done();
135
			monitor.done();
134
		}
136
		}
135
	}
137
	}
138
139
	private boolean performBatchChange(Change change) {
140
		try {
141
			change.initializeValidationData(new NullProgressMonitor());
142
			if (change.isValid(new NullProgressMonitor()).isOK()) {
143
				change.perform(new NullProgressMonitor());
144
				return true;
145
			}
146
			return false;
147
		} catch (OperationCanceledException e) {
148
			return false;
149
		} catch (CoreException e) {
150
			ToolsUiPlugin.logError(e);
151
			return false;
152
		}
153
	}
154
	
155
	protected boolean performChange(Refactoring refactoring) {
156
		Preferences prefs = ToolsUiPlugin.getDefault().getPluginPreferences();
157
		int previewPref = prefs.getInt(JUnitPreferences.UPDATE_PREVIEW_MODE);
158
		boolean showWizard = previewPref != JUnitPreferences.PREVIEW_NEVER;
159
		Change change = null;
160
		try {
161
			RefactoringStatus status = refactoring.checkAllConditions(new NullProgressMonitor());
162
			if (status.hasEntries()) {
163
				// If there's something that the user should be aware of, always show the
164
				// preview.
165
				showWizard = true;
166
			} else {
167
				change = refactoring.createChange(new NullProgressMonitor());
168
				if (previewPref == JUnitPreferences.PREVIEW_IF_DESTRUCTIVE && !Helper.isDestructiveChange(change)) {
169
					showWizard = false;
170
				}
171
			}
172
		} catch (OperationCanceledException e1) {
173
			return false;
174
		} catch (CoreException e1) {
175
			ToolsUiPlugin.logError(e1);
176
			return false;
177
		}
178
		if (showWizard || (change != null && !performBatchChange(change))) {
179
			UpdateCodeWizard wizard = new UpdateCodeWizard(refactoring, showWizard);
180
			wizard.setDefaultPageTitle("Code Update Preview");
181
			RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
182
			try {
183
				return op.run(this.getHyadesEditorPart().getEditorPart().getEditorSite().getShell(), "Refactoring Preview") == IDialogConstants.OK_ID;
184
			} catch (InterruptedException e) {
185
				ToolsUiPlugin.logError(e);
186
				return false;
187
			}
188
		}
189
		return true;
190
	}
136
}
191
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/editor/JUnitTestCasesForm.java (+5 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 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 / +96 lines)
Lines 39-44 Link Here
39
import org.eclipse.hyades.test.ui.editor.form.util.WidgetFactory;
39
import org.eclipse.hyades.test.ui.editor.form.util.WidgetFactory;
40
import org.eclipse.hyades.test.ui.internal.util.SpecialFieldsBidiListener;
40
import org.eclipse.hyades.test.ui.internal.util.SpecialFieldsBidiListener;
41
import org.eclipse.hyades.ui.internal.util.GridDataUtil;
41
import org.eclipse.hyades.ui.internal.util.GridDataUtil;
42
import org.eclipse.jdt.core.ICompilationUnit;
42
import org.eclipse.jdt.core.IJavaElement;
43
import org.eclipse.jdt.core.IJavaElement;
43
import org.eclipse.jdt.core.IJavaProject;
44
import org.eclipse.jdt.core.IJavaProject;
44
import org.eclipse.jdt.core.IPackageFragment;
45
import org.eclipse.jdt.core.IPackageFragment;
Lines 62-67 Link Here
62
import org.eclipse.swt.widgets.Button;
63
import org.eclipse.swt.widgets.Button;
63
import org.eclipse.swt.widgets.Composite;
64
import org.eclipse.swt.widgets.Composite;
64
import org.eclipse.swt.widgets.Label;
65
import org.eclipse.swt.widgets.Label;
66
import org.eclipse.ui.PartInitException;
65
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
67
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
66
import org.eclipse.ui.dialogs.SelectionDialog;
68
import org.eclipse.ui.dialogs.SelectionDialog;
67
69
Lines 80-85 Link Here
80
	private Button sourceFolderButton;
82
	private Button sourceFolderButton;
81
	private Button packageButton;
83
	private Button packageButton;
82
	private Button updateFromCodeButton;
84
	private Button updateFromCodeButton;
85
	private Button openClassButton;
83
	
86
	
84
	private IImplementor implementor;
87
	private IImplementor implementor;
85
	private VerifyKeyListener verifyKeyListener;
88
	private VerifyKeyListener verifyKeyListener;
Lines 154-160 Link Here
154
157
155
		if(widgetFactory != null)
158
		if(widgetFactory != null)
156
			sourceFolderText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT,
159
			sourceFolderText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT,
157
					ToolsUiPlugin.getString("STR_WB_SRCFOLD"));
160
					ToolsUiPlugin.getString("STR_WB_SRCFOLD")); //$NON-NLS-1$
158
		else
161
		else
159
			sourceFolderText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT | SWT.BORDER);
162
			sourceFolderText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT | SWT.BORDER);
160
		sourceFolderText.setLayoutData(GridDataUtil.createHorizontalFill());
163
		sourceFolderText.setLayoutData(GridDataUtil.createHorizontalFill());
Lines 170-176 Link Here
170
			sourceFolderButton = new Button(composite, SWT.PUSH);
173
			sourceFolderButton = new Button(composite, SWT.PUSH);
171
			sourceFolderButton.setText(ToolsUiPlugin.getString("STR_WB_SRCFOLD_BTN")); //$NON-NLS-1$
174
			sourceFolderButton.setText(ToolsUiPlugin.getString("STR_WB_SRCFOLD_BTN")); //$NON-NLS-1$
172
		}
175
		}
173
		sourceFolderButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
176
		sourceFolderButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
174
		sourceFolderButton.addSelectionListener(this);
177
		sourceFolderButton.addSelectionListener(this);
175
		
178
		
176
		if(widgetFactory != null) {
179
		if(widgetFactory != null) {
Lines 183-189 Link Here
183
186
184
		if(widgetFactory != null)
187
		if(widgetFactory != null)
185
			packageText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT,
188
			packageText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT,
186
					ToolsUiPlugin.getString("STR_WB_PACK"));
189
					ToolsUiPlugin.getString("STR_WB_PACK")); //$NON-NLS-1$
187
		else
190
		else
188
			packageText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT | SWT.BORDER);
191
			packageText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.LEFT_TO_RIGHT | SWT.BORDER);
189
		packageText.setLayoutData(GridDataUtil.createHorizontalFill());
192
		packageText.setLayoutData(GridDataUtil.createHorizontalFill());
Lines 200-206 Link Here
200
			packageButton.setText(ToolsUiPlugin.getString("STR_WB_PACK_BTN")); //$NON-NLS-1$
203
			packageButton.setText(ToolsUiPlugin.getString("STR_WB_PACK_BTN")); //$NON-NLS-1$
201
		}
204
		}
202
		
205
		
203
		packageButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
206
		packageButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
204
		packageButton.addSelectionListener(this);
207
		packageButton.addSelectionListener(this);
205
208
206
		if(widgetFactory != null) {
209
		if(widgetFactory != null) {
Lines 213-227 Link Here
213
216
214
		if(widgetFactory != null)
217
		if(widgetFactory != null)
215
			classNameText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE,
218
			classNameText = widgetFactory.createStyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE,
216
					ToolsUiPlugin.getString("STR_WB_CLASS"));
219
					ToolsUiPlugin.getString("STR_WB_CLASS")); //$NON-NLS-1$
217
		else
220
		else
218
			classNameText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
221
			classNameText =  new StyledText(composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
219
		classNameText.setEditable(false);
222
		classNameText.setEditable(false);
220
		classNameText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false, 2, 1));
223
		
221
			
224
		if(widgetFactory != null) {
225
			classNameText.setLayoutData(GridDataUtil.createHorizontalFill());
226
			openClassButton = widgetFactory.createButton(composite, ToolsUiPlugin.getString("SOURCE_INFO_VIEWER_OPEN_CLASS"), SWT.PUSH); //$NON-NLS-1$
227
			openClassButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
228
			openClassButton.addSelectionListener(this);
229
		} else {
230
			classNameText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false, 2, 1));
231
		}
232
		
222
		if (advanced) {
233
		if (advanced) {
223
			if (showExternalBehavior) {
234
			if (showExternalBehavior) {
224
				updateFromCodeButton = widgetFactory.createButton(composite, "Refresh test methods from code", SWT.PUSH);
235
				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));
236
				updateFromCodeButton.setLayoutData(new GridData(SWT.END, SWT.BEGINNING, false, false, 2, 1));
226
				updateFromCodeButton.addSelectionListener(this);
237
				updateFromCodeButton.addSelectionListener(this);
227
			}
238
			}
Lines 357-364 Link Here
357
			else
368
			else
358
				getImplementor().setResource(pack + cls);
369
				getImplementor().setResource(pack + cls);
359
			
370
			
360
			markDirty();
361
		}
371
		}
372
		packageButton.setEnabled(findSourceFolder() != null);
373
		openClassButton.setEnabled(findCompilationUnit() != null);
374
		markDirty();
362
	}
375
	}
363
	
376
	
364
	/**
377
	/**
Lines 396-434 Link Here
396
					markDirty();
409
					markDirty();
397
				}
410
				}
398
			} else if (e.widget == packageButton) {
411
			} else if (e.widget == packageButton) {
399
				IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(getImplementor().getLocation());
412
				try {
400
				if (res == null) {
413
					IPackageFragmentRoot srcFolder = findSourceFolder();
401
					e.doit = false;
414
					if (srcFolder != null) {
402
				} else {
403
					IJavaElement element = JavaCore.create(res);
404
					try {
405
						IPackageFragmentRoot srcFolder = null;
406
						String initialPackageName = getPackage();
415
						String initialPackageName = getPackage();
407
						if (element instanceof IJavaProject) {
416
						SelectionDialog dialog = JavaUI.createPackageDialog(packageButton.getShell(), srcFolder);
408
							srcFolder = ((IJavaProject)element).findPackageFragmentRoot(res.getFullPath());
417
						IPackageFragment initialPackage = null;
409
						} else if (element instanceof IPackageFragmentRoot) {
418
						if (initialPackageName != null) {
410
							srcFolder = (IPackageFragmentRoot)element;
419
							initialPackage = srcFolder.getPackageFragment(initialPackageName);
411
						}
420
						}
412
						if (srcFolder != null) {
421
						if (initialPackage != null && initialPackage.exists()) {
413
							SelectionDialog dialog = JavaUI.createPackageDialog(packageButton.getShell(), srcFolder);
422
							dialog.setInitialSelections(new Object[] {initialPackage});
414
							IPackageFragment initialPackage = null;
423
						}
415
							if (initialPackageName != null) {
424
						dialog.setTitle(ToolsUiPlugin.getString("TITLE_PACK_SELECT")); //$NON-NLS-1$
416
								initialPackage = srcFolder.getPackageFragment(initialPackageName);
425
						dialog.setMessage(ToolsUiPlugin.getString("STR_PACK_SELECT")); //$NON-NLS-1$
417
							}
426
						if (dialog.open() == IDialogConstants.OK_ID) {
418
							if (initialPackage != null && initialPackage.exists()) {
427
							IPackageFragment packageFragment = (IPackageFragment)dialog.getResult()[0];
419
								dialog.setInitialSelections(new Object[] {initialPackage});
428
							setPackage(packageFragment.getElementName());
420
							}
429
							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
						}
430
						}
429
					} catch (JavaModelException e1) {
430
						e.doit = false;
431
					}
431
					}
432
				} catch (JavaModelException e1) {
433
					e.doit = false;
432
				}
434
				}
433
			} else if (e.widget == externalBehavior) {
435
			} else if (e.widget == externalBehavior) {
434
				if (externalBehavior.getSelection()) {
436
				if (externalBehavior.getSelection()) {
Lines 460-467 Link Here
460
				} catch (CoreException e1) {
462
				} catch (CoreException e1) {
461
					CorePlugin.logError(e1);
463
					CorePlugin.logError(e1);
462
				}
464
				}
465
			} else if (e.widget == openClassButton) {
466
				ICompilationUnit cu = findCompilationUnit();
467
				if (cu != null) {
468
					try {
469
						JavaUI.openInEditor(cu);
470
					} catch (PartInitException e1) {
471
						ToolsUiPlugin.logError(e1);
472
						e.doit = false;
473
					} catch (JavaModelException e1) {
474
						ToolsUiPlugin.logError(e1);
475
						e.doit = false;
476
					}
477
				}
478
			}
479
		}
480
	}
481
	
482
	protected IPackageFragmentRoot findSourceFolder() {
483
		IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(getImplementor().getLocation());
484
		if (res == null) {
485
			return null;
486
		}
487
		IJavaElement element = JavaCore.create(res);
488
		if (element == null) return null;
489
		try {
490
			IPackageFragmentRoot srcFolder = null;
491
			if (element instanceof IJavaProject) {
492
				srcFolder = ((IJavaProject)element).findPackageFragmentRoot(res.getFullPath());
493
			} else if (element instanceof IPackageFragmentRoot) {
494
				srcFolder = (IPackageFragmentRoot)element;
495
			}
496
			return srcFolder;
497
		} catch (JavaModelException e) {
498
			ToolsUiPlugin.logError(e);
499
			return null;
500
		}
501
	}
502
	
503
	protected IPackageFragment findPackage() {
504
		IPackageFragmentRoot srcFolder = findSourceFolder();
505
		if (srcFolder != null) {
506
			IPackageFragment pack = srcFolder.getPackageFragment(getPackage());
507
			if (pack.exists()) {
508
				return pack;
509
			}
510
		}
511
		return null;
512
	}
513
	
514
	protected ICompilationUnit findCompilationUnit() {
515
		IPackageFragment pack = findPackage();
516
		if (pack != null) {
517
			ICompilationUnit cu = pack.getCompilationUnit(getClassName() + ".java"); //$NON-NLS-1$
518
			if (cu.exists()) {
519
				return cu;
463
			}
520
			}
464
		}
521
		}
522
		return null;
465
	}
523
	}
466
	
524
	
467
	static IBlock createBlock(IImplementor implementor) {
525
	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/JUnitTestSuiteNewWizard.java (-6 / +16 lines)
Lines 16-21 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.CorePlugin;
21
import org.eclipse.hyades.test.tools.core.common.TestCommon;
22
import org.eclipse.hyades.test.tools.core.common.TestCommon;
Lines 32-37 Link Here
32
import org.eclipse.jdt.core.JavaModelException;
33
import org.eclipse.jdt.core.JavaModelException;
33
import org.eclipse.jface.dialogs.IDialogSettings;
34
import org.eclipse.jface.dialogs.IDialogSettings;
34
import org.eclipse.jface.viewers.IStructuredSelection;
35
import org.eclipse.jface.viewers.IStructuredSelection;
36
import org.eclipse.ltk.core.refactoring.Change;
37
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
35
38
36
/**
39
/**
37
 * Extends the HyadesNewWizard to create the JUnit Test Suite.
40
 * Extends the HyadesNewWizard to create the JUnit Test Suite.
Lines 217-231 Link Here
217
	}
220
	}
218
	
221
	
219
	protected JUnitGenerator createGenerator() {
222
	protected JUnitGenerator createGenerator() {
220
		return new JUnitGenerator(new AutomaticDependencyUpdater(), getSourcePage().getSuperClass());
223
		return new JUnitGenerator(getGeneratedTestSuite(), new AutomaticDependencyUpdater(), getSourcePage().getSuperClass());
221
	}
224
	}
222
	
225
	
223
	private void generateCode(ITestSuite testSuite, IProgressMonitor monitor) throws Exception {
226
	private void generateCode(ITestSuite testSuite, IProgressMonitor monitor) throws Exception {
224
		JUnitGenerator generator = createGenerator();
227
		monitor.beginTask("", 4);
225
		generator.getProjectDependencyUpdater().addRequiredPlugin("org.junit", null); //$NON-NLS-1$
228
		try {
226
		generator.getProjectDependencyUpdater().addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
229
			JUnitGenerator generator = createGenerator();
227
		generator.getProjectDependencyUpdater().addRequiredPlugin(CorePlugin.getID(), "java.runner.jar"); //$NON-NLS-1$
230
			RefactoringStatus status = generator.checkAllConditions(new SubProgressMonitor(monitor, 1));
228
		generator.generate(getGeneratedTestSuite(), monitor);
231
			if (status.hasFatalError()) {
232
				throw new IllegalStateException("Refactor conditions not met"); // TODO Treat this appropriately
233
			}
234
			Change change = generator.createChange(new SubProgressMonitor(monitor, 1));
235
			change.perform(new SubProgressMonitor(monitor, 2));
236
		} finally {
237
			monitor.done();
238
		}
229
	}
239
	}
230
	
240
	
231
	protected void setSourcePage(SourcePage page) {
241
	protected void setSourcePage(SourcePage page) {
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/GenerateWizard.java (-13 / +16 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 147-153 Link Here
147
			}
157
			}
148
			
158
			
149
			Generator generator = createGenerator();
159
			Generator generator = createGenerator();
150
			if(generator.getFileHandle(getTestSuite()).exists())
160
			if(generator.getFileHandle().exists())
151
			{
161
			{
152
				MessageDialog dialog = new MessageDialog(
162
				MessageDialog dialog = new MessageDialog(
153
				getShell(), ToolsUiPlugin.getString("W_QUESTION"),  //$NON-NLS-1$
163
				getShell(), ToolsUiPlugin.getString("W_QUESTION"),  //$NON-NLS-1$
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/plugin/internal/junit/wizard/PluginJUnitTestSuiteNewWizard.java (-1 / +1 lines)
Lines 54-60 Link Here
54
	}
54
	}
55
55
56
	protected JUnitGenerator createGenerator() {
56
	protected JUnitGenerator createGenerator() {
57
		return new JUnitGenerator(new PluginProjectDependencyUpdater(), getSourcePage().getSuperClass());
57
		return new JUnitGenerator(getGeneratedTestSuite(), new PluginProjectDependencyUpdater(), getSourcePage().getSuperClass());
58
	}
58
	}
59
59
60
	protected void initSourcePage(IStructuredSelection structuredSelection, LocationPage locationPage) {
60
	protected void initSourcePage(IStructuredSelection structuredSelection, LocationPage locationPage) {
(-)src/org/eclipse/hyades/test/tools/ui/http/internal/codegen/HttpGenerator.java (-15 / +48 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.Helper;
21
import org.eclipse.hyades.test.tools.core.internal.common.codegen.Helper;
22
import org.eclipse.hyades.test.tools.core.internal.common.codegen.IProjectDependencyUpdater;
22
import org.eclipse.hyades.test.tools.core.internal.common.codegen.JavaGenerator;
23
import org.eclipse.hyades.test.tools.core.internal.common.codegen.JavaGenerator;
23
24
24
/**
25
/**
25
 * @author marcelop
26
 * @author marcelop
26
 * @since 1.0.2
27
 * @since 1.0.2
27
 */
28
 */
28
public class HttpGenerator extends JavaGenerator
29
public class HttpGenerator extends JavaGenerator {
29
{
30
	
30
	
31
	public HttpGenerator() {
31
	public final static String PLUGIN_ID_JUNIT = "org.junit"; //$NON-NLS-1$
32
		super(new AutomaticDependencyUpdater());
32
	public final static String PLUGIN_ID_EXECUTION_CORE = "org.eclipse.hyades.execution.core"; //$NON-NLS-1$
33
	public final static String PLUGIN_ID_EXECUTION_REMOTE = "org.eclipse.hyades.execution.remote"; //$NON-NLS-1$
34
35
	public HttpGenerator(ITestSuite testSuite, IProjectDependencyUpdater updater) {
36
		super(testSuite, new HttpProjectDependencyUpdater(updater));
33
	}
37
	}
34
	
38
	
35
	/**
39
	/**
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)
40
	 * @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
	 */
41
	 */
38
	protected void generateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor)
42
	protected String generateCode(IProgressMonitor monitor) throws CoreException
39
	throws Exception
40
	{
43
	{
41
		GenTestSuite genTestSuite = new GenTestSuite();
44
		GenTestSuite genTestSuite = new GenTestSuite();
42
		Helper helper = new Helper();
45
		Helper helper = new Helper();
43
		computeTestMethodNames(testSuite, false, helper);
46
		computeTestMethodNames(getTestSuite(), false, helper);
44
		String content = Helper.formatContent(genTestSuite.generate(testSuite, helper));
47
		String content = Helper.formatContent(genTestSuite.generate(getTestSuite(), helper));
45
		helper.dispose();
48
		helper.dispose();
46
		// use UTF-8 encoding - bugzilla_88029 running test with non-ASCII characters.
49
		return content;
47
		file.create(new ByteArrayInputStream(content.getBytes(CHARSET_UTF8)), true, monitor);
50
	}
48
		file.setCharset(CHARSET_UTF8, monitor);
51
52
	public static class HttpProjectDependencyUpdater implements IProjectDependencyUpdater {
53
54
		private IProjectDependencyUpdater delegate;
55
		
56
		public HttpProjectDependencyUpdater(IProjectDependencyUpdater delegate) {
57
			this.delegate = delegate;
58
			delegate.addRequiredPlugin(PLUGIN_ID_JUNIT, null);
59
			delegate.addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
60
			delegate.addRequiredPlugin(CorePlugin.getID(), "http.runner.jar"); //$NON-NLS-1$
61
			//add additional libraries in order to run as a JUnit - bugzilla_98741  jn
62
			delegate.addRequiredPlugin("org.eclipse.hyades.logging.core", null); //$NON-NLS-1$
63
			delegate.addRequiredPlugin("org.eclipse.emf.ecore", null); //$NON-NLS-1$
64
			delegate.addRequiredPlugin("org.eclipse.emf.common", null); //$NON-NLS-1$
65
		}
66
67
		public void addRequiredPlugin(String pluginId, String jarName) {
68
			delegate.addRequiredPlugin(pluginId, jarName);
69
		}
70
71
		public void addRequiredProject(IProject project) {
72
			delegate.addRequiredProject(project);
73
		}
74
75
		public void adjustProject(IProject project, IProgressMonitor monitor) throws CoreException {
76
			delegate.adjustProject(project, monitor);
77
		}
78
79
		public Collection previewAdjustProject(IProject project) {
80
			return delegate.previewAdjustProject(project);
81
		}
49
	}
82
	}
50
83
51
}
84
}
(-)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
73
Eclipse-LazyStart: true
74
Eclipse-LazyStart: true
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/JUnitPreferences.java (+32 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;
14
15
16
/**
17
 * Preferences constants for JUnit preferences.
18
 * @author jcanches
19
 * @since 4.3
20
 */
21
public class JUnitPreferences {
22
23
	public final static String UPDATE_PREVIEW_MODE = "junit.previewMode"; //$NON-NLS-1$
24
	public final static int PREVIEW_ALWAYS = 0;
25
	public final static int PREVIEW_IF_DESTRUCTIVE = 1;
26
	public final static int PREVIEW_NEVER = 2;
27
	public final static int DEFAULT_UPDATE_PREVIEW_MODE = PREVIEW_ALWAYS;
28
	
29
	public final static String SKIP_TO_PREVIEW_PAGE = "junit.skipToPreviewPage"; //$NON-NLS-1$
30
	public final static boolean DEFAULT_SKIP_TO_PREVIEW_PAGE = false;
31
	
32
}
(-)src/org/eclipse/hyades/test/tools/ui/java/internal/junit/wizard/UpdateCodeWizardPage.java (+109 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.JUnitPreferences;
18
import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
19
import org.eclipse.swt.SWT;
20
import org.eclipse.swt.layout.GridData;
21
import org.eclipse.swt.layout.GridLayout;
22
import org.eclipse.swt.layout.RowLayout;
23
import org.eclipse.swt.widgets.Button;
24
import org.eclipse.swt.widgets.Composite;
25
import org.eclipse.swt.widgets.Control;
26
import org.eclipse.swt.widgets.Group;
27
28
public class UpdateCodeWizardPage extends UserInputWizardPage {
29
30
	protected UpdateCodeWizardPage() {
31
		super("JUnit Code Update Preview Options");
32
	}
33
34
	private Button skipPage;
35
	private Button alwaysPreview;
36
	private Button onlyDestructive;
37
	private Button neverPreview;
38
39
	public void createControl(Composite parent) {
40
		initializeDialogUnits(parent);
41
		Composite composite = new Composite(parent, SWT.NONE);
42
		GridLayout layout = new GridLayout(1, false);
43
		layout.verticalSpacing = 15;
44
		composite.setLayout(layout);
45
		
46
		Control group = createPreviewGroup(composite);
47
		group.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
48
		
49
		skipPage = new Button(composite, SWT.CHECK);
50
		skipPage.setText("Always skip to the preview page");
51
		
52
		setControl(composite);
53
		initializeContent();
54
	}
55
	
56
	/**
57
	 * @param parent
58
	 */
59
	private Control createPreviewGroup(Composite parent) {
60
		Group composite = new Group(parent, SWT.NONE);
61
		composite.setText("Show the preview page");
62
		RowLayout layout = new RowLayout(SWT.VERTICAL);
63
		layout.spacing = 6;
64
		layout.marginWidth = 5;
65
		layout.marginHeight = 6;
66
		composite.setLayout(layout);
67
		
68
		alwaysPreview = new Button(composite, SWT.RADIO);
69
		alwaysPreview.setText("Always");
70
		
71
		onlyDestructive = new Button(composite, SWT.RADIO);
72
		onlyDestructive.setText("Only when there are destructive changes");
73
		
74
		neverPreview = new Button(composite, SWT.RADIO);
75
		neverPreview.setText("Never");
76
		return composite;
77
	}
78
	
79
	private void initializeContent() {
80
		Preferences prefs = ToolsUiPlugin.getDefault().getPluginPreferences();
81
		switch (prefs.getInt(JUnitPreferences.UPDATE_PREVIEW_MODE)) {
82
		case JUnitPreferences.PREVIEW_ALWAYS:
83
			alwaysPreview.setSelection(true);
84
			break;
85
		case JUnitPreferences.PREVIEW_IF_DESTRUCTIVE:
86
			onlyDestructive.setSelection(true);
87
			break;
88
		case JUnitPreferences.PREVIEW_NEVER:
89
			neverPreview.setSelection(true);
90
			break;
91
		}
92
		skipPage.setSelection(prefs.getBoolean(JUnitPreferences.SKIP_TO_PREVIEW_PAGE));
93
	}
94
	
95
	/* package */ void saveContent() {
96
		Preferences prefs = ToolsUiPlugin.getDefault().getPluginPreferences();
97
		int value;
98
		if (alwaysPreview.getSelection()) {
99
			value = JUnitPreferences.PREVIEW_ALWAYS;
100
		} else if (onlyDestructive.getSelection()) {
101
			value = JUnitPreferences.PREVIEW_IF_DESTRUCTIVE;
102
		} else {
103
			value = JUnitPreferences.PREVIEW_NEVER;
104
		}
105
		prefs.setValue(JUnitPreferences.UPDATE_PREVIEW_MODE, value);
106
		prefs.setValue(JUnitPreferences.SKIP_TO_PREVIEW_PAGE, skipPage.getSelection());
107
	}
108
109
}
(-)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.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
}
(-)src/org/eclipse/hyades/test/tools/core/internal/java/codegen/GenTestSuiteConstructor.java (-2 / +2 lines)
Lines 1-10 Link Here
1
/**********************************************************************
1
/**********************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
2
 * Copyright (c) 2005, 2006 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
3
 * All rights reserved.   This program and the accompanying materials
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.1 2006/05/16 15:02:26 jcanches 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 (-113 / +256 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;
15
import java.util.Collection;
17
import java.util.Iterator;
16
import java.util.Iterator;
18
import java.util.List;
17
import java.util.List;
19
18
20
import org.eclipse.core.resources.IFile;
19
import org.eclipse.core.resources.IProject;
20
import org.eclipse.core.runtime.CoreException;
21
import org.eclipse.core.runtime.IProgressMonitor;
21
import org.eclipse.core.runtime.IProgressMonitor;
22
import org.eclipse.core.runtime.NullProgressMonitor;
23
import org.eclipse.core.runtime.SubProgressMonitor;
22
import org.eclipse.core.runtime.SubProgressMonitor;
24
import org.eclipse.emf.ecore.EObject;
25
import org.eclipse.hyades.models.common.facades.behavioral.ITestCase;
23
import org.eclipse.hyades.models.common.facades.behavioral.ITestCase;
26
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
24
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;
25
import org.eclipse.hyades.test.tools.core.CorePlugin;
26
import org.eclipse.hyades.test.tools.core.internal.common.codegen.ASTHelper;
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.
58
 * This concrete implementation handles code generation and code update for JUnit and
59
 * JUnit Plugin types.
42
 * @author marcelop, jcanches
60
 * @author marcelop, jcanches
43
 * @since 1.0.2
61
 * @since 1.0.2
44
 */
62
 */
45
public class JUnitGenerator extends JavaGenerator {
63
public class JUnitGenerator extends JavaGenerator {
46
	
64
	
47
	private String superclassName;
65
	private String superclassName;
66
	private boolean destructiveChangeFound;
48
67
49
	public JUnitGenerator(IProjectDependencyUpdater updater) {
68
	public JUnitGenerator(ITestSuite testSuite, IProjectDependencyUpdater updater) {
50
		super(updater);
69
		super(testSuite, new JUnitProjectDependencyUpdater(updater, !testSuite.getImplementor().isExternalImplementor()));
51
	}
70
	}
52
	
71
	
53
	public JUnitGenerator(IProjectDependencyUpdater updater, String superclassName) {
72
	public JUnitGenerator(ITestSuite testSuite, IProjectDependencyUpdater updater, String superclassName) {
54
		this(updater);
73
		this(testSuite, updater);
55
		this.superclassName = superclassName;
74
		this.superclassName = superclassName;
56
	}
75
	}
57
	
76
	
58
	/**
77
	/**
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)
78
	 * @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
	 */
79
	 */
61
	protected void generateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor)
80
	protected String generateCode(IProgressMonitor monitor) throws CoreException {
62
	throws Exception
63
	{
64
		Helper helper = new Helper();
81
		Helper helper = new Helper();
65
		if (this.superclassName != null) {
82
		try {
66
			helper.setSuperclassName(this.superclassName);
83
			if (this.superclassName != null) {
84
				helper.setSuperclassName(this.superclassName);
85
			}
86
			ITestSuite testSuite = getTestSuite();
87
			computeTestMethodNames(testSuite, testSuite.getImplementor().isExternalImplementor(), helper);
88
			GenTestSuite generator = new GenTestSuite();
89
			return Helper.formatContent(generator.generate(testSuite, helper));
90
		} finally {
91
			helper.dispose();
67
		}
92
		}
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
	}
93
	}
78
	
94
	
79
	protected void updateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor) {
95
	protected Change createPostCodegenerationChange(IProgressMonitor monitor) throws CoreException {
96
		PotentialChange change = new AssociateModelSourceChange(getFileHandle(), getTestSuite());
97
		if (change.isRequired()) {
98
			return change;
99
		}
100
		return new NullChange();
101
	}
102
103
	protected Change createSourceUpdateChange(SubProgressMonitor monitor) throws CoreException {
80
		monitor.beginTask("", 4); //$NON-NLS-1$
104
		monitor.beginTask("", 4); //$NON-NLS-1$
81
		try {
105
		try {
82
			ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
106
			ASTParser parser = ASTParser.newParser(AST.JLS3); // TODO Compute the argument
107
			ITestSuite testSuite = getTestSuite();
108
			ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(getFileHandle());
109
			
83
			Helper helper = new Helper();
110
			Helper helper = new Helper();
84
			String packageName = helper.getPackageName(testSuite);
111
			String packageName = helper.getPackageName(testSuite);
85
			helper.setImportManager(new ImportManager(packageName));
112
			helper.setImportManager(new ImportManager(packageName));
86
			try {
113
			try {
87
				if (cu == null || !cu.isStructureKnown()) {
114
				// Parse the source code
88
					// TODO ask the user whether to override the code or not modify it
115
				destructiveChangeFound = false;
89
					return;
116
				Document doc = new Document(compilationUnit.getBuffer().getContents());
90
				}
117
				parser.setSource(doc.get().toCharArray());
91
				IType mainClass = cu.findPrimaryType();
118
				CompilationUnit cu = (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1));
92
				cu.becomeWorkingCopy(null, new SubProgressMonitor(monitor, 1));
119
				cu.recordModifications();
93
				try {
120
				TypeDeclaration mainType = ASTHelper.getMainType(cu);
94
					updateTestMethods(testSuite, mainClass, helper,
121
				if (mainType == null) {
95
							new SubProgressMonitor(monitor, 1));
122
					// TODO Error
96
					// The generation of suite() must be performed after the test methods update
123
					return new NullChange();
97
					// because the methods names might change during the update.
124
				}
98
					if (!testSuite.getImplementor().isExternalImplementor()) {
125
				
99
						updateSuiteMethod(testSuite, mainClass, helper);
126
				// Modify the AST tree
100
						checkConstructor(mainClass, helper);
127
				updateTestMethods(testSuite, mainType, helper, new SubProgressMonitor(monitor, 1));
101
					}
128
				// The generation of suite() must be performed after the test methods update
102
					monitor.worked(1);
129
				// because the methods names might change during the update.
103
					helper.emitSortedImports(cu);
130
				if (!testSuite.getImplementor().isExternalImplementor()) {
104
131
					updateSuiteMethod(testSuite, mainType, helper);
105
					cu.commitWorkingCopy(/*force*/false,
132
					checkConstructor(mainType, helper);
106
							new SubProgressMonitor(monitor, 1));
133
					checkSuperType(mainType, helper);
107
					// Associate the java file to the testsuite file
134
				}
108
					associateJavaFileToTestSuite(file, testSuite);
135
				monitor.worked(1);
109
				} finally {
136
				// Emit to AST the imports that are newly required by the updated code
110
					cu.discardWorkingCopy();
137
				helper.emitSortedImports(cu);
138
				
139
				// Compute the resulting document and save it
140
				TextEdit edit = cu.rewrite(doc, /*options*/null);
141
				if (edit.getChildrenSize() != 0) {
142
					CompilationUnitChange change = new CompilationUnitChange(JavaMessages.UPDATE_JUNIT_CODE, compilationUnit, destructiveChangeFound);
143
					change.setEdit(edit);
144
					return change;
111
				}
145
				}
112
			} catch (JavaModelException e) {
146
			} catch (JavaModelException e) {
113
				CorePlugin.logError(e);
147
				CorePlugin.logError(e);
148
			} catch (MalformedTreeException e) {
149
				CorePlugin.logError(e);
114
			} finally {
150
			} finally {
115
				helper.dispose();
151
				helper.dispose();
116
			}
152
			}
117
		} finally {
153
		} finally {
118
			monitor.done();
154
			monitor.done();
119
		}
155
		}
156
		return new NullChange();
120
	}
157
	}
121
158
159
	protected void checkSuperType(TypeDeclaration mainType, Helper helper) {
160
		boolean doIt = false;
161
		Type superclassType = mainType.getSuperclassType();
162
		if (superclassType == null) {
163
			doIt = true;
164
		}
165
		
166
		if (superclassType.isSimpleType()) {
167
			SimpleType st = (SimpleType)superclassType;
168
			Name supertypeName = ASTHelper.resolveName((CompilationUnit)mainType.getParent(), st.getName());
169
			if (supertypeName != null && !Helper.HYADES_TEST_CASE_CLASS_NAME.equals(supertypeName.getFullyQualifiedName())) {
170
				doIt = true;
171
			}
172
		}
173
		if (doIt) {
174
			destructiveChangeFound = true;
175
			helper.addImport(Helper.HYADES_TEST_CASE_CLASS_NAME);
176
			Name newName = mainType.getAST().newName(helper.getImportedName(Helper.HYADES_TEST_CASE_CLASS_NAME));
177
			if (superclassType == null) {
178
				superclassType = mainType.getAST().newSimpleType(newName);
179
				mainType.setSuperclassType(superclassType);
180
			} else {
181
				((SimpleType)superclassType).setName(newName);
182
			}
183
		}
184
	}
185
	
122
	/**
186
	/**
123
	 * Update the content of the suite() method for the specified class,
187
	 * Update the content of the suite() method for the specified class,
124
	 * with the behavior of the specified test suite.
188
	 * with the behavior of the specified test suite.
Lines 126-152 Link Here
126
	 * the method if it does not exist.
190
	 * the method if it does not exist.
127
	 * @throws JavaModelException 
191
	 * @throws JavaModelException 
128
	 */
192
	 */
129
	protected void updateSuiteMethod(ITestSuite testSuite, IType mainClass, Helper helper) throws JavaModelException {
193
	protected void updateSuiteMethod(ITestSuite testSuite, TypeDeclaration mainType, Helper helper) throws JavaModelException {
130
		// Compute the suite() method body
194
		// Compute the suite() method body
131
		GenSuiteMethod generator = new GenSuiteMethod();
195
		GenSuiteMethod generator = new GenSuiteMethod();
132
		String content = generator.generate(testSuite, helper);
196
		String content = generator.generate(testSuite, helper);
133
		IMethod suiteMethod = mainClass.getMethod("suite", new String[0]); //$NON-NLS-1$
197
		MethodDeclaration newSuiteMethod = ASTHelper.parseMethod(mainType.getAST(), content);
134
		IMethod sibling = null; // The suite() method sits before this method
198
		
135
		if (suiteMethod.exists()) {
199
		// Compute the existing suite() method index and removes it if it exists
136
			IMethod[] methods = mainClass.getMethods();
200
		MethodDeclaration suiteMethod = ASTHelper.findMethodWithNoParameter(mainType, "suite"); //$NON-NLS-1$
137
			int index = Arrays.asList(methods).indexOf(suiteMethod);
201
		int index;
138
			suiteMethod.delete(/*force*/false, new NullProgressMonitor());
202
		if (suiteMethod == null) {
139
			methods = mainClass.getMethods();
203
			index = ASTHelper.getFirstMethodIndex(mainType);
140
			if (index < methods.length) {
141
				sibling = methods[index];
142
			}
143
		} else {
204
		} else {
144
			IMethod[] methods = mainClass.getMethods();
205
			destructiveChangeFound = true;
145
			if (methods.length > 0) {
206
			index = mainType.bodyDeclarations().indexOf(suiteMethod);
146
				sibling = methods[0];
207
			mainType.bodyDeclarations().remove(index);
147
			}
208
		}
209
		
210
		// Inserts the new MethodDeclaration at the right position
211
		if (index == -1) {
212
			mainType.bodyDeclarations().add(newSuiteMethod);
213
		} else {
214
			mainType.bodyDeclarations().add(index, newSuiteMethod);
148
		}
215
		}
149
		mainClass.createMethod(Helper.formatContent(content, 0), sibling, /*force*/true, new NullProgressMonitor());
150
	}
216
	}
151
	
217
	
152
	/**
218
	/**
Lines 156-168 Link Here
156
	 * @param helper
222
	 * @param helper
157
	 * @throws JavaModelException 
223
	 * @throws JavaModelException 
158
	 */
224
	 */
159
	protected void checkConstructor(IType mainClass, Helper helper) throws JavaModelException {
225
	protected void checkConstructor(TypeDeclaration mainType, Helper helper) throws JavaModelException {
160
		IMethod method = mainClass.getMethod(mainClass.getElementName(), new String[] { "QString;" }); //$NON-NLS-1$
226
		MethodDeclaration pattern = mainType.getAST().newMethodDeclaration();
161
		if (method.exists()) return;
227
		pattern.setName(mainType.getAST().newSimpleName(mainType.getName().getIdentifier()));
162
		GenTestSuiteConstructor generator = new GenTestSuiteConstructor();
228
		SingleVariableDeclaration svd = mainType.getAST().newSingleVariableDeclaration();
163
		String contents = generator.generate(mainClass.getElementName(), helper);
229
		svd.setType(mainType.getAST().newSimpleType(mainType.getAST().newSimpleName("String"))); //$NON-NLS-1$
164
		IMethod[] methods = mainClass.getMethods();
230
		pattern.parameters().add(svd);
165
		mainClass.createMethod(Helper.formatContent(contents, 0), methods.length == 0 ? null : methods[0], /*force*/true, new NullProgressMonitor());
231
		
232
		MethodDeclaration constructor = ASTHelper.findMethod(mainType, pattern);
233
		if (constructor == null) {
234
			GenTestSuiteConstructor generator = new GenTestSuiteConstructor();
235
			String contents = generator.generate(mainType.getName().getIdentifier(), helper);
236
			constructor = ASTHelper.parseMethod(mainType.getAST(), contents);
237
			int index = ASTHelper.getFirstMethodIndex(mainType);
238
			if (index == -1) {
239
				mainType.bodyDeclarations().add(constructor);
240
			} else {
241
				mainType.bodyDeclarations().add(index, constructor);
242
			}
243
		}
244
	}
245
	
246
	/**
247
	 * Returns whether a method is a test method.
248
	 * @param method
249
	 * @return
250
	 */
251
	public static boolean isTestMethod(MethodDeclaration method) {
252
		String name = method.getName().getIdentifier();
253
		return name.startsWith("test") && method.parameters().size() == 0; //$NON-NLS-1$
166
	}
254
	}
167
	
255
	
168
	/**
256
	/**
Lines 175-181 Link Here
175
		String[] types = method.getParameterTypes();
263
		String[] types = method.getParameterTypes();
176
		return name.startsWith("test") && types.length == 0; //$NON-NLS-1$
264
		return name.startsWith("test") && types.length == 0; //$NON-NLS-1$
177
	}
265
	}
178
	
266
179
	/**
267
	/**
180
	 * Update the list of test methods in the specified class, so that the list of
268
	 * 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.
269
	 * test methods matches the list of test cases of the specified test suite.
Lines 184-191 Link Here
184
	 * @param helper
272
	 * @param helper
185
	 * @throws JavaModelException
273
	 * @throws JavaModelException
186
	 */
274
	 */
187
	protected void updateTestMethods(ITestSuite testSuite, IType mainClass, Helper helper, IProgressMonitor monitor) throws JavaModelException {
275
	protected void updateTestMethods(ITestSuite testSuite, TypeDeclaration mainType, Helper helper, IProgressMonitor monitor) throws JavaModelException {
188
		IMethod[] methods = mainClass.getMethods();
276
		MethodDeclaration[] methods = mainType.getMethods();
189
		monitor.beginTask("", methods.length + testSuite.getITestCases().size()); //$NON-NLS-1$
277
		monitor.beginTask("", methods.length + testSuite.getITestCases().size()); //$NON-NLS-1$
190
		try {
278
		try {
191
			List usedTestMethods = new ArrayList(methods.length);
279
			List usedTestMethods = new ArrayList(methods.length);
Lines 200-222 Link Here
200
					actualMethodName = computedMethodName;
288
					actualMethodName = computedMethodName;
201
					Helper.setTestMethodName(testCase, actualMethodName);
289
					Helper.setTestMethodName(testCase, actualMethodName);
202
				}
290
				}
203
				IMethod method = mainClass.getMethod(actualMethodName, new String[0]);
291
				MethodDeclaration method = ASTHelper.findMethodWithNoParameter(mainType, actualMethodName);
204
				if (!method.exists()) {
292
				if (method == null) {
205
					method = createTestMethod(mainClass, testCase, helper);
293
					method = createTestMethod(mainType, testCase, helper);
206
				} else {
294
				} else {
207
					// We still need to rename the method to conform to the computed name
295
					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
				}
296
				}
213
				usedTestMethods.add(method);
297
				usedTestMethods.add(method);
214
				monitor.worked(1);
298
				monitor.worked(1);
215
			}
299
			}
216
			// 2) Remove unused test methods
300
			// 2) Remove unused test methods
217
			for (int i = 0; i< methods.length; i++) {
301
			for (int i = 0; i < methods.length; i++) {
218
				if (isTestMethod(methods[i]) && !usedTestMethods.contains(methods[i])) {
302
				if (isTestMethod(methods[i]) && !usedTestMethods.contains(methods[i])) {
219
					methods[i].delete(/*force*/false, new NullProgressMonitor());
303
					destructiveChangeFound = true;
304
					mainType.bodyDeclarations().remove(methods[i]);
220
				}
305
				}
221
				monitor.worked(1);
306
				monitor.worked(1);
222
			}
307
			}
Lines 224-263 Link Here
224
			monitor.done();
309
			monitor.done();
225
		}
310
		}
226
	}
311
	}
312
	
313
	protected void updateTestMethod(ITestCase testCase, String newName, MethodDeclaration method, Helper helper) {
314
		// Update method name if necessary
315
		if (!newName.equals(method.getName().getIdentifier())) {
316
			destructiveChangeFound = true;
317
			method.setName(method.getAST().newSimpleName(newName));
318
			Helper.setTestMethodName(testCase, newName);
319
		}
320
		// Update comments if necessary
321
		Javadoc javadoc = method.getJavadoc();
322
		if (javadoc == null) {
323
			javadoc = method.getAST().newJavadoc();
324
			method.setJavadoc(javadoc);
325
		}
326
		updateDescriptionTag(javadoc, testCase);
327
	}
328
	
329
	protected void updateDescriptionTag(Javadoc javadoc, ITestCase testCase) {
330
		TagElement oldtag = null;
331
		if (!javadoc.tags().isEmpty()) {
332
			TagElement tag = (TagElement) javadoc.tags().get(0);
333
			if (tag.getTagName() == null) {
334
				oldtag = tag;
335
			}
336
		}
337
		
338
		if (oldtag != null) {
339
			String sourceDescription = ASTHelper.extractDescription(oldtag);
340
			String modelDescription = makeJavadocDescription(testCase);
341
			if (!Helper.compareJavaComments(sourceDescription, modelDescription)) {
342
				destructiveChangeFound = true;
343
				javadoc.tags().remove(oldtag);
344
				ASTHelper.addDescriptionToJavadoc(javadoc, modelDescription);
345
			}
346
		} else {
347
			ASTHelper.addDescriptionToJavadoc(javadoc, makeJavadocDescription(testCase));
348
		}
349
	}
350
	
351
	public static String makeJavadocDescription(ITestCase testCase) {
352
		StringBuffer buf = new StringBuffer();
353
		buf.append(testCase.getName());
354
		if (testCase.getDescription() != null) {
355
			String descr = testCase.getDescription().trim();
356
			if (descr.length() > 0) {
357
				buf.append("\r\n"); //$NON-NLS-1$
358
				buf.append(descr);
359
			}
360
		}
361
		return buf.toString();
362
	}
227
363
228
	/**
364
	/**
229
	 * Creates a test method for the specified test case.
365
	 * Creates a test method for the specified test case.
230
	 * @param mainClass
231
	 * @param testCase
232
	 * @param helper
233
	 * @throws JavaModelException 
234
	 */
366
	 */
235
	protected IMethod createTestMethod(IType mainClass, ITestCase testCase, Helper helper) throws JavaModelException {
367
	protected MethodDeclaration createTestMethod(TypeDeclaration mainType, ITestCase testCase, Helper helper) throws JavaModelException {
236
		GenTestMethod generator = new GenTestMethod();
368
		GenTestMethod generator = new GenTestMethod();
237
		String content = generator.generate(testCase, helper);
369
		String content = generator.generate(testCase, helper);
238
		return mainClass.createMethod(content, null, /*force*/false, new NullProgressMonitor());
370
		MethodDeclaration method = ASTHelper.parseMethod(mainType.getAST(), content);
371
		mainType.bodyDeclarations().add(method);
372
		return method;
239
	}
373
	}
240
	
374
	
241
	private void associateJavaFileToTestSuite(IFile javaFile, ITestSuite testSuite) {
375
	public static class JUnitProjectDependencyUpdater implements IProjectDependencyUpdater {
242
		try {
376
243
			if (testSuite instanceof EObject) {
377
		private IProjectDependencyUpdater delegate;
244
				EObject eObject = (EObject) testSuite;
378
		
245
				IFile testSuiteFile = EMFUtil.getWorkspaceFile(eObject);
379
		public JUnitProjectDependencyUpdater(IProjectDependencyUpdater delegate, boolean modelBehavioring) {
246
				if (testSuiteFile != null && testSuiteFile.exists()) {
380
			this.delegate = delegate;
247
					// Add the Junit builder to the file's project (if not already installed)
381
			delegate.addRequiredPlugin("org.junit", "junit.jar"); //$NON-NLS-1$ //$NON-NLS-2$
248
					JUnitProjectBuilder.installBuilder(javaFile.getProject());
382
			if (modelBehavioring) {
249
					// Also add the JUnit builder to the test suite's project (the source file
383
				delegate.addRequiredPlugin(CorePlugin.getID(), "common.runner.jar"); //$NON-NLS-1$
250
					// and the test suite usually are under the same project, but this is not
384
				delegate.addRequiredPlugin(CorePlugin.getID(), "java.runner.jar"); //$NON-NLS-1$
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
			}
385
			}
258
		} catch (Throwable t) {
259
			CorePlugin.logError(t);
260
		}
386
		}
387
388
		public void addRequiredPlugin(String pluginId, String jarName) {
389
			delegate.addRequiredPlugin(pluginId, jarName);
390
		}
391
392
		public void addRequiredProject(IProject project) {
393
			delegate.addRequiredProject(project);
394
		}
395
396
		public void adjustProject(IProject project, IProgressMonitor monitor) throws CoreException {
397
			delegate.adjustProject(project, monitor);
398
		}
399
400
		public Collection previewAdjustProject(IProject project) {
401
			return delegate.previewAdjustProject(project);
402
		}
403
		
261
	}
404
	}
262
	
405
	
263
}
406
}
(-)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.8 2006/05/16 15:02:26 jcanches 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/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.10 2006/05/16 15:02:26 jcanches 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.7 2006/05/16 15:02:25 jcanches 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/common/CommonPluginMessages.java (-1 / +22 lines)
Lines 23-35 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 DEFINE_SOURCE_FOLDER;
31
	public static String DELETE_FILE;
32
	public static String DELETING_FILE;
33
	public static String E_CODEGEN_PACK_DIAG;
27
    public static String E_CODEGEN_CLASS_DIAG;
34
    public static String E_CODEGEN_CLASS_DIAG;
28
    public static String E_CODEGEN_CLOSED_PROJECT;
35
    public static String E_CODEGEN_CLOSED_PROJECT;
29
    public static String E_CODEGEN_NO_SRCFOLDER;
36
    public static String E_CODEGEN_NO_SRCFOLDER;
30
    
37
    
31
    public static String _ERROR_LAUNCH_VALIDATOR;
38
    public static String _ERROR_LAUNCH_VALIDATOR;
32
    public static String _WARNING_LAUNCH_VALIDATOR;
39
    public static String _WARNING_LAUNCH_VALIDATOR;
40
	public static String GENERATE_CODE;
41
	public static String GENERATE_FILE;
42
	public static String GENERATING_FILE;
43
	public static String GENERIC_GENERATOR;
44
	public static String NO_FILE;
45
	public static String NO_SOURCE_FOLDER;
46
	public static String NOT_A_SOURCE_FOLDER;
47
	public static String NOT_IN_JAVA_PROJECT;
48
	public static String PROJECT_NOT_ACCESSIBLE;
49
	public static String READ_ONLY_FILE;
50
	public static String RESOURCE_NOT_ACCESSIBLE;
51
	public static String SETUP_CONTEXT;
52
	public static String UNKNOWN_LOCATION;
53
	public static String UPDATE_CODE;
33
    public static String VALIDATION_NO_HOST_NAME_ERROR;
54
    public static String VALIDATION_NO_HOST_NAME_ERROR;
34
    public static String VALIDATION_BAD_ROOTDIR_ERROR_;
55
    public static String VALIDATION_BAD_ROOTDIR_ERROR_;
35
    public static String _WARNING_BUILD_PATH_PROBLEM;
56
    public static String _WARNING_BUILD_PATH_PROBLEM;
(-)src/org/eclipse/hyades/test/tools/core/internal/common/messages.properties (-1 / +22 lines)
Lines 22-25 Link Here
22
VALIDATION_NO_HOST_NAME_ERROR	= No host name found
22
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}
23
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}.
24
_WARNING_BUILD_PATH_PROBLEM		= Java build path errors exist in enclosing project: {0}.
25
_WARNING_COMPILATION_PROBLEM	= Compilation errors exist in enclosing project: {0}.
25
_WARNING_COMPILATION_PROBLEM	= Compilation errors exist in enclosing project: {0}.
26
CREATE_PACKAGE=Create package {0}
27
CREATE_CONTAINER=Create container {0}
28
NO_SOURCE_FOLDER=Source folder doesn't exist
29
NOT_A_SOURCE_FOLDER=Package fragment root is not a source folder
30
NOT_IN_JAVA_PROJECT=Container {0} does not belong to a Java project
31
ASSOCIATE_TEST_TO_SOURCE=Associate test {0} to source {1}
32
NO_FILE=File does not exist
33
READ_ONLY_FILE=File is read-only
34
DELETING_FILE=Deleting file
35
DELETE_FILE=Delete file {0}
36
DEFINE_SOURCE_FOLDER=Define {0} as a source folder
37
RESOURCE_NOT_ACCESSIBLE=Resource {0} is not accessible
38
ADJUST_CLASSPATH=Adjust classpath for project {0}
39
PROJECT_NOT_ACCESSIBLE=Project '{0}' is not accessible
40
GENERATE_FILE=Generate file {0}
41
GENERATE_CODE=Generate code
42
UNKNOWN_LOCATION=Unknown location for file 
43
GENERATING_FILE=Generating file
44
GENERIC_GENERATOR=Generic TPTP code generator
45
SETUP_CONTEXT=Setup context
46
UPDATE_CODE=Update code
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/JavaGenerator.java (-82 / +166 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.PotentialChange;
37
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.ProjectAdjustChange;
40
import org.eclipse.jdt.core.IJavaProject;
38
import org.eclipse.jdt.core.IJavaProject;
39
import org.eclipse.jdt.core.IPackageFragmentRoot;
41
import org.eclipse.jdt.core.JavaConventions;
40
import org.eclipse.jdt.core.JavaConventions;
42
import org.eclipse.jdt.core.JavaCore;
41
import org.eclipse.jdt.core.JavaCore;
42
import org.eclipse.ltk.core.refactoring.Change;
43
import org.eclipse.ltk.core.refactoring.CompositeChange;
44
import org.eclipse.ltk.core.refactoring.NullChange;
45
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
43
import org.eclipse.osgi.util.NLS;
46
import org.eclipse.osgi.util.NLS;
44
47
45
/**
48
/**
46
 * @author marcelop
49
 * Abstract Java code generator.
47
 * @author jcanches
50
 * <p>Although this abstract class does not implement any code generation
51
 * or code update, it provides additional features for generating java code, and also
52
 * makes additional assumptions about the test suite behavior model.</p>
53
 * <p>Sub-classes must implement {@link Generator#generateCode(IProgressMonitor)}, and
54
 * need to redefine {@link #createSourceUpdateChange(SubProgressMonitor)} if code update
55
 * is desired.</p>
56
 * <p>Sub-classes may also redefine {@link #computeTestMethodNames(ITestSuite, boolean, Helper)},
57
 * and extend {@link #createAdjustProjectClasspathChange(IProgressMonitor)},
58
 * {@link #createPreCodegenerationChange(IProgressMonitor)},
59
 * {@link Generator#createPostCodegenerationChange(IProgressMonitor)}, and all conditions
60
 * checking methods.</p>
61
 * @author marcelop, jcanches
48
 * @since 1.0.1
62
 * @since 1.0.1
49
 */
63
 */
50
abstract public class JavaGenerator extends Generator {
64
abstract public class JavaGenerator extends Generator {
51
	
65
	
52
	private IProjectDependencyUpdater projectDependencyUpdater;
66
	private IProjectDependencyUpdater projectDependencyUpdater;
53
	
67
	
54
	protected JavaGenerator(IProjectDependencyUpdater updater) {
68
	/**
69
	 * Creates a JavaGenerator for a Java test suite.
70
	 * @param testSuite
71
	 * @param updater A Project dependency updater that will perform project
72
	 * adjustment to comply with additional classpath requirements.
73
	 */
74
	protected JavaGenerator(ITestSuite testSuite, IProjectDependencyUpdater updater) {
75
		super(testSuite);
55
		this.projectDependencyUpdater = updater;
76
		this.projectDependencyUpdater = updater;
56
	}
77
	}
57
	
78
	
58
	protected void adjustProjectClasspath(ITestSuite testSuite, IProject project, IProgressMonitor monitor) throws CoreException {
79
	/**
59
		Collection dependentProjects = getDependentProjects(testSuite, project);
80
	 * Creates the change that adjusts the project classpath.
60
		for(Iterator it = dependentProjects.iterator(); it.hasNext(); ) {
81
	 * <p>This implementation creates a change that invokes the generator's project
61
			projectDependencyUpdater.addRequiredProject((IProject)it.next());
82
	 * dependency updater.</p>
83
	 * <p>Sub-classes may extend or redefine this implementation.</p> 
84
	 * @param monitor
85
	 * @return
86
	 * @throws CoreException
87
	 */
88
	protected Change createAdjustProjectClasspathChange(IProgressMonitor monitor) throws CoreException {
89
		monitor.beginTask("", 1); //$NON-NLS-1$
90
		try {
91
			IProject project = getFileHandle().getProject();
92
			Collection dependentProjects = getDependentProjects(getTestSuite(), project);
93
			for(Iterator it = dependentProjects.iterator(); it.hasNext(); ) {
94
				projectDependencyUpdater.addRequiredProject((IProject)it.next());
95
			}
96
			if (!projectDependencyUpdater.previewAdjustProject(project).isEmpty()) {
97
				monitor.worked(1);
98
				return new ProjectAdjustChange(projectDependencyUpdater, project);
99
			} else {
100
				monitor.worked(1);
101
				return null;
102
			}
103
		} finally {
104
			monitor.done();
62
		}
105
		}
63
		projectDependencyUpdater.adjustProject(project, monitor);
64
	}
106
	}
65
	
107
	
66
	protected String getPackageName(ITestSuite testSuite) {
108
	/**
67
		String cls = testSuite.getImplementor().getResource();
109
	 * Returns the package name that the generated class must belong to.
110
	 * @return A Java package name.
111
	 */
112
	protected String getPackageName() {
113
		String cls = getTestSuite().getImplementor().getResource();
68
		String packageName;
114
		String packageName;
69
		int index = cls.lastIndexOf('.');
115
		int index = cls.lastIndexOf('.');
70
		if (index == -1) {
116
		if (index == -1) {
Lines 75-82 Link Here
75
		return packageName;
121
		return packageName;
76
	}
122
	}
77
	
123
	
78
	protected String getClassName(ITestSuite testSuite) {
124
	/**
79
		String cls = testSuite.getImplementor().getResource();
125
	 * Returns the class name of the generated class.
126
	 * @return
127
	 */
128
	protected String getClassName() {
129
		String cls = getTestSuite().getImplementor().getResource();
80
		String className;
130
		String className;
81
		int index = cls.lastIndexOf('.');
131
		int index = cls.lastIndexOf('.');
82
		if (index == -1) {
132
		if (index == -1) {
Lines 87-151 Link Here
87
		return className;
137
		return className;
88
	}
138
	}
89
	
139
	
90
	protected void doGenerateFile(ITestSuite testSuite, IContainer sourceContainer, IFile file, IProgressMonitor monitor)
140
	/**
91
	throws Exception
141
	 * In addition to its super implementation, this implementation creates a change that ensures 
142
	 * that the source container is a source folder, creates the package, and adjusts the project
143
	 * classpath if necessary.
144
	 */
145
	protected Change createPreCodegenerationChange(IProgressMonitor monitor) throws CoreException
92
	{
146
	{
93
		monitor.beginTask("", 10); //$NON-NLS-1$
147
		monitor.beginTask("", 10); //$NON-NLS-1$
94
		try {
148
		try {
95
			String packageName = getPackageName(testSuite);
149
			CompositeChange change = new CompositeChange(CommonPluginMessages.SETUP_CONTEXT);
96
			adjustSourceContainer(sourceContainer, packageName, new SubProgressMonitor(monitor, 1));
150
			addPotentialChange(super.createPreCodegenerationChange(monitor), change);
97
			adjustProjectClasspath(testSuite, file.getProject(), new SubProgressMonitor(monitor, 4));
151
			addPotentialChange(createAdjustSourceContainerChange(), change);
98
			generateFile(testSuite, file, new SubProgressMonitor(monitor, 5));
152
			addPotentialChange(createCreatePackageChange(), change);
153
			addPotentialChange(createAdjustProjectClasspathChange(new SubProgressMonitor(monitor, 1)), change);
154
			return packCompositeChange(change);
99
		} finally {
155
		} finally {
100
			monitor.done();
156
			monitor.done();
101
		}
157
		}
102
	}
158
	}
159
	
160
	/**
161
	 * Helper method to create a change that makes sure that the source container is a java
162
	 * source folder.
163
	 * @return
164
	 */
165
	final protected Change createAdjustSourceContainerChange() {
166
		PotentialChange change = new AdjustSourceContainerChange(getSourceContainerHandle());
167
		if (change.isRequired()) return change;
168
		else return new NullChange();
169
	}
170
	
171
	/**
172
	 * Helper method to create a change that creates the package, if necessary.
173
	 */
174
	final protected Change createCreatePackageChange() {
175
		IJavaProject jproject = JavaCore.create(getSourceContainerHandle().getProject());
176
		IPackageFragmentRoot sourceFolder = jproject.getPackageFragmentRoot(getSourceContainerHandle());
177
		PotentialChange change = new CreatePackageFragmentChange(sourceFolder, getPackageName());
178
		if (change.isRequired()) return change;
179
		else return new NullChange();
180
	}
103
181
104
	protected void doUpdateFile(ITestSuite testSuite, IContainer sourceContainer, IFile file, IProgressMonitor monitor) throws Exception {
182
	protected final Change createUpdateChange(IFile file, IProgressMonitor monitor) throws CoreException, UnsupportedOperationException {
105
		monitor.beginTask("", 2); //$NON-NLS-1$
183
		monitor.beginTask("", 2); //$NON-NLS-1$
106
		try {
184
		try {
107
			adjustProjectClasspath(testSuite, sourceContainer.getProject(), new SubProgressMonitor(monitor, 1));
185
			Change sourceUpdateChange = createSourceUpdateChange(new SubProgressMonitor(monitor, 1));
108
			updateFile(testSuite, file, new SubProgressMonitor(monitor, 1));
186
			CompositeChange change = new CompositeChange(CommonPluginMessages.UPDATE_CODE);
187
			addPotentialChange(createAdjustProjectClasspathChange(new SubProgressMonitor(monitor, 1)), change);
188
			addPotentialChange(sourceUpdateChange, change);
189
			addPotentialChange(createPostCodegenerationChange(new SubProgressMonitor(monitor, 1)), change);
190
			change.markAsSynthetic();
191
			return packCompositeChange(change);
109
		} finally {
192
		} finally {
110
			monitor.done();
193
			monitor.done();
111
		}
194
		}
112
	}
195
	}
113
196
114
	public IStatus validate(ITestSuite testSuite) {
197
	/**
115
		IStatus status;
198
	 * Creates the source update change. This implementation throws a {@link UnsupportedOperationException}.
116
		
199
	 * Sub-classes need to redefine this method in order to be code-update-capable.
117
		// Super validation
200
	 * @param monitor A progress monitor
118
		status = super.validate(testSuite);
201
	 * @return
119
		if (status.getSeverity() != IStatus.OK) return status;
202
	 * @throws CoreException, UnsupportedOperationException
120
		
203
	 */
121
		// Package name
204
	protected Change createSourceUpdateChange(SubProgressMonitor monitor) throws CoreException, UnsupportedOperationException {
122
		String packageName = getPackageName(testSuite);
205
		throw new UnsupportedOperationException();
123
		if (packageName.length() > 0) {
206
	}
124
			status = JavaConventions.validatePackageName(packageName);
207
125
			if (status.getSeverity() != IStatus.OK) {
208
	/**
126
				if (status.getSeverity() == IStatus.ERROR) {
209
	 * In addition to its super implementation, this implementation checks that the package name
127
					// Replace the diagnosis of JDT with something more explicit
210
	 * and class name are valid.
128
					return new Status(status.getSeverity(), CorePlugin.PLUGIN_ID, 0, NLS.bind(CommonPluginMessages.E_CODEGEN_PACK_DIAG, status.getMessage()), null);
211
	 */
212
	public RefactoringStatus checkInitialConditions(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
213
		monitor.beginTask("", 4); //$NON-NLS-1$
214
		try {
215
			// Super validation
216
			RefactoringStatus status = super.checkInitialConditions(new SubProgressMonitor(monitor, 2));
217
			
218
			// Package name
219
			String packageName = getPackageName();
220
			if (packageName.length() > 0) {
221
				IStatus st = JavaConventions.validatePackageName(packageName);
222
				if (st.getSeverity() != IStatus.OK) {
223
					if (st.getSeverity() == IStatus.ERROR) {
224
						// Replace the diagnosis of JDT with something more explicit
225
						status.addError(NLS.bind(CommonPluginMessages.E_CODEGEN_PACK_DIAG, st.getMessage()));
226
					}
129
				}
227
				}
130
				return status;
131
			}
228
			}
132
		}
229
			monitor.worked(1);
133
		
230
			
134
		// Class name
231
			// Class name
135
		String className = getClassName(testSuite);
232
			String className = getClassName();
136
		status = JavaConventions.validateJavaTypeName(className);
233
			IStatus st = JavaConventions.validateJavaTypeName(className);
137
		if (status.getSeverity() != IStatus.OK) {
234
			if (st.getSeverity() != IStatus.OK) {
138
			if (status.getSeverity() == IStatus.ERROR) {
235
				if (st.getSeverity() == IStatus.ERROR) {
139
				// Replace the diagnosis of JDT with something more explicit
236
					// Replace the diagnosis of JDT with something more explicit
140
				return new Status(status.getSeverity(), CorePlugin.PLUGIN_ID, 0, NLS.bind(CommonPluginMessages.E_CODEGEN_CLASS_DIAG, status.getMessage()), null);
237
					status.addError(NLS.bind(CommonPluginMessages.E_CODEGEN_CLASS_DIAG, st.getMessage()));
238
				}
141
			}
239
			}
240
			monitor.worked(1);
241
			
142
			return status;
242
			return status;
243
		} finally {
244
			monitor.done();
143
		}
245
		}
144
		
145
		// Otherwise OK
146
		return Status.OK_STATUS;
147
	}
246
	}
148
	
247
	
248
	/**
249
	 * Computes the names of the test methods associated to the test cases of the specified test
250
	 * suite. Test methods names should be typically stored in the model.
251
	 * @param testSuite
252
	 * @param isExternalBehavior
253
	 * @param helper
254
	 * @see Helper#setTestMethodName(ITestCase, String)
255
	 */
149
	protected void computeTestMethodNames(ITestSuite testSuite, boolean isExternalBehavior, Helper helper) {
256
	protected void computeTestMethodNames(ITestSuite testSuite, boolean isExternalBehavior, Helper helper) {
150
		Iterator it = testSuite.getITestCases().iterator();
257
		Iterator it = testSuite.getITestCases().iterator();
151
		while (it.hasNext()) {
258
		while (it.hasNext()) {
Lines 155-184 Link Here
155
		}
262
		}
156
	}
263
	}
157
	
264
	
158
	public IFile getFileHandle(ITestSuite testSuite)
265
	public IFile getFileHandle() {
159
	{
266
		IContainer sourceContainer = getSourceContainerHandle();
160
		IContainer sourceContainer = getSourceContainerHandle(testSuite);
267
		return sourceContainer.getFile(new Path(getTestSuite().getImplementor().getResource().replace('.','/') + ".java")); //$NON-NLS-1$
161
		return sourceContainer.getFile(new Path(testSuite.getImplementor().getResource().replace('.','/') + ".java")); //$NON-NLS-1$
162
	}
268
	}
163
			
269
			
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)
270
	protected static Collection getDependentProjects(ITestSuite testSuite, IProject project)
183
	{
271
	{
184
		if((testSuite.getIReferencedSuites() == null) || (testSuite.getIReferencedSuites().isEmpty()))
272
		if((testSuite.getIReferencedSuites() == null) || (testSuite.getIReferencedSuites().isEmpty()))
Lines 203-210 Link Here
203
		return entries;
291
		return entries;
204
	}
292
	}
205
293
206
	public IProjectDependencyUpdater getProjectDependencyUpdater() {
207
		return projectDependencyUpdater;
208
	}
209
	
210
}
294
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/Helper.java (+141 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.ProjectAdjustChange;
29
import org.eclipse.jdt.core.ICompilationUnit;
32
import org.eclipse.jdt.core.ICompilationUnit;
30
import org.eclipse.jdt.core.JavaModelException;
33
import org.eclipse.jdt.core.JavaModelException;
31
import org.eclipse.jdt.core.ToolFactory;
34
import org.eclipse.jdt.core.ToolFactory;
35
import org.eclipse.jdt.core.dom.CompilationUnit;
36
import org.eclipse.jdt.core.dom.ImportDeclaration;
32
import org.eclipse.jdt.core.formatter.CodeFormatter;
37
import org.eclipse.jdt.core.formatter.CodeFormatter;
33
import org.eclipse.jface.text.Document;
38
import org.eclipse.jface.text.Document;
39
import org.eclipse.ltk.core.refactoring.Change;
40
import org.eclipse.ltk.core.refactoring.CompositeChange;
34
import org.eclipse.text.edits.TextEdit;
41
import org.eclipse.text.edits.TextEdit;
35
42
36
/**
43
/**
Lines 353-358 Link Here
353
			cu.createImport(importName, /*sibling*/null, /*progressMonitor*/null);
360
			cu.createImport(importName, /*sibling*/null, /*progressMonitor*/null);
354
		}
361
		}
355
	}
362
	}
363
	
364
	public void emitSortedImports(CompilationUnit cu) {
365
		Iterator it = importManager.getImports().iterator();
366
		while (it.hasNext()) {
367
			String importName = (String) it.next();
368
			if (!ASTHelper.hasImport(cu, importName)) {
369
				ImportDeclaration id = cu.getAST().newImportDeclaration();
370
				id.setName(cu.getAST().newName(importName));
371
				cu.imports().add(id);
372
			}
373
		}
374
		// TODO Remove unused imports
375
	}
356
376
357
	public String getImportedName(String qualifiedName)
377
	public String getImportedName(String qualifiedName)
358
	{
378
	{
Lines 424-427 Link Here
424
	public String getSuperclassName() {
444
	public String getSuperclassName() {
425
		return superClassName;
445
		return superClassName;
426
	}
446
	}
447
	
448
	/**
449
	 * Compares two strings appearing within a java comment/javadoc comment and return true
450
	 * if they contain the same strings, ignoring differences such as line breaks, tabs and
451
	 * space indentation.
452
	 * @param comment1
453
	 * @param comment2
454
	 * @return
455
	 */
456
	public static boolean compareJavaComments(CharSequence comment1, String comment2) {
457
		// Compare character by character, ignoring separating characters
458
		final String separators = "\n\r\t "; //$NON-NLS-1$
459
		StringIterator i1 = new StringIterator(comment1, separators);
460
		StringIterator i2 = new StringIterator(comment2, separators);
461
		while(i1.hasNextCharacter() && i2.hasNextCharacter()) {
462
			if (i1.getNextCharacter() != i2.getNextCharacter()) return false;
463
		}
464
		return !i1.hasNextCharacter() && !i2.hasNextCharacter();
465
	}
466
	
467
	/**
468
	 * String iterator that iterates character by character through a string. It has
469
	 * the ability to group a certain class of characters, replacing a sequence of one or 
470
	 * more of such characters by a single space. 
471
	 * @author jcanches
472
	 */
473
	public static class StringIterator {
474
		private int currentIndex;
475
		private int length;
476
		private CharSequence string;
477
		private String spaceCharacters;
478
		private boolean issueSpace;
479
		public StringIterator(CharSequence string, String spaceCharacters) {
480
			this.string = string;
481
			this.length = string.length();
482
			this.spaceCharacters = spaceCharacters;
483
			this.currentIndex = 0;
484
			this.issueSpace = false;
485
			skipIgnoredCharacters();
486
		}
487
		private void skipIgnoredCharacters() {
488
			while (currentIndex < length
489
				   && spaceCharacters.indexOf(string.charAt(currentIndex)) != -1) {
490
				issueSpace = true;
491
				currentIndex++;
492
			}
493
		}
494
		public boolean hasNextCharacter() {
495
			return issueSpace || currentIndex < length;
496
		}
497
		public char getNextCharacter() {
498
			if (issueSpace) {
499
				issueSpace = false;
500
				return ' ';
501
			}
502
			char ret = string.charAt(currentIndex++);
503
			skipIgnoredCharacters();
504
			return ret;
505
		}
506
	}
507
508
	public static class LineIterator {
509
		private final static String lineDelimiters = "\n\r"; //$NON-NLS-1$
510
		private StringIterator iterator;
511
		private String nextLine;
512
		public LineIterator(CharSequence string, String spaceCharacters) {
513
			this.iterator = new StringIterator(string, spaceCharacters);
514
			computeNextLine();
515
		}
516
		public boolean hasNextLine() {
517
			return nextLine != null;
518
		}
519
		public String getNextLine() {
520
			String ret = nextLine;
521
			computeNextLine();
522
			return ret;
523
		}
524
		private void computeNextLine() {
525
			StringBuffer line = new StringBuffer();
526
			boolean lineBegins = true;
527
			while (iterator.hasNextCharacter()) {
528
				char c = iterator.getNextCharacter();
529
				if (lineBegins) {
530
					if (c == ' ' || lineDelimiters.indexOf(c) != -1) {
531
						continue;
532
					}
533
					lineBegins = false;
534
				}
535
				if (lineDelimiters.indexOf(c) == -1) {
536
					line.append(c);
537
				} else {
538
					break;
539
				}
540
			}
541
			nextLine = line.toString().trim();
542
			if (nextLine.length() == 0) nextLine = null;
543
		}
544
	}
545
	
546
	public static boolean isDestructiveChange(Change change) {
547
		if (change instanceof ProjectAdjustChange) {
548
			return true;
549
		}
550
		if (change instanceof CompilationUnitChange) {
551
			return ((CompilationUnitChange)change).isDestructive();
552
		}
553
		if (change instanceof DeleteFileChange) {
554
			return true;
555
		}
556
		if (change instanceof CompositeChange) {
557
			CompositeChange cchange = (CompositeChange)change;
558
			Change[] children = cchange.getChildren();
559
			for (int i = 0; i < children.length; i++) {
560
				Change c = children[i];
561
				if (isDestructiveChange(c)) return true;
562
			}
563
			return false;
564
		}
565
		return false;
566
	}
567
427
}
568
}
(-)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/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/common/codegen/Generator.java (-59 / +217 lines)
Lines 15-111 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;
23
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
24
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
24
import org.eclipse.hyades.models.common.util.ResourceUtil;
25
import org.eclipse.hyades.test.tools.core.CorePlugin;
26
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
25
import org.eclipse.hyades.test.tools.core.internal.common.CommonPluginMessages;
26
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.CreateContainerChange;
27
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.CreateFileChange;
28
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.DeleteFileChange;
29
import org.eclipse.hyades.test.tools.core.internal.common.codegen.changes.PotentialChange;
30
import org.eclipse.ltk.core.refactoring.Change;
31
import org.eclipse.ltk.core.refactoring.CompositeChange;
32
import org.eclipse.ltk.core.refactoring.NullChange;
33
import org.eclipse.ltk.core.refactoring.Refactoring;
34
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
27
import org.eclipse.osgi.util.NLS;
35
import org.eclipse.osgi.util.NLS;
28
36
29
/**
37
/**
30
 * @author marcelop
38
 * Abstract code generator / code updater.<br>
39
 * <p>The typical use of the generator to generate the code for a test suite is:
40
 * <pre>
41
 * Generator generator = new Generator(testSuite);
42
 * if (generator.checkAllConditions(new SubProgressMonitor(pm, 1)).isOk()) {
43
 *   Change change = generator.createChange(new SubProgressMonitor(pm, 1));
44
 *   change.perform(new SubProgressMonitor(pm, 1));
45
 * }
46
 * </pre>
47
 * Since this class implements Refactoring, it can also be used in the context of a refactor
48
 * wizard (see {@link org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation}).</p>
49
 * <p>As of release 4.3, the Generator class has been completely redesigned, and now extends
50
 * the Refactoring framework provided by Eclipse SDK. This allows the user to preview
51
 * the changes implied by code generation/code update, and also to revert these changes.</p>
52
 * <p>This class is abstract. Sub-classes must provide {@link #generateCode(IProgressMonitor)}.
53
 * Optionally, if specific actions are needed before and/or after code generation, they can
54
 * extend {@link #createPreCodegenerationChange(IProgressMonitor)} and
55
 * {@link #createPostCodegenerationChange(IProgressMonitor)}.
56
 * If code update is desired they must override {@link #createUpdateChange(IFile, IProgressMonitor)}.
57
 * If additional checkings are needed, sub-classes may extend {@link #checkInitialConditions(IProgressMonitor)},
58
 * {@link #checkFinalConditions(IProgressMonitor)} and {@link #checkAllConditions(IProgressMonitor)}.
59
 * </p>
60
 * <p>The location and name of the generated file may be customized by overriding the methods
61
 * {@link #getFileHandle()} and {@link #getSourceContainerHandle()}.</p>
62
 * <p>A couple of helper methods are available to sub-classes: to manipulate Changes, see 
63
 * {@link #addPotentialChange(Change, CompositeChange)} and {@link #packCompositeChange(CompositeChange)}.</p>
64
 * <p>The package {@link org.eclipse.hyades.test.tools.core.internal.common.codegen.changes} provides a
65
 * library of pre-defined Changes for achieving various actions related to code-generation.</p>
66
 * @author marcelop, jcanches
31
 * @since 1.0.1
67
 * @since 1.0.1
32
 */
68
 */
33
abstract public class Generator
69
abstract public class Generator extends Refactoring
34
{
70
{
35
	public static final String CHARSET_UTF8 = "UTF-8"; //$NON-NLS-1$
71
	public static final String CHARSET_UTF8 = "UTF-8"; //$NON-NLS-1$
36
	
72
	
73
	private ITestSuite testSuite;
74
	
37
	/**
75
	/**
38
	 * Generates the code for the specified test suite, creating all the required
76
	 * 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
77
	 * @param testSuite
46
	 * @param monitor
47
	 * @throws Exception
48
	 */
78
	 */
49
	public void generate(ITestSuite testSuite, IProgressMonitor monitor) throws Exception
79
	protected Generator(ITestSuite testSuite) {
50
	{
80
		this.testSuite = testSuite;
51
		IFile file = getFileHandle(testSuite);
81
	}
52
		IContainer sourceContainer = getSourceContainerHandle(testSuite);
82
	
53
		
83
	/**
54
		boolean mustGenerate = true;
84
	 * Returns the test suite for which this generator is generating or updating code.
85
	 * @return
86
	 */
87
	final public ITestSuite getTestSuite() {
88
		return testSuite;
89
	}
90
	
91
	/**
92
	 * Add a change to a composite change, if this change has a real effect.
93
	 * A change is considered to have an effect if it not <code>null</code>, if it is not
94
	 * an instance of {@link NullChange}, and if it is not an instance of {@link PotentialChange},
95
	 * unless this potential change reports to be required.
96
	 * @param change A change or <code>null</code>.
97
	 * @param composite The composite change that will receive the change if necessary.
98
	 */
99
	protected final void addPotentialChange(Change change, CompositeChange composite) {
100
		if (change != null) {
101
			if (change instanceof NullChange) return;
102
			if (change instanceof PotentialChange && !((PotentialChange)change).isRequired()) return;
103
			composite.add(change);
104
		}
105
	}
106
	
107
	/**
108
	 * Pack a composite change. If the composite change
109
	 * has zero children, a {@link NullChange} is returned. Otherwise, the composite itself is
110
	 * returned.
111
	 * @param change
112
	 * @return
113
	 */
114
	protected final Change packCompositeChange(CompositeChange change) {
115
		if (change.getChildren().length > 0) return change;
116
		return new NullChange();
117
	}
118
	
119
	/**
120
	 * This implementation always return a OK status.
121
	 */
122
	public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
123
		pm.beginTask("", 1); //$NON-NLS-1$
124
		try {
125
			return new RefactoringStatus();
126
		} finally {
127
			pm.done();
128
		}
129
	}
130
131
	/**
132
	 * This implementation checks existence of the source container, and the accessibility of its project.
133
	 */
134
	public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
135
		pm.beginTask("", 2); //$NON-NLS-1$
136
		try {
137
			RefactoringStatus status = new RefactoringStatus();
138
			IContainer container = getSourceContainerHandle();
139
			pm.worked(1);
140
			if (container == null) {
141
				status.addError(CommonPluginMessages.E_CODEGEN_NO_SRCFOLDER);
142
			} else {
143
				IProject project = container.getProject();
144
				if (project.exists() && !project.isOpen()) {
145
					status.addError(NLS.bind(CommonPluginMessages.E_CODEGEN_CLOSED_PROJECT, container.getFullPath().toString()));
146
				}
147
				pm.worked(1);
148
			}
149
			return status;
150
		} finally {
151
			pm.done();
152
		}
153
	}
154
155
	final public Change createChange(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
156
		Change change = null;	
157
		IFile file = getFileHandle();
55
		if(file.exists()) {
158
		if(file.exists()) {
56
			try {
159
			try {
57
				doUpdateFile(testSuite, sourceContainer, file, monitor);
160
				change = createUpdateChange(file, monitor);
58
				mustGenerate = false;
59
			} catch (UnsupportedOperationException e) {
161
			} catch (UnsupportedOperationException e) {
60
				file.delete(/*force*/true, null);
162
				//Fall back to code generation.
61
			}
163
			}
62
		}
164
		}
63
		
165
		if (change == null) {
64
		if (mustGenerate) {
166
			change = createGenerateChange(monitor);
65
			ResourceUtil.createContainer(sourceContainer, monitor);
167
		}
66
			doGenerateFile(testSuite, sourceContainer, file, monitor);
168
		return change;
169
	}
170
171
	public String getName() {
172
		return CommonPluginMessages.GENERIC_GENERATOR;
173
	}
174
175
	private Change createGenerateChange(IProgressMonitor monitor) throws CoreException {
176
		monitor.beginTask("", 6); //$NON-NLS-1$
177
		try {
178
			CompositeChange change = new CompositeChange(CommonPluginMessages.GENERATE_CODE);
179
			Change subChange = createPreCodegenerationChange(new SubProgressMonitor(monitor, 1));
180
			if (subChange != null) {
181
				change.add(subChange);
182
			}
183
			IFile file = getFileHandle();
184
			if (file.exists()) {
185
				change.add(new DeleteFileChange(file));
186
			}
187
			monitor.worked(1);
188
			String code = generateCode(monitor);
189
			change.add(new CreateFileChange(file, code, CHARSET_UTF8));
190
			monitor.worked(3);
191
			subChange = createPostCodegenerationChange(new SubProgressMonitor(monitor, 1));
192
			if (subChange != null) {
193
				change.add(subChange);
194
			}
195
			return change;
196
		} finally {
197
			monitor.done();
67
		}
198
		}
68
	}
199
	}
69
	
200
	
70
	/**
201
	/**
71
	 * Validates whether code can be generated for the specified test suite.
202
	 * 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.
203
	 * @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
204
	 * @return
205
	 * @throws CoreException
79
	 */
206
	 */
80
	public IStatus validate(ITestSuite testSuite) {
207
	protected Change createPreCodegenerationChange(IProgressMonitor monitor) throws CoreException {
81
		IContainer container = getSourceContainerHandle(testSuite);
208
		monitor.beginTask("", 1); //$NON-NLS-1$
82
		if (container == null) {
209
		try {
83
			return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, 0, CommonPluginMessages.E_CODEGEN_NO_SRCFOLDER, null);
210
			IContainer sourceContainer = getSourceContainerHandle();
84
		}
211
			if (!sourceContainer.exists()) {
85
		IProject project = container.getProject();
212
				return new CreateContainerChange(sourceContainer);
86
		if (project.exists() && !project.isOpen()) {
213
			}
87
			return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, 0, NLS.bind(CommonPluginMessages.E_CODEGEN_CLOSED_PROJECT, container.getFullPath().toString()), null);
214
			return new NullChange();
215
		} finally {
216
			monitor.done();
88
		}
217
		}
89
		return Status.OK_STATUS;
90
	}
218
	}
91
	
219
	
92
	protected void doGenerateFile(ITestSuite testSuite, IContainer sourceContainer, IFile file, IProgressMonitor monitor) throws Exception
220
	/**
93
	{
221
	 * This implementation does nothing.
94
		generateFile(testSuite, file, monitor);
222
	 * @param monitor
223
	 * @return
224
	 * @throws CoreException
225
	 */
226
	protected Change createPostCodegenerationChange(IProgressMonitor monitor) throws CoreException {
227
		monitor.beginTask("", 1); //$NON-NLS-1$
228
		try {
229
			return new NullChange();
230
		} finally {
231
			monitor.done();
232
		}
95
	}
233
	}
96
	
234
	
97
	protected void doUpdateFile(ITestSuite testSuite, IContainer sourceContainer, IFile file, IProgressMonitor monitor) throws Exception {
235
	/**
98
		updateFile(testSuite, file, monitor);		
236
	 * Creates the change that describes the update of the specified file.
237
	 * <p>This implementation throws a {@link UnsupportedOperationException}. If code update
238
	 * is desired, the sub-class must override this implementation.</p>
239
	 * @param file The file to update
240
	 * @param monitor A progress monitor
241
	 * @return A change describing the update.
242
	 * @throws CoreException if the update creation failed, UnsupportedOperationException if code
243
	 * update is not supported.
244
	 */
245
	protected Change createUpdateChange(IFile file, IProgressMonitor monitor) throws CoreException, UnsupportedOperationException {
246
		throw new UnsupportedOperationException();
99
	}
247
	}
100
		
248
		
101
	public IFile getFileHandle(ITestSuite testSuite)
249
	/**
102
	{
250
	 * Returns the generated file. This is handle-only method, i.e. the returned file is
103
		IContainer sourceContainer = getSourceContainerHandle(testSuite);
251
	 * not required to exist. 
252
	 * @return The generated file.
253
	 */
254
	public IFile getFileHandle() {
255
		IContainer sourceContainer = getSourceContainerHandle();
104
		return sourceContainer.getFile(new Path(testSuite.getImplementor().getResource()));
256
		return sourceContainer.getFile(new Path(testSuite.getImplementor().getResource()));
105
	}
257
	}
106
	
258
	
107
	protected IContainer getSourceContainerHandle(ITestSuite testSuite)
259
	/**
108
	{
260
	 * Returns the container that will receive the generated file.
261
	 * @return
262
	 */
263
	final protected IContainer getSourceContainerHandle() {
109
		IContainer container = null;
264
		IContainer container = null;
110
		String location = testSuite.getImplementor().getLocation();
265
		String location = testSuite.getImplementor().getLocation();
111
		if (location != null) {
266
		if (location != null) {
Lines 119-128 Link Here
119
		return container;
274
		return container;
120
	}
275
	}
121
	
276
	
122
	abstract protected void generateFile(ITestSuite testSuite, IFile file, IProgressMonitor monitor) throws Exception;
277
	/**
123
	
278
	 * 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 {
279
	 * by {@link #getFileHandle()}.
125
		throw new UnsupportedOperationException();
280
	 * @param monitor A progress monitor
126
	}
281
	 * @return Source code.
282
	 * @throws CoreException
283
	 */
284
	abstract protected String generateCode(IProgressMonitor monitor) throws CoreException;
127
	
285
	
128
}
286
}
(-)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/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 (+11 lines)
Lines 1-3 Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 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 - Initial API and implementation
11
 **********************************************************************/
1
package org.eclipse.hyades.test.tools.core.internal.manual.codegen;
12
package org.eclipse.hyades.test.tools.core.internal.manual.codegen;
2
13
3
import java.util.Iterator;
14
import java.util.Iterator;
(-)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 (-5 / +6 lines)
Lines 2-8 Link Here
2
Bundle-ManifestVersion: 2
2
Bundle-ManifestVersion: 2
3
Bundle-Name: TPTP Test Tools Core Plug-In
3
Bundle-Name: TPTP Test Tools Core Plug-In
4
Bundle-SymbolicName: org.eclipse.hyades.test.tools.core; singleton:=true
4
Bundle-SymbolicName: org.eclipse.hyades.test.tools.core; singleton:=true
5
Bundle-Version: 4.2.0.qualifier
5
Bundle-Version: 4.2.1.qualifier
6
Bundle-ClassPath: tools-core.jar,
6
Bundle-ClassPath: tools-core.jar,
7
 common.runner.jar,
7
 common.runner.jar,
8
 manual.runner.jar,
8
 manual.runner.jar,
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/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/CompilationUnitChange.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
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
 * Copied from org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange.
24
 * @author jcanches
25
 * @since 4.3
26
 */
27
public class CompilationUnitChange extends TextFileChange {
28
29
	private ICompilationUnit fCUnit;
30
	private boolean destructive;
31
	
32
	/**
33
	 * Creates a new <code>CompilationUnitChange</code>.
34
	 * 
35
	 * @param name the change's name mainly used to render the change in the UI
36
	 * @param cunit the compilation unit this text change works on
37
	 * @param destructive Whether this change contains destructive changes (i.e. applying it
38
	 * will delete some existing code)
39
	 */
40
	public CompilationUnitChange(String name, ICompilationUnit cunit, boolean destructive) {
41
		super(name, getFile(cunit));
42
		Assert.isNotNull(cunit);
43
		fCUnit= cunit;
44
		setTextType("java"); //$NON-NLS-1$
45
		this.destructive = destructive;
46
	}
47
	
48
	private static IFile getFile(ICompilationUnit cunit) {
49
		return (IFile) cunit.getResource();
50
	}
51
	
52
	/* non java-doc
53
	 * Method declared in IChange.
54
	 */
55
	public Object getModifiedElement(){
56
		return fCUnit;
57
	}
58
	
59
	/**
60
	 * Returns the compilation unit this change works on.
61
	 * 
62
	 * @return the compilation unit this change works on
63
	 */
64
	public ICompilationUnit getCompilationUnit() {
65
		return fCUnit;
66
	}
67
	
68
	/**
69
	 * {@inheritDoc}
70
	 */
71
	protected IDocument acquireDocument(IProgressMonitor pm) throws CoreException {
72
		pm.beginTask("", 2); //$NON-NLS-1$
73
		fCUnit.becomeWorkingCopy(null, new SubProgressMonitor(pm, 1));
74
		return super.acquireDocument(new SubProgressMonitor(pm, 1));
75
	}
76
	
77
	/**
78
	 * {@inheritDoc}
79
	 */
80
	protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException {
81
		super.releaseDocument(document, pm);
82
		try {
83
			fCUnit.discardWorkingCopy();
84
		} finally {
85
			if (!isDocumentAcquired()) {
86
				if (fCUnit.isWorkingCopy())
87
					fCUnit.reconcile(
88
							ICompilationUnit.NO_AST, 
89
							false /* don't force problem detection */, 
90
							null /* use primary owner */, 
91
							null /* no progress monitor */);
92
93
				else
94
					fCUnit.makeConsistent(pm);
95
			}
96
		}
97
	}
98
	
99
//	/**
100
//	 * {@inheritDoc}
101
//	 */
102
//	protected Change createUndoChange(UndoEdit edit, ContentStamp stampToRestore) {
103
//		try {
104
//			return new UndoCompilationUnitChange(getName(), fCUnit, edit, stampToRestore, getSaveMode());
105
//		} catch (CoreException e) {
106
//			JavaPlugin.log(e);
107
//			return null;
108
//		}
109
//	}
110
	
111
	/**
112
	 * {@inheritDoc}
113
	 */
114
	public Object getAdapter(Class adapter) {
115
		if (ICompilationUnit.class.equals(adapter))
116
			return fCUnit;
117
		return super.getAdapter(adapter);
118
	}
119
	
120
	public boolean isDestructive() {
121
		return destructive;
122
	}
123
}
124
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/AdjustSourceContainerChange.java (+95 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
public class AdjustSourceContainerChange extends PotentialChange {
33
34
	private IContainer container;
35
36
	public AdjustSourceContainerChange(IContainer container) {
37
		this.container = container;
38
	}
39
	
40
	public Object getModifiedElement() {
41
		return container;
42
	}
43
44
	public String getName() {
45
		return NLS.bind(CommonPluginMessages.DEFINE_SOURCE_FOLDER, container.getFullPath().toString());
46
	}
47
48
	public void initializeValidationData(IProgressMonitor pm) {
49
		// NOP
50
	}
51
52
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException,	OperationCanceledException {
53
		pm.beginTask("", 2); //$NON-NLS-1$
54
		try {
55
			RefactoringStatus status = new RefactoringStatus();
56
			if (!container.isAccessible()) {
57
				status.addFatalError(NLS.bind(CommonPluginMessages.RESOURCE_NOT_ACCESSIBLE, container.getFullPath().toString()));
58
			}
59
			pm.worked(1);
60
			IJavaProject javaProject = JavaCore.create(container.getProject());
61
			if (!javaProject.exists()) {
62
				status.addFatalError(NLS.bind(CommonPluginMessages.NOT_IN_JAVA_PROJECT, container.getFullPath().toString()));
63
			}
64
			pm.worked(1);
65
			return status;
66
		} finally {
67
			pm.done();
68
		}
69
	}
70
71
	public Change perform(IProgressMonitor monitor) throws CoreException {
72
		IJavaProject javaProject = JavaCore.create(container.getProject());
73
		if(container.getType() == IResource.FOLDER)
74
		{
75
			if(!javaProject.isOnClasspath(container))
76
			{
77
				IClasspathEntry entry = JavaCore.newSourceEntry(container.getFullPath());
78
				List entries = new ArrayList(Arrays.asList(javaProject.getRawClasspath()));
79
				entries.add(1, entry);
80
				javaProject.setRawClasspath((IClasspathEntry[])entries.toArray(new IClasspathEntry[entries.size()]), monitor);
81
			}
82
		}
83
		return null;
84
	}
85
86
	public boolean isRequired() {
87
		IJavaProject javaProject = JavaCore.create(container.getProject());
88
		if(container.getType() == IResource.FOLDER)
89
		{
90
			return !javaProject.isOnClasspath(container);
91
		}
92
		return true;
93
	}
94
95
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/ProjectAdjustChange.java (+60 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
public class ProjectAdjustChange extends Change {
26
27
	private IProject project;
28
	private IProjectDependencyUpdater updater;
29
	
30
	public ProjectAdjustChange(IProjectDependencyUpdater updater, IProject project) {
31
		this.updater = updater;
32
		this.project = project;
33
	}
34
	
35
	public Object getModifiedElement() {
36
		return project;
37
	}
38
39
	public String getName() {
40
		return NLS.bind(CommonPluginMessages.ADJUST_CLASSPATH, project.getName());
41
	}
42
43
	public void initializeValidationData(IProgressMonitor pm) {
44
		// NOP
45
	}
46
47
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException {
48
		RefactoringStatus status = new RefactoringStatus();
49
		if (!project.isAccessible()) {
50
			status.addFatalError(NLS.bind(CommonPluginMessages.PROJECT_NOT_ACCESSIBLE, project.getName()));
51
		}
52
		return status;
53
	}
54
55
	public Change perform(IProgressMonitor monitor) throws CoreException {
56
		updater.adjustProject(project, monitor);
57
		return null;
58
	}
59
60
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/CreatePackageFragmentChange.java (+66 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
public class CreatePackageFragmentChange extends PotentialChange {
26
27
	private IPackageFragmentRoot sourceFolder;
28
	private String packageName;
29
30
	public CreatePackageFragmentChange(IPackageFragmentRoot sourceFolder, String packageName) {
31
		this.sourceFolder = sourceFolder;
32
		this.packageName = packageName;
33
	}
34
	
35
	public boolean isRequired() {
36
		return !sourceFolder.getPackageFragment(packageName).exists();
37
	}
38
39
	public Object getModifiedElement() {
40
		return sourceFolder;
41
	}
42
43
	public String getName() {
44
		return NLS.bind(CommonPluginMessages.CREATE_PACKAGE, packageName); 
45
	}
46
47
	public void initializeValidationData(IProgressMonitor monitor) {
48
		// NOP
49
	}
50
51
	public RefactoringStatus isValid(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
52
		RefactoringStatus status = new RefactoringStatus();
53
		if (!sourceFolder.exists()) {
54
			status.addFatalError(CommonPluginMessages.NO_SOURCE_FOLDER);
55
		} else if (sourceFolder.getResource().getType() != IResource.FOLDER) {
56
			status.addFatalError(CommonPluginMessages.NOT_A_SOURCE_FOLDER);
57
		}
58
		return status;
59
	}
60
61
	public Change perform(IProgressMonitor monitor) throws CoreException {
62
		sourceFolder.createPackageFragment(packageName, true, monitor);
63
		return null;
64
	}
65
66
}
(-)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 isRequired();
32
	
33
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/AssociateModelSourceChange.java (+109 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
public class AssociateModelSourceChange extends PotentialChange {
31
	
32
	private IFile javaFile;
33
	private ITestSuite testSuite;
34
	
35
	/**
36
	 * @param javaFile
37
	 * @param testSuite
38
	 */
39
	public AssociateModelSourceChange(IFile javaFile, ITestSuite testSuite) {
40
		this.javaFile = javaFile;
41
		this.testSuite = testSuite;
42
	}
43
44
	public Object getModifiedElement() {
45
		return javaFile;
46
	}
47
48
	public String getName() {
49
		return NLS.bind(CommonPluginMessages.ASSOCIATE_TEST_TO_SOURCE, new Object[] { testSuite.getName(), javaFile.getFullPath().toString() });
50
	}
51
52
	public void initializeValidationData(IProgressMonitor pm) {
53
		// NOP
54
	}
55
56
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException,	OperationCanceledException {
57
		return new RefactoringStatus();
58
	}
59
60
	public Change perform(IProgressMonitor pm) throws CoreException {
61
		pm.beginTask("", 3); //$NON-NLS-1$
62
		try {
63
			if (testSuite instanceof EObject) {
64
				EObject eObject = (EObject) testSuite;
65
				IFile testSuiteFile = EMFUtil.getWorkspaceFile(eObject);
66
				if (testSuiteFile != null && testSuiteFile.exists()) {
67
					// Add the Junit builder to the file's project (if not already installed)
68
					JUnitProjectBuilder.installBuilder(javaFile.getProject());
69
					pm.worked(1);
70
					// Also add the JUnit builder to the test suite's project (the source file
71
					// and the test suite usually are under the same project, but this is not
72
					// mandatory).
73
					JUnitProjectBuilder.installBuilder(testSuiteFile.getProject());
74
					pm.worked(1);
75
					// Record the link from the java file to the testsuite file
76
					JUnitModelUpdater.associateTestSuiteToJUnitSourceFile(javaFile, testSuiteFile);
77
					pm.worked(1);
78
				}
79
			}
80
		} catch (Throwable t) {
81
			CorePlugin.logError(t);
82
		} finally {
83
			pm.done();
84
		}
85
		return null;
86
	}
87
88
	public boolean isRequired() {
89
		if (!javaFile.exists()) return true;
90
		try {
91
			if (!JUnitProjectBuilder.isBuilderInstalled(javaFile.getProject())) return true;
92
			if (testSuite instanceof EObject) {
93
				EObject eObject = (EObject) testSuite;
94
				IFile testSuiteFile = EMFUtil.getWorkspaceFile(eObject);
95
				if (testSuiteFile != null && testSuiteFile.exists()) {
96
					if (!JUnitProjectBuilder.isBuilderInstalled(testSuiteFile.getProject())) return true;
97
				}
98
				IFile registeredTestSuiteFile = JUnitModelUpdater.getRegisteredTestSuiteFile(javaFile);
99
				if (registeredTestSuiteFile == null || !registeredTestSuiteFile.equals(testSuiteFile)) return true;
100
				return false;
101
			}
102
			return true;
103
		} catch (CoreException e) {
104
			CorePlugin.logError(e);
105
			return false;
106
		}
107
	}
108
109
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/DeleteFileChange.java (+119 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
public class DeleteFileChange extends Change {
29
30
	private IFile file;
31
	private String fSource;
32
	
33
	public DeleteFileChange(IFile file){
34
		Assert.isNotNull(file, "file"); //$NON-NLS-1$
35
		this.file = file;
36
	}
37
	
38
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
39
		RefactoringStatus status = new RefactoringStatus();
40
		if (!file.exists()) {
41
			status.addError(CommonPluginMessages.NO_FILE);
42
		}
43
		if (file.isReadOnly()) {
44
			status.addWarning(CommonPluginMessages.READ_ONLY_FILE);
45
		}
46
		return status;
47
	}
48
	
49
	public Change perform(IProgressMonitor pm) throws CoreException {
50
		try {
51
			pm.beginTask(CommonPluginMessages.DELETING_FILE, 1); 
52
			Assert.isNotNull(file);
53
			Assert.isTrue(file.exists());
54
			fSource= getSource(file);
55
			CreateFileChange undo= createUndoChange(file, file.getModificationStamp(), fSource);
56
			file.delete(true, true, pm);
57
			return undo;
58
		} finally {
59
			pm.done();
60
		}
61
	}
62
	
63
	private String getSource(IFile file) throws CoreException {
64
		String encoding= null;
65
		try {
66
			encoding= file.getCharset();
67
		} catch (CoreException ex) {
68
			// fall through. Take default encoding.
69
		}
70
		
71
		StringBuffer sb= new StringBuffer();
72
		BufferedReader br= null;
73
		InputStream in= null;
74
		try {
75
			in= file.getContents();
76
		    if (encoding != null)
77
		        br= new BufferedReader(new InputStreamReader(in, encoding));	
78
		    else
79
		        br= new BufferedReader(new InputStreamReader(in));	
80
			int read= 0;
81
			while ((read= br.read()) != -1)
82
				sb.append((char) read);
83
		} catch (IOException e){
84
			throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
85
		} finally {
86
			try{
87
				if (br != null) br.close();
88
				if (in != null) in.close();
89
			} catch (IOException e){
90
				throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
91
			}	
92
		}
93
		return sb.toString();
94
	}
95
	
96
	private static CreateFileChange createUndoChange(IFile file, long stampToRestore, String source) {
97
		String encoding;
98
		try {
99
			encoding= file.getCharset(false);
100
		} catch (CoreException e) {
101
			encoding= null;
102
		}
103
		return new CreateFileChange(file, source, encoding, stampToRestore);
104
	}
105
106
	public String getName() {
107
		return NLS.bind(CommonPluginMessages.DELETE_FILE, file.getFullPath().toString()); 
108
	}
109
110
	public Object getModifiedElement() {
111
		return file;
112
	}
113
114
	public void initializeValidationData(IProgressMonitor pm) {
115
		// TODO Auto-generated method stub
116
		
117
	}
118
}
119
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/CreateFileChange.java (+173 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
public class CreateFileChange extends Change {
34
35
	private IFile fFile;
36
	private String fSource;
37
	private String fEncoding;
38
	private boolean fExplicitEncoding;
39
	private long fStampToRestore;
40
41
	public CreateFileChange(IFile file, String source, String encoding) {
42
		this(file, source, encoding, IResource.NULL_STAMP);
43
	}
44
45
	public CreateFileChange(IFile file, String source, String encoding, long stampToRestore) {
46
		Assert.isNotNull(file, "file"); //$NON-NLS-1$
47
		Assert.isNotNull(source, "source"); //$NON-NLS-1$
48
		fFile = file;
49
		fSource= source;
50
		fEncoding= encoding;
51
		fExplicitEncoding= fEncoding != null;
52
		fStampToRestore= stampToRestore;
53
	}
54
55
	protected void setEncoding(String encoding, boolean explicit) {
56
		Assert.isNotNull(encoding, "encoding"); //$NON-NLS-1$
57
		fEncoding= encoding;
58
		fExplicitEncoding= explicit;
59
	}
60
61
	public String getName() {
62
		return NLS.bind(CommonPluginMessages.GENERATE_FILE, fFile.getFullPath().toString());
63
	}
64
65
	protected void setSource(String source) {
66
		fSource= source;
67
	}
68
69
	protected String getSource() {
70
		return fSource;
71
	}
72
73
	protected IFile getFile() {
74
		return fFile;
75
	}
76
77
	public Object getModifiedElement() {
78
		return fFile;
79
	}
80
81
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
82
		RefactoringStatus status = new RefactoringStatus();
83
		
84
		URI location = fFile.getLocationURI();
85
		if (location == null) {
86
			status.addFatalError(NLS.bind(CommonPluginMessages.UNKNOWN_LOCATION, fFile.getFullPath().toString()));
87
			return status;
88
		}
89
		
90
//		IFileInfo jFile= EFS.getStore(location).fetchInfo();
91
//		if (jFile.exists()) {
92
//			status.addFatalError(Messages.format(
93
//				NLSChangesMessages.CreateFileChange_error_exists, 
94
//				file.getFullPath().toString()));
95
//			return status;
96
//		}
97
		return status;
98
	}
99
100
	public Change perform(IProgressMonitor pm) throws CoreException {
101
102
		InputStream is= null;
103
		try {
104
			pm.beginTask(CommonPluginMessages.GENERATING_FILE, 2); 
105
106
			initializeEncoding();
107
			/*
108
			if (file.exists()) {
109
				CompositeChange composite= new CompositeChange(getName());
110
				composite.add(new DeleteFileChange(file));
111
				composite.add(new CreateFileChange(fPath, fSource, fEncoding, fStampToRestore, fExplicitEncoding));
112
				pm.worked(1);
113
				return composite.perform(new SubProgressMonitor(pm, 1));
114
			} else { */
115
			try {
116
				is= new ByteArrayInputStream(fSource.getBytes(fEncoding));
117
				fFile.create(is, false, new SubProgressMonitor(pm, 1));
118
				if (fStampToRestore != IResource.NULL_STAMP) {
119
					fFile.revertModificationStamp(fStampToRestore);
120
				}
121
				if (fExplicitEncoding) {
122
					fFile.setCharset(fEncoding, new SubProgressMonitor(pm, 1));
123
				} else {
124
					pm.worked(1);
125
				}
126
				return new DeleteFileChange(fFile);
127
			} catch (UnsupportedEncodingException e) {
128
				throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
129
			}
130
		} finally {
131
			try {
132
				if (is != null)
133
					is.close();
134
			} catch (IOException ioe) {
135
				throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
136
			} finally {
137
				pm.done();
138
			}
139
		}
140
	}
141
142
	private void initializeEncoding() {
143
		if (fEncoding == null) {
144
			fExplicitEncoding= false;
145
			if (fFile != null) {
146
				try {
147
					if (fFile.exists()) {
148
						fEncoding= fFile .getCharset(false);
149
						if (fEncoding == null) {
150
							fEncoding= fFile.getCharset(true);
151
						} else {
152
							fExplicitEncoding= true;
153
						}
154
					} else {
155
						fEncoding= fFile.getCharset(true);
156
					}
157
				} catch (CoreException e) {
158
					fEncoding= ResourcesPlugin.getEncoding();
159
					fExplicitEncoding= true;
160
				}
161
			} else {
162
				fEncoding= ResourcesPlugin.getEncoding();
163
				fExplicitEncoding= true;
164
			}
165
		}
166
		Assert.isNotNull(fEncoding);
167
	}
168
169
	public void initializeValidationData(IProgressMonitor pm) {
170
		// TODO Auto-generated method stub
171
		
172
	}
173
}
(-)src/org/eclipse/hyades/test/tools/core/internal/common/codegen/changes/CreateContainerChange.java (+58 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
public class CreateContainerChange extends PotentialChange {
26
27
	private IContainer container;
28
29
	public CreateContainerChange(IContainer container) {
30
		this.container = container;
31
	}
32
	
33
	public Object getModifiedElement() {
34
		return container;
35
	}
36
37
	public String getName() {
38
		return NLS.bind(CommonPluginMessages.CREATE_CONTAINER, container.getFullPath().toString());
39
	}
40
41
	public void initializeValidationData(IProgressMonitor pm) {
42
		// NOP
43
	}
44
45
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException,	OperationCanceledException {
46
		return new RefactoringStatus();
47
	}
48
49
	public Change perform(IProgressMonitor monitor) throws CoreException {
50
		ResourceUtil.createContainer(container, monitor);
51
		return null;
52
	}
53
54
	public boolean isRequired() {
55
		return !container.isAccessible();
56
	}
57
58
}

Return to bug 134254