diff --git a/base-test/org.eclipse.jdt.groovy.core.tests.compiler/src/org/eclipse/jdt/groovy/core/tests/xform/StaticCompilationTests.java b/base-test/org.eclipse.jdt.groovy.core.tests.compiler/src/org/eclipse/jdt/groovy/core/tests/xform/StaticCompilationTests.java index 2cdf7d0005..43e840fad4 100644 --- a/base-test/org.eclipse.jdt.groovy.core.tests.compiler/src/org/eclipse/jdt/groovy/core/tests/xform/StaticCompilationTests.java +++ b/base-test/org.eclipse.jdt.groovy.core.tests.compiler/src/org/eclipse/jdt/groovy/core/tests/xform/StaticCompilationTests.java @@ -5138,16 +5138,16 @@ public void testCompileStatic9771() { "Main.groovy", "@groovy.transform.CompileStatic\n" + "class Main {\n" + - " private final Map map = [:]\n" + - " void test() {\n" + - " { ->\n" + - " map['key'] = true\n" + - " }.call()\n" + - " print map\n" + - " }\n" + - " static main(args) {\n" + - " newInstance().test()\n" + - " }\n" + + " private final Map map = [:]\n" + + " void test() {\n" + + " { ->\n" + + " map['key'] = true\n" + + " }.call()\n" + + " print map\n" + + " }\n" + + " static main(args) {\n" + + " newInstance().test()\n" + + " }\n" + "}\n", }; //@formatter:on diff --git a/ide-test/org.codehaus.groovy.eclipse.codeassist.test/src/org/codehaus/groovy/eclipse/codeassist/tests/CompletionTestSuite.groovy b/ide-test/org.codehaus.groovy.eclipse.codeassist.test/src/org/codehaus/groovy/eclipse/codeassist/tests/CompletionTestSuite.groovy index ee0115823b..cd32d42c18 100644 --- a/ide-test/org.codehaus.groovy.eclipse.codeassist.test/src/org/codehaus/groovy/eclipse/codeassist/tests/CompletionTestSuite.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.codeassist.test/src/org/codehaus/groovy/eclipse/codeassist/tests/CompletionTestSuite.groovy @@ -15,6 +15,7 @@ */ package org.codehaus.groovy.eclipse.codeassist.tests +import static org.eclipse.jdt.core.groovy.tests.search.SearchTestSuite.waitUntilReady import static org.junit.Assert.* import java.util.regex.Pattern @@ -25,7 +26,6 @@ import org.codehaus.groovy.eclipse.codeassist.completions.GroovyExtendedCompleti import org.codehaus.groovy.eclipse.codeassist.requestor.ContentAssistContext import org.codehaus.groovy.eclipse.codeassist.requestor.GroovyCompletionProposalComputer import org.codehaus.groovy.eclipse.test.GroovyEclipseTestSuite -import org.codehaus.groovy.eclipse.test.SynchronizationUtils import org.codehaus.jdt.groovy.model.GroovyCompilationUnit import org.eclipse.jdt.core.ICompilationUnit import org.eclipse.jdt.core.IJavaElement @@ -55,7 +55,6 @@ abstract class CompletionTestSuite extends GroovyEclipseTestSuite { @Before final void setUpCompletionTestCase() { - SynchronizationUtils.waitForDSLDProcessingToComplete() setJavaPreference(PreferenceConstants.CODEASSIST_ADDIMPORT, true) setJavaPreference(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true) setJavaPreference(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, false) @@ -91,8 +90,7 @@ abstract class CompletionTestSuite extends GroovyEclipseTestSuite { /** Use {@link #createProposalsAtOffset} if testing {@link GroovyCompletionProposalComputer}. */ protected ICompletionProposal[] performContentAssist(ICompilationUnit unit, int offset, Class computerClass) { - JavaEditor editor = openInEditor(unit) - SynchronizationUtils.waitForIndexingToComplete(unit) + JavaEditor editor = openInEditor(unit); waitUntilReady(unit.javaProject) JavaSourceViewer viewer = editor.viewer viewer.setSelectedRange(offset, 0) diff --git a/ide-test/org.codehaus.groovy.eclipse.codebrowsing.test/src/org/codehaus/groovy/eclipse/codebrowsing/tests/CodeSelectGenericsTests.groovy b/ide-test/org.codehaus.groovy.eclipse.codebrowsing.test/src/org/codehaus/groovy/eclipse/codebrowsing/tests/CodeSelectGenericsTests.groovy index f34793d640..56d1e59374 100644 --- a/ide-test/org.codehaus.groovy.eclipse.codebrowsing.test/src/org/codehaus/groovy/eclipse/codebrowsing/tests/CodeSelectGenericsTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.codebrowsing.test/src/org/codehaus/groovy/eclipse/codebrowsing/tests/CodeSelectGenericsTests.groovy @@ -142,7 +142,7 @@ final class CodeSelectGenericsTests extends BrowsingTestSuite { String contents = '[a: Number].collect { k,v -> "" }' IJavaElement elem = assertCodeSelect([contents], 'collect') MethodNode method = ((GroovyResolvedBinaryMethod) elem).inferredElement - assert method.returnType.toString(false) == 'java.util.List ' + assert method.returnType.toString(false) == 'java.util.List ' } @Test diff --git a/ide-test/org.codehaus.groovy.eclipse.core.test/src/org/codehaus/groovy/eclipse/core/test/SyntheticMemberSearchTests.groovy b/ide-test/org.codehaus.groovy.eclipse.core.test/src/org/codehaus/groovy/eclipse/core/test/SyntheticMemberSearchTests.groovy index 85c5685547..37278e8e70 100644 --- a/ide-test/org.codehaus.groovy.eclipse.core.test/src/org/codehaus/groovy/eclipse/core/test/SyntheticMemberSearchTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.core.test/src/org/codehaus/groovy/eclipse/core/test/SyntheticMemberSearchTests.groovy @@ -21,6 +21,7 @@ import org.codehaus.groovy.eclipse.core.search.SyntheticAccessorSearchRequestor import org.codehaus.groovy.eclipse.test.GroovyEclipseTestSuite import org.eclipse.jdt.core.IJavaElement import org.eclipse.jdt.core.IType +import org.eclipse.jdt.core.groovy.tests.search.SearchTestSuite import org.eclipse.jdt.core.search.IJavaSearchConstants import org.eclipse.jdt.core.search.SearchEngine import org.eclipse.jdt.core.search.SearchMatch @@ -44,7 +45,7 @@ final class SyntheticMemberSearchTests extends GroovyEclipseTestSuite { | void setZzzz(boolean value) {} |} |'''.stripMargin(), 'G', 'p' - + gUnit.discardWorkingCopy() gType = gUnit.getType('G') assert gType?.exists() } @@ -235,7 +236,6 @@ final class SyntheticMemberSearchTests extends GroovyEclipseTestSuite { @Test void testSearchInJava5() { addJavaSource '''\ - |package p; |class C { | public boolean isXxxx() { | return false; @@ -252,7 +252,7 @@ final class SyntheticMemberSearchTests extends GroovyEclipseTestSuite { List matches = [] new SyntheticAccessorSearchRequestor().findSyntheticMatches(gType.children.find { it.elementName == 'xxxx' }, IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE, - [SearchEngine.defaultSearchParticipant] as SearchParticipant[], + [SearchEngine.getDefaultSearchParticipant()] as SearchParticipant[], SearchEngine.createWorkspaceScope(), matches.&add, null) @@ -264,7 +264,8 @@ final class SyntheticMemberSearchTests extends GroovyEclipseTestSuite { private List performSearch(String searchName, IType type = gType) { IJavaElement target = type.children.find { it.elementName == searchName } - assert target != null : "child not found: $searchName" + assert target?.exists() : "child not found: $searchName" + SearchTestSuite.waitUntilReady(type.javaProject) new LinkedList().tap { new SyntheticAccessorSearchRequestor().findSyntheticMatches(target, it.&add, null) @@ -275,34 +276,20 @@ final class SyntheticMemberSearchTests extends GroovyEclipseTestSuite { assert matches.size() == expected : "Wrong number of matches found in:\n${ -> matches.join('\n')}" } - /** - * Ensures that the given match exists at least once in the list. - */ private void assertMatch(String enclosingName, String matchName, String contents, List matches) { - int matchIndex = 0 - int matchStart = 0 - boolean matchFound = false - for (match in matches) { - if (isMatchOf(enclosingName, matchName, matchStart, contents, match)) { - matchFound = true - break - } - matchIndex += 1 - } - assert matchFound : "Match name $matchName not found in\n${ -> matches.join('\n')}" - - SearchMatch match = matches.remove(matchIndex) + SearchMatch match = matches.find(this.&isMatchOf.curry(enclosingName, matchName, contents)) + assert match : "Match for '$matchName' not found in:\n${ -> matches.join('\n')}" assert (match.element as IJavaElement).exists() } private void assertNoMatch(String enclosingName, String matchName, String contents, List matches) { boolean matchFound = matches.any(this.&isMatchOf.curry(enclosingName, matchName, contents)) - assert !matchFound : "Match name $matchName was found, but should not have been.\n${ -> matches.join('\n')}" + assert !matchFound : "Match for '$matchName' was found in:\n${ -> matches.join('\n')}" } - private static boolean isMatchOf(String enclosingName, String matchName, int matchStart = 0, String contents, SearchMatch match) { + private static boolean isMatchOf(String enclosingName, String matchName, String contents, SearchMatch match) { (match.element as IJavaElement).elementName == enclosingName && - contents.indexOf(matchName, matchStart) == match.offset && + contents.indexOf(matchName) == match.offset && matchName.length() == match.length } } diff --git a/ide-test/org.codehaus.groovy.eclipse.dsl.tests/src/org/codehaus/groovy/eclipse/dsl/tests/DSLInferencingTests.groovy b/ide-test/org.codehaus.groovy.eclipse.dsl.tests/src/org/codehaus/groovy/eclipse/dsl/tests/DSLInferencingTests.groovy index 6c38c996e7..9bf1bb1189 100644 --- a/ide-test/org.codehaus.groovy.eclipse.dsl.tests/src/org/codehaus/groovy/eclipse/dsl/tests/DSLInferencingTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.dsl.tests/src/org/codehaus/groovy/eclipse/dsl/tests/DSLInferencingTests.groovy @@ -15,6 +15,8 @@ */ package org.codehaus.groovy.eclipse.dsl.tests +import static org.eclipse.core.resources.IncrementalProjectBuilder.FULL_BUILD + import org.codehaus.groovy.eclipse.dsl.GroovyDSLCoreActivator import org.codehaus.groovy.eclipse.test.TestProject import org.eclipse.jdt.groovy.core.util.GroovyUtils @@ -1800,7 +1802,7 @@ final class DSLInferencingTests extends DSLInferencingTestSuite { | property name:'other', type:Integer |} |'''.stripMargin()) - otherProject.fullBuild() + otherProject.project.build(FULL_BUILD, null) addProjectReference(otherProject.javaProject) GroovyDSLCoreActivator.default.contextStoreManager.initialize(project, true) diff --git a/ide-test/org.codehaus.groovy.eclipse.dsl.tests/src/org/codehaus/groovy/eclipse/dsl/tests/DSLStoreTests.groovy b/ide-test/org.codehaus.groovy.eclipse.dsl.tests/src/org/codehaus/groovy/eclipse/dsl/tests/DSLStoreTests.groovy index 5d05dbfbbd..acc57727ca 100644 --- a/ide-test/org.codehaus.groovy.eclipse.dsl.tests/src/org/codehaus/groovy/eclipse/dsl/tests/DSLStoreTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.dsl.tests/src/org/codehaus/groovy/eclipse/dsl/tests/DSLStoreTests.groovy @@ -32,8 +32,6 @@ import org.eclipse.core.resources.IncrementalProjectBuilder import org.eclipse.core.runtime.FileLocator import org.eclipse.core.runtime.Path import org.eclipse.jdt.core.JavaCore -import org.eclipse.jdt.core.groovy.tests.SimpleProgressMonitor -import org.eclipse.jdt.internal.core.JavaModelManager import org.junit.Test final class DSLStoreTests extends DSLInferencingTestSuite { @@ -43,22 +41,12 @@ final class DSLStoreTests extends DSLInferencingTestSuite { * @param allExpectedPointcuts map: dsl file name -> all pointcuts in that file * @param expectedContributionCounts map: pointcut name -> all contribution group associated with */ - private void assertDSLStore(int expectedNumDslFiles, Map> allExpectedPointcuts, Map expectedContributionCounts) { - // ensure DSLDs are refreshed - // don't schedule. instead run in the same thread. - println 'About to run RefreshDSLDJob' - - SimpleProgressMonitor spm = new SimpleProgressMonitor('clean build') - project.build(IncrementalProjectBuilder.CLEAN_BUILD, spm) - spm.waitForCompletion() - - JavaModelManager.indexManager.removeIndex(project.location) - JavaModelManager.indexManager.cleanUpIndexes() - SynchronizationUtils.waitForIndexingToComplete(javaProject) + private void runTest(int expectedNumDslFiles, Map> allExpectedPointcuts, Map expectedContributionCounts) { + project.build(IncrementalProjectBuilder.CLEAN_BUILD, null) + SynchronizationUtils.waitForDSLDProcessingToComplete() DSLDStoreManager manager = GroovyDSLCoreActivator.default.contextStoreManager manager.initialize(project, true) - println 'Finished RefreshDSLDJob' DSLDStore store = manager.getDSLDStore(project) Set disabledScripts = DSLPreferences.disabledScriptsAsSet @@ -131,14 +119,14 @@ final class DSLStoreTests extends DSLInferencingTestSuite { @Test void testNothing() { - assertDSLStore(0, [:], [:]) + runTest(0, [:], [:]) } @Test void testSingleSimple() { createDsls('currentType().accept { }') - assertDSLStore(1, + runTest(1, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ]), @@ -156,7 +144,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { 'g.accept { }\n' + 'g.accept { }') - assertDSLStore(1, + runTest(1, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ]), @@ -172,7 +160,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { void testTwoPointcuts() { createDsls('currentType().accept { }\nfields().accept { }') - assertDSLStore(1, + runTest(1, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0), createSemiUniqueName(FindFieldPointcut, 0) @@ -190,7 +178,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { void testTwoPointcutsTwoFiles() { createDsls('currentType().accept { }', 'fields().accept { }') - assertDSLStore(2, + runTest(2, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ], [ @@ -209,7 +197,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { void testTwoFilesEachWith2Pointcuts() { createDsls('currentType().accept { }\nfields().accept { }', 'currentType().accept { }\nfields().accept { }') - assertDSLStore(2, + runTest(2, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0), createSemiUniqueName(FindFieldPointcut, 0) @@ -233,7 +221,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { createDsls('def a = currentType()\ndef b = fields()\na.accept { }\na.accept { }\nb.accept { }\nb.accept { }', 'def a = currentType()\ndef b = fields()\na.accept { }\na.accept { }\nb.accept { }\nb.accept { }') - assertDSLStore(2, + runTest(2, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0), createSemiUniqueName(FindFieldPointcut, 0) @@ -259,7 +247,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { 'def a = currentType()\na.accept { }\na.accept { }\na.accept { }\na.accept { }\na.accept { }', '') // not in store - assertDSLStore(3, + runTest(3, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0), createSemiUniqueName(FindFieldPointcut, 0) @@ -284,11 +272,11 @@ final class DSLStoreTests extends DSLInferencingTestSuite { @Test void testAddAndRemove() { - assertDSLStore(0, [:], [:]) + runTest(0, [:], [:]) // add one createDsls('currentType().accept { }') - assertDSLStore(1, + runTest(1, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ]), @@ -302,7 +290,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { // add another createDsls('currentType().accept { }') - assertDSLStore(2, + runTest(2, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ], [ @@ -318,7 +306,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { // remove second deleteDslFile(1) - assertDSLStore(1, + runTest(1, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ]), @@ -331,13 +319,13 @@ final class DSLStoreTests extends DSLInferencingTestSuite { // remove first deleteDslFile(0) - assertDSLStore(0, [:], [:]) + runTest(0, [:], [:]) } @Test void testChange() { createDsls('currentType().accept { }') - assertDSLStore(1, + runTest(1, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ]), @@ -351,7 +339,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { // overwrite the original deleteDslFile(0); index = 0 createDsls('currentType().accept { }\nfields().accept { }') - assertDSLStore(1, + runTest(1, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0), createSemiUniqueName(FindFieldPointcut, 0) @@ -368,7 +356,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { @Test void testDisabledOfFile() { createDsls('currentType().accept { }', 'fields().accept { }') - assertDSLStore(2, + runTest(2, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ], [ @@ -385,7 +373,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { // disable script setDisabledScripts(DSLDStore.toUniqueString(project.getFile('dsl0.dsld'))) - assertDSLStore(2, + runTest(2, createExpectedPointcuts([], [ createSemiUniqueName(FindFieldPointcut, 1) ]), @@ -402,7 +390,7 @@ final class DSLStoreTests extends DSLInferencingTestSuite { deleteDslFile(0); deleteDslFile(1); index = 0 createDsls('currentType().accept { }', 'fields().accept { }') - assertDSLStore(2, + runTest(2, createExpectedPointcuts([ createSemiUniqueName(CurrentTypePointcut, 0) ], [ @@ -428,21 +416,21 @@ final class DSLStoreTests extends DSLInferencingTestSuite { IStorage storage = javaProject.getPackageFragmentRoot(jarPath).getPackageFragment('dsld').nonJavaResources[0] String dsld = DSLDStore.toUniqueString(storage), pcut = createSemiUniqueName(CurrentTypePointcut, storage) - assertDSLStore(1, [(dsld): [pcut]], [(pcut): 1]) + runTest(1, [(dsld): [pcut]], [(pcut): 1]) // disable script setDisabledScripts(dsld) - assertDSLStore(1, [:], [:]) + runTest(1, [:], [:]) // re-enable setDisabledScripts() - assertDSLStore(1, [(dsld): [pcut]], [(pcut): 1]) + runTest(1, [(dsld): [pcut]], [(pcut): 1]) // remove from classpath GroovyRuntime.removeClasspathEntry(javaProject, cpEntry) project.refreshLocal(IResource.DEPTH_INFINITE, null) buildProject() - assertDSLStore(0, [:], [:]) + runTest(0, [:], [:]) } } diff --git a/ide-test/org.codehaus.groovy.eclipse.junit.test/src/org/codehaus/groovy/eclipse/junit/test/JUnitTestSuite.groovy b/ide-test/org.codehaus.groovy.eclipse.junit.test/src/org/codehaus/groovy/eclipse/junit/test/JUnitTestSuite.groovy index 12837d2ef5..c1c84998be 100644 --- a/ide-test/org.codehaus.groovy.eclipse.junit.test/src/org/codehaus/groovy/eclipse/junit/test/JUnitTestSuite.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.junit.test/src/org/codehaus/groovy/eclipse/junit/test/JUnitTestSuite.groovy @@ -31,6 +31,7 @@ package org.codehaus.groovy.eclipse.junit.test import org.codehaus.groovy.eclipse.test.GroovyEclipseTestSuite +import org.codehaus.groovy.eclipse.test.SynchronizationUtils import org.codehaus.jdt.groovy.model.GroovyCompilationUnit import org.junit.Before @@ -44,7 +45,7 @@ abstract class JUnitTestSuite extends GroovyEclipseTestSuite { @Override protected GroovyCompilationUnit addGroovySource(CharSequence contents, String name = nextUnitName(), String pack = 'p') { GroovyCompilationUnit unit = super.addGroovySource(contents, name, pack) - waitForIndex() + SynchronizationUtils.waitForIndexingToComplete() return unit } } diff --git a/ide-test/org.codehaus.groovy.eclipse.quickfix.test/src/org/codehaus/groovy/eclipse/quickfix/test/QuickFixTestSuite.groovy b/ide-test/org.codehaus.groovy.eclipse.quickfix.test/src/org/codehaus/groovy/eclipse/quickfix/test/QuickFixTestSuite.groovy index fb5bcfc535..d027fe9f77 100644 --- a/ide-test/org.codehaus.groovy.eclipse.quickfix.test/src/org/codehaus/groovy/eclipse/quickfix/test/QuickFixTestSuite.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.quickfix.test/src/org/codehaus/groovy/eclipse/quickfix/test/QuickFixTestSuite.groovy @@ -64,7 +64,6 @@ abstract class QuickFixTestSuite extends GroovyEclipseTestSuite { protected IMarker[] getJavaProblemMarkers(IResource resource) { buildProject() - waitForIndex() return resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE) } } diff --git a/ide-test/org.codehaus.groovy.eclipse.quickfix.test/src/org/codehaus/groovy/eclipse/quickfix/test/resolvers/GroovyProjectGroovyQuickFixTests.groovy b/ide-test/org.codehaus.groovy.eclipse.quickfix.test/src/org/codehaus/groovy/eclipse/quickfix/test/resolvers/GroovyProjectGroovyQuickFixTests.groovy index 49a1804c9a..7ab2ea030c 100644 --- a/ide-test/org.codehaus.groovy.eclipse.quickfix.test/src/org/codehaus/groovy/eclipse/quickfix/test/resolvers/GroovyProjectGroovyQuickFixTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.quickfix.test/src/org/codehaus/groovy/eclipse/quickfix/test/resolvers/GroovyProjectGroovyQuickFixTests.groovy @@ -225,7 +225,7 @@ final class GroovyProjectGroovyQuickFixTests extends QuickFixTestSuite { def proposals = getGroovyQuickFixes(unit) - assert proposals*.displayString == ['Import \'Target\' (java.lang.annotation)', 'Import \'Target\' (groovy.lang.DelegatesTo)'] + assert proposals*.displayString == ['Import \'Target\' (groovy.lang.DelegatesTo)', 'Import \'Target\' (java.lang.annotation)'] } @Test diff --git a/ide-test/org.codehaus.groovy.eclipse.refactoring.test/src/org/codehaus/groovy/eclipse/refactoring/test/internal/JavaProjectHelper.java b/ide-test/org.codehaus.groovy.eclipse.refactoring.test/src/org/codehaus/groovy/eclipse/refactoring/test/internal/JavaProjectHelper.java index fd330bd7c5..b56e53666e 100644 --- a/ide-test/org.codehaus.groovy.eclipse.refactoring.test/src/org/codehaus/groovy/eclipse/refactoring/test/internal/JavaProjectHelper.java +++ b/ide-test/org.codehaus.groovy.eclipse.refactoring.test/src/org/codehaus/groovy/eclipse/refactoring/test/internal/JavaProjectHelper.java @@ -41,10 +41,8 @@ import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.core.ClasspathEntry; -import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.launching.JavaRuntime; -import org.eclipse.swt.widgets.Display; import org.osgi.framework.Bundle; /** @@ -124,31 +122,10 @@ public static void delete(final IJavaElement element) throws CoreException { } delete(element.getResource()); }, null); - - Display display = Display.getCurrent(); - if (display != null) { - while (display.readAndDispatch()) { - // continue - } - } } public static void delete(final IResource resource) throws CoreException { - for (int i = 0; i < MAX_RETRY; i += 1) { - try { - resource.delete(true, null); - i = MAX_RETRY; - } catch (CoreException e) { - if (i == MAX_RETRY - 1) { - JavaPlugin.log(e); - throw e; - } - try { - Thread.sleep(1000); // sleep a second - } catch (InterruptedException ignore) { - } - } - } + org.eclipse.jdt.core.tests.util.Util.delete(resource); } /** diff --git a/ide-test/org.codehaus.groovy.eclipse.refactoring.test/src/org/codehaus/groovy/eclipse/refactoring/test/rename/RenameRefactoringTestSuite.groovy b/ide-test/org.codehaus.groovy.eclipse.refactoring.test/src/org/codehaus/groovy/eclipse/refactoring/test/rename/RenameRefactoringTestSuite.groovy index 3d919f2295..1058300935 100644 --- a/ide-test/org.codehaus.groovy.eclipse.refactoring.test/src/org/codehaus/groovy/eclipse/refactoring/test/rename/RenameRefactoringTestSuite.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.refactoring.test/src/org/codehaus/groovy/eclipse/refactoring/test/rename/RenameRefactoringTestSuite.groovy @@ -40,23 +40,17 @@ abstract class RenameRefactoringTestSuite extends GroovyEclipseTestSuite { } protected final ICompilationUnit[] createUnits(TestSource... sources) { - try { - return sources.findResults { - if (it.name.endsWith('.groovy')) { - addGroovySource(it.contents, it.name - ~/.groovy$/, it.pack).tap { - discardWorkingCopy() - save(null, true) - } - } else if (it.name.endsWith('.java')) { - addJavaSource(it.contents, it.name - ~/.java$/, it.pack).tap { - discardWorkingCopy() - save(null, true) - } + return sources.findResults { + if (it.name.endsWith('.groovy')) { + addGroovySource(it.contents, it.name - ~/.groovy$/, it.pack).tap { + discardWorkingCopy() } - }.toArray(new ICompilationUnit[0]) - } finally { - waitForIndex() - } + } else if (it.name.endsWith('.java')) { + addJavaSource(it.contents, it.name - ~/.java$/, it.pack).tap { + discardWorkingCopy() + } + } + }.toArray(new ICompilationUnit[0]) } @CompileDynamic diff --git a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/GroovyEclipseTestSuite.groovy b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/GroovyEclipseTestSuite.groovy index 92017d4057..15a5b00d39 100644 --- a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/GroovyEclipseTestSuite.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/GroovyEclipseTestSuite.groovy @@ -24,6 +24,7 @@ import groovy.transform.stc.ClosureParams import groovy.transform.stc.SimpleType import org.codehaus.groovy.eclipse.core.compiler.GroovySnippetCompiler +import org.codehaus.groovy.eclipse.core.model.GroovyRuntime import org.codehaus.jdt.groovy.model.GroovyCompilationUnit import org.codehaus.jdt.groovy.model.GroovyNature import org.eclipse.core.internal.utils.UniversalUniqueIdentifier @@ -56,7 +57,7 @@ abstract class GroovyEclipseTestSuite { @BeforeClass static final void setUpTestSuite() { - testProject = new TestProject(autoBuilding: false) + testProject = new TestProject() def projectScope = new ProjectScope(testProject.project) projectScope.getNode(Platform.PI_RUNTIME).put(Platform.PREF_LINE_SEPARATOR, '\n') projectScope.getNode('org.eclipse.jdt.launching').put('org.eclipse.jdt.launching.PREF_COMPILER_COMPLIANCE_DOES_NOT_MATCH_JRE', JavaCore.IGNORE) @@ -95,7 +96,7 @@ abstract class GroovyEclipseTestSuite { groovyPlugin.activeWorkbenchWindow?.activePage?.closeAllEditors(false) undoManager?.flush() - testProject.deleteWorkingCopies() + testProject.discardWorkingCopies() testProject.project.build(IncrementalProjectBuilder.CLEAN_BUILD, null) // for some reason the source folder is not always present in getPackageFragmentRoots(): @@ -184,7 +185,7 @@ abstract class GroovyEclipseTestSuite { } protected final boolean hasGroovyLibraries() { - testProject.hasGroovyLibraries() + GroovyRuntime.hasGroovyClasspathContainer(testProject.javaProject) } protected final GroovySnippetCompiler getGroovySnippetCompiler() { @@ -201,22 +202,35 @@ abstract class GroovyEclipseTestSuite { protected final JavaEditor openInEditor(ICompilationUnit unit) { setJavaPreference(EDITOR_MARK_OCCURRENCES, false) - try { - EditorUtility.openInEditor(unit) - } finally { - SynchronizationUtils.runEventQueue() + EditorUtility.openInEditor(unit).tap { + final reconcile = new java.util.concurrent.CountDownLatch(1) + addReconcileListener(reconcile.&countDown as ReconcileListener) + reconcile.await(1500, java.util.concurrent.TimeUnit.MILLISECONDS) + + SynchronizationUtils.joinBackgroundActivities() } } protected final void buildProject() { - testProject.fullBuild() - } - - protected final void waitForIndex() { - testProject.waitForIndexer() + testProject.project.build(IncrementalProjectBuilder.FULL_BUILD, null) } protected final void withProject(@ClosureParams(value=SimpleType, options='org.eclipse.core.resources.IProject') Closure closure) { closure(testProject.project) } + + //-------------------------------------------------------------------------- + + abstract static class ReconcileListener implements org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener { + @Override + void aboutToBeReconciled() { + } + + @Override + void reconciled(org.eclipse.jdt.core.dom.CompilationUnit ast, boolean forced, org.eclipse.core.runtime.IProgressMonitor monitor) { + reconcile() + } + + abstract reconcile() + } } diff --git a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/SynchronizationUtils.java b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/SynchronizationUtils.java index 0995615d8a..45b75abdce 100644 --- a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/SynchronizationUtils.java +++ b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/SynchronizationUtils.java @@ -19,10 +19,12 @@ import java.util.List; import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.internal.core.JavaModelManager; +import org.eclipse.jdt.internal.core.search.processing.IJob; import org.eclipse.swt.SWTException; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IViewPart; @@ -56,134 +58,144 @@ public static void joinBackgroundActivities() { } } while (interrupted); - joinJobs(100, 1000, 100); - } - - private static boolean joinJobs(long minTime, long maxTime, long intervalTime) { - long startTime = System.currentTimeMillis() + minTime; runEventQueue(); - while (System.currentTimeMillis() < startTime) { - runEventQueue(intervalTime); - } - long endTime = maxTime > 0 && maxTime < Long.MAX_VALUE ? System.currentTimeMillis() + maxTime : Long.MAX_VALUE; - boolean calm = allJobsQuiet(); - while (!calm && System.currentTimeMillis() < endTime) { - runEventQueue(intervalTime); - //printJobs(); - calm = allJobsQuiet(); + final long stopTime = (System.currentTimeMillis() + 1500); + while (anyRunJobs() && System.currentTimeMillis() < stopTime) { + runEventQueue(); + printJobs(); + sleep(100); } - return calm; } - public static void sleep(int intervalTime) { - try { - Thread.sleep(intervalTime); - } catch (InterruptedException ignore) { + public static void waitForIndexingToComplete() { + if (JavaModelManager.getIndexManager().awaitingJobsCount() > 0) { + // adapted from org.eclipse.jdt.internal.core.JavaModelManager#secondaryTypes and + // org.eclipse.jdt.internal.core.SearchableEnvironment#findConstructorDeclarations + JavaModelManager.getIndexManager().performConcurrentJob(new IJob() { + @Override + public boolean belongsTo(final String family) { + return true; + } + + @Override + public void cancel() { + } + + @Override + public void ensureReadyToRun() { + } + + @Override + public boolean execute(final IProgressMonitor progress) { + return progress == null || !progress.isCanceled(); + } + + @Override + public String getJobFamily() { + return ""; + } + }, IJob.WaitUntilReady, null); } - } - private static void runEventQueue() { - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (window != null) { - runEventQueue(window.getShell()); + for (Job job : Job.getJobManager().find(null)) { + switch (job.getState()) { + case Job.RUNNING: + case Job.WAITING: + if (job.getName().contains("Java index")) { + joinUninterruptibly(job); + } + } } } - private static void runEventQueue(Shell shell) { - try { - while (shell.getDisplay().readAndDispatch()) { - // do nothing + public static void waitForDSLDProcessingToComplete() { + for (Job job : Job.getJobManager().find(null)) { + switch (job.getState()) { + case Job.RUNNING: + case Job.WAITING: + if (job.getName().startsWith("Refresh DSLD")) { + joinUninterruptibly(job); + } } - } catch (SWTException e) { - e.printStackTrace(); } } - private static void runEventQueue(long minTime) { - long nextCheck = System.currentTimeMillis() + minTime; - while (System.currentTimeMillis() < nextCheck) { - runEventQueue(); - sleep(1); + public static void sleep(final int ms) { + try { + Thread.sleep(ms); + } catch (InterruptedException ignore) { } } - public static IViewPart showView(String id) throws Exception { + public static IViewPart showView(final String id) { try { return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id); + } catch (CoreException e) { + throw new RuntimeException(e); } finally { runEventQueue(); } } - private static boolean allJobsQuiet() { - for (Job job : Job.getJobManager().find(null)) { - switch (job.getState()) { - case Job.RUNNING: - case Job.WAITING: - if (!SKIP_JOBS.contains(job.getName().toLowerCase())) { - return false; - } + public static void joinUninterruptibly(final Job job) { + boolean interrupted; + do { + interrupted = false; + try { + System.err.println("Waiting for: " + job.getName()); + job.join(); + } catch (OperationCanceledException ignore) { + + } catch (InterruptedException e) { + interrupted = true; } - } - return true; + } while (interrupted); } - public static void printJobs() { - System.out.println("=============Printing Jobs=============="); - for (Job job : Job.getJobManager().find(null)) { - switch (job.getState()) { - case Job.RUNNING: - case Job.WAITING: - if (!SKIP_JOBS.contains(job.getName().toLowerCase())) { - System.out.println(job.getName()); + //-------------------------------------------------------------------------- + + private static void runEventQueue() { + IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (window != null) { + Shell shell = window.getShell(); + try { + while (shell.getDisplay().readAndDispatch()) { + // do nothing } + } catch (SWTException e) { + e.printStackTrace(); } } - System.out.println("========================================"); } - public static void waitForIndexingToComplete(final IJavaElement element) { - JavaModelManager.getIndexManager().indexAll(element.getJavaProject().getProject()); - org.eclipse.jdt.core.groovy.tests.search.SearchTestSuite.waitUntilReady(element); - SynchronizationUtils.joinBackgroundActivities(); + private static boolean anyRunJobs() { for (Job job : Job.getJobManager().find(null)) { switch (job.getState()) { case Job.RUNNING: case Job.WAITING: - if (job.getName().contains("Java index")) { - joinUninterruptibly(job); + if (!SKIP_JOBS.contains(job.getName().toLowerCase())) { + return true; } } } + return false; } - public static void waitForDSLDProcessingToComplete() { - SynchronizationUtils.joinBackgroundActivities(); + private static void printJobs() { + /* + System.out.println("=============Printing Jobs=============="); for (Job job : Job.getJobManager().find(null)) { switch (job.getState()) { case Job.RUNNING: case Job.WAITING: - if (job.getName().startsWith("Refresh DSLD scripts")) { - joinUninterruptibly(job); + if (!SKIP_JOBS.contains(job.getName().toLowerCase())) { + System.out.println(job.getName()); } } } - } - - private static void joinUninterruptibly(Job job) { - boolean interrupted; - do { - interrupted = false; - try { - System.err.println("Waiting for: " + job.getName()); - job.join(); - } catch (OperationCanceledException ignore) { - - } catch (InterruptedException e) { - interrupted = true; - } - } while (interrupted); + System.out.println("========================================"); + */ } private static final List SKIP_JOBS = Arrays.asList("animation start", "change cursor", "decoration calculation", "flush cache job", "open blocked dialog", "refreshing view", "sending problem marker updates...", "update for decoration completion", "update dynamic java sources working sets", "update package explorer", "update progress", "usage data event consumer"); diff --git a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/TestProject.java b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/TestProject.java index 85a8238081..d1cf5bf40d 100644 --- a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/TestProject.java +++ b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/TestProject.java @@ -15,43 +15,40 @@ */ package org.codehaus.groovy.eclipse.test; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; -import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; +import java.io.UnsupportedEncodingException; import org.codehaus.groovy.eclipse.core.model.GroovyRuntime; import org.codehaus.groovy.runtime.IOGroovyMethods; import org.codehaus.jdt.groovy.model.GroovyNature; import org.eclipse.core.internal.events.BuildCommand; import org.eclipse.core.resources.ICommand; -import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceDescription; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.groovy.tests.SimpleProgressMonitor; +import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.tests.util.Util; import org.eclipse.jdt.groovy.core.util.ArrayUtils; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.core.DefaultWorkingCopyOwner; import org.eclipse.jdt.internal.core.JavaModelManager; +import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.launching.JavaRuntime; public class TestProject { @@ -62,78 +59,55 @@ public class TestProject { private IPackageFragmentRoot sourceFolder; - public TestProject() throws Exception { + /*package*/ TestProject() throws CoreException { this("TestProject"); } - public TestProject(String name) throws Exception { + public TestProject(final String name) throws CoreException { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); project = root.getProject(name); - if (!project.exists()) { - project.create(null); - } + assertFalse(project.exists()); + project.create(null); project.open(null); - javaProject = JavaCore.create(project); - prepareForJava(); - prepareForGroovy(); - - createOutputFolder(createBinFolder()); - sourceFolder = createSourceFolder(); - - javaProject.setOption(CompilerOptions.OPTION_Source, "1.6"); - javaProject.setOption(CompilerOptions.OPTION_Compliance, "1.6"); - javaProject.setOption(CompilerOptions.OPTION_TargetPlatform, "1.6"); - } - - public IProject getProject() { - return project; - } - - public IJavaProject getJavaProject() { - return javaProject; - } + CoreUtility.setAutoBuilding(false); + IFolder binFolder = project.getFolder("bin"); + IFolder srcFolder = project.getFolder("src"); + CoreUtility.createFolder(srcFolder, true, true, null); - public IPackageFragmentRoot getSourceFolder() { - return sourceFolder; - } - - public boolean hasGroovyLibraries() throws Exception { - return GroovyRuntime.hasGroovyClasspathContainer(javaProject); - } - - /** Adds base Java nature and classpath entries to project. */ - private void prepareForJava() throws Exception { addNature(JavaCore.NATURE_ID); - - javaProject.setRawClasspath(new IClasspathEntry[] {JavaRuntime.getDefaultJREContainerEntry()}, null); - } - - /** Adds base Groovy nature and classpath entries to project. */ - private void prepareForGroovy() throws Exception { - addNature(GroovyNature.GROOVY_NATURE); - - if (!GroovyRuntime.hasGroovyClasspathContainer(javaProject)) { - GroovyRuntime.addGroovyClasspathContainer(javaProject); + javaProject = JavaCore.create(project); + javaProject.setOption(CompilerOptions.OPTION_Source, "1.8"); + javaProject.setOption(CompilerOptions.OPTION_Compliance, "1.8"); + javaProject.setOption(CompilerOptions.OPTION_TargetPlatform, "1.8"); + + javaProject.setRawClasspath(new IClasspathEntry[] { + JavaCore.newSourceEntry(srcFolder.getFullPath()), + GroovyRuntime.newGroovyClasspathContainerEntry(false, false, false), + JavaRuntime.getDefaultJREContainerEntry()}, binFolder.getFullPath(), null); + + sourceFolder = javaProject.findPackageFragmentRoot(srcFolder.getFullPath()); + + addNature(GroovyNature.GROOVY_NATURE); // <-- schedules a job for clean and build + for (Job job : Job.getJobManager().find(null)) { + switch (job.getState()) { + case Job.RUNNING: + case Job.WAITING: + if (job.getName().startsWith("Cleaning/Rebuilding")) { + SynchronizationUtils.joinUninterruptibly(job); + } + } } + SynchronizationUtils.waitForIndexingToComplete(); } - public void addBuilder(String newBuilder) throws Exception { - ICommand buildCommand = new BuildCommand(); - buildCommand.setBuilderName(newBuilder); - - final IProjectDescription description = project.getDescription(); - description.setBuildSpec((ICommand[]) ArrayUtils.add(description.getBuildSpec(), 0, buildCommand)); - project.setDescription(description, null); - } - - public void addNature(String natureId) throws Exception { + public void addNature(final String natureId) throws CoreException { final IProjectDescription description = project.getDescription(); description.setNatureIds((String[]) ArrayUtils.add(description.getNatureIds(), 0, natureId)); project.setDescription(description, null); } - public void removeNature(String natureId) throws Exception { + public void removeNature(final String natureId) throws CoreException { final IProjectDescription description = project.getDescription(); final String[] ids = description.getNatureIds(); for (int i = 0, n = ids.length; i < n; i += 1) { @@ -145,37 +119,34 @@ public void removeNature(String natureId) throws Exception { } } - public void addClasspathEntry(IClasspathEntry entry) throws Exception { + public void addBuilder(final String newBuilder) throws CoreException { + ICommand buildCommand = new BuildCommand(); + buildCommand.setBuilderName(newBuilder); + + final IProjectDescription description = project.getDescription(); + description.setBuildSpec((ICommand[]) ArrayUtils.add(description.getBuildSpec(), 0, buildCommand)); + project.setDescription(description, null); + } + + public void addClasspathEntry(final IClasspathEntry entry) throws JavaModelException { if (!GroovyRuntime.findClasspathEntry(javaProject, entry::equals).isPresent()) { GroovyRuntime.appendClasspathEntry(javaProject, entry); } } - public void addExternalLibrary(IPath libraryPath) throws Exception { + public void addExternalLibrary(final IPath libraryPath) throws JavaModelException { addClasspathEntry(JavaCore.newLibraryEntry(libraryPath, null, null)); } - public void addProjectReference(IJavaProject referent) throws Exception { + public void addProjectReference(final IJavaProject referent) throws JavaModelException { addClasspathEntry(JavaCore.newProjectEntry(referent.getPath())); } - public IPackageFragment createPackage(String name) throws Exception { - return sourceFolder.createPackageFragment(name, true, null); - } - - public void deletePackage(String name) throws CoreException { - sourceFolder.getPackageFragment(name).delete(true, null); - } - - private void appendPackage(StringBuilder b, IPackageFragment p, CharSequence source) { - if (!p.isDefaultPackage() && (source.length() < 8 || !source.subSequence(0, 7).toString().equals("package"))) { - b.append("package "); - b.append(p.getElementName()); - b.append(";\n\n"); - } + public IPackageFragment createPackage(final String packageName) throws JavaModelException { + return sourceFolder.createPackageFragment(packageName, true, null); } - public ICompilationUnit createJavaType(IPackageFragment packageFrag, String fileName, CharSequence source) throws Exception { + public ICompilationUnit createJavaType(final IPackageFragment packageFrag, final String fileName, final CharSequence source) throws JavaModelException { StringBuilder buf = new StringBuilder(); appendPackage(buf, packageFrag, source); buf.append(source); @@ -185,19 +156,25 @@ public ICompilationUnit createJavaType(IPackageFragment packageFrag, String file return unit; } - public ICompilationUnit createJavaTypeAndPackage(String packageName, String fileName, CharSequence source) throws Exception { + public ICompilationUnit createJavaTypeAndPackage(final String packageName, final String fileName, final CharSequence source) throws JavaModelException { return createJavaType(createPackage(packageName), fileName, source); } - public ICompilationUnit createGroovyTypeAndPackage(String packageName, String fileName, InputStream source) throws Exception { - return createGroovyType(createPackage(packageName), fileName, IOGroovyMethods.getText(source)); + public ICompilationUnit createGroovyTypeAndPackage(final String packageName, final String fileName, final InputStream source) throws JavaModelException { + String fileText; + try { + fileText = IOGroovyMethods.getText(source); + } catch (IOException e) { + throw new RuntimeException(e); + } + return createGroovyType(createPackage(packageName), fileName, fileText); } - public ICompilationUnit createGroovyTypeAndPackage(String packageName, String fileName, CharSequence source) throws Exception { + public ICompilationUnit createGroovyTypeAndPackage(final String packageName, final String fileName, final CharSequence source) throws JavaModelException { return createGroovyType(createPackage(packageName), fileName, source); } - public ICompilationUnit createGroovyType(IPackageFragment packageFrag, String fileName, CharSequence source) throws Exception { + public ICompilationUnit createGroovyType(final IPackageFragment packageFrag, final String fileName, final CharSequence source) throws JavaModelException { StringBuilder buf = new StringBuilder(); appendPackage(buf, packageFrag, source); buf.append(source); @@ -207,54 +184,39 @@ public ICompilationUnit createGroovyType(IPackageFragment packageFrag, String fi return unit; } - public void dispose() throws Exception { - deleteWorkingCopies(); - Util.delete(project); - } - - public void deleteContents() throws Exception { - deleteWorkingCopies(); - for (IPackageFragment frag : javaProject.getPackageFragments()) { - if (!frag.isReadOnly()) { - frag.delete(true, null); - } - } - } - - private void deleteWorkingCopies() throws Exception { - SynchronizationUtils.joinBackgroundActivities(); - - ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, true); - if (workingCopies != null && workingCopies.length > 0) { - for (ICompilationUnit workingCopy : workingCopies) { - if (workingCopy.isWorkingCopy()) { - workingCopy.discardWorkingCopy(); - } - } + private static void appendPackage(final StringBuilder sb, final IPackageFragment pf, final CharSequence cs) { + if (!pf.isDefaultPackage() && (cs.length() < 8 || !cs.subSequence(0, 7).toString().equals("package"))) { + sb.append("package "); + sb.append(pf.getElementName()); + sb.append(";\n\n"); } } - private IFolder createBinFolder() throws Exception { - final IFolder binFolder = project.getFolder("bin"); - if (!binFolder.exists()) { - ensureExists(binFolder); + /** + * Creates a text file within the project's source folder. + * + * @param path relative file path + */ + public IFile createFile(final String path, final String contents) throws CoreException, UnsupportedEncodingException { + IFile file = project.getFolder("src").getFile(new Path(path)); + if (!file.getParent().exists()) { + CoreUtility.createFolder((IFolder) file.getParent(), true, true, null); } - return binFolder; - } - - private void createOutputFolder(IFolder binFolder) throws Exception { - IPath outputLocation = binFolder.getFullPath(); - javaProject.setOutputLocation(outputLocation, null); - } - - private IPackageFragmentRoot createSourceFolder() throws Exception { - return createSourceFolder("src", null, (IPath[]) null); + String encoding = project.getDefaultCharset(); + InputStream stream = new java.io.ByteArrayInputStream(encoding == null ? contents.getBytes() : contents.getBytes(encoding)); + file.create(stream, true, null); + return file; } - public IPackageFragmentRoot createSourceFolder(String path, String outPath, IPath... exclusionPatterns) throws Exception { + /** + * Creates a source folder within the project. + * + * @param path relative file path + */ + public IPackageFragmentRoot createSourceFolder(final String path, /*@Nullable*/ final String outPath, final IPath... exclusions) throws CoreException { IFolder folder = project.getFolder(path); if (!folder.exists()) { - ensureExists(folder); + CoreUtility.createFolder(folder, true, true, null); } IClasspathEntry sourceFolderEntry = null; for (IClasspathEntry entry : javaProject.getRawClasspath()) { @@ -264,99 +226,46 @@ public IPackageFragmentRoot createSourceFolder(String path, String outPath, IPat } } if (sourceFolderEntry == null) { - IPath outPathPath = (outPath == null ? null : getProject().getFullPath().append(outPath).makeAbsolute()); - sourceFolderEntry = JavaCore.newSourceEntry(folder.getFullPath(), exclusionPatterns, outPathPath); + IPath outPathPath = (outPath == null ? null : project.getFullPath().append(outPath).makeAbsolute()); + sourceFolderEntry = JavaCore.newSourceEntry(folder.getFullPath(), exclusions, outPathPath); addClasspathEntry(sourceFolderEntry); } return javaProject.findPackageFragmentRoots(sourceFolderEntry)[0]; } - private void ensureExists(IFolder folder) throws Exception { - if (folder.getParent().getType() == IResource.FOLDER && !folder.getParent().exists()) { - ensureExists((IFolder) folder.getParent()); - } - folder.create(false, true, null); - } + //-------------------------------------------------------------------------- - public void waitForIndexer() { - SynchronizationUtils.waitForIndexingToComplete(getJavaProject()); - } - - public void fullBuild() throws Exception { - SimpleProgressMonitor spm = new SimpleProgressMonitor("full build of " + getProject().getName()); - getProject().build(org.eclipse.core.resources.IncrementalProjectBuilder.FULL_BUILD, spm); - spm.waitForCompletion(); + public IProject getProject() { + return project; } - public String getProblems() throws Exception { - IMarker[] markers = getProject().findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); - if (markers == null || markers.length == 0) { - return null; - } - boolean errorFound = false; - StringBuilder sb = new StringBuilder("Problems:\n"); - for (IMarker marker : markers) { - if (((Number) marker.getAttribute(IMarker.SEVERITY)).intValue() == IMarker.SEVERITY_ERROR) { - errorFound = true; - - sb.append(" "); - sb.append(marker.getResource().getName()); - sb.append(" : "); - sb.append(marker.getAttribute(IMarker.LOCATION)); - sb.append(" : "); - sb.append(marker.getAttribute(IMarker.MESSAGE)); - sb.append("\n"); - } - } - return errorFound ? sb.toString() : null; + public IJavaProject getJavaProject() { + return javaProject; } - public IFile createFile(String name, String contents) throws Exception { - String encoding = null; - try { - encoding = project.getDefaultCharset(); // get project encoding as file is not accessible - } catch (CoreException ce) { - // use no encoding - } - InputStream stream = new ByteArrayInputStream(encoding == null ? contents.getBytes() : contents.getBytes(encoding)); - IFile file = project.getFolder("src").getFile(new Path(name)); - if (!file.getParent().exists()) { - createFolder(file.getParent()); - } - file.create(stream, true, null); - return file; + public IPackageFragmentRoot getSourceFolder() { + return sourceFolder; } - private void createFolder(IContainer parent) throws Exception { - if (!parent.getParent().exists()) { - assertEquals("Project doesn't exist " + parent.getParent(), parent.getParent().getType(), IResource.FOLDER); - createFolder(parent.getParent()); - } - ((IFolder) parent).create(true, true, null); - } + //-------------------------------------------------------------------------- - public ICompilationUnit[] createUnits(String[] packages, String[] cuNames, String[] cuContents) throws Exception { - ICompilationUnit[] units = new ICompilationUnit[packages.length]; - for (int i = 0, n = cuContents.length; i < n; i += 1) { - units[i] = createPackage(packages[i]).createCompilationUnit(cuNames[i], cuContents[i], false, null); - } - return units; + public void dispose() { + SynchronizationUtils.joinBackgroundActivities(); + discardWorkingCopies(); + Util.delete(project); } - public static void setAutoBuilding(boolean value) { - try { - IWorkspace w = ResourcesPlugin.getWorkspace(); - IWorkspaceDescription d = w.getDescription(); - d.setAutoBuilding(value); - w.setDescription(d); - } catch (CoreException e) { - throw new RuntimeException(e); + /*package*/ void discardWorkingCopies() { + ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, true); + if (workingCopies != null && workingCopies.length > 0) { + for (ICompilationUnit workingCopy : workingCopies) { + if (workingCopy.isWorkingCopy()) { + try { + workingCopy.discardWorkingCopy(); + } catch (JavaModelException ignore) { + } + } + } } } - - public static boolean isAutoBuilding() { - IWorkspace w = ResourcesPlugin.getWorkspace(); - IWorkspaceDescription d = w.getDescription(); - return d.isAutoBuilding(); - } } diff --git a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/launch/GroovyScriptLaunchShortcutTests.groovy b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/launch/GroovyScriptLaunchShortcutTests.groovy index 7dea982171..8127e7ef1d 100644 --- a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/launch/GroovyScriptLaunchShortcutTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/launch/GroovyScriptLaunchShortcutTests.groovy @@ -74,25 +74,16 @@ final class GroovyScriptLaunchShortcutTests extends GroovyEclipseTestSuite { def classpath = buildScriptClasspath(p1.javaProject) - def entries = [ - ['P1', 'bin' ], - ['P1', 'src' ], - ['P2', 'bin' ], - ['P2', 'src' ], - ['P3', 'bin' ], - ['P3', 'src' ], - ['P3', 'bin2'], - ['P3', 'src2'], - ['P4', 'bin' ], - ['P4', 'src' ], - ['P4', 'bin2'], - ['P4', 'src2'], - ] - String expected_classpath = entries.collect { String proj, String path -> - '${workspace_loc:' + proj + '}' + File.separator + path - }.join(File.pathSeparator) - - assert classpath.endsWith(expected_classpath) + ['P1', 'P2', 'P3', 'P4'].each { + def entries = [[it], ['bin', 'src']].combinations() + + String expected_classpath = entries.collect { String proj, String path -> + '${workspace_loc:' + proj + '}' + File.separator + path + }.join(File.pathSeparator) + + assert classpath.contains(expected_classpath) + } + assert classpath.contains(CompilerUtils.exportedGroovyAllJar.toOSString()) } finally { p1.dispose() @@ -120,14 +111,16 @@ final class GroovyScriptLaunchShortcutTests extends GroovyEclipseTestSuite { String classpath = buildScriptClasspath(p1.javaProject) - String expected_classpath = [ + assert classpath.contains([ '${workspace_loc:' + 'P1a}' + File.separator + 'bin', '${workspace_loc:' + 'P1a}' + File.separator + 'src', + ].join(File.pathSeparator)) + + assert classpath.endsWith([ '${workspace_loc:' + 'P1a}' + File.separator + 'empty.jar', '${workspace_loc:' + 'P2a}' + File.separator + 'empty2.jar' - ].join(File.pathSeparator) + ].join(File.pathSeparator)) - assert classpath.endsWith(expected_classpath) assert classpath.contains(CompilerUtils.exportedGroovyAllJar.toOSString()) } finally { p1.dispose() diff --git a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/ui/OutlineExtenderTests.groovy b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/ui/OutlineExtenderTests.groovy index 3adb706c0e..5433637f6d 100644 --- a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/ui/OutlineExtenderTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/ui/OutlineExtenderTests.groovy @@ -175,7 +175,6 @@ final class OutlineExtenderTests extends GroovyEclipseTestSuite { viewer.textWidget.selection = 0 viewer.textWidget.insert('Long field3 = 100 \n') buildProject() - waitForIndex() tu.refresh() // check consistency diff --git a/ide/org.codehaus.groovy.eclipse.quickfix/src/org/codehaus/groovy/eclipse/quickfix/GroovyQuickFixProcessor.groovy b/ide/org.codehaus.groovy.eclipse.quickfix/src/org/codehaus/groovy/eclipse/quickfix/GroovyQuickFixProcessor.groovy index 951632ef61..0b93f19f98 100644 --- a/ide/org.codehaus.groovy.eclipse.quickfix/src/org/codehaus/groovy/eclipse/quickfix/GroovyQuickFixProcessor.groovy +++ b/ide/org.codehaus.groovy.eclipse.quickfix/src/org/codehaus/groovy/eclipse/quickfix/GroovyQuickFixProcessor.groovy @@ -26,6 +26,7 @@ import org.codehaus.groovy.eclipse.refactoring.actions.TypeSearch import org.codehaus.jdt.groovy.model.GroovyCompilationUnit import org.eclipse.core.runtime.Adapters import org.eclipse.core.runtime.CoreException +import org.eclipse.core.runtime.NullProgressMonitor import org.eclipse.jdt.core.ICompilationUnit import org.eclipse.jdt.core.SourceRange import org.eclipse.jdt.core.compiler.IProblem @@ -79,7 +80,7 @@ class GroovyQuickFixProcessor implements IQuickFixProcessor { boolean isAnnotation = (locations.any { IProblemLocation it -> it.problemArguments && it.problemArguments[0] =~ / (an|for) annotation/ }) def typeData = new TypeSearch.UnresolvedTypeData(typeName, isAnnotation, new SourceRange(location.offset, location.length)) - new TypeSearch().searchForTypes(unit, Collections.singletonMap(typeName, typeData), null) + new TypeSearch().searchForTypes(unit, Collections.singletonMap(typeName, typeData), new NullProgressMonitor()) typeData.foundInfos.findResults { it.type }.each { type -> if (types.add(type.fullyQualifiedName)) proposals << new ImportResolvedTypeProposal(unit: unit, type: type)