diff --git a/bundles/tools.vitruv.applications.pcmjava/src/tools/vitruv/applications/pcmjava/java2pcm/Java2PcmClassifier.reactions b/bundles/tools.vitruv.applications.pcmjava/src/tools/vitruv/applications/pcmjava/java2pcm/Java2PcmClassifier.reactions index d2271c5df..1e3fc1bea 100644 --- a/bundles/tools.vitruv.applications.pcmjava/src/tools/vitruv/applications/pcmjava/java2pcm/Java2PcmClassifier.reactions +++ b/bundles/tools.vitruv.applications.pcmjava/src/tools/vitruv/applications/pcmjava/java2pcm/Java2PcmClassifier.reactions @@ -16,6 +16,7 @@ import static tools.vitruv.applications.util.temporary.java.JavaTypeUtil.* import static tools.vitruv.applications.util.temporary.java.JavaPersistenceHelper.* import static extension edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.claimNotMany import static extension tools.vitruv.applications.pcmjava.PcmJavaTransformationUtil.isPackageFor +import tools.vitruv.dsls.reactions.runtime.helper.PersistenceHelper import "http://www.emftext.org/java" as java import "http://palladiosimulator.org/PalladioComponentModel/5.2" as pcm @@ -153,10 +154,11 @@ routine createRepository(java::Package javaPackage, String packageName, String n update { // If the package-info.java is not persisted, do it val packageUri = javaPackage.eResource.URI; - if (!URIUtil.existsResourceAtUri(packageUri)) { - val projectRelativeResourcePath = packageUri.segmentsList.tail.fold("", [a, b|a + "/" + b]) - persistProjectRelative(javaPackage, javaPackage, projectRelativeResourcePath) - } +// if (!URIUtil.existsResourceAtUri(packageUri)) { +// val projectRelativeResourcePath = PersistenceHelper.getRelativeUriPathFromElement(javaPackage) +//// val projectRelativeResourcePath = packageUri.segmentsList.tail.fold("", [a, b|a + "/" + b]) +// persistProjectRelative(javaPackage, javaPackage, projectRelativeResourcePath) +// } pcmRepository.entityName = packageName.toFirstUpper persistProjectRelative(javaPackage, pcmRepository, "model/" + pcmRepository.entityName + ".repository") diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/META-INF/MANIFEST.MF b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/META-INF/MANIFEST.MF index 5cddf3e20..69d1a8e94 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/META-INF/MANIFEST.MF +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/META-INF/MANIFEST.MF @@ -13,12 +13,14 @@ Require-Bundle: org.apache.log4j, org.eclipse.text, org.eclipse.core.resources, org.junit.jupiter.api, + org.junit.jupiter.params, edu.kit.ipd.sdq.commons.util.eclipse, edu.kit.ipd.sdq.commons.util.emf, edu.kit.ipd.sdq.commons.util.java, tools.vitruv.testutils.vsum, + tools.vitruv.framework.views, tools.vitruv.applications.util.temporary, tools.vitruv.applications.pcmjava, tools.vitruv.applications.pcmjava.tests -Export-Package: tools.vitruv.applications.pcmjava.javaeditor.java2pcm +Export-Package: tools.vitruv.applications.pcmjava.javaeditor.java2pcm.legacy Bundle-Vendor: vitruv.tools diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ClassMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ClassMappingTransformationTest.java index afa48525f..413b23c6c 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ClassMappingTransformationTest.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ClassMappingTransformationTest.java @@ -1,164 +1,194 @@ package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; -import static org.junit.jupiter.api.Assertions.fail; - -import org.eclipse.emf.ecore.EObject; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil.claimPackage; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimComponent; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimDataType; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleRepository; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleSystem; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.BASIC_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.COMPOSITE_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.IMPLEMENTING_CLASS_SUFFIX; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.RENAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.REPOSITORY_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.SYSTEM_NAME; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.containers.Package; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.palladiosimulator.pcm.repository.BasicComponent; -import org.palladiosimulator.pcm.repository.CollectionDataType; import org.palladiosimulator.pcm.repository.CompositeComponent; import org.palladiosimulator.pcm.repository.CompositeDataType; import org.palladiosimulator.pcm.repository.Repository; import org.palladiosimulator.pcm.system.System; import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; -import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; - -public class ClassMappingTransformationTest extends Java2PcmPackageMappingTransformationTest { +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory; +class ClassMappingTransformationTest extends Java2PcmTransformationTest { /** * Class that in mapped package and same name as component + impl--> should be * the new implementing class for the component - * - * @throws Exception */ - @Test - public void testAddComponentClassInPackageWithCorrespondingComponent() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - final BasicComponent bc = super.addSecondPackageCorrespondsToBasicComponent(); - - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); - final BasicComponent bcForClass = super.addClassInSecondPackage(BasicComponent.class); - - super.assertRepositoryAndPCMName(repo, bcForClass, bc.getEntityName()); + @ParameterizedTest() + @EnumSource(value = Java2PcmUserSelection.class, names = { "SELECT_BASIC_COMPONENT", + "SELECT_NOTHING_DECIDE_LATER" }) + void testAddClassInSecondPackageAsBasicComponent(Java2PcmUserSelection packageSelection) throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(packageSelection.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + view.getManipulationUtil().createClass(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, componentPackage, + null); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimComponent(repository, BASIC_COMPONENT_NAME, BasicComponent.class); + }); } - @Test - public void testAddCompositeComponentClassInPackageWithCorrespondingCompositeComponent() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - final CompositeComponent cc = super.addSecondPackageCorrespondsToCompositeComponent(); - - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_COMPONENT.getSelection()); - final CompositeComponent ccForClass = this.addClassInSecondPackage(CompositeComponent.class); - - super.assertRepositoryAndPCMName(repo, ccForClass, cc.getEntityName()); + @ParameterizedTest() + @EnumSource(value = Java2PcmUserSelection.class, names = { "SELECT_COMPOSITE_COMPONENT", + "SELECT_NOTHING_DECIDE_LATER" }) + void testAddClassInSecondPackageAsCompositeComponent(Java2PcmUserSelection packageSelection) throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(packageSelection.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, COMPOSITE_COMPONENT_NAME); + }); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_COMPONENT.getSelection()); + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, COMPOSITE_COMPONENT_NAME); + view.getManipulationUtil().createClass(COMPOSITE_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, + componentPackage, null); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimComponent(repository, COMPOSITE_COMPONENT_NAME, CompositeComponent.class); + }); } - @Test - public void testAddSystemClassInPackageWithCorrespondingSystem() throws Throwable { - super.addRepoContractsAndDatatypesPackage(); - final System pcmSystem = super.addSecondPackageCorrespondsToSystem(); - - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_SYSTEM.getSelection()); - final System systemForClass = super.addClassInSecondPackage(System.class); - - super.assertPCMNamedElement(systemForClass, pcmSystem.getEntityName()); + @ParameterizedTest() + @EnumSource(value = Java2PcmUserSelection.class, names = { "SELECT_SYSTEM", "SELECT_NOTHING_DECIDE_LATER" }) + void testAddClassInSecondPackageAsSystem(Java2PcmUserSelection packageSelection) throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(packageSelection.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, SYSTEM_NAME); + }); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_SYSTEM.getSelection()); + changeJavaEditorView(view -> { + Package systemPackage = claimPackage(view, SYSTEM_NAME); + view.getManipulationUtil().createClass(SYSTEM_NAME + IMPLEMENTING_CLASS_SUFFIX, systemPackage, null); + }); + + validatePcmView(view -> { + System system = claimSingleSystem(view); + assertEquals(SYSTEM_NAME, system.getEntityName(), "system has wrong name"); + }); } /** * Test ii) class in non corresponding package --> should not be mapped to a * Basic Component - * - * @throws Throwable */ @Test - public void testAddClassInPackageWithoutCorrespondingComponent() throws Throwable { - super.addRepoContractsAndDatatypesPackage(); - super.addSecondPackageCorrespondsWithoutCorrespondences(); - - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_NOTHING_DECIDE_LATER.getSelection()); - try { - final EObject eObject = super.addClassInPackage(this.secondPackage, EObject.class); - fail("The class should not have any correspondences, but it has a correspondence to eObject: " + eObject); - } catch (final RuntimeException re) { - // expected exception - } + void testAddClassInSecondPackageAsNone() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_NOTHING_DECIDE_LATER.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_NOTHING_DECIDE_LATER.getSelection()); + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + view.getManipulationUtil().createClass(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, componentPackage, + null); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + assertTrue(repository.getComponents__Repository().isEmpty(), + "there must not exist any contained Component"); + assertTrue(view.getRootObjects(System.class).isEmpty(), "there must not exist any System"); + }); } @Test - public void testAddBasicComponentClassInPackageWithoutCorrespondence() throws Throwable { - final Repository repo = this.addRepoContractsAndDatatypesPackage(); - super.addSecondPackageCorrespondsWithoutCorrespondences(); - - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); - final BasicComponent newBc = super.addClassInSecondPackage(BasicComponent.class); - - super.assertRepositoryAndPCMName(repo, newBc, newBc.getEntityName()); + void testAddClassInDataTypesPackageAsCompositeDataType() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_DATA_TYPE.getSelection()); + changeJavaEditorView(view -> { + Package dataTypesPackage = claimPackage(view, JavaQueryUtil.DATATYPES_PACKAGE); + view.getManipulationUtil().createClass(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, dataTypesPackage, + null); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimDataType(repository, BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, CompositeDataType.class); + }); } @Test - public void testAddCompositeComponentClassInPackageWithoutCorrespondence() throws Throwable { - final Repository repo = this.addRepoContractsAndDatatypesPackage(); - super.addSecondPackageCorrespondsWithoutCorrespondences(); - - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_COMPONENT.getSelection()); - final CompositeComponent cc = super.addClassInSecondPackage(CompositeComponent.class); - - super.assertRepositoryAndPCMName(repo, cc, cc.getEntityName()); + void testAddClassInDataTypesPackageAsNone() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_NOTHING_DECIDE_LATER.getSelection()); + changeJavaEditorView(view -> { + Package dataTypesPackage = claimPackage(view, JavaQueryUtil.DATATYPES_PACKAGE); + view.getManipulationUtil().createClass(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, dataTypesPackage, + null); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + assertEquals(0, repository.getDataTypes__Repository().size(), "repository must not have any data type"); + }); } - @Test - public void testAddSystemClassInPackageWithoutCorrespondence() throws Throwable { - this.addRepoContractsAndDatatypesPackage(); - super.addSecondPackageCorrespondsWithoutCorrespondences(); - - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_SYSTEM.getSelection()); - final System pcmSystem = super.addClassInSecondPackage(System.class); - - this.assertPCMNamedElement(pcmSystem, Pcm2JavaTestUtils.IMPLEMENTING_CLASS_NAME); + @ParameterizedTest() + @EnumSource(value = Java2PcmUserSelection.class, names = { "SELECT_BASIC_COMPONENT", + "SELECT_NOTHING_DECIDE_LATER" }) + void testRenameClassCorrespondingToBasicComponent(Java2PcmUserSelection packageSelection) throws Exception { + testAddClassInSecondPackageAsBasicComponent(packageSelection); + + String changedName = BASIC_COMPONENT_NAME + RENAME; + + changeJavaEditorView(view -> { + String componentClassName = BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX; + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + ICompilationUnit componentClass = view.getManipulationUtil().claimCompilationUnit(componentClassName, + componentPackage); + TextEdit renameEdit = JavaTextEditFactory.renameCompilationUnit(componentClass, componentClassName, + changedName + IMPLEMENTING_CLASS_SUFFIX); + view.getManipulationUtil().editCompilationUnit(componentClass, renameEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimComponent(repository, changedName, BasicComponent.class); + assertEquals(1, repository.getComponents__Repository().size(), "too many components in repository"); + }); } - - @Test - public void testAddCompositeDatatypeClassInDatatypePackage() throws Throwable { - final Repository repo = this.addRepoContractsAndDatatypesPackage(); - - final CompositeDataType cdt = this.addClassThatCorrespondsToCompositeDatatype(); - - this.assertRepositoryAndPCMNameForDatatype(repo, cdt, Pcm2JavaTestUtils.IMPLEMENTING_CLASS_NAME); - } - - @Test - public void testAddCollectionDatatypeClassInDatatypePackage() throws Throwable { - final Repository repo = this.addRepoContractsAndDatatypesPackage(); - - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_COMPONENT.getSelection()); - final CollectionDataType collection = super.addClassInPackage(this.getDatatypesPackage(), - CollectionDataType.class); - - this.assertRepositoryAndPCMNameForDatatype(repo, collection, Pcm2JavaTestUtils.IMPLEMENTING_CLASS_NAME); - } - - @Test - public void testAddClassInDatatypePackage() throws Throwable { - this.addRepoContractsAndDatatypesPackage(); - try { - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_NOTHING_DECIDE_LATER.getSelection()); - final EObject eObject = super.addClassInPackage(this.getDatatypesPackage(), EObject.class); - fail("The class should not have any datatype correspondences, but it has a correspondence to eObject: " - + eObject); - } catch (final RuntimeException re) { - // expected Exception - } - } - - @Test - public void testRenameBasicComponentClass() throws Throwable { - final Repository repo = this.addRepoContractsAndDatatypesPackage(); - this.addSecondPackageCorrespondsWithoutCorrespondences(); - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); - final BasicComponent basicComponent = this.addClassInSecondPackage(BasicComponent.class); - - final BasicComponent newBasicComponent = super.renameClassifierWithName(basicComponent.getEntityName() + "Impl", - Pcm2JavaTestUtils.IMPLEMENTING_CLASS_NAME + Pcm2JavaTestUtils.RENAME, BasicComponent.class); - - this.assertRepositoryAndPCMName(repo, newBasicComponent, - Pcm2JavaTestUtils.IMPLEMENTING_CLASS_NAME + Pcm2JavaTestUtils.RENAME); - this.assertFilesOnlyForEObjects(newBasicComponent); - } - } diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ClassMethodMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ClassMethodMappingTransformationTest.java index 450f54981..102d09c49 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ClassMethodMappingTransformationTest.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ClassMethodMappingTransformationTest.java @@ -1,36 +1,92 @@ package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; +import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.claimOne; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil.claimPackage; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory.Visibility.PUBLIC; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimComponent; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimInterface; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimNamedElement; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleRepository; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.BASIC_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.IMPLEMENTING_CLASS_SUFFIX; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.INTERFACE_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.REPOSITORY_NAME; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IType; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.containers.Package; import org.junit.jupiter.api.Test; -import org.palladiosimulator.pcm.seff.ResourceDemandingSEFF; +import org.palladiosimulator.pcm.repository.BasicComponent; +import org.palladiosimulator.pcm.repository.OperationInterface; +import org.palladiosimulator.pcm.repository.OperationProvidedRole; +import org.palladiosimulator.pcm.repository.Repository; +import org.palladiosimulator.pcm.repository.Signature; +import org.palladiosimulator.pcm.seff.ServiceEffectSpecification; +import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory; import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; -public class ClassMethodMappingTransformationTest extends Java2PcmPackageMappingTransformationTest { - +class ClassMethodMappingTransformationTest extends Java2PcmTransformationTest { @Test - public void testAddClassMethodWithCorrespondence() throws Throwable { - // create repo - super.addRepoContractsAndDatatypesPackage(); - // this.getUserInteractor().addNextSelections(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); - // create component implementing class - super.addPackageAndImplementingClass(Pcm2JavaTestUtils.BASIC_COMPONENT_NAME); - // create interface - super.createInterfaceInPackageBasedOnJaMoPPPackageWithCorrespondence("contracts", - Pcm2JavaTestUtils.INTERFACE_NAME); - // create interface method - super.addMethodToInterfaceWithCorrespondence(Pcm2JavaTestUtils.INTERFACE_NAME, - Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME); - // add implements/provided role - super.addImplementsCorrespondingToOperationProvidedRoleToClass(Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Impl", - Pcm2JavaTestUtils.INTERFACE_NAME); - - // actual test: add class method to implementing class that overrides the - // interface - final ResourceDemandingSEFF correspondingSeff = super.addClassMethodToClassThatOverridesInterfaceMethod( - Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Impl", Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME); - - // assert the correspondingSEFF - assertCorrespondingSEFF(correspondingSeff, Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME); - } + void testCreateClassMethod() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); + + // setup interface with one method + // setup class corresponding to basic component, implementing interface + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + view.getManipulationUtil().createClass(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, componentPackage, + null); + ICompilationUnit componentClass = view.getManipulationUtil() + .claimCompilationUnit(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, componentPackage); + IType basicComponentType = componentClass.getType(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX); + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + view.getManipulationUtil().createInterface(INTERFACE_NAME, contractsPackage, null); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + IType interfaceType = anInterface.getType(INTERFACE_NAME); + + TextEdit addMethodEdit = JavaTextEditFactory.addMethodSignature(interfaceType, "void", OPERATION_SIGNATURE_1_NAME); + view.getManipulationUtil().editCompilationUnit(anInterface, addMethodEdit); + + view.getManipulationUtil().addImportToCompilationUnit(componentClass, anInterface, INTERFACE_NAME); + TextEdit implementsEdit = JavaTextEditFactory.addImplementsRelation(basicComponentType, INTERFACE_NAME); + view.getManipulationUtil().editCompilationUnit(componentClass, implementsEdit); + }); + + // add implementation of interface method to class + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + ICompilationUnit componentClass = view.getManipulationUtil() + .claimCompilationUnit(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, componentPackage); + IType componentClassType = componentClass.getType(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX); + + TextEdit addMethodEdit = JavaTextEditFactory.addMethodWithEmptyBody(componentClassType, PUBLIC, "void", OPERATION_SIGNATURE_1_NAME); + view.getManipulationUtil().editCompilationUnit(componentClass, addMethodEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + BasicComponent component = claimComponent(repository, BASIC_COMPONENT_NAME, BasicComponent.class); + OperationInterface anInterface = claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + Signature signature = claimOne(anInterface.getSignatures__OperationInterface()); + claimNamedElement(component.getProvidedRoles_InterfaceProvidingEntity(), + Pcm2JavaTestUtils.providesInterfaceName(BASIC_COMPONENT_NAME, INTERFACE_NAME), + OperationProvidedRole.class); + ServiceEffectSpecification seff = claimOne(component.getServiceEffectSpecifications__BasicComponent()); + assertEquals(signature, seff.getDescribedService__SEFF(), "SEFF is describing wrong service"); + }); + } } diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/FieldMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/FieldMappingTransformationTest.java index fa2203f71..498f1d63e 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/FieldMappingTransformationTest.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/FieldMappingTransformationTest.java @@ -1,186 +1,262 @@ package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; +import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.claimOne; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil.claimPackage; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory.Visibility.PRIVATE; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimComponent; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimDataType; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimInterface; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimNamedElement; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleRepository; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.BASIC_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.COMPOSITE_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.IMPLEMENTING_CLASS_SUFFIX; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.INTERFACE_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.RENAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.REPOSITORY_NAME; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.emf.ecore.EObject; import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IType; -import org.eclipse.text.edits.DeleteEdit; -import org.eclipse.text.edits.InsertEdit; -import org.emftext.language.java.members.Field; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.containers.Package; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.palladiosimulator.pcm.repository.BasicComponent; import org.palladiosimulator.pcm.repository.CompositeDataType; import org.palladiosimulator.pcm.repository.InnerDeclaration; +import org.palladiosimulator.pcm.repository.OperationInterface; import org.palladiosimulator.pcm.repository.OperationRequiredRole; +import org.palladiosimulator.pcm.repository.Repository; -import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; +import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory; -import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.*; +class FieldMappingTransformationTest extends Java2PcmTransformationTest { + private static final String FIELD_TYPE = "String"; + private static final String FIELD_NAME = "stringField"; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class FieldMappingTransformationTest extends Java2PcmPackageMappingTransformationTest { + private static final String PROVIDING_COMPONENT_NAME = BASIC_COMPONENT_NAME + "Providing"; + private static final String REQUIRING_COMPONENT_NAME = BASIC_COMPONENT_NAME + "Requiring"; @Test - public void testAddFieldToClassThatCorrespondsToCompositeDatatype() throws Throwable { - super.addRepoContractsAndDatatypesPackage(); - final CompositeDataType cdt = super.addClassThatCorrespondsToCompositeDatatype(); - final String fieldType = "String"; - final String fieldName = "stringField"; - - final InnerDeclaration innerDeclaration = this.addFieldToClassWithName(cdt.getEntityName(), fieldType, - fieldName, InnerDeclaration.class); - - this.assertInnerDeclaration(innerDeclaration, fieldType, fieldName); + void testAddFieldToClassCorrespondingToCompositeDataType() throws Exception { + createRepositoryPackage(); + + String compilationUnitName = COMPOSITE_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX; + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_DATA_TYPE.getSelection()); + changeJavaEditorView(view -> { + Package dataTypesPackage = claimPackage(view, JavaQueryUtil.DATATYPES_PACKAGE); + view.getManipulationUtil().createClass(compilationUnitName, dataTypesPackage, null); + }); + + changeJavaEditorView(view -> { + Package datatypesPackage = JavaQueryUtil.claimPackage(view, JavaQueryUtil.DATATYPES_PACKAGE); + ICompilationUnit compilationUnit = view.getManipulationUtil().claimCompilationUnit(compilationUnitName, + datatypesPackage); + IType compilationUnitType = compilationUnit.getType(compilationUnitName); + + TextEdit addFieldEdit = JavaTextEditFactory.addField(compilationUnitType, PRIVATE, FIELD_NAME, FIELD_TYPE); + view.getManipulationUtil().editCompilationUnit(compilationUnit, addFieldEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + CompositeDataType dataType = claimDataType(repository, compilationUnitName, CompositeDataType.class); + InnerDeclaration innerDeclaration = claimOne(dataType.getInnerDeclaration_CompositeDataType()); + assertEquals(FIELD_NAME, innerDeclaration.getEntityName(), "incorrect name for InnerDeclaration"); + assertEquals(FIELD_TYPE, getTypeNameOfPcmDataType(innerDeclaration.getDatatype_InnerDeclaration())); + }); } @Test - public void testRenameFieldInClassThatCorrespondsToCompositeDatatype() throws Throwable { - final String fieldTypeName = "String"; - final String fieldName = "stringField"; - super.addRepoContractsAndDatatypesPackage(); - final CompositeDataType cdt = super.addClassThatCorrespondsToCompositeDatatype(); - this.addFieldToClassWithName(cdt.getEntityName(), fieldTypeName, fieldName, InnerDeclaration.class); - - final String newFieldName = fieldName + Pcm2JavaTestUtils.RENAME; - final InnerDeclaration newInnerDeclaration = this.renameFieldInClass(cdt.getEntityName(), fieldName, - newFieldName); - - this.assertInnerDeclaration(newInnerDeclaration, fieldTypeName, newFieldName); + void testRenameFieldInClassCorrespondingToCompositeDataType() throws Exception { + testAddFieldToClassCorrespondingToCompositeDataType(); + + String compilationUnitName = COMPOSITE_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX; + String changedFieldName = FIELD_NAME + RENAME; + + changeJavaEditorView(view -> { + Package datatypesPackage = JavaQueryUtil.claimPackage(view, JavaQueryUtil.DATATYPES_PACKAGE); + ICompilationUnit compilationUnit = view.getManipulationUtil().claimCompilationUnit(compilationUnitName, + datatypesPackage); + IType type = compilationUnit.getType(compilationUnitName); + + TextEdit renameFieldEdit = JavaTextEditFactory.renameField(type, FIELD_NAME, changedFieldName); + view.getManipulationUtil().editCompilationUnit(compilationUnit, renameFieldEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + CompositeDataType dataType = claimDataType(repository, compilationUnitName, CompositeDataType.class); + InnerDeclaration innerDeclaration = claimOne(dataType.getInnerDeclaration_CompositeDataType()); + assertEquals(changedFieldName, innerDeclaration.getEntityName(), "incorrect name for InnerDeclaration"); + assertEquals(FIELD_TYPE, getTypeNameOfPcmDataType(innerDeclaration.getDatatype_InnerDeclaration())); + }); } @Test - public void testChangeTypeOfFieldInClassThatCorrespondsToCompositeDatatype() throws Throwable { - final String fieldTypeName = "String"; - final String fieldName = "stringField"; - super.addRepoContractsAndDatatypesPackage(); - final CompositeDataType cdt = super.addClassThatCorrespondsToCompositeDatatype(); - this.addFieldToClassWithName(cdt.getEntityName(), fieldTypeName, fieldName, InnerDeclaration.class); - - final String newFieldTypeName = "int"; - final InnerDeclaration newInnerDeclaration = this.changeFieldTypeInClass(cdt.getEntityName(), fieldName, - newFieldTypeName); - - this.assertInnerDeclaration(newInnerDeclaration, newFieldTypeName, fieldName); + void testChangeTypeOfFieldInClassCorrespondingToCompositeDataType() throws Exception { + testAddFieldToClassCorrespondingToCompositeDataType(); + + String compilationUnitName = COMPOSITE_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX; + String changedFieldTypeName = "int"; + + changeJavaEditorView(view -> { + Package datatypesPackage = JavaQueryUtil.claimPackage(view, JavaQueryUtil.DATATYPES_PACKAGE); + ICompilationUnit compilationUnit = view.getManipulationUtil().claimCompilationUnit(compilationUnitName, + datatypesPackage); + IType type = compilationUnit.getType(compilationUnitName); + + TextEdit changeTypeEdit = JavaTextEditFactory.changeTypeOfField(type, FIELD_NAME, changedFieldTypeName); + view.getManipulationUtil().editCompilationUnit(compilationUnit, changeTypeEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + CompositeDataType dataType = claimDataType(repository, compilationUnitName, CompositeDataType.class); + InnerDeclaration innerDeclaration = claimOne(dataType.getInnerDeclaration_CompositeDataType()); + assertEquals(FIELD_NAME, innerDeclaration.getEntityName(), "incorrect name for InnerDeclaration"); + assertEquals(changedFieldTypeName, + getTypeNameOfPcmDataType(innerDeclaration.getDatatype_InnerDeclaration()), + "incorrect type for InnerDeclaration"); + }); } @Disabled("Not yet implemented") @Test - public void testRemoveFieldInClassThatCorrespondsToBasicComponent() { + void testRemoveFieldInClassCorrespondingToBasicComponent() throws Exception { } @Disabled("Not yet implemented") @Test - public void testAddFieldToClassThatCorrespondsToBasicComponent() { + void testAddFieldToClassCorrespondingToBasicComponent() throws Exception { } @Disabled("Not yet implemented") @Test - public void testAddFieldInClassWithoutCorrespondence() { + void testAddFieldInClassWithoutCorrespondence() throws Exception { } @Test - public void testAddFieldWithTypeOfInterface() throws Throwable { - this.createRepoBasicComponentAndInterface(); - - // create required role from Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Requiring" to Interface - final OperationRequiredRole orrToInterface = this.addFieldToClassWithName( - Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Requiring" + "Impl", Pcm2JavaTestUtils.INTERFACE_NAME, - "i" + Pcm2JavaTestUtils.INTERFACE_NAME, OperationRequiredRole.class); - - this.assertOperationRequiredRole(orrToInterface); + void testAddFieldWithTypeOfInterface() throws Exception { + setupExampleWithProvidingAndRequiringComponent(); + + String fieldType = INTERFACE_NAME; + String fieldName = "i" + INTERFACE_NAME; + + changeJavaEditorView(view -> { + Package providingPackage = JavaQueryUtil.claimPackage(view, PROVIDING_COMPONENT_NAME); + ICompilationUnit providingCompilationUnit = view.getManipulationUtil() + .claimCompilationUnit(PROVIDING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, providingPackage); + IType providingCompilationUnitType = providingCompilationUnit.getType(PROVIDING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX); + + Package contractsPackage = JavaQueryUtil.claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + + view.getManipulationUtil().addImportToCompilationUnit(providingCompilationUnit, anInterface, + INTERFACE_NAME); + TextEdit addFieldEdit = JavaTextEditFactory.addField(providingCompilationUnitType, PRIVATE, fieldName, fieldType); + view.getManipulationUtil().editCompilationUnit(providingCompilationUnit, addFieldEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + BasicComponent providingComponent = claimComponent(repository, PROVIDING_COMPONENT_NAME, + BasicComponent.class); + OperationInterface anInterface = claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + OperationRequiredRole requiredRole = claimNamedElement( + providingComponent.getRequiredRoles_InterfaceRequiringEntity(), fieldName, + OperationRequiredRole.class); + assertEquals(fieldName, requiredRole.getEntityName(), "incorrect name for RequiredRole"); + assertEquals(anInterface, requiredRole.getRequiredInterface__OperationRequiredRole(), + "incorrect interface for RequiredRole"); + }); } @Test - public void testAddFieldWithTypeOfBasicComponentToClass() throws Throwable { - this.createRepoBasicComponentAndInterface(); - - // create required role from Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Requiring" to - // Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Providing" - final OperationRequiredRole orrToInterface = this.addFieldToClassWithName( - Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Requiring" + "Impl", - Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Providing" + "Impl", - Pcm2JavaTestUtils.BASIC_COMPONENT_NAME.toLowerCase() + "Providing", OperationRequiredRole.class); - - this.assertOperationRequiredRole(orrToInterface); + void testAddFieldWithTypeOfBasicComponent() throws Exception { + setupExampleWithProvidingAndRequiringComponent(); + + String fieldName = PROVIDING_COMPONENT_NAME.substring(0, 1).toLowerCase() + + PROVIDING_COMPONENT_NAME.substring(1); + String fieldType = PROVIDING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX; + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaEditorView(view -> { + Package requiringPackage = JavaQueryUtil.claimPackage(view, REQUIRING_COMPONENT_NAME); + ICompilationUnit requiringCompilationUnit = view.getManipulationUtil() + .claimCompilationUnit(REQUIRING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, requiringPackage); + IType requiringCompilationUnitType = requiringCompilationUnit.getType(REQUIRING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX); + + Package providingPackage = JavaQueryUtil.claimPackage(view, PROVIDING_COMPONENT_NAME); + ICompilationUnit providingCompilationUnit = view.getManipulationUtil() + .claimCompilationUnit(PROVIDING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, providingPackage); + + view.getManipulationUtil().addImportToCompilationUnit(requiringCompilationUnit, providingCompilationUnit, + PROVIDING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX); + TextEdit addFieldEdit = JavaTextEditFactory.addField(requiringCompilationUnitType, PRIVATE, fieldName, fieldType); + view.getManipulationUtil().editCompilationUnit(requiringCompilationUnit, addFieldEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + BasicComponent requiringComponent = claimComponent(repository, REQUIRING_COMPONENT_NAME, + BasicComponent.class); + OperationInterface anInterface = claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + OperationRequiredRole requiredRole = claimNamedElement( + requiringComponent.getRequiredRoles_InterfaceRequiringEntity(), fieldName, + OperationRequiredRole.class); + assertEquals(fieldName, requiredRole.getEntityName(), "incorrect name for RequiredRole"); + assertEquals(anInterface, requiredRole.getRequiredInterface__OperationRequiredRole(), + "incorrect interface for RequiredRole"); + }); } - private void createRepoBasicComponentAndInterface() throws CoreException, IOException, InterruptedException { - // create main package - super.addRepoContractsAndDatatypesPackage(); - // create package and classes - this.addPackageAndImplementingClass(Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Providing"); - this.addPackageAndImplementingClass(Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Requiring"); - // create interface - super.createInterfaceInPackageBasedOnJaMoPPPackageWithCorrespondence("contracts", - Pcm2JavaTestUtils.INTERFACE_NAME); - // create provided role from providing component to interface - super.addImplementsCorrespondingToOperationProvidedRoleToClass( - Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + "Providing" + "Impl", Pcm2JavaTestUtils.INTERFACE_NAME); + /** + * Sets up an example scenario with the root Repository and two packages named + * {@link REQUIRING_COMPONENT_NAME} and {@link PROVIDING_COMPONENT_NAME} with + * each one class with suffix {IMPLEMENTING_CLASS_SUFFIX} as basic components. + * Sets up an interface named {@link INTERFACE_NAME} in the contracts package. + * Sets up an {@code implements} relation between the providing component class + * and the interface. + */ + private void setupExampleWithProvidingAndRequiringComponent() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, REQUIRING_COMPONENT_NAME); + createPackageWithPackageInfo(view, REPOSITORY_NAME, PROVIDING_COMPONENT_NAME); + }); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaEditorView(view -> { + Package requiringPackage = JavaQueryUtil.claimPackage(view, REQUIRING_COMPONENT_NAME); + view.getManipulationUtil().createClass(REQUIRING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, + requiringPackage, null); + + Package providingPackage = JavaQueryUtil.claimPackage(view, PROVIDING_COMPONENT_NAME); + view.getManipulationUtil().createClass(PROVIDING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, + providingPackage, null); + ICompilationUnit providingCompilationUnit = view.getManipulationUtil() + .claimCompilationUnit(PROVIDING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, providingPackage); + + Package contractsPackage = JavaQueryUtil.claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + view.getManipulationUtil().createInterface(INTERFACE_NAME, contractsPackage, null); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + + view.getManipulationUtil().addImportToCompilationUnit(providingCompilationUnit, anInterface, + INTERFACE_NAME); + IType classType = providingCompilationUnit.getType(PROVIDING_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX); + TextEdit implementsEdit = JavaTextEditFactory.addImplementsRelation(classType, INTERFACE_NAME); + view.getManipulationUtil().editCompilationUnit(providingCompilationUnit, implementsEdit); + }); } - - private void assertOperationRequiredRole(final OperationRequiredRole operationRequiredRole) throws Throwable { - Iterable correspondingEObjects = getCorrespondingEObjects(operationRequiredRole, EObject.class); - - boolean fieldFound = false; - for (final EObject correspondingEObject : correspondingEObjects) { - if (correspondingEObject instanceof Field) { - fieldFound = true; - } else { - fail("OperationRequiredRole should correspond to field only, but corresonds also to: " - + correspondingEObject); - } - } - assertTrue(fieldFound, "OperationRequiredRole does not correspond to a field"); - } - - private InnerDeclaration renameFieldInClass(final String className, final String fieldName, - final String newFieldName) throws Throwable { - final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, - this.getCurrentTestProject()); - final IType type = icu.getType(className); - final IField fieldToRename = type.getField(fieldName); - final String fieldToRenameStr = fieldToRename.getSource(); - final String fieldToRenameType = fieldToRenameStr.split(" ")[1]; - final String fieldToRenameName = fieldToRenameStr.split(" ")[2]; - final int offset = fieldToRename.getSourceRange().getOffset() + fieldToRenameStr.indexOf(fieldToRenameType) - + fieldToRenameType.length() + 1; - final int lengthToDelete = fieldToRenameName.length(); - final DeleteEdit deleteEdit = new DeleteEdit(offset, lengthToDelete); - final InsertEdit insertEdit = new InsertEdit(offset, newFieldName + ";"); - editCompilationUnit(icu, deleteEdit, insertEdit); - final Field newJaMoPPField = this.getJaMoPPFieldFromClass(icu, newFieldName); - return claimOne(getCorrespondingEObjects(newJaMoPPField, InnerDeclaration.class)); - } - - private InnerDeclaration changeFieldTypeInClass(final String className, final String fieldName, - final String newFieldTypeName) throws Throwable { - final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, - this.getCurrentTestProject()); - final IType type = icu.getType(className); - final IField fieldToRename = type.getField(fieldName); - final String fieldSrc = fieldToRename.getSource(); - final String fieldType = fieldSrc.split(" ")[1]; - final int offset = fieldToRename.getSourceRange().getOffset() + fieldSrc.indexOf(fieldType); - final int lengthToDelete = fieldType.length(); - final DeleteEdit deleteEdit = new DeleteEdit(offset, lengthToDelete); - final InsertEdit insertEdit = new InsertEdit(offset, newFieldTypeName); - editCompilationUnit(icu, deleteEdit, insertEdit); - final Field newJaMoPPField = this.getJaMoPPFieldFromClass(icu, fieldName); - return claimOne(getCorrespondingEObjects(newJaMoPPField, InnerDeclaration.class)); - } - - private void assertInnerDeclaration(final InnerDeclaration innerDeclaration, final String fieldType, - final String fieldName) throws Throwable { - super.assertPCMNamedElement(innerDeclaration, fieldName); - final String pcmDataTypeName = super.getNameFromPCMDataType(innerDeclaration.getDatatype_InnerDeclaration()); - assertEquals(pcmDataTypeName, fieldType, "The name of the PCM datatype does not equal the JaMoPP type name"); - } - } diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/InterfaceMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/InterfaceMappingTransformationTest.java index b040f1665..14f98fe5d 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/InterfaceMappingTransformationTest.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/InterfaceMappingTransformationTest.java @@ -1,74 +1,119 @@ package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; -import org.eclipse.emf.ecore.EObject; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil.claimPackage; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimInterface; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleRepository; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.BASIC_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.INTERFACE_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.RENAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.REPOSITORY_NAME; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.containers.Package; import org.junit.jupiter.api.Test; -import org.palladiosimulator.pcm.repository.BasicComponent; import org.palladiosimulator.pcm.repository.OperationInterface; import org.palladiosimulator.pcm.repository.Repository; -import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; - -import static org.junit.jupiter.api.Assertions.assertTrue; +import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory; -public class InterfaceMappingTransformationTest extends Java2PcmPackageMappingTransformationTest { +class InterfaceMappingTransformationTest extends Java2PcmTransformationTest { /** * interface in contracts package --> should automatically be mapped to * operation interface - * - * @throws Throwable */ @Test - public void testAddInterfaceInContractsPackage() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); + void testAddInterfaceInContractsPackage() throws Exception { + createRepositoryPackage(); - final OperationInterface opIf = super.addInterfaceInContractsPackage(); + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + view.getManipulationUtil().createInterface(INTERFACE_NAME, contractsPackage, null); + }); - this.assertOperationInterface(repo, opIf, Pcm2JavaTestUtils.INTERFACE_NAME); + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + }); } /** * interface in non-repository package --> "user" should be asked and decide to * add it - * - * @throws Exception */ @Test - public void testAddArchitecturalInterfaceInNonRepositoryPackage() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - final BasicComponent bc = super.addSecondPackageCorrespondsToBasicComponent(); + void testAddInterfaceInNonRepositoryPackageAsArchitecturalInterface() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); - final OperationInterface opInterface = super.addInterfaceInSecondPackageWithCorrespondence(bc.getEntityName()); + getUserInteraction() + .addNextSingleSelection(Java2PcmUserSelection.SELECT_CREATE_INTERFACE_NOT_IN_CONTRACTS.getSelection()); + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + view.getManipulationUtil().createInterface(INTERFACE_NAME, componentPackage, null); + }); - this.assertOperationInterface(repo, opInterface, Pcm2JavaTestUtils.INTERFACE_NAME); + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + }); } /** * interface in non-repository package --> "user" should be asked and decide to * not add it - * - * @throws Exception */ @Test - public void testAddTechnicalInterfaceInNonRepositoryPackage() throws Throwable { - super.addRepoContractsAndDatatypesPackage(); - final BasicComponent bc = super.addSecondPackageCorrespondsToBasicComponent(); + void testAddInterfaceInNonRepositoryPackageAsTechnicalInterface() throws Exception { + createRepositoryPackage(); - final EObject eObject = super.addInterfaceInPackageWithoutCorrespondence(bc.getEntityName()); + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); - assertTrue(null == eObject, - "Corresponding object for interface that is created in non main package is not null: " + eObject); + getUserInteraction().addNextSingleSelection( + Java2PcmUserSelection.SELECT_DONT_CREATE_INTERFACE_NOT_IN_CONTRACTS.getSelection()); + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + view.getManipulationUtil().createInterface(INTERFACE_NAME, componentPackage, null); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + assertEquals(0, repository.getInterfaces__Repository().size(), "there must not exist an interface"); + }); } @Test - public void testRenameInterfaceWithCorrespondence() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - super.addSecondPackageCorrespondsToBasicComponent(); - final OperationInterface opInterface = super.addInterfaceInContractsPackage(); + void testRenameInterface() throws Exception { + createRepositoryPackage(); + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + view.getManipulationUtil().createInterface(INTERFACE_NAME, contractsPackage, null); + }); - final OperationInterface newOpInterface = this.renameClassifierWithName(opInterface.getEntityName(), - Pcm2JavaTestUtils.INTERFACE_NAME + Pcm2JavaTestUtils.RENAME, OperationInterface.class); + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + TextEdit renameEdit = JavaTextEditFactory.renameCompilationUnit(anInterface, INTERFACE_NAME, + INTERFACE_NAME + RENAME); + view.getManipulationUtil().editCompilationUnit(anInterface, renameEdit); + }); - this.assertOperationInterface(repo, newOpInterface, - Pcm2JavaTestUtils.INTERFACE_NAME + Pcm2JavaTestUtils.RENAME); + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimInterface(repository, INTERFACE_NAME + RENAME, OperationInterface.class); + assertEquals(1, repository.getInterfaces__Repository().size(), "too many interfaces in repository"); + }); } } diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/JaMoPPParameterMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/JaMoPPParameterMappingTransformationTest.java deleted file mode 100644 index f51d292d5..000000000 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/JaMoPPParameterMappingTransformationTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; - -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.ILocalVariable; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.text.edits.ReplaceEdit; -import org.junit.jupiter.api.Test; -import org.palladiosimulator.pcm.core.entity.NamedElement; -import org.palladiosimulator.pcm.repository.CollectionDataType; -import org.palladiosimulator.pcm.repository.CompositeDataType; -import org.palladiosimulator.pcm.repository.OperationInterface; -import org.palladiosimulator.pcm.repository.OperationSignature; -import org.palladiosimulator.pcm.repository.Parameter; -import org.palladiosimulator.pcm.repository.PrimitiveDataType; - -import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; - -import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class JaMoPPParameterMappingTransformationTest extends Java2PcmPackageMappingTransformationTest { - - @Test - public void testAddParameter() throws Throwable { - super.addRepoContractsAndDatatypesPackage(); - final OperationInterface opInterface = super.addInterfaceInContractsPackage(); - final OperationSignature opSig = super.addMethodToInterfaceWithCorrespondence(opInterface.getEntityName()); - final Parameter parameter = super.addParameterToSignature(opInterface.getEntityName(), opSig.getEntityName(), - "String", Pcm2JavaTestUtils.PARAMETER_NAME, null); - - this.assertParameter(opSig, parameter, "String", Pcm2JavaTestUtils.PARAMETER_NAME); - } - - @Test - public void testRenameParameter() throws Throwable { - super.addRepoContractsAndDatatypesPackage(); - final OperationInterface opInterface = super.addInterfaceInContractsPackage(); - final OperationSignature opSig = super.addMethodToInterfaceWithCorrespondence(opInterface.getEntityName()); - final Parameter parameter = super.addParameterToSignature(opInterface.getEntityName(), opSig.getEntityName(), - "String", Pcm2JavaTestUtils.PARAMETER_NAME, null); - - final Parameter newParameter = this.renameParameterInSignature(opInterface.getEntityName(), - opSig.getEntityName(), parameter.getParameterName(), - Pcm2JavaTestUtils.PARAMETER_NAME + Pcm2JavaTestUtils.RENAME); - - this.assertParameter(opSig, newParameter, "String", - Pcm2JavaTestUtils.PARAMETER_NAME + Pcm2JavaTestUtils.RENAME); - } - - @Test - public void testChangeParameterType() throws Throwable { - super.addRepoContractsAndDatatypesPackage(); - final OperationInterface opInterface = super.addInterfaceInContractsPackage(); - final OperationSignature opSig = super.addMethodToInterfaceWithCorrespondence(opInterface.getEntityName()); - final Parameter parameter = super.addParameterToSignature(opInterface.getEntityName(), opSig.getEntityName(), - "String", Pcm2JavaTestUtils.PARAMETER_NAME, null); - final String expectedParamType = "int"; - - final Parameter changedParameter = this.changeParameterType(opInterface.getEntityName(), opSig.getEntityName(), - parameter.getParameterName(), expectedParamType); - - this.assertParameter(opSig, changedParameter, expectedParamType, changedParameter.getParameterName()); - } - - private Parameter renameParameterInSignature(final String interfaceName, final String methodName, - final String oldParameterName, final String newParameterName) throws Throwable { - final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(interfaceName, - this.getCurrentTestProject()); - final IMethod iMethod = this.findIMethodByName(interfaceName, methodName, icu); - final ILocalVariable localVariable = this.findParameterInIMethod(iMethod, oldParameterName); - final String typeName = localVariable.getSource().split(" ")[0]; - final String paramName = localVariable.getSource().split(" ")[1]; - final int offset = localVariable.getSourceRange().getOffset() + typeName.length() + 1; - final int length = paramName.length(); - final ReplaceEdit replaceEdit = new ReplaceEdit(offset, length, newParameterName); - editCompilationUnit(icu, replaceEdit); - final org.emftext.language.java.parameters.Parameter newJaMoPPParameter = super.findJaMoPPParameterInICU(icu, - interfaceName, methodName, newParameterName); - return claimOne(getCorrespondingEObjects(newJaMoPPParameter, Parameter.class)); - } - - private Parameter changeParameterType(final String interfaceName, final String methodName, final String paramName, - final String newTypeName) throws Throwable { - final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(interfaceName, - this.getCurrentTestProject()); - final IMethod iMethod = this.findIMethodByName(interfaceName, methodName, icu); - final ILocalVariable parameter = this.findParameterInIMethod(iMethod, paramName); - final int offset = parameter.getSourceRange().getOffset(); - final int length = parameter.getSource().split(" ")[0].length(); - final ReplaceEdit replaceEdit = new ReplaceEdit(offset, length, newTypeName); - editCompilationUnit(icu, replaceEdit); - final org.emftext.language.java.parameters.Parameter newJaMoPPParameter = super.findJaMoPPParameterInICU(icu, - interfaceName, methodName, paramName); - Iterable correspondingEObjectsByType = getCorrespondingEObjects(newJaMoPPParameter, Parameter.class); - return claimOne(correspondingEObjectsByType); - } - - private ILocalVariable findParameterInIMethod(final IMethod iMethod, final String parameterName) - throws JavaModelException { - for (final ILocalVariable localVariable : iMethod.getParameters()) { - if (localVariable.getElementName().equals(parameterName)) { - return localVariable; - } - } - throw new RuntimeException("Old parameter with name " + parameterName + " not found"); - } - - private void assertParameter(final OperationSignature opSig, final Parameter parameter, - final String expectedTypeName, final String expectedName) throws Throwable { - OperationSignature operationSignature__Parameter = parameter.getOperationSignature__Parameter(); - assertEquals(opSig.getId(), operationSignature__Parameter.getId(), - "The parameter is not contained in the expected operation signature"); - this.assertPcmParameter(parameter, expectedName); - if (parameter.getDataType__Parameter() instanceof CollectionDataType - || parameter.getDataType__Parameter() instanceof CompositeDataType) { - this.assertPCMNamedElement((NamedElement) parameter.getDataType__Parameter(), expectedTypeName); - } else { - final String primitiveTypeName = this - .getNameFromPCMPrimitiveDataType((PrimitiveDataType) parameter.getDataType__Parameter()); - assertTrue(expectedTypeName.equalsIgnoreCase(primitiveTypeName), - "The primitve type parameter has the wrong name"); - } - } -} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/Java2PcmPackageMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/Java2PcmPackageMappingTransformationTest.java deleted file mode 100644 index 507da0053..000000000 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/Java2PcmPackageMappingTransformationTest.java +++ /dev/null @@ -1,26 +0,0 @@ - -package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; -import java.util.Collections; -import java.util.List; - -import org.palladiosimulator.pcm.repository.CompositeDataType; - -import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; -import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmChangePropagationSpecification; -import tools.vitruv.change.propagation.ChangePropagationSpecification; - -public class Java2PcmPackageMappingTransformationTest extends Java2PcmTransformationTest { - - @Override - protected List getChangePropagationSpecifications() { - return Collections.singletonList(new Java2PcmChangePropagationSpecification()); - } - - protected CompositeDataType addClassThatCorrespondsToCompositeDatatype() throws Throwable { - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_DATA_TYPE.getSelection()); - final CompositeDataType cdt = this.addClassInPackage(this.getDatatypesPackage(), CompositeDataType.class); - return cdt; - } - -} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/Java2PcmTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/Java2PcmTransformationTest.java index 27fa03eb8..a188e2b1e 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/Java2PcmTransformationTest.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/Java2PcmTransformationTest.java @@ -1,687 +1,92 @@ package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; -import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.claimOne; -import static edu.kit.ipd.sdq.commons.util.org.eclipse.emf.common.util.URIUtil.createPlatformResourceURI; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static tools.vitruv.applications.util.temporary.java.JavaQueryUtil.getNameFromJaMoPPType; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.REPOSITORY_NAME; -import java.io.IOException; import java.nio.file.Path; -import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; +import java.util.function.Consumer; -import org.apache.log4j.Logger; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.resource.ResourceSet; -import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; -import org.eclipse.jdt.core.IBuffer; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IField; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.refactoring.IJavaRefactorings; -import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; -import org.eclipse.jdt.internal.core.manipulation.StubUtility; -import org.eclipse.ltk.core.refactoring.Change; -import org.eclipse.ltk.core.refactoring.Refactoring; -import org.eclipse.ltk.core.refactoring.RefactoringContribution; -import org.eclipse.ltk.core.refactoring.RefactoringCore; -import org.eclipse.ltk.core.refactoring.RefactoringStatus; -import org.eclipse.text.edits.InsertEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; -import org.emftext.language.java.classifiers.Classifier; -import org.emftext.language.java.classifiers.ConcreteClassifier; -import org.emftext.language.java.classifiers.Interface; -import org.emftext.language.java.containers.CompilationUnit; import org.emftext.language.java.containers.ContainersFactory; -import org.emftext.language.java.containers.ContainersPackage; -import org.emftext.language.java.containers.JavaRoot; import org.emftext.language.java.containers.Package; -import org.emftext.language.java.members.ClassMethod; -import org.emftext.language.java.members.Field; -import org.emftext.language.java.members.Member; -import org.emftext.language.java.members.Method; -import org.emftext.language.java.modifiers.AnnotableAndModifiable; -import org.emftext.language.java.types.TypeReference; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.function.ThrowingConsumer; import org.palladiosimulator.pcm.core.entity.NamedElement; -import org.palladiosimulator.pcm.repository.BasicComponent; -import org.palladiosimulator.pcm.repository.CollectionDataType; -import org.palladiosimulator.pcm.repository.CompositeComponent; -import org.palladiosimulator.pcm.repository.CompositeDataType; import org.palladiosimulator.pcm.repository.DataType; -import org.palladiosimulator.pcm.repository.OperationInterface; -import org.palladiosimulator.pcm.repository.OperationProvidedRole; -import org.palladiosimulator.pcm.repository.OperationSignature; -import org.palladiosimulator.pcm.repository.Parameter; import org.palladiosimulator.pcm.repository.PrimitiveDataType; -import org.palladiosimulator.pcm.repository.Repository; -import org.palladiosimulator.pcm.repository.RepositoryComponent; -import org.palladiosimulator.pcm.seff.ResourceDemandingSEFF; -import org.palladiosimulator.pcm.system.System; -import edu.kit.ipd.sdq.commons.util.org.eclipse.core.resources.IProjectUtil; -import edu.kit.ipd.sdq.commons.util.org.eclipse.emf.common.util.URIUtil; -import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; -import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; +import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmChangePropagationSpecification; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaEditorView; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaPcmViewFactory; +import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaChangePropagationSpecification; +import tools.vitruv.applications.util.temporary.java.JavaPersistenceHelper; import tools.vitruv.applications.util.temporary.java.JavaSetup; -import tools.vitruv.change.composite.description.VitruviusChange; -import tools.vitruv.change.propagation.ChangePropagationMode; -import tools.vitruv.framework.views.changederivation.DefaultStateBasedChangeResolutionStrategy; -import tools.vitruv.framework.views.changederivation.StateBasedChangeResolutionStrategy; -import tools.vitruv.testutils.LegacyVitruvApplicationTest; +import tools.vitruv.change.propagation.ChangePropagationSpecification; +import tools.vitruv.framework.views.CommittableView; +import tools.vitruv.framework.views.View; import tools.vitruv.testutils.TestProject; -import tools.vitruv.testutils.views.UriMode; -import static edu.kit.ipd.sdq.commons.util.org.eclipse.emf.ecore.resource.ResourceSetUtil.loadOrCreateResource; +import tools.vitruv.testutils.ViewBasedVitruvApplicationTest; -/** - * Test class that contains utility methods that can be used by JaMoPP2PCM - * transformation tests - * - */ -@SuppressWarnings("restriction") -public abstract class Java2PcmTransformationTest extends LegacyVitruvApplicationTest { - private static final Logger logger = Logger.getLogger(Java2PcmTransformationTest.class); - private static final int MAXIMUM_EDIT_WAITING_TIME = 5000; - - protected Package mainPackage; - protected Package secondPackage; - - private IProject testEclipseProject; - - private Map oldToNewURIsOfModifiedResources; - private volatile boolean isWaitingForFinishingsEdits = false; - - protected IProject getCurrentTestProject() { - return testEclipseProject; - } - - /* - * JDT functionality requires platform URIs. - */ - @Override - protected UriMode getUriMode() { - return UriMode.PLATFORM_URIS; - } - - private void refreshProject() { - try { - testEclipseProject.refreshLocal(IResource.DEPTH_INFINITE, null); - } catch (CoreException e) { - String message = "Could not refresh project " + testEclipseProject.getName(); - logger.error(message, e); - } - } +public class Java2PcmTransformationTest extends ViewBasedVitruvApplicationTest { + protected JavaPcmViewFactory viewFactory; @BeforeAll - public static void setupJavaFactories() { + public static final void setupJavaFactories() { JavaSetup.prepareFactories(); } @BeforeEach - public void setupJavaProject(@TestProject Path testProjectFolder) { - String projectName = testProjectFolder.getFileName().toString(); - testEclipseProject = IProjectUtil.createProjectAt(projectName, testProjectFolder); - IProjectUtil.configureAsJavaProject(testEclipseProject); + public final void setupJavaClasspath() { JavaSetup.resetClasspathAndRegisterStandardLibrary(); } @BeforeEach - public void disableTransitiveChangePropagation() { - this.getVirtualModel().setChangePropagationMode(ChangePropagationMode.SINGLE_STEP); + public final void setupViewFactory(@TestProject Path testProjectFolder) { + viewFactory = new JavaPcmViewFactory(testProjectFolder, getVirtualModel()); } - @BeforeEach - public void cleanupModifiedResources() { - this.oldToNewURIsOfModifiedResources = new HashMap<>(); - } - - @AfterEach - public void closeJavaProject() throws JavaModelException, CoreException { - getIJavaProject().close(); - } - - private void saveCurrentStateOfRenamedResourceAndRegisterForChangePropagation(final URI resourceURI, - final URI newResourceURI) { - oldToNewURIsOfModifiedResources.put(resourceURI, newResourceURI); - // Access the resource such that the initial state is present in the test view - resourceAt(resourceURI); + @Override + protected boolean enableTransitiveCyclicChangePropagation() { + return false; } - private void saveCurrentStateOfResourceAndRegisterForSynchronization(final URI resourceURI) { - saveCurrentStateOfRenamedResourceAndRegisterForChangePropagation(resourceURI, resourceURI); + @Override + protected Iterable getChangePropagationSpecifications() { + return List.of(new Java2PcmChangePropagationSpecification(), new Pcm2JavaChangePropagationSpecification()); } - private Resource loadResourceIndependentFromView(final URI resourceURI) { - ResourceSet resourceSet = new ResourceSetImpl(); - Resource resource = loadOrCreateResource(resourceSet, resourceURI); - return resource; + protected void createRepositoryPackage() throws Exception { + changeJavaView(view -> { + createPackageWithPackageInfo(view, new String[] { REPOSITORY_NAME }); + }); } - protected Package createPackageWithPackageInfo(final String... namespace) throws IOException { - String packageFile = String.join("/", namespace); - packageFile = packageFile + "/package-info.java"; + protected Package createPackageWithPackageInfo(View view, final String... namespace) { final Package jaMoPPPackage = ContainersFactory.eINSTANCE.createPackage(); final List namespaceList = Arrays.asList(namespace); jaMoPPPackage.setName(namespaceList.get(namespaceList.size() - 1)); jaMoPPPackage.getNamespaces().addAll(namespaceList.subList(0, namespaceList.size() - 1)); - URI createPackageURI = getUri(Path.of(getPathInProjectForSrcFile(packageFile))); - saveCurrentStateOfResourceAndRegisterForSynchronization(createPackageURI); - final Resource resource = loadResourceIndependentFromView(createPackageURI); - resource.getContents().add(jaMoPPPackage); - resource.save(null); - propagateChanges(); - return jaMoPPPackage; - } - - private ICompilationUnit createCompilationUnit(IPackageFragment packageFragment, String cuName) - throws JavaModelException { - URI createdCompilationUnitURI = getURIForElementInPackage(packageFragment, cuName); - saveCurrentStateOfResourceAndRegisterForSynchronization(createdCompilationUnitURI); - ICompilationUnit compilationUnit = packageFragment.createCompilationUnit(cuName + ".java", "", false, null); - return compilationUnit; - } - - public void editCompilationUnit(final ICompilationUnit cu, final TextEdit... edits) throws JavaModelException { - saveCurrentStateOfResourceAndRegisterForSynchronization(URIUtil.createPlatformResourceURI(cu.getResource())); - cu.becomeWorkingCopy(new NullProgressMonitor()); - for (final TextEdit edit : edits) { - cu.applyTextEdit(edit, null); - } - cu.reconcile(ICompilationUnit.NO_AST, false, null, null); - cu.commitWorkingCopy(false, new NullProgressMonitor()); - cu.discardWorkingCopy(); - cu.save(new NullProgressMonitor() { - public void done() { - Java2PcmTransformationTest.this.isWaitingForFinishingsEdits = false; - Java2PcmTransformationTest.this.notifyAll(); - } - }, true); - propagateChanges(); - } - - public void propagateChanges() { - logger.debug("Starting to wait for edits to be finished"); - try { - if (isWaitingForFinishingsEdits) { - wait(MAXIMUM_EDIT_WAITING_TIME); - if (isWaitingForFinishingsEdits) { - logger.error("Waiting for edits timed out in project " + testEclipseProject.getName()); - fail("Waiting for edits timed out"); - } - } - } catch (InterruptedException e) { - fail("An interrupt occurred unexpectedly"); - } - refreshProject(); - StateBasedChangeResolutionStrategy changeResolutionStrategy = new DefaultStateBasedChangeResolutionStrategy(); - for (Entry modifiedResourceURI : oldToNewURIsOfModifiedResources.entrySet()) { - Resource currentResource = loadResourceIndependentFromView(modifiedResourceURI.getValue()); - VitruviusChange change = changeResolutionStrategy.getChangeSequenceBetween(currentResource, - resourceAt(modifiedResourceURI.getKey())); - VitruviusChange unresolvedChange = change.unresolve(); - record(resourceAt(modifiedResourceURI.getKey()).getResourceSet(), - resourceSet -> unresolvedChange.resolveAndApply(resourceSet)); - } - oldToNewURIsOfModifiedResources.clear(); - propagate(); - disposeViewResources(); - } - - protected Repository addRepoContractsAndDatatypesPackage() throws IOException, CoreException { - this.mainPackage = this.createPackageWithPackageInfo(new String[] { Pcm2JavaTestUtils.REPOSITORY_NAME }); - final Repository repo = claimOne(getCorrespondingEObjects(this.mainPackage, Repository.class)); - return repo; - } - - protected BasicComponent addSecondPackageCorrespondsToBasicComponent() throws Throwable { - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); - return this.createSecondPackage(BasicComponent.class, Pcm2JavaTestUtils.REPOSITORY_NAME, - Pcm2JavaTestUtils.BASIC_COMPONENT_NAME); - } - - protected T createSecondPackage(final Class correspondingType, final String... namespace) - throws Throwable { - this.secondPackage = this.createPackageWithPackageInfo(namespace); - return claimOne(getCorrespondingEObjects(this.secondPackage, correspondingType)); - } - - private void createSecondPackageWithoutCorrespondence(final String... namespace) throws Throwable { - this.secondPackage = this.createPackageWithPackageInfo(namespace); - } - - protected Package renamePackage(final Package packageToRename, final String newName) throws CoreException { - final Resource resource = packageToRename.eResource(); - final IFile iFile = URIUtil.getIFileForEMFUri(resource.getURI()); - IPath iPath = iFile.getProjectRelativePath(); - iPath = iPath.removeLastSegments(1); - final String newQualifiedName = packageToRename.getNamespacesAsString() + newName; - final IFolder iFolder = iFile.getProject().getFolder(iPath); - final IJavaElement javaPackage = JavaCore.create(iFolder); - String packageFile = String.join("/", packageToRename.getNamespaces()); - packageFile = packageFile + "/" + newName + "/package-info.java"; - saveCurrentStateOfRenamedResourceAndRegisterForChangePropagation(resource.getURI(), - getUri(Path.of(getPathInProjectForSrcFile(packageFile)))); - this.refactorRenameJavaElement(newQualifiedName, javaPackage, IJavaRefactorings.RENAME_PACKAGE); - final Package newPackage = this.findJaMoPPPackageWithName(newQualifiedName); - return newPackage; - } - - private void refactorRenameJavaElement(final String newName, final IJavaElement iJavaElement, - final String refactorRenameActionName) throws CoreException { - final RefactoringContribution refacContrib = RefactoringCore - .getRefactoringContribution(refactorRenameActionName); - final RefactoringStatus status = new RefactoringStatus(); - final RenameJavaElementDescriptor desc = (RenameJavaElementDescriptor) refacContrib.createDescriptor(); - desc.setUpdateReferences(true); - desc.setJavaElement(iJavaElement); - desc.setNewName(newName); - final NullProgressMonitor monitor = new NullProgressMonitor(); - final Refactoring refactoring = desc.createRefactoring(status); - refactoring.checkInitialConditions(monitor); - refactoring.checkFinalConditions(monitor); - final Change change = refactoring.createChange(monitor); - change.perform(monitor); - propagateChanges(); - } - - protected T renameClassifierWithName(final String entityName, final String newName, - final Class type) throws Throwable { - try { - final ICompilationUnit cu = CompilationUnitManipulatorHelper - .findICompilationUnitWithClassName(entityName + ".java", this.getCurrentTestProject()); - final int offset = cu.getBuffer().getContents().indexOf(entityName); - if (cu.getBuffer() instanceof IBuffer.ITextEditCapability) { - logger.info(cu.getBuffer()); - } - final ReplaceEdit edit = new ReplaceEdit(offset, entityName.length(), newName); - editCompilationUnit(cu, edit); - final URI uri = createPlatformResourceURI(cu.getResource()); - final Classifier jaMoPPClass = this.getJaMoPPClassifierForURI(uri); - return claimOne(getCorrespondingEObjects(jaMoPPClass, type)); - } catch (final Throwable e) { - logger.warn(e.getMessage()); - } - return null; - - } - - private Package findJaMoPPPackageWithName(final String newName) throws JavaModelException { - final IJavaProject javaProject = JavaCore.create(this.getCurrentTestProject()); - for (final IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) { - final IJavaElement[] children = packageFragmentRoot.getChildren(); - for (final IJavaElement iJavaElement : children) { - if (iJavaElement instanceof IPackageFragment) { - final IPackageFragment fragment = (IPackageFragment) iJavaElement; - if (fragment.getElementName().equals(newName)) { - final URI uri = this.getURIForElementInPackage(fragment, "package-info"); - final Package jaMoPPPackage = this.getJaMoPPRootForURI(uri); - return jaMoPPPackage; - } - } - } - } - throw new RuntimeException("Could not find a compilation unit with name " + newName); - } - - private IPackageFragmentRoot getIJavaProject() throws CoreException { - final IProject project = this.getCurrentTestProject(); - final IJavaProject javaProject = JavaCore.create(project); - final IFolder sourceFolder = project.getFolder("src"); - if (!sourceFolder.exists()) { - final boolean force = true; - final boolean local = true; - sourceFolder.create(force, local, new NullProgressMonitor()); - } - final IPackageFragmentRoot packageFragment = javaProject.getPackageFragmentRoot(sourceFolder); - return packageFragment; - } - - private String getPathInProjectForSrcFile(final String srcFilePath) { - return "src/" + srcFilePath; - } - - protected T addClassInSecondPackage(final Class classOfCorrespondingObject) - throws Throwable { - final T createdEObject = this.addClassInPackage(this.secondPackage, classOfCorrespondingObject); - return createdEObject; - } - - protected T addClassInPackage(final Package packageForClass, - final Class classOfCorrespondingObject) throws Throwable { - final String implementingClassName = Pcm2JavaTestUtils.IMPLEMENTING_CLASS_NAME; - return this.addClassInPackage(packageForClass, classOfCorrespondingObject, implementingClassName); - } - - protected T addClassInPackage(final Package packageForClass, - final Class classOfCorrespondingObject, final String implementingClassName) - throws CoreException, InterruptedException { - final Classifier jaMoPPClass = this.createClassInPackage(packageForClass, implementingClassName); - final Iterable eObjectsByType = getCorrespondingEObjects(jaMoPPClass, classOfCorrespondingObject); - return claimOne(eObjectsByType); - } - - protected Classifier createClassInPackage(final Package packageForClass, final String implementingClassName) - throws CoreException { - String packageName = packageForClass.getName(); - String packageNamespace = packageForClass.getNamespacesAsString() + packageName; - return createClassInPackage(implementingClassName, packageNamespace); - } - - protected Classifier createClassInPackage(final String implementingClassName, String packageNamespace) - throws CoreException { - final IPackageFragment packageFragment = this.getPackageFragment(packageNamespace); - createEmptyClass(packageFragment, implementingClassName); - final URI uri = this.getURIForElementInPackage(packageFragment, implementingClassName); - final Classifier jaMoPPClass = this.getJaMoPPClassifierForURI(uri); - return jaMoPPClass; - } - - private URI getURIForElementInPackage(final IPackageFragment packageFragment, final String elementName) { - String uriString = packageFragment.getResource().getFullPath().toString() + "/" + elementName + ".java"; - return URI.createPlatformResourceURI(uriString, true); - } - - private IPackageFragment getPackageFragment(String packageNamespace) throws CoreException { - final IPackageFragmentRoot packageRoot = this.getIJavaProject(); - for (final IJavaElement javaElement : packageRoot.getChildren()) { - if (javaElement instanceof IPackageFragment && javaElement.getElementName().equals(packageNamespace)) { - return (IPackageFragment) javaElement; - } - } - throw new RuntimeException("No packageFragment found for JaMoPP package " + packageNamespace); - } - - protected ConcreteClassifier getJaMoPPClassifierForURI(final URI uri) { - final CompilationUnit cu = this.getJaMoPPRootForURI(uri); - final Classifier jaMoPPClassifier = cu.getClassifiers().get(0); - return (ConcreteClassifier) jaMoPPClassifier; - } - - private T getJaMoPPRootForURI(final URI uri) { - final Resource resource = new ResourceSetImpl().getResource(uri, true); - // unchecked is OK for the test. - @SuppressWarnings("unchecked") - final T javaRoot = (T) resource.getContents().get(0); - return javaRoot; - } - - protected CompositeComponent addSecondPackageCorrespondsToCompositeComponent() throws Throwable { - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_COMPONENT.getSelection()); - return this.createSecondPackage(CompositeComponent.class, Pcm2JavaTestUtils.REPOSITORY_NAME, - Pcm2JavaTestUtils.COMPOSITE_COMPONENT_NAME); - } - - protected org.palladiosimulator.pcm.system.System addSecondPackageCorrespondsToSystem() throws Throwable { - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_SYSTEM.getSelection()); - return this.createSecondPackage(System.class, Pcm2JavaTestUtils.SYSTEM_NAME); - } - - protected void addSecondPackageCorrespondsWithoutCorrespondences() throws Throwable { - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_NOTHING_DECIDE_LATER.getSelection()); - this.createSecondPackageWithoutCorrespondence(Pcm2JavaTestUtils.REPOSITORY_NAME, - Pcm2JavaTestUtils.BASIC_COMPONENT_NAME); - } - - protected void assertRepositoryAndPCMName(final Repository repo, final RepositoryComponent repoComponent, - final String expectedName) throws Throwable { - - assertEquals(repo.getId(), repoComponent.getRepository__RepositoryComponent().getId(), - "Repository of compoennt is not the repository: " + repo); - - this.assertPCMNamedElement(repoComponent, expectedName); - } - - protected void assertResourceAndFileForEObjects(final EObject... eObjects) throws Throwable { - for (final EObject eObject : eObjects) { - final Resource eResource = eObject.eResource(); - assertNotNull(eResource, "Resource of eObject " + eObject + " is null"); - final IFile iFile = URIUtil.getIFileForEMFUri(eResource.getURI()); - assertTrue(iFile.exists(), "No IFile for eObject " + eObject + " in resource " + eResource + " found."); - } - } - - protected void assertFilesOnlyForEObjects(final EObject... eObjects) throws Throwable { - final Set fullFilePaths = new HashSet(); - for (final EObject eObject : eObjects) { - final IFile iFile = URIUtil.getIFileForEMFUri(eObject.eResource().getURI()); - fullFilePaths.add(iFile.getFullPath().toString()); - } - final IFolder folder = this.getCurrentTestProject().getFolder("model"); - final List foundAdditionalFiles = new ArrayList<>(); - for (final IResource iResource : folder.members()) { - final String iResourcePath = iResource.getFullPath().toString(); - if (!fullFilePaths.contains(iResourcePath)) { - foundAdditionalFiles.add(iResourcePath); - } - } - if (0 < foundAdditionalFiles.size()) { - final StringBuilder failMsg = new StringBuilder("Found addtional files in model folder: "); - foundAdditionalFiles.forEach(str -> failMsg.append(str).append(", ")); - fail(failMsg.toString()); - } - } - - protected void assertRepositoryAndPCMNameForDatatype(final Repository repo, final DataType dt, - final String expectedName) throws Throwable { - - assertEquals(repo.getId(), dt.getRepository__DataType().getId(), - "Repository of compoennt is not the repository: " + repo); - if (dt instanceof CompositeDataType) { - this.assertPCMNamedElement((CompositeDataType) dt, expectedName); - } else if (dt instanceof CollectionDataType) { - this.assertPCMNamedElement((CollectionDataType) dt, expectedName); - } else { - throw new RuntimeException("Primitive data types should not have a correspondence to classes"); - } - } - - protected void assertPCMNamedElement(final NamedElement pcmNamedElement, final String expectedName) - throws Throwable { - assertEquals(expectedName, pcmNamedElement.getEntityName(), - "The name of pcm named element is not " + expectedName); - this.assertResourceAndFileForEObjects(pcmNamedElement); - } - - protected void assertPcmParameter(final Parameter pcmParameter, final String expectedName) throws Throwable { - assertEquals(expectedName, pcmParameter.getParameterName(), "The name of pcm parameter is not " + expectedName); - this.assertResourceAndFileForEObjects(pcmParameter); - } - protected OperationInterface addInterfaceInContractsPackage() throws Throwable { - return this.createInterfaceInPackage("contracts"); - } - - private OperationInterface createInterfaceInPackage(final String packageName) - throws Throwable, CoreException, InterruptedException { - final String interfaceName = Pcm2JavaTestUtils.INTERFACE_NAME; - return this.createInterfaceInPackageBasedOnJaMoPPPackageWithCorrespondence(packageName, interfaceName); - } - - protected OperationInterface createInterfaceInPackageBasedOnJaMoPPPackageWithCorrespondence( - final String packageName, final String interfaceName) throws CoreException { - Package jaMoPPPackage = this.getPackageWithNameFromCorrespondenceModel(packageName); - return this.createInterfaceInPackage(jaMoPPPackage.getNamespacesAsString() + jaMoPPPackage.getName(), - interfaceName, true); - } - - protected ConcreteClassifier createInterfaceInPackageBasedOnJaMoPPPackageWithoutCorrespondence( - final String packageName, final String interfaceName) - throws Throwable, CoreException, InterruptedException { - Package jaMoPPPackage = this.getPackageWithNameFromCorrespondenceModel(packageName); - return this.createJaMoPPInterfaceInPackage(jaMoPPPackage.getNamespacesAsString() + jaMoPPPackage.getName(), - interfaceName); - } - - protected OperationInterface createInterfaceInPackage(String packageNamespace, final String interfaceName, - boolean claimOne) throws CoreException { - final Classifier jaMoPPIf = createJaMoPPInterfaceInPackage(packageNamespace, interfaceName); - Iterable correspondingOpInterfaces = getCorrespondingEObjects(jaMoPPIf, - OperationInterface.class); - if (claimOne) { - return claimOne(correspondingOpInterfaces); - } - if (null == correspondingOpInterfaces || !correspondingOpInterfaces.iterator().hasNext()) { - return null; - } - logger.warn("More than one corresponding interfaces found for interface " + jaMoPPIf + ". Returning the first"); - return correspondingOpInterfaces.iterator().next(); - } - - protected ConcreteClassifier createJaMoPPInterfaceInPackage(String packageNamespace, final String interfaceName) - throws CoreException { - final IPackageFragment packageFragment = this.getPackageFragment(packageNamespace); - createEmptyInterface(packageFragment, interfaceName); - final URI uri = this.getURIForElementInPackage(packageFragment, interfaceName); - final ConcreteClassifier jaMoPPIf = this.getJaMoPPClassifierForURI(uri); - - return jaMoPPIf; - } - - private void createEmptyCompilationUnit(IPackageFragment packageFragment, String typeName, String cuName) - throws JavaModelException { - String lineDelimiter = null; - lineDelimiter = StubUtility.getLineDelimiterUsed(packageFragment.getJavaProject()); - ICompilationUnit compilationUnit = createCompilationUnit(packageFragment, cuName); - InsertEdit edit = new InsertEdit(0, "package " + packageFragment.getElementName() + ";" + lineDelimiter - + lineDelimiter + "public " + typeName + " " + cuName + " { }"); - editCompilationUnit(compilationUnit, edit); - } - - protected void createEmptyInterface(IPackageFragment packageFragment, String interfaceName) - throws JavaModelException { - createEmptyCompilationUnit(packageFragment, "interface", interfaceName); - } - - protected void createEmptyClass(IPackageFragment packageFragment, String className) throws JavaModelException { - createEmptyCompilationUnit(packageFragment, "class", className); - } - - protected OperationInterface addInterfaceInSecondPackageWithCorrespondence(final String packageName) - throws Throwable { - this.getUserInteraction() - .addNextSingleSelection(Java2PcmUserSelection.SELECT_CREATE_INTERFACE_NOT_IN_CONTRACTS.getSelection()); - return this.createInterfaceInPackage(packageName); - } - - protected EObject addInterfaceInPackageWithoutCorrespondence(final String packageName) throws Throwable { - this.getUserInteraction().addNextSingleSelection( - Java2PcmUserSelection.SELECT_DONT_CREATE_INTERFACE_NOT_IN_CONTRACTS.getSelection()); - Package jaMoPPPackage = this.getPackageWithNameFromCorrespondenceModel(packageName); - return this.createInterfaceInPackage(jaMoPPPackage.getNamespacesAsString() + jaMoPPPackage.getName(), - "I" + packageName, false); - } - - protected Package getPackageWithNameFromCorrespondenceModel(final String name) throws CoreException { - final Iterable packages = getCorrespondingEObjects(ContainersPackage.Literals.PACKAGE, Package.class); - for (final Package currentPackage : packages) { - if (currentPackage.getName().equals(name)) { - return currentPackage; - } - } - throw new RuntimeException("Could not find package with name " + name); - } - - protected OperationSignature addMethodToInterfaceWithCorrespondence(final String interfaceName) throws Throwable { - final String methodName = Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME; - return this.addMethodToInterfaceWithCorrespondence(interfaceName, methodName); - } - - protected OperationSignature addMethodToInterfaceWithCorrespondence(final String interfaceName, - final String methodName) throws Throwable, JavaModelException { - final String methodString = "\nvoid " + methodName + "();\n"; - final ICompilationUnit cu = addMethodToCompilationUnit(interfaceName, methodString, - this.getCurrentTestProject()); - return this.findOperationSignatureForJaMoPPMethodInCompilationUnit(methodName, interfaceName, cu); - } - - protected ResourceDemandingSEFF addClassMethodToClassThatOverridesInterfaceMethod(final String className, - final String methodName) throws Throwable { - final String methodString = "\n\tpublic void " + methodName + " () {\n\t}\n"; - final ICompilationUnit icu = addMethodToCompilationUnit(className, methodString, this.getCurrentTestProject()); - final Method jaMoPPMethod = this.findJaMoPPMethodInICU(icu, methodName); - final ClassMethod classMethod = (ClassMethod) jaMoPPMethod; - return claimOne(getCorrespondingEObjects(classMethod, ResourceDemandingSEFF.class)); - } - - protected OperationSignature findOperationSignatureForJaMoPPMethodInCompilationUnit(final String methodName, - final String interfaceName, final ICompilationUnit cu) throws Throwable { - final URI uri = createPlatformResourceURI(cu.getResource()); - final Classifier classifier = this.getJaMoPPClassifierForURI(uri); - final Interface jaMoPPInterface = (Interface) classifier; - for (final Method jaMoPPMethod : jaMoPPInterface.getMethods()) { - if (jaMoPPMethod.getName().equals(methodName)) { - return claimOne(getCorrespondingEObjects(jaMoPPMethod, OperationSignature.class)); - } - } - logger.warn("No JaMoPP method with name " + methodName + " found in " + interfaceName); - return null; - } - - protected OperationSignature renameMethodInClassWithName(final String className, final String methodName) - throws Throwable { - final ICompilationUnit cu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, - this.getCurrentTestProject()); - final IMethod iMethod = cu.getType(className).getMethod(methodName, null); - final int offset = iMethod.getNameRange().getOffset(); - final int length = iMethod.getNameRange().getLength(); - final String newMethodName = methodName + Pcm2JavaTestUtils.RENAME; - final ReplaceEdit replaceEdit = new ReplaceEdit(offset, length, newMethodName); - editCompilationUnit(cu, replaceEdit); - return this.findOperationSignatureForJaMoPPMethodInCompilationUnit(newMethodName, className, cu); - } - - protected void assertDataTypeName(final TypeReference typeReference, final DataType pcmDataType) { - final String jaMoPPTypeName = getNameFromJaMoPPType(typeReference); - final String pcmTypeName = this.getNameFromPCMDataType(pcmDataType); - assertEquals(jaMoPPTypeName, pcmTypeName, "The name of the PCM datatype does not equal the JaMoPP type name"); + URI createPackageURI = getUri(Path.of(JavaPersistenceHelper.buildJavaFilePath(jaMoPPPackage))); + view.registerRoot(jaMoPPPackage, createPackageURI); + return jaMoPPPackage; } - protected String getNameFromPCMDataType(final DataType pcmDataType) { - if (null == pcmDataType) { + protected String getTypeNameOfPcmDataType(DataType dataType) { + if (dataType == null) { return "void"; - } else if (pcmDataType instanceof CollectionDataType) { - return ((CollectionDataType) pcmDataType).getEntityName(); - } else if (pcmDataType instanceof CompositeDataType) { - return ((CompositeDataType) pcmDataType).getEntityName(); - } else if (pcmDataType instanceof PrimitiveDataType) { - return this.getNameFromPrimitveDataType((PrimitiveDataType) pcmDataType); + } else if (dataType instanceof PrimitiveDataType) { + return getTypeNameFromPrimitveDataType((PrimitiveDataType) dataType); + } else if (dataType instanceof NamedElement) { + return ((NamedElement) dataType).getEntityName(); } - throw new RuntimeException("getNameFromPCMDataType failed"); + throw new RuntimeException("Unknown data type " + dataType); } - private String getNameFromPrimitveDataType(final PrimitiveDataType pcmDataType) { - switch (pcmDataType.getType()) { + private String getTypeNameFromPrimitveDataType(final PrimitiveDataType dataType) { + switch (dataType.getType()) { case BOOL: return "boolean"; case CHAR: @@ -697,243 +102,24 @@ private String getNameFromPrimitveDataType(final PrimitiveDataType pcmDataType) case STRING: return "String"; } - throw new RuntimeException("getNameFromPrimitveDataType"); - } - - protected Parameter addParameterToSignature(final String interfaceName, final String methodName, - final String typeName, final String parameterName, final String[] parameterTypeSignatures) - throws Throwable { - final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(interfaceName, - this.getCurrentTestProject()); - final IMethod iMethod = icu.getType(interfaceName).getMethod(methodName, parameterTypeSignatures); - final String parameterStr = typeName + " " + parameterName; - return this.insertParameterIntoSignature(methodName, parameterName, icu, iMethod, parameterStr); - } - - protected Parameter insertParameterIntoSignature(final String methodName, final String parameterName, - final ICompilationUnit icu, final IMethod iMethod, final String parameterStr) - throws JavaModelException, Throwable { - final int offset = iMethod.getSourceRange().getOffset() + iMethod.getSourceRange().getLength() - 2; - final InsertEdit insertEdit = new InsertEdit(offset, parameterStr); - editCompilationUnit(icu, insertEdit); - final ConcreteClassifier concreateClassifier = this - .getJaMoPPClassifierForURI(createPlatformResourceURI(icu.getResource())); - final Method jaMoPPMethod = (Method) concreateClassifier.getMembersByName(methodName).get(0); - final org.emftext.language.java.parameters.Parameter jaMoPPParam = this - .getJaMoPPParameterFromJaMoPPMethod(jaMoPPMethod, parameterName); - return claimOne(getCorrespondingEObjects(jaMoPPParam, Parameter.class)); - } - - protected OperationSignature addReturnTypeToSignature(final String interfaceName, final String methodName, - final String typeName, String oldTypeName) throws Throwable { - if (null == oldTypeName) { - oldTypeName = "void"; - } - final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(interfaceName, - this.getCurrentTestProject()); - final IMethod iMethod = icu.getType(interfaceName).getMethod(methodName, null); - final String retTypeStr = typeName; - final int offset = iMethod.getSourceRange().getOffset() - + iMethod.getSourceRange().toString().indexOf(oldTypeName); - final ReplaceEdit replaceEdit = new ReplaceEdit(offset + 1, oldTypeName.length() + 1, retTypeStr); - editCompilationUnit(icu, replaceEdit); - final ConcreteClassifier concreateClassifier = this - .getJaMoPPClassifierForURI(createPlatformResourceURI(icu.getResource())); - final Method jaMoPPMethod = (Method) concreateClassifier.getMembersByName(methodName).get(0); - return claimOne(getCorrespondingEObjects(jaMoPPMethod, OperationSignature.class)); - } - - protected org.emftext.language.java.parameters.Parameter getJaMoPPParameterFromJaMoPPMethod( - final Method jaMoPPMethod, final String parameterName) { - for (final org.emftext.language.java.parameters.Parameter jaMoPPParam : jaMoPPMethod.getParameters()) { - if (jaMoPPParam.getName().equals(parameterName)) { - return jaMoPPParam; - } - } - throw new RuntimeException( - "JaMoPP param with name " + parameterName + " not found in method " + jaMoPPMethod.getName()); - } - - protected org.emftext.language.java.parameters.Parameter findJaMoPPParameterInICU(final ICompilationUnit icu, - final String interfaceName, final String methodName, final String parameterName) { - final Method method = this.findJaMoPPMethodInICU(icu, methodName); - return this.getJaMoPPParameterFromJaMoPPMethod(method, parameterName); - } - - protected Method findJaMoPPMethodInICU(final ICompilationUnit icu, final String methodName) { - final ConcreteClassifier cc = this.getJaMoPPClassifierForURI(createPlatformResourceURI(icu.getResource())); - final List jaMoPPMethods = cc.getMembersByName(methodName); - for (final Member member : jaMoPPMethods) { - if (member instanceof Method && member.getName().equals(methodName)) { - return (Method) member; - } - } - throw new RuntimeException("No method with name " + methodName + " found in " + icu); - } - - protected String getNameFromPCMPrimitiveDataType(final PrimitiveDataType primitiveDataType) { - return primitiveDataType.getType().getName(); - } - - protected Package getDatatypesPackage() throws Throwable { - return this.getPackageWithNameFromCorrespondenceModel("datatypes"); - } - - protected IMethod findIMethodByName(final String typeName, final String methodName, final ICompilationUnit icu) - throws JavaModelException { - final IType type = icu.getAllTypes()[0]; - logger.info(type.getMethods()); - for (final IMethod method : type.getMethods()) { - if (method.getElementName().equals(methodName)) { - return method; - } - } - throw new RuntimeException("Method not " + methodName + " not found in classifier " + typeName); - } - - protected IField findIFieldByName(final String className, final String fieldName, final ICompilationUnit icu) - throws JavaModelException { - final IType type = icu.getType(className); - return type.getField(fieldName); - } - - protected String addPackageAndImplementingClass(final String componentName) - throws CoreException, IOException, InterruptedException { - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); - final Package mediaStorePackage = this.createPackageWithPackageInfo(Pcm2JavaTestUtils.REPOSITORY_NAME, - componentName); - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); - - final String implementingClassName = componentName + "Impl"; - this.addClassInPackage(mediaStorePackage, BasicComponent.class, implementingClassName); - return implementingClassName; - } - - protected OperationProvidedRole addImplementsCorrespondingToOperationProvidedRoleToClass(final String className, - final String implementingInterfaceName) throws CoreException { - final ICompilationUnit classCompilationUnit = CompilationUnitManipulatorHelper - .findICompilationUnitWithClassName(className, this.getCurrentTestProject()); - this.importCompilationUnitWithName(implementingInterfaceName, classCompilationUnit); - - final IType classType = classCompilationUnit.getType(className); - final String newSource = " implements " + implementingInterfaceName; - int offset = classType.getSourceRange().getOffset(); - final int firstBracket = classType.getSource().indexOf("{"); - offset = offset + firstBracket - 1; - final InsertEdit insertEdit = new InsertEdit(offset, newSource); - editCompilationUnit(classCompilationUnit, insertEdit); - final org.emftext.language.java.classifiers.Class jaMoPPClass = (org.emftext.language.java.classifiers.Class) this - .getJaMoPPClassifierForURI(createPlatformResourceURI(classCompilationUnit.getResource())); - final EList classImplements = jaMoPPClass.getImplements(); - logger.debug("Found implements: " + classImplements); - for (final TypeReference implementsReference : classImplements) { - logger.debug("Implements data: " + implementsReference.getTarget()); - final Iterable correspondingEObjects = getCorrespondingEObjects(implementsReference, - OperationProvidedRole.class); - logger.debug("Corresponding provided roles: " + correspondingEObjects); - if (null != correspondingEObjects && correspondingEObjects.iterator().hasNext()) { - return correspondingEObjects.iterator().next(); - } - } - throw new RuntimeException("Could not find an operation provided role for the newly created implements"); + throw new RuntimeException("Unknown primitive data type " + dataType); } - protected void importCompilationUnitWithName(final String implementingInterfaceName, - final ICompilationUnit classCompilationUnit) throws JavaModelException { - final ICompilationUnit interfaceCompilationUnit = CompilationUnitManipulatorHelper - .findICompilationUnitWithClassName(implementingInterfaceName, this.getCurrentTestProject()); - final String namespace = interfaceCompilationUnit.getType(implementingInterfaceName).getFullyQualifiedName(); - saveCurrentStateOfResourceAndRegisterForSynchronization( - URIUtil.createPlatformResourceURI(interfaceCompilationUnit.getResource())); - saveCurrentStateOfResourceAndRegisterForSynchronization( - URIUtil.createPlatformResourceURI(classCompilationUnit.getResource())); - classCompilationUnit.createImport(namespace, null, null); - } + // === Shortcuts === - protected T addFieldToClassWithName(final String className, final String fieldType, - final String fieldName, final Class correspondingType) throws Throwable { - final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, - this.getCurrentTestProject()); - if (!fieldType.equals("String")) { - this.importCompilationUnitWithName(fieldType, icu); - } - final IType iClass = icu.getAllTypes()[0]; - final int offset = CompilationUnitManipulatorHelper.getOffsetForClassifierManipulation(iClass); - final String fieldStr = "private " + fieldType + " " + fieldName + ";"; - final InsertEdit insertEdit = new InsertEdit(offset, fieldStr); - editCompilationUnit(icu, insertEdit); - final Field jaMoPPField = this.getJaMoPPFieldFromClass(icu, fieldName); - if (correspondingType == null) { - return null; - } - return claimOne(getCorrespondingEObjects(jaMoPPField, correspondingType)); + protected void changeJavaView(Consumer modelModification) throws Exception { + viewFactory.changeJavaView(modelModification); } - protected Field getJaMoPPFieldFromClass(final ICompilationUnit icu, final String fieldName) { - final ConcreteClassifier cc = this.getJaMoPPClassifierForURI(createPlatformResourceURI(icu.getResource())); - final Field field = (Field) cc.getMembersByName(fieldName).get(0); - return field; + protected void changeJavaEditorView(ThrowingConsumer modelModification) throws Exception { + viewFactory.changeJavaEditorView(modelModification); } - // add Annotation via the framework - protected T addAnnotationToClassifier(final AnnotableAndModifiable annotable, - final String annotationName, final String annotationParameter, final Class classOfCorrespondingObject, - final String className) throws Throwable { - final ICompilationUnit cu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, - this.getCurrentTestProject()); - final IType type = cu.getType(className); - final int offset = CompilationUnitManipulatorHelper.getOffsetForAddingAnntationToClass(type); - final String composedName = "@" + annotationName - + (annotationParameter != null ? "(\"" + annotationParameter + "\")" : "") - + java.lang.System.lineSeparator(); - final InsertEdit insertEdit = new InsertEdit(offset, composedName); - editCompilationUnit(cu, insertEdit); - final Iterable eObjectsByType = getCorrespondingEObjects(annotable, classOfCorrespondingObject); - return claimOne(eObjectsByType); - } + protected void changeJavaEditorViewThrowing(ThrowingConsumer modelModification) throws Exception { - // add Annotation via the framework - protected T addAnnotationToField(final String fieldName, final String annotationName, - final String annotationParameter, final Class classOfCorrespondingObject, final String className) - throws Throwable { - final ICompilationUnit cu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, - this.getCurrentTestProject()); - final IType type = cu.getType(className); - final int offset = CompilationUnitManipulatorHelper.getOffsetForAddingAnntationToField(type, fieldName); - final String composedName = "@" + annotationName - + (annotationParameter != null ? "(\"" + annotationParameter + "\")" : "") - + java.lang.System.lineSeparator(); - final InsertEdit insertEdit = new InsertEdit(offset, composedName); - editCompilationUnit(cu, insertEdit); - final Field jaMoPPField = this.getJaMoPPFieldFromClass(cu, fieldName); - final Iterable eObjectsByType = getCorrespondingEObjects(jaMoPPField, classOfCorrespondingObject); - return claimOne(eObjectsByType); } - protected void assertCorrespondingSEFF(final ResourceDemandingSEFF correspondingSeff, String methodName) - throws Throwable { - final ClassMethod jaMoPPMethod = claimOne(getCorrespondingEObjects(correspondingSeff, ClassMethod.class)); - assertEquals(jaMoPPMethod.getName(), methodName); + protected void validatePcmView(Consumer viewValidation) throws Exception { + viewFactory.validatePcmView(viewValidation); } - - protected void assertOperationInterface(final Repository repo, final OperationInterface opIf, - final String expectedName) { - assertTrue(null != opIf, "The created operation interface is null"); - assertEquals(opIf.getEntityName(), expectedName, - "OperationInterface name does not equals the expected interface Name."); - assertEquals(repo.getId(), opIf.getRepository__Interface().getId(), - "The created operation interface is not in the repository"); - } - - public ICompilationUnit addMethodToCompilationUnit(final String compilationUnitName, final String methodString, - final IProject currentTestProject) throws JavaModelException { - final ICompilationUnit cu = CompilationUnitManipulatorHelper - .findICompilationUnitWithClassName(compilationUnitName, currentTestProject); - final IType firstType = cu.getAllTypes()[0]; - final int offset = CompilationUnitManipulatorHelper.getOffsetForClassifierManipulation(firstType); - final InsertEdit insertEdit = new InsertEdit(offset, methodString); - editCompilationUnit(cu, insertEdit); - return cu; - } - } diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/MethodMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/MethodMappingTransformationTest.java index e64d23546..420a762e7 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/MethodMappingTransformationTest.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/MethodMappingTransformationTest.java @@ -1,81 +1,113 @@ package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil.claimPackage; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimInterface; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimNamedElement; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleRepository; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.INTERFACE_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.RENAME; + import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.text.edits.DeleteEdit; -import org.eclipse.text.edits.InsertEdit; -import org.emftext.language.java.members.Method; +import org.eclipse.jdt.core.IType; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.containers.Package; import org.junit.jupiter.api.Test; import org.palladiosimulator.pcm.repository.OperationInterface; import org.palladiosimulator.pcm.repository.OperationSignature; +import org.palladiosimulator.pcm.repository.Repository; -import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; - -import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class MethodMappingTransformationTest extends Java2PcmPackageMappingTransformationTest { +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory; +class MethodMappingTransformationTest extends Java2PcmTransformationTest { @Test - public void testAddMethod() throws Throwable { - super.addRepoContractsAndDatatypesPackage(); - final OperationInterface opInterface = super.addInterfaceInContractsPackage(); - - final OperationSignature opSig = super.addMethodToInterfaceWithCorrespondence(opInterface.getEntityName()); - - this.assertOperationSignature(opSig, opInterface, Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME); + void testAddMethod() throws Exception { + createRepositoryPackage(); + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + view.getManipulationUtil().createInterface(INTERFACE_NAME, contractsPackage, null); + }); + + String returnType = "void"; + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + IType interfaceType = anInterface.getType(INTERFACE_NAME); + + TextEdit addMethodEdit = JavaTextEditFactory.addMethodSignature(interfaceType, returnType, + OPERATION_SIGNATURE_1_NAME); + view.getManipulationUtil().editCompilationUnit(anInterface, addMethodEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + OperationInterface operationInterface = claimInterface(repository, INTERFACE_NAME, + OperationInterface.class); + OperationSignature operationSignature = claimNamedElement( + operationInterface.getSignatures__OperationInterface(), OPERATION_SIGNATURE_1_NAME); + assertEquals(0, operationSignature.getParameters__OperationSignature().size(), + "signature must not have any parameters"); + assertEquals(returnType, getTypeNameOfPcmDataType(operationSignature.getReturnType__OperationSignature()), + "signature has wrong return type"); + }); } @Test - public void testRenameMethod() throws Throwable { - this.addRepoContractsAndDatatypesPackage(); - final OperationInterface opInterface = super.addInterfaceInContractsPackage(); - final OperationSignature opSig = super.addMethodToInterfaceWithCorrespondence(opInterface.getEntityName()); - - final OperationSignature newOpSig = super.renameMethodInClassWithName(opInterface.getEntityName(), - opSig.getEntityName()); - - this.assertOperationSignature(newOpSig, opInterface, - Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME + Pcm2JavaTestUtils.RENAME); + void testRenameMethod() throws Exception { + testAddMethod(); + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + IType interfaceType = anInterface.getType(INTERFACE_NAME); + + TextEdit renameMethodEdit = JavaTextEditFactory.renameMethod(interfaceType, OPERATION_SIGNATURE_1_NAME, + OPERATION_SIGNATURE_1_NAME + RENAME); + view.getManipulationUtil().editCompilationUnit(anInterface, renameMethodEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + OperationInterface operationInterface = claimInterface(repository, INTERFACE_NAME, + OperationInterface.class); + claimNamedElement(operationInterface.getSignatures__OperationInterface(), + OPERATION_SIGNATURE_1_NAME + RENAME); + assertEquals(1, operationInterface.getSignatures__OperationInterface().size(), + "too many operation signatures"); + }); } @Test - public void testAddReturnType() throws Throwable { - this.addRepoContractsAndDatatypesPackage(); - - final OperationInterface opInterface = super.addInterfaceInContractsPackage(); - final OperationSignature opSig = super.addMethodToInterfaceWithCorrespondence(opInterface.getEntityName()); - - final OperationSignature newOpSig = this.changeReturnType(opSig); - - this.assertOperationSignature(newOpSig, opInterface, Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME); - } - - private OperationSignature changeReturnType(final OperationSignature opSig) throws Throwable { - final String className = opSig.getInterface__OperationSignature().getEntityName(); - final String methodName = opSig.getEntityName(); - final ICompilationUnit cu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, - this.getCurrentTestProject()); - final IMethod iMethod = cu.getType(className).getMethod(methodName, null); - final int returnTypeOffset = iMethod.getSourceRange().getOffset(); - final String retTypeName = iMethod.getSource().split(" ")[0]; - final int returnTypeLength = retTypeName.length(); - final String newReturnTypeName = "String "; - final DeleteEdit deleteEdit = new DeleteEdit(returnTypeOffset, returnTypeLength); - final InsertEdit insertEdit = new InsertEdit(returnTypeOffset, newReturnTypeName); - editCompilationUnit(cu, deleteEdit, insertEdit); - return super.findOperationSignatureForJaMoPPMethodInCompilationUnit(methodName, className, cu); - } - - private void assertOperationSignature(final OperationSignature opSig, final OperationInterface opInterface, - final String expectedName) throws Throwable { - assertEquals(opSig.getInterface__OperationSignature().getId(), opInterface.getId(), - "OperationSignature " + opSig + " is not in OperationInterface " + opInterface); - this.assertPCMNamedElement(opSig, expectedName); - - Method jaMoPPMethod = claimOne(getCorrespondingEObjects(opSig, Method.class)); - MethodMappingTransformationTest.this.assertDataTypeName(jaMoPPMethod.getTypeReference(), - opSig.getReturnType__OperationSignature()); + void testAddReturnType() throws Exception { + testAddMethod(); + + String changedReturnType = "String"; + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + IType interfaceType = anInterface.getType(INTERFACE_NAME); + + TextEdit changeReturnTypeEdit = JavaTextEditFactory.changeReturnTypeOfMethod(interfaceType, OPERATION_SIGNATURE_1_NAME, changedReturnType); + view.getManipulationUtil().editCompilationUnit(anInterface, changeReturnTypeEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + OperationInterface operationInterface = claimInterface(repository, INTERFACE_NAME, + OperationInterface.class); + OperationSignature operationSignature = claimNamedElement( + operationInterface.getSignatures__OperationInterface(), OPERATION_SIGNATURE_1_NAME); + assertEquals(0, operationSignature.getParameters__OperationSignature().size(), "signature must not have any parameters"); + assertEquals(changedReturnType, + getTypeNameOfPcmDataType(operationSignature.getReturnType__OperationSignature()), "signature has wrong return type"); + }); } } diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/PackageMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/PackageMappingTransformationTest.java index 9ba19a3f0..bece2b5dc 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/PackageMappingTransformationTest.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/PackageMappingTransformationTest.java @@ -1,5 +1,18 @@ package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil.claimPackage; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimComponent; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleRepository; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleSystem; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.BASIC_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.COMPOSITE_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.RENAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.REPOSITORY_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.REPOSITORY_NAME_EXPECTED; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.SYSTEM_NAME; + import org.emftext.language.java.containers.Package; import org.junit.jupiter.api.Test; import org.palladiosimulator.pcm.repository.BasicComponent; @@ -7,92 +20,116 @@ import org.palladiosimulator.pcm.repository.Repository; import org.palladiosimulator.pcm.system.System; -import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; - -import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -public class PackageMappingTransformationTest extends Java2PcmPackageMappingTransformationTest { +import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; +class PackageMappingTransformationTest extends Java2PcmTransformationTest { /** * first package is created --> should be mapped to a repository - * - * @throws Throwable */ @Test - public void testAddFirstPackage() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - assertEquals(Pcm2JavaTestUtils.REPOSITORY_NAME_EXPECTED, repo.getEntityName(), - "Name of the repository is not the same as the name of the package"); - this.assertResourceAndFileForEObjects(repo); - this.assertFilesOnlyForEObjects(repo); + void testAddFirstPackage() throws Exception { + createRepositoryPackage(); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + assertEquals(REPOSITORY_NAME_EXPECTED, repository.getEntityName(), "repository has wrong name"); + }); } /** - * second packages is added --> should be mapped to a basic component - * - * @throws Throwable + * second package is added --> should be mapped to a basic component */ @Test - public void testAddSecondPackage() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - - final BasicComponent bc = super.addSecondPackageCorrespondsToBasicComponent(); - - this.assertRepositoryAndPCMName(repo, bc, Pcm2JavaTestUtils.BASIC_COMPONENT_NAME); - this.assertFilesOnlyForEObjects(bc); + void testAddSecondPackageAsBasicComponent() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimComponent(repository, BASIC_COMPONENT_NAME, BasicComponent.class); + }); } + /** + * second package is added --> should be mapped to a composite component + */ @Test - public void testCreateCompositeComponent() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - - final CompositeComponent cc = super.addSecondPackageCorrespondsToCompositeComponent(); - - this.assertRepositoryAndPCMName(repo, cc, Pcm2JavaTestUtils.COMPOSITE_COMPONENT_NAME); - this.assertFilesOnlyForEObjects(cc); + void testAddSecondPackageAsCompositeComponent() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_COMPONENT.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, COMPOSITE_COMPONENT_NAME); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + claimComponent(repository, COMPOSITE_COMPONENT_NAME, CompositeComponent.class); + }); } + /** + * second package is added --> should be mapped to a system + */ @Test - public void testCreateSystem() throws Throwable { - final Repository repository = super.addRepoContractsAndDatatypesPackage(); - - final System system = super.addSecondPackageCorrespondsToSystem(); - - this.assertPCMNamedElement(system, Pcm2JavaTestUtils.SYSTEM_NAME); - this.assertFilesOnlyForEObjects(repository, system); + void testAddSecondPackageAsSystem() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_SYSTEM.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, SYSTEM_NAME); + }); + + validatePcmView(view -> { + System system = claimSingleSystem(view); + assertEquals(SYSTEM_NAME, system.getEntityName(), "system has wrong name"); + }); } + /** + * second package is added --> should be mapped to nothing + */ @Test - public void testCreateNoCorrespondingObject() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - - super.addSecondPackageCorrespondsWithoutCorrespondences(); - assertNotNull(repo); - // TODO:what to check? + void testAddSecondPackageAsNone() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_NOTHING_DECIDE_LATER.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + assertTrue(repository.getComponents__Repository().isEmpty(), + "there must not exist any contained Component"); + assertTrue(view.getRootObjects(System.class).isEmpty(), "there must not exist any System"); + }); } @Test - public void testRenamePackage() throws Throwable { - final Repository repo = super.addRepoContractsAndDatatypesPackage(); - super.addSecondPackageCorrespondsToBasicComponent(); - - final String packageName = Pcm2JavaTestUtils.BASIC_COMPONENT_NAME + Pcm2JavaTestUtils.RENAME; - - final Package renamedPackage = super.renamePackage(this.secondPackage, packageName); - - final BasicComponent bc = claimOne(getCorrespondingEObjects(renamedPackage, BasicComponent.class)); - // repository of basic component has to be the repository - assertEquals(repo.getId(), bc.getRepository__RepositoryComponent().getId(), - "Repository of basic compoennt is not the repository: " + repo); - // name should be changed since there is no implementing class (yet) for the - // component - assertTrue(packageName.toLowerCase().contains(bc.getEntityName().toLowerCase()), - "The name of the basic component, which is '" + bc.getEntityName() - + "', is not contained in the name of the package: " + packageName + " "); - this.assertResourceAndFileForEObjects(bc); + void testRenameRepository() throws Exception { + createRepositoryPackage(); + + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); + + String changedPackageName = BASIC_COMPONENT_NAME + RENAME; + + changeJavaEditorView(view -> { + Package innerPackage = claimPackage(view, BASIC_COMPONENT_NAME); + view.getManipulationUtil().renamePackage(innerPackage, changedPackageName); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + assertEquals(1, repository.getComponents__Repository().size(), "wrong number of components in repository"); + claimComponent(repository, changedPackageName, BasicComponent.class); + }); } } diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ParameterMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ParameterMappingTransformationTest.java new file mode 100644 index 000000000..4232e0752 --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/ParameterMappingTransformationTest.java @@ -0,0 +1,126 @@ +package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; + +import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.claimOne; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil.claimPackage; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimInterface; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimNamedElement; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleRepository; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.INTERFACE_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.PARAMETER_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.RENAME; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IType; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.containers.Package; +import org.junit.jupiter.api.Test; +import org.palladiosimulator.pcm.repository.OperationInterface; +import org.palladiosimulator.pcm.repository.OperationSignature; +import org.palladiosimulator.pcm.repository.Parameter; +import org.palladiosimulator.pcm.repository.Repository; + +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory; + +class ParameterMappingTransformationTest extends Java2PcmTransformationTest { + private static final String PARAMETER_TYPE = "String"; + + @Test + void testAddParameter() throws Exception { + createRepositoryPackage(); + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + view.getManipulationUtil().createInterface(INTERFACE_NAME, contractsPackage, null); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + IType interfaceType = anInterface.getType(INTERFACE_NAME); + + TextEdit addMethodEdit = JavaTextEditFactory.addMethodSignature(interfaceType, "void", + OPERATION_SIGNATURE_1_NAME); + view.getManipulationUtil().editCompilationUnit(anInterface, addMethodEdit); + }); + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + IType interfaceType = anInterface.getType(INTERFACE_NAME); + + TextEdit addParameterEdit = JavaTextEditFactory.addMethodParameter(interfaceType, + OPERATION_SIGNATURE_1_NAME, PARAMETER_NAME, PARAMETER_TYPE); + view.getManipulationUtil().editCompilationUnit(anInterface, addParameterEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + OperationInterface anInterface = claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + OperationSignature operationSignature = claimNamedElement(anInterface.getSignatures__OperationInterface(), + OPERATION_SIGNATURE_1_NAME); + Parameter parameter = claimOne(operationSignature.getParameters__OperationSignature()); + assertEquals(PARAMETER_NAME, parameter.getParameterName(), "invalid parameter name"); + assertEquals(PARAMETER_TYPE, getTypeNameOfPcmDataType(parameter.getDataType__Parameter()), + "invalid parameter type"); + }); + } + + @Test + void testRenameParameter() throws Exception { + testAddParameter(); + + String changedParameterName = PARAMETER_NAME + RENAME; + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + IType interfaceType = anInterface.getType(INTERFACE_NAME); + + TextEdit renameParameterEdit = JavaTextEditFactory.renameMethodParameter(interfaceType, + OPERATION_SIGNATURE_1_NAME, PARAMETER_NAME, changedParameterName); + view.getManipulationUtil().editCompilationUnit(anInterface, renameParameterEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + OperationInterface anInterface = claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + OperationSignature operationSignature = claimNamedElement(anInterface.getSignatures__OperationInterface(), + OPERATION_SIGNATURE_1_NAME); + Parameter parameter = claimOne(operationSignature.getParameters__OperationSignature()); + assertEquals(changedParameterName, parameter.getParameterName(), "invalid parameter name"); + assertEquals(PARAMETER_TYPE, getTypeNameOfPcmDataType(parameter.getDataType__Parameter()), + "invalid parameter type"); + }); + } + + @Test + void testChangeParameterType() throws Exception { + testAddParameter(); + + String changedParameterType = "int"; + + changeJavaEditorView(view -> { + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + IType interfaceType = anInterface.getType(INTERFACE_NAME); + + TextEdit changeParameterTypeEdit = JavaTextEditFactory.changeParameterType(interfaceType, + OPERATION_SIGNATURE_1_NAME, PARAMETER_NAME, changedParameterType); + view.getManipulationUtil().editCompilationUnit(anInterface, changeParameterTypeEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + OperationInterface anInterface = claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + OperationSignature operationSignature = claimNamedElement(anInterface.getSignatures__OperationInterface(), + OPERATION_SIGNATURE_1_NAME); + Parameter parameter = claimOne(operationSignature.getParameters__OperationSignature()); + assertEquals(PARAMETER_NAME, parameter.getParameterName(), "invalid parameter name"); + assertEquals(changedParameterType, getTypeNameOfPcmDataType(parameter.getDataType__Parameter()), + "invalid parameter type"); + }); + } +} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/SynchronizationAwaitCallback.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/SynchronizationAwaitCallback.java deleted file mode 100644 index 754116093..000000000 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/SynchronizationAwaitCallback.java +++ /dev/null @@ -1,5 +0,0 @@ -package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; - -public interface SynchronizationAwaitCallback { - void waitForSynchronization(int numberOfExpectedSynchronizationCalls); -} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/TypeReferenceMappingTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/TypeReferenceMappingTransformationTest.java index 6eaee7424..4fda9b41e 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/TypeReferenceMappingTransformationTest.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/TypeReferenceMappingTransformationTest.java @@ -1,37 +1,76 @@ package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil.claimPackage; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimComponent; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimInterface; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimNamedElement; +import static tools.vitruv.applications.pcmjava.javaeditor.util.PcmQueryUtil.claimSingleRepository; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.BASIC_COMPONENT_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.IMPLEMENTING_CLASS_SUFFIX; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.INTERFACE_NAME; +import static tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils.REPOSITORY_NAME; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IType; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.containers.Package; import org.junit.jupiter.api.Test; import org.palladiosimulator.pcm.repository.BasicComponent; import org.palladiosimulator.pcm.repository.OperationInterface; import org.palladiosimulator.pcm.repository.OperationProvidedRole; +import org.palladiosimulator.pcm.repository.Repository; import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaQueryUtil; +import tools.vitruv.applications.pcmjava.javaeditor.util.JavaTextEditFactory; import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; -import static org.junit.jupiter.api.Assertions.assertEquals; +class TypeReferenceMappingTransformationTest extends Java2PcmTransformationTest { + @Test + void testAddImplementsToClassCorrespondingToBasicComponent() throws Exception { + createRepositoryPackage(); -public class TypeReferenceMappingTransformationTest extends Java2PcmPackageMappingTransformationTest { + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaView(view -> { + createPackageWithPackageInfo(view, REPOSITORY_NAME, BASIC_COMPONENT_NAME); + }); - @Test - public void testAddImplementsToClassWithCorrespondingComponent() throws Throwable { - // create repo - this.addRepoContractsAndDatatypesPackage(); - // create class - this.addSecondPackageCorrespondsWithoutCorrespondences(); - this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); - final BasicComponent basicComponent = this.addClassInSecondPackage(BasicComponent.class); - // create interface - final OperationInterface opInterface = this.createInterfaceInPackageBasedOnJaMoPPPackageWithCorrespondence( - "contracts", Pcm2JavaTestUtils.INTERFACE_NAME); - - // add the implement relation - final OperationProvidedRole opr = super.addImplementsCorrespondingToOperationProvidedRoleToClass( - basicComponent.getEntityName() + "Impl", opInterface.getEntityName()); - - assertEquals(opr.getProvidedInterface__OperationProvidedRole().getId(), opInterface.getId(), - "The interface proivieded by the provided role is not the expected interface"); - assertEquals(opr.getProvidingEntity_ProvidedRole().getId(), basicComponent.getId(), - "The component that provides the interface is not the expected component"); - } + getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + view.getManipulationUtil().createClass(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, componentPackage, + null); + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + view.getManipulationUtil().createInterface(INTERFACE_NAME, contractsPackage, null); + }); + + changeJavaEditorView(view -> { + Package componentPackage = claimPackage(view, BASIC_COMPONENT_NAME); + ICompilationUnit componentClass = view.getManipulationUtil() + .claimCompilationUnit(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX, componentPackage); + + Package contractsPackage = claimPackage(view, JavaQueryUtil.CONTRACTS_PACKAGE); + ICompilationUnit anInterface = view.getManipulationUtil().claimCompilationUnit(INTERFACE_NAME, + contractsPackage); + view.getManipulationUtil().addImportToCompilationUnit(componentClass, anInterface, INTERFACE_NAME); + + IType classType = componentClass.getType(BASIC_COMPONENT_NAME + IMPLEMENTING_CLASS_SUFFIX); + TextEdit implementsEdit = JavaTextEditFactory.addImplementsRelation(classType, INTERFACE_NAME); + view.getManipulationUtil().editCompilationUnit(componentClass, implementsEdit); + }); + + validatePcmView(view -> { + Repository repository = claimSingleRepository(view); + BasicComponent component = claimComponent(repository, BASIC_COMPONENT_NAME, BasicComponent.class); + OperationInterface anInterface = claimInterface(repository, INTERFACE_NAME, OperationInterface.class); + OperationProvidedRole providedRole = claimNamedElement( + component.getProvidedRoles_InterfaceProvidingEntity(), + Pcm2JavaTestUtils.providesInterfaceName(BASIC_COMPONENT_NAME, INTERFACE_NAME), + OperationProvidedRole.class); + assertEquals(anInterface, providedRole.getProvidedInterface__OperationProvidedRole(), + "incorrect provided interface"); + }); + } } diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/CompilationUnitManipulatorHelper.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/legacy/CompilationUnitManipulatorHelper.java similarity index 97% rename from tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/CompilationUnitManipulatorHelper.java rename to tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/legacy/CompilationUnitManipulatorHelper.java index 9d0164cb4..53251e913 100644 --- a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/CompilationUnitManipulatorHelper.java +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/legacy/CompilationUnitManipulatorHelper.java @@ -1,4 +1,4 @@ -package tools.vitruv.applications.pcmjava.javaeditor.java2pcm; +package tools.vitruv.applications.pcmjava.javaeditor.java2pcm.legacy; import org.eclipse.core.resources.IProject; import org.eclipse.jdt.core.ICompilationUnit; diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/legacy/Java2PcmTransformationTest.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/legacy/Java2PcmTransformationTest.java new file mode 100644 index 000000000..cb544b115 --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/java2pcm/legacy/Java2PcmTransformationTest.java @@ -0,0 +1,939 @@ +package tools.vitruv.applications.pcmjava.javaeditor.java2pcm.legacy; + +import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.claimOne; +import static edu.kit.ipd.sdq.commons.util.org.eclipse.emf.common.util.URIUtil.createPlatformResourceURI; +import static edu.kit.ipd.sdq.commons.util.org.eclipse.emf.ecore.resource.ResourceSetUtil.loadOrCreateResource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static tools.vitruv.applications.util.temporary.java.JavaQueryUtil.getNameFromJaMoPPType; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.apache.log4j.Logger; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.ResourceSet; +import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; +import org.eclipse.jdt.core.IBuffer; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; +import org.eclipse.jdt.internal.core.manipulation.StubUtility; +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringContribution; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.text.edits.InsertEdit; +import org.eclipse.text.edits.ReplaceEdit; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.classifiers.Classifier; +import org.emftext.language.java.classifiers.ConcreteClassifier; +import org.emftext.language.java.classifiers.Interface; +import org.emftext.language.java.containers.CompilationUnit; +import org.emftext.language.java.containers.ContainersFactory; +import org.emftext.language.java.containers.ContainersPackage; +import org.emftext.language.java.containers.JavaRoot; +import org.emftext.language.java.containers.Package; +import org.emftext.language.java.members.ClassMethod; +import org.emftext.language.java.members.Field; +import org.emftext.language.java.members.Member; +import org.emftext.language.java.members.Method; +import org.emftext.language.java.modifiers.AnnotableAndModifiable; +import org.emftext.language.java.types.TypeReference; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.palladiosimulator.pcm.core.entity.NamedElement; +import org.palladiosimulator.pcm.repository.BasicComponent; +import org.palladiosimulator.pcm.repository.CollectionDataType; +import org.palladiosimulator.pcm.repository.CompositeComponent; +import org.palladiosimulator.pcm.repository.CompositeDataType; +import org.palladiosimulator.pcm.repository.DataType; +import org.palladiosimulator.pcm.repository.OperationInterface; +import org.palladiosimulator.pcm.repository.OperationProvidedRole; +import org.palladiosimulator.pcm.repository.OperationSignature; +import org.palladiosimulator.pcm.repository.Parameter; +import org.palladiosimulator.pcm.repository.PrimitiveDataType; +import org.palladiosimulator.pcm.repository.Repository; +import org.palladiosimulator.pcm.repository.RepositoryComponent; +import org.palladiosimulator.pcm.seff.ResourceDemandingSEFF; +import org.palladiosimulator.pcm.system.System; + +import edu.kit.ipd.sdq.commons.util.org.eclipse.core.resources.IProjectUtil; +import edu.kit.ipd.sdq.commons.util.org.eclipse.emf.common.util.URIUtil; +import tools.vitruv.applications.pcmjava.java2pcm.Java2PcmUserSelection; +import tools.vitruv.applications.pcmjava.pcm2java.Pcm2JavaTestUtils; +import tools.vitruv.applications.util.temporary.java.JavaSetup; +import tools.vitruv.change.composite.description.VitruviusChange; +import tools.vitruv.change.propagation.ChangePropagationMode; +import tools.vitruv.framework.views.changederivation.DefaultStateBasedChangeResolutionStrategy; +import tools.vitruv.framework.views.changederivation.StateBasedChangeResolutionStrategy; +import tools.vitruv.testutils.LegacyVitruvApplicationTest; +import tools.vitruv.testutils.TestProject; +import tools.vitruv.testutils.views.UriMode; + +/** + * Test class that contains utility methods that can be used by JaMoPP2PCM + * transformation tests + * + */ +@SuppressWarnings("restriction") +public abstract class Java2PcmTransformationTest extends LegacyVitruvApplicationTest { + private static final Logger logger = Logger.getLogger(Java2PcmTransformationTest.class); + private static final int MAXIMUM_EDIT_WAITING_TIME = 5000; + + protected Package mainPackage; + protected Package secondPackage; + + private IProject testEclipseProject; + + private Map oldToNewURIsOfModifiedResources; + private volatile boolean isWaitingForFinishingsEdits = false; + + protected IProject getCurrentTestProject() { + return testEclipseProject; + } + + /* + * JDT functionality requires platform URIs. + */ + @Override + protected UriMode getUriMode() { + return UriMode.PLATFORM_URIS; + } + + private void refreshProject() { + try { + testEclipseProject.refreshLocal(IResource.DEPTH_INFINITE, null); + } catch (CoreException e) { + String message = "Could not refresh project " + testEclipseProject.getName(); + logger.error(message, e); + } + } + + @BeforeAll + public static void setupJavaFactories() { + JavaSetup.prepareFactories(); + } + + @BeforeEach + public void setupJavaProject(@TestProject Path testProjectFolder) { + String projectName = testProjectFolder.getFileName().toString(); + testEclipseProject = IProjectUtil.createProjectAt(projectName, testProjectFolder); + IProjectUtil.configureAsJavaProject(testEclipseProject); + JavaSetup.resetClasspathAndRegisterStandardLibrary(); + } + + @BeforeEach + public void disableTransitiveChangePropagation() { + this.getVirtualModel().setChangePropagationMode(ChangePropagationMode.SINGLE_STEP); + } + + @BeforeEach + public void cleanupModifiedResources() { + this.oldToNewURIsOfModifiedResources = new HashMap<>(); + } + + @AfterEach + public void closeJavaProject() throws JavaModelException, CoreException { + getIJavaProject().close(); + } + + private void saveCurrentStateOfRenamedResourceAndRegisterForChangePropagation(final URI resourceURI, + final URI newResourceURI) { + oldToNewURIsOfModifiedResources.put(resourceURI, newResourceURI); + // Access the resource such that the initial state is present in the test view + resourceAt(resourceURI); + } + + private void saveCurrentStateOfResourceAndRegisterForSynchronization(final URI resourceURI) { + saveCurrentStateOfRenamedResourceAndRegisterForChangePropagation(resourceURI, resourceURI); + } + + private Resource loadResourceIndependentFromView(final URI resourceURI) { + ResourceSet resourceSet = new ResourceSetImpl(); + Resource resource = loadOrCreateResource(resourceSet, resourceURI); + return resource; + } + + protected Package createPackageWithPackageInfo(final String... namespace) throws IOException { + String packageFile = String.join("/", namespace); + packageFile = packageFile + "/package-info.java"; + final Package jaMoPPPackage = ContainersFactory.eINSTANCE.createPackage(); + final List namespaceList = Arrays.asList(namespace); + jaMoPPPackage.setName(namespaceList.get(namespaceList.size() - 1)); + jaMoPPPackage.getNamespaces().addAll(namespaceList.subList(0, namespaceList.size() - 1)); + URI createPackageURI = getUri(Path.of(getPathInProjectForSrcFile(packageFile))); + saveCurrentStateOfResourceAndRegisterForSynchronization(createPackageURI); + final Resource resource = loadResourceIndependentFromView(createPackageURI); + resource.getContents().add(jaMoPPPackage); + resource.save(null); + propagateChanges(); + return jaMoPPPackage; + } + + private ICompilationUnit createCompilationUnit(IPackageFragment packageFragment, String cuName) + throws JavaModelException { + URI createdCompilationUnitURI = getURIForElementInPackage(packageFragment, cuName); + saveCurrentStateOfResourceAndRegisterForSynchronization(createdCompilationUnitURI); + ICompilationUnit compilationUnit = packageFragment.createCompilationUnit(cuName + ".java", "", false, null); + return compilationUnit; + } + + public void editCompilationUnit(final ICompilationUnit cu, final TextEdit... edits) throws JavaModelException { + saveCurrentStateOfResourceAndRegisterForSynchronization(URIUtil.createPlatformResourceURI(cu.getResource())); + cu.becomeWorkingCopy(new NullProgressMonitor()); + for (final TextEdit edit : edits) { + cu.applyTextEdit(edit, null); + } + cu.reconcile(ICompilationUnit.NO_AST, false, null, null); + cu.commitWorkingCopy(false, new NullProgressMonitor()); + cu.discardWorkingCopy(); + cu.save(new NullProgressMonitor() { + public void done() { + Java2PcmTransformationTest.this.isWaitingForFinishingsEdits = false; + Java2PcmTransformationTest.this.notifyAll(); + } + }, true); + propagateChanges(); + } + + public void propagateChanges() { + logger.debug("Starting to wait for edits to be finished"); + try { + if (isWaitingForFinishingsEdits) { + wait(MAXIMUM_EDIT_WAITING_TIME); + if (isWaitingForFinishingsEdits) { + logger.error("Waiting for edits timed out in project " + testEclipseProject.getName()); + fail("Waiting for edits timed out"); + } + } + } catch (InterruptedException e) { + fail("An interrupt occurred unexpectedly"); + } + refreshProject(); + StateBasedChangeResolutionStrategy changeResolutionStrategy = new DefaultStateBasedChangeResolutionStrategy(); + for (Entry modifiedResourceURI : oldToNewURIsOfModifiedResources.entrySet()) { + Resource currentResource = loadResourceIndependentFromView(modifiedResourceURI.getValue()); + VitruviusChange change = changeResolutionStrategy.getChangeSequenceBetween(currentResource, + resourceAt(modifiedResourceURI.getKey())); + VitruviusChange unresolvedChange = change.unresolve(); + record(resourceAt(modifiedResourceURI.getKey()).getResourceSet(), + resourceSet -> unresolvedChange.resolveAndApply(resourceSet)); + } + oldToNewURIsOfModifiedResources.clear(); + propagate(); + disposeViewResources(); + } + + protected Repository addRepoContractsAndDatatypesPackage() throws IOException, CoreException { + this.mainPackage = this.createPackageWithPackageInfo(new String[] { Pcm2JavaTestUtils.REPOSITORY_NAME }); + final Repository repo = claimOne(getCorrespondingEObjects(this.mainPackage, Repository.class)); + return repo; + } + + protected BasicComponent addSecondPackageCorrespondsToBasicComponent() throws Throwable { + this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + return this.createSecondPackage(BasicComponent.class, Pcm2JavaTestUtils.REPOSITORY_NAME, + Pcm2JavaTestUtils.BASIC_COMPONENT_NAME); + } + + protected T createSecondPackage(final Class correspondingType, final String... namespace) + throws Throwable { + this.secondPackage = this.createPackageWithPackageInfo(namespace); + return claimOne(getCorrespondingEObjects(this.secondPackage, correspondingType)); + } + + private void createSecondPackageWithoutCorrespondence(final String... namespace) throws Throwable { + this.secondPackage = this.createPackageWithPackageInfo(namespace); + } + + protected Package renamePackage(final Package packageToRename, final String newName) throws CoreException { + final Resource resource = packageToRename.eResource(); + final IFile iFile = URIUtil.getIFileForEMFUri(resource.getURI()); + IPath iPath = iFile.getProjectRelativePath(); + iPath = iPath.removeLastSegments(1); + final String newQualifiedName = packageToRename.getNamespacesAsString() + newName; + final IFolder iFolder = iFile.getProject().getFolder(iPath); + final IJavaElement javaPackage = JavaCore.create(iFolder); + String packageFile = String.join("/", packageToRename.getNamespaces()); + packageFile = packageFile + "/" + newName + "/package-info.java"; + saveCurrentStateOfRenamedResourceAndRegisterForChangePropagation(resource.getURI(), + getUri(Path.of(getPathInProjectForSrcFile(packageFile)))); + this.refactorRenameJavaElement(newQualifiedName, javaPackage, IJavaRefactorings.RENAME_PACKAGE); + final Package newPackage = this.findJaMoPPPackageWithName(newQualifiedName); + return newPackage; + } + + private void refactorRenameJavaElement(final String newName, final IJavaElement iJavaElement, + final String refactorRenameActionName) throws CoreException { + final RefactoringContribution refacContrib = RefactoringCore + .getRefactoringContribution(refactorRenameActionName); + final RefactoringStatus status = new RefactoringStatus(); + final RenameJavaElementDescriptor desc = (RenameJavaElementDescriptor) refacContrib.createDescriptor(); + desc.setUpdateReferences(true); + desc.setJavaElement(iJavaElement); + desc.setNewName(newName); + final NullProgressMonitor monitor = new NullProgressMonitor(); + final Refactoring refactoring = desc.createRefactoring(status); + refactoring.checkInitialConditions(monitor); + refactoring.checkFinalConditions(monitor); + final Change change = refactoring.createChange(monitor); + change.perform(monitor); + propagateChanges(); + } + + protected T renameClassifierWithName(final String entityName, final String newName, + final Class type) throws Throwable { + try { + final ICompilationUnit cu = CompilationUnitManipulatorHelper + .findICompilationUnitWithClassName(entityName + ".java", this.getCurrentTestProject()); + final int offset = cu.getBuffer().getContents().indexOf(entityName); + if (cu.getBuffer() instanceof IBuffer.ITextEditCapability) { + logger.info(cu.getBuffer()); + } + final ReplaceEdit edit = new ReplaceEdit(offset, entityName.length(), newName); + editCompilationUnit(cu, edit); + final URI uri = createPlatformResourceURI(cu.getResource()); + final Classifier jaMoPPClass = this.getJaMoPPClassifierForURI(uri); + return claimOne(getCorrespondingEObjects(jaMoPPClass, type)); + } catch (final Throwable e) { + logger.warn(e.getMessage()); + } + return null; + + } + + private Package findJaMoPPPackageWithName(final String newName) throws JavaModelException { + final IJavaProject javaProject = JavaCore.create(this.getCurrentTestProject()); + for (final IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) { + final IJavaElement[] children = packageFragmentRoot.getChildren(); + for (final IJavaElement iJavaElement : children) { + if (iJavaElement instanceof IPackageFragment) { + final IPackageFragment fragment = (IPackageFragment) iJavaElement; + if (fragment.getElementName().equals(newName)) { + final URI uri = this.getURIForElementInPackage(fragment, "package-info"); + final Package jaMoPPPackage = this.getJaMoPPRootForURI(uri); + return jaMoPPPackage; + } + } + } + } + throw new RuntimeException("Could not find a compilation unit with name " + newName); + } + + private IPackageFragmentRoot getIJavaProject() throws CoreException { + final IProject project = this.getCurrentTestProject(); + final IJavaProject javaProject = JavaCore.create(project); + final IFolder sourceFolder = project.getFolder("src"); + if (!sourceFolder.exists()) { + final boolean force = true; + final boolean local = true; + sourceFolder.create(force, local, new NullProgressMonitor()); + } + final IPackageFragmentRoot packageFragment = javaProject.getPackageFragmentRoot(sourceFolder); + return packageFragment; + } + + private String getPathInProjectForSrcFile(final String srcFilePath) { + return "src/" + srcFilePath; + } + + protected T addClassInSecondPackage(final Class classOfCorrespondingObject) + throws Throwable { + final T createdEObject = this.addClassInPackage(this.secondPackage, classOfCorrespondingObject); + return createdEObject; + } + + protected T addClassInPackage(final Package packageForClass, + final Class classOfCorrespondingObject) throws Throwable { + final String implementingClassName = Pcm2JavaTestUtils.IMPLEMENTING_CLASS_NAME; + return this.addClassInPackage(packageForClass, classOfCorrespondingObject, implementingClassName); + } + + protected T addClassInPackage(final Package packageForClass, + final Class classOfCorrespondingObject, final String implementingClassName) + throws CoreException, InterruptedException { + final Classifier jaMoPPClass = this.createClassInPackage(packageForClass, implementingClassName); + final Iterable eObjectsByType = getCorrespondingEObjects(jaMoPPClass, classOfCorrespondingObject); + return claimOne(eObjectsByType); + } + + protected Classifier createClassInPackage(final Package packageForClass, final String implementingClassName) + throws CoreException { + String packageName = packageForClass.getName(); + String packageNamespace = packageForClass.getNamespacesAsString() + packageName; + return createClassInPackage(implementingClassName, packageNamespace); + } + + protected Classifier createClassInPackage(final String implementingClassName, String packageNamespace) + throws CoreException { + final IPackageFragment packageFragment = this.getPackageFragment(packageNamespace); + createEmptyClass(packageFragment, implementingClassName); + final URI uri = this.getURIForElementInPackage(packageFragment, implementingClassName); + final Classifier jaMoPPClass = this.getJaMoPPClassifierForURI(uri); + return jaMoPPClass; + } + + private URI getURIForElementInPackage(final IPackageFragment packageFragment, final String elementName) { + String uriString = packageFragment.getResource().getFullPath().toString() + "/" + elementName + ".java"; + return URI.createPlatformResourceURI(uriString, true); + } + + private IPackageFragment getPackageFragment(String packageNamespace) throws CoreException { + final IPackageFragmentRoot packageRoot = this.getIJavaProject(); + for (final IJavaElement javaElement : packageRoot.getChildren()) { + if (javaElement instanceof IPackageFragment && javaElement.getElementName().equals(packageNamespace)) { + return (IPackageFragment) javaElement; + } + } + throw new RuntimeException("No packageFragment found for JaMoPP package " + packageNamespace); + } + + protected ConcreteClassifier getJaMoPPClassifierForURI(final URI uri) { + final CompilationUnit cu = this.getJaMoPPRootForURI(uri); + final Classifier jaMoPPClassifier = cu.getClassifiers().get(0); + return (ConcreteClassifier) jaMoPPClassifier; + } + + private T getJaMoPPRootForURI(final URI uri) { + final Resource resource = new ResourceSetImpl().getResource(uri, true); + // unchecked is OK for the test. + @SuppressWarnings("unchecked") + final T javaRoot = (T) resource.getContents().get(0); + return javaRoot; + } + + protected CompositeComponent addSecondPackageCorrespondsToCompositeComponent() throws Throwable { + this.getUserInteraction() + .addNextSingleSelection(Java2PcmUserSelection.SELECT_COMPOSITE_COMPONENT.getSelection()); + return this.createSecondPackage(CompositeComponent.class, Pcm2JavaTestUtils.REPOSITORY_NAME, + Pcm2JavaTestUtils.COMPOSITE_COMPONENT_NAME); + } + + protected org.palladiosimulator.pcm.system.System addSecondPackageCorrespondsToSystem() throws Throwable { + this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_SYSTEM.getSelection()); + return this.createSecondPackage(System.class, Pcm2JavaTestUtils.SYSTEM_NAME); + } + + protected void addSecondPackageCorrespondsWithoutCorrespondences() throws Throwable { + this.getUserInteraction() + .addNextSingleSelection(Java2PcmUserSelection.SELECT_NOTHING_DECIDE_LATER.getSelection()); + this.createSecondPackageWithoutCorrespondence(Pcm2JavaTestUtils.REPOSITORY_NAME, + Pcm2JavaTestUtils.BASIC_COMPONENT_NAME); + } + + protected void assertRepositoryAndPCMName(final Repository repo, final RepositoryComponent repoComponent, + final String expectedName) throws Throwable { + + assertEquals(repo.getId(), repoComponent.getRepository__RepositoryComponent().getId(), + "Repository of compoennt is not the repository: " + repo); + + this.assertPCMNamedElement(repoComponent, expectedName); + } + + protected void assertResourceAndFileForEObjects(final EObject... eObjects) throws Throwable { + for (final EObject eObject : eObjects) { + final Resource eResource = eObject.eResource(); + assertNotNull(eResource, "Resource of eObject " + eObject + " is null"); + final IFile iFile = URIUtil.getIFileForEMFUri(eResource.getURI()); + assertTrue(iFile.exists(), "No IFile for eObject " + eObject + " in resource " + eResource + " found."); + } + } + + protected void assertFilesOnlyForEObjects(final EObject... eObjects) throws Throwable { + final Set fullFilePaths = new HashSet(); + for (final EObject eObject : eObjects) { + final IFile iFile = URIUtil.getIFileForEMFUri(eObject.eResource().getURI()); + fullFilePaths.add(iFile.getFullPath().toString()); + } + final IFolder folder = this.getCurrentTestProject().getFolder("model"); + final List foundAdditionalFiles = new ArrayList<>(); + for (final IResource iResource : folder.members()) { + final String iResourcePath = iResource.getFullPath().toString(); + if (!fullFilePaths.contains(iResourcePath)) { + foundAdditionalFiles.add(iResourcePath); + } + } + if (0 < foundAdditionalFiles.size()) { + final StringBuilder failMsg = new StringBuilder("Found addtional files in model folder: "); + foundAdditionalFiles.forEach(str -> failMsg.append(str).append(", ")); + fail(failMsg.toString()); + } + } + + protected void assertRepositoryAndPCMNameForDatatype(final Repository repo, final DataType dt, + final String expectedName) throws Throwable { + + assertEquals(repo.getId(), dt.getRepository__DataType().getId(), + "Repository of compoennt is not the repository: " + repo); + if (dt instanceof CompositeDataType) { + this.assertPCMNamedElement((CompositeDataType) dt, expectedName); + } else if (dt instanceof CollectionDataType) { + this.assertPCMNamedElement((CollectionDataType) dt, expectedName); + } else { + throw new RuntimeException("Primitive data types should not have a correspondence to classes"); + } + } + + protected void assertPCMNamedElement(final NamedElement pcmNamedElement, final String expectedName) + throws Throwable { + assertEquals(expectedName, pcmNamedElement.getEntityName(), + "The name of pcm named element is not " + expectedName); + this.assertResourceAndFileForEObjects(pcmNamedElement); + } + + protected void assertPcmParameter(final Parameter pcmParameter, final String expectedName) throws Throwable { + assertEquals(expectedName, pcmParameter.getParameterName(), "The name of pcm parameter is not " + expectedName); + this.assertResourceAndFileForEObjects(pcmParameter); + } + + protected OperationInterface addInterfaceInContractsPackage() throws Throwable { + return this.createInterfaceInPackage("contracts"); + } + + private OperationInterface createInterfaceInPackage(final String packageName) + throws Throwable, CoreException, InterruptedException { + final String interfaceName = Pcm2JavaTestUtils.INTERFACE_NAME; + return this.createInterfaceInPackageBasedOnJaMoPPPackageWithCorrespondence(packageName, interfaceName); + } + + protected OperationInterface createInterfaceInPackageBasedOnJaMoPPPackageWithCorrespondence( + final String packageName, final String interfaceName) throws CoreException { + Package jaMoPPPackage = this.getPackageWithNameFromCorrespondenceModel(packageName); + return this.createInterfaceInPackage(jaMoPPPackage.getNamespacesAsString() + jaMoPPPackage.getName(), + interfaceName, true); + } + + protected ConcreteClassifier createInterfaceInPackageBasedOnJaMoPPPackageWithoutCorrespondence( + final String packageName, final String interfaceName) + throws Throwable, CoreException, InterruptedException { + Package jaMoPPPackage = this.getPackageWithNameFromCorrespondenceModel(packageName); + return this.createJaMoPPInterfaceInPackage(jaMoPPPackage.getNamespacesAsString() + jaMoPPPackage.getName(), + interfaceName); + } + + protected OperationInterface createInterfaceInPackage(String packageNamespace, final String interfaceName, + boolean claimOne) throws CoreException { + final Classifier jaMoPPIf = createJaMoPPInterfaceInPackage(packageNamespace, interfaceName); + Iterable correspondingOpInterfaces = getCorrespondingEObjects(jaMoPPIf, + OperationInterface.class); + if (claimOne) { + return claimOne(correspondingOpInterfaces); + } + if (null == correspondingOpInterfaces || !correspondingOpInterfaces.iterator().hasNext()) { + return null; + } + logger.warn("More than one corresponding interfaces found for interface " + jaMoPPIf + ". Returning the first"); + return correspondingOpInterfaces.iterator().next(); + } + + protected ConcreteClassifier createJaMoPPInterfaceInPackage(String packageNamespace, final String interfaceName) + throws CoreException { + final IPackageFragment packageFragment = this.getPackageFragment(packageNamespace); + createEmptyInterface(packageFragment, interfaceName); + final URI uri = this.getURIForElementInPackage(packageFragment, interfaceName); + final ConcreteClassifier jaMoPPIf = this.getJaMoPPClassifierForURI(uri); + + return jaMoPPIf; + } + + private void createEmptyCompilationUnit(IPackageFragment packageFragment, String typeName, String cuName) + throws JavaModelException { + String lineDelimiter = null; + lineDelimiter = StubUtility.getLineDelimiterUsed(packageFragment.getJavaProject()); + ICompilationUnit compilationUnit = createCompilationUnit(packageFragment, cuName); + InsertEdit edit = new InsertEdit(0, "package " + packageFragment.getElementName() + ";" + lineDelimiter + + lineDelimiter + "public " + typeName + " " + cuName + " { }"); + editCompilationUnit(compilationUnit, edit); + } + + protected void createEmptyInterface(IPackageFragment packageFragment, String interfaceName) + throws JavaModelException { + createEmptyCompilationUnit(packageFragment, "interface", interfaceName); + } + + protected void createEmptyClass(IPackageFragment packageFragment, String className) throws JavaModelException { + createEmptyCompilationUnit(packageFragment, "class", className); + } + + protected OperationInterface addInterfaceInSecondPackageWithCorrespondence(final String packageName) + throws Throwable { + this.getUserInteraction() + .addNextSingleSelection(Java2PcmUserSelection.SELECT_CREATE_INTERFACE_NOT_IN_CONTRACTS.getSelection()); + return this.createInterfaceInPackage(packageName); + } + + protected EObject addInterfaceInPackageWithoutCorrespondence(final String packageName) throws Throwable { + this.getUserInteraction().addNextSingleSelection( + Java2PcmUserSelection.SELECT_DONT_CREATE_INTERFACE_NOT_IN_CONTRACTS.getSelection()); + Package jaMoPPPackage = this.getPackageWithNameFromCorrespondenceModel(packageName); + return this.createInterfaceInPackage(jaMoPPPackage.getNamespacesAsString() + jaMoPPPackage.getName(), + "I" + packageName, false); + } + + protected Package getPackageWithNameFromCorrespondenceModel(final String name) throws CoreException { + final Iterable packages = getCorrespondingEObjects(ContainersPackage.Literals.PACKAGE, Package.class); + for (final Package currentPackage : packages) { + if (currentPackage.getName().equals(name)) { + return currentPackage; + } + } + throw new RuntimeException("Could not find package with name " + name); + } + + protected OperationSignature addMethodToInterfaceWithCorrespondence(final String interfaceName) throws Throwable { + final String methodName = Pcm2JavaTestUtils.OPERATION_SIGNATURE_1_NAME; + return this.addMethodToInterfaceWithCorrespondence(interfaceName, methodName); + } + + protected OperationSignature addMethodToInterfaceWithCorrespondence(final String interfaceName, + final String methodName) throws Throwable, JavaModelException { + final String methodString = "\nvoid " + methodName + "();\n"; + final ICompilationUnit cu = addMethodToCompilationUnit(interfaceName, methodString, + this.getCurrentTestProject()); + return this.findOperationSignatureForJaMoPPMethodInCompilationUnit(methodName, interfaceName, cu); + } + + protected ResourceDemandingSEFF addClassMethodToClassThatOverridesInterfaceMethod(final String className, + final String methodName) throws Throwable { + final String methodString = "\n\tpublic void " + methodName + " () {\n\t}\n"; + final ICompilationUnit icu = addMethodToCompilationUnit(className, methodString, this.getCurrentTestProject()); + final Method jaMoPPMethod = this.findJaMoPPMethodInICU(icu, methodName); + final ClassMethod classMethod = (ClassMethod) jaMoPPMethod; + return claimOne(getCorrespondingEObjects(classMethod, ResourceDemandingSEFF.class)); + } + + protected OperationSignature findOperationSignatureForJaMoPPMethodInCompilationUnit(final String methodName, + final String interfaceName, final ICompilationUnit cu) throws Throwable { + final URI uri = createPlatformResourceURI(cu.getResource()); + final Classifier classifier = this.getJaMoPPClassifierForURI(uri); + final Interface jaMoPPInterface = (Interface) classifier; + for (final Method jaMoPPMethod : jaMoPPInterface.getMethods()) { + if (jaMoPPMethod.getName().equals(methodName)) { + return claimOne(getCorrespondingEObjects(jaMoPPMethod, OperationSignature.class)); + } + } + logger.warn("No JaMoPP method with name " + methodName + " found in " + interfaceName); + return null; + } + + protected OperationSignature renameMethodInClassWithName(final String className, final String methodName) + throws Throwable { + final ICompilationUnit cu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, + this.getCurrentTestProject()); + final IMethod iMethod = cu.getType(className).getMethod(methodName, null); + final int offset = iMethod.getNameRange().getOffset(); + final int length = iMethod.getNameRange().getLength(); + final String newMethodName = methodName + Pcm2JavaTestUtils.RENAME; + final ReplaceEdit replaceEdit = new ReplaceEdit(offset, length, newMethodName); + editCompilationUnit(cu, replaceEdit); + return this.findOperationSignatureForJaMoPPMethodInCompilationUnit(newMethodName, className, cu); + } + + protected void assertDataTypeName(final TypeReference typeReference, final DataType pcmDataType) { + final String jaMoPPTypeName = getNameFromJaMoPPType(typeReference); + final String pcmTypeName = this.getNameFromPCMDataType(pcmDataType); + assertEquals(jaMoPPTypeName, pcmTypeName, "The name of the PCM datatype does not equal the JaMoPP type name"); + } + + protected String getNameFromPCMDataType(final DataType pcmDataType) { + if (null == pcmDataType) { + return "void"; + } else if (pcmDataType instanceof CollectionDataType) { + return ((CollectionDataType) pcmDataType).getEntityName(); + } else if (pcmDataType instanceof CompositeDataType) { + return ((CompositeDataType) pcmDataType).getEntityName(); + } else if (pcmDataType instanceof PrimitiveDataType) { + return this.getNameFromPrimitveDataType((PrimitiveDataType) pcmDataType); + } + throw new RuntimeException("getNameFromPCMDataType failed"); + } + + private String getNameFromPrimitveDataType(final PrimitiveDataType pcmDataType) { + switch (pcmDataType.getType()) { + case BOOL: + return "boolean"; + case CHAR: + return "char"; + case BYTE: + return "byte"; + case DOUBLE: + return "double"; + case INT: + return "int"; + case LONG: + return "long"; + case STRING: + return "String"; + } + throw new RuntimeException("getNameFromPrimitveDataType"); + } + + protected Parameter addParameterToSignature(final String interfaceName, final String methodName, + final String typeName, final String parameterName, final String[] parameterTypeSignatures) + throws Throwable { + final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(interfaceName, + this.getCurrentTestProject()); + final IMethod iMethod = icu.getType(interfaceName).getMethod(methodName, parameterTypeSignatures); + final String parameterStr = typeName + " " + parameterName; + return this.insertParameterIntoSignature(methodName, parameterName, icu, iMethod, parameterStr); + } + + protected Parameter insertParameterIntoSignature(final String methodName, final String parameterName, + final ICompilationUnit icu, final IMethod iMethod, final String parameterStr) + throws JavaModelException, Throwable { + final int offset = iMethod.getSourceRange().getOffset() + iMethod.getSourceRange().getLength() - 2; + final InsertEdit insertEdit = new InsertEdit(offset, parameterStr); + editCompilationUnit(icu, insertEdit); + final ConcreteClassifier concreateClassifier = this + .getJaMoPPClassifierForURI(createPlatformResourceURI(icu.getResource())); + final Method jaMoPPMethod = (Method) concreateClassifier.getMembersByName(methodName).get(0); + final org.emftext.language.java.parameters.Parameter jaMoPPParam = this + .getJaMoPPParameterFromJaMoPPMethod(jaMoPPMethod, parameterName); + return claimOne(getCorrespondingEObjects(jaMoPPParam, Parameter.class)); + } + + protected OperationSignature addReturnTypeToSignature(final String interfaceName, final String methodName, + final String typeName, String oldTypeName) throws Throwable { + if (null == oldTypeName) { + oldTypeName = "void"; + } + final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(interfaceName, + this.getCurrentTestProject()); + final IMethod iMethod = icu.getType(interfaceName).getMethod(methodName, null); + final String retTypeStr = typeName; + final int offset = iMethod.getSourceRange().getOffset() + + iMethod.getSourceRange().toString().indexOf(oldTypeName); + final ReplaceEdit replaceEdit = new ReplaceEdit(offset + 1, oldTypeName.length() + 1, retTypeStr); + editCompilationUnit(icu, replaceEdit); + final ConcreteClassifier concreateClassifier = this + .getJaMoPPClassifierForURI(createPlatformResourceURI(icu.getResource())); + final Method jaMoPPMethod = (Method) concreateClassifier.getMembersByName(methodName).get(0); + return claimOne(getCorrespondingEObjects(jaMoPPMethod, OperationSignature.class)); + } + + protected org.emftext.language.java.parameters.Parameter getJaMoPPParameterFromJaMoPPMethod( + final Method jaMoPPMethod, final String parameterName) { + for (final org.emftext.language.java.parameters.Parameter jaMoPPParam : jaMoPPMethod.getParameters()) { + if (jaMoPPParam.getName().equals(parameterName)) { + return jaMoPPParam; + } + } + throw new RuntimeException( + "JaMoPP param with name " + parameterName + " not found in method " + jaMoPPMethod.getName()); + } + + protected org.emftext.language.java.parameters.Parameter findJaMoPPParameterInICU(final ICompilationUnit icu, + final String interfaceName, final String methodName, final String parameterName) { + final Method method = this.findJaMoPPMethodInICU(icu, methodName); + return this.getJaMoPPParameterFromJaMoPPMethod(method, parameterName); + } + + protected Method findJaMoPPMethodInICU(final ICompilationUnit icu, final String methodName) { + final ConcreteClassifier cc = this.getJaMoPPClassifierForURI(createPlatformResourceURI(icu.getResource())); + final List jaMoPPMethods = cc.getMembersByName(methodName); + for (final Member member : jaMoPPMethods) { + if (member instanceof Method && member.getName().equals(methodName)) { + return (Method) member; + } + } + throw new RuntimeException("No method with name " + methodName + " found in " + icu); + } + + protected String getNameFromPCMPrimitiveDataType(final PrimitiveDataType primitiveDataType) { + return primitiveDataType.getType().getName(); + } + + protected Package getDatatypesPackage() throws Throwable { + return this.getPackageWithNameFromCorrespondenceModel("datatypes"); + } + + protected IMethod findIMethodByName(final String typeName, final String methodName, final ICompilationUnit icu) + throws JavaModelException { + final IType type = icu.getAllTypes()[0]; + logger.info(type.getMethods()); + for (final IMethod method : type.getMethods()) { + if (method.getElementName().equals(methodName)) { + return method; + } + } + throw new RuntimeException("Method not " + methodName + " not found in classifier " + typeName); + } + + protected IField findIFieldByName(final String className, final String fieldName, final ICompilationUnit icu) + throws JavaModelException { + final IType type = icu.getType(className); + return type.getField(fieldName); + } + + protected String addPackageAndImplementingClass(final String componentName) + throws CoreException, IOException, InterruptedException { + this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + final Package mediaStorePackage = this.createPackageWithPackageInfo(Pcm2JavaTestUtils.REPOSITORY_NAME, + componentName); + this.getUserInteraction().addNextSingleSelection(Java2PcmUserSelection.SELECT_BASIC_COMPONENT.getSelection()); + + final String implementingClassName = componentName + "Impl"; + this.addClassInPackage(mediaStorePackage, BasicComponent.class, implementingClassName); + return implementingClassName; + } + + protected OperationProvidedRole addImplementsCorrespondingToOperationProvidedRoleToClass(final String className, + final String implementingInterfaceName) throws CoreException { + final ICompilationUnit classCompilationUnit = CompilationUnitManipulatorHelper + .findICompilationUnitWithClassName(className, this.getCurrentTestProject()); + this.importCompilationUnitWithName(implementingInterfaceName, classCompilationUnit); + + final IType classType = classCompilationUnit.getType(className); + final String newSource = " implements " + implementingInterfaceName; + int offset = classType.getSourceRange().getOffset(); + final int firstBracket = classType.getSource().indexOf("{"); + offset = offset + firstBracket - 1; + final InsertEdit insertEdit = new InsertEdit(offset, newSource); + editCompilationUnit(classCompilationUnit, insertEdit); + final org.emftext.language.java.classifiers.Class jaMoPPClass = (org.emftext.language.java.classifiers.Class) this + .getJaMoPPClassifierForURI(createPlatformResourceURI(classCompilationUnit.getResource())); + final EList classImplements = jaMoPPClass.getImplements(); + logger.debug("Found implements: " + classImplements); + for (final TypeReference implementsReference : classImplements) { + logger.debug("Implements data: " + implementsReference.getTarget()); + final Iterable correspondingEObjects = getCorrespondingEObjects(implementsReference, + OperationProvidedRole.class); + logger.debug("Corresponding provided roles: " + correspondingEObjects); + if (null != correspondingEObjects && correspondingEObjects.iterator().hasNext()) { + return correspondingEObjects.iterator().next(); + } + } + throw new RuntimeException("Could not find an operation provided role for the newly created implements"); + } + + protected void importCompilationUnitWithName(final String implementingInterfaceName, + final ICompilationUnit classCompilationUnit) throws JavaModelException { + final ICompilationUnit interfaceCompilationUnit = CompilationUnitManipulatorHelper + .findICompilationUnitWithClassName(implementingInterfaceName, this.getCurrentTestProject()); + final String namespace = interfaceCompilationUnit.getType(implementingInterfaceName).getFullyQualifiedName(); + saveCurrentStateOfResourceAndRegisterForSynchronization( + URIUtil.createPlatformResourceURI(interfaceCompilationUnit.getResource())); + saveCurrentStateOfResourceAndRegisterForSynchronization( + URIUtil.createPlatformResourceURI(classCompilationUnit.getResource())); + classCompilationUnit.createImport(namespace, null, null); + } + + protected T addFieldToClassWithName(final String className, final String fieldType, + final String fieldName, final Class correspondingType) throws Throwable { + final ICompilationUnit icu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, + this.getCurrentTestProject()); + if (!fieldType.equals("String")) { + this.importCompilationUnitWithName(fieldType, icu); + } + final IType iClass = icu.getAllTypes()[0]; + final int offset = CompilationUnitManipulatorHelper.getOffsetForClassifierManipulation(iClass); + final String fieldStr = "private " + fieldType + " " + fieldName + ";"; + final InsertEdit insertEdit = new InsertEdit(offset, fieldStr); + editCompilationUnit(icu, insertEdit); + final Field jaMoPPField = this.getJaMoPPFieldFromClass(icu, fieldName); + if (correspondingType == null) { + return null; + } + return claimOne(getCorrespondingEObjects(jaMoPPField, correspondingType)); + } + + protected Field getJaMoPPFieldFromClass(final ICompilationUnit icu, final String fieldName) { + final ConcreteClassifier cc = this.getJaMoPPClassifierForURI(createPlatformResourceURI(icu.getResource())); + final Field field = (Field) cc.getMembersByName(fieldName).get(0); + return field; + } + + // add Annotation via the framework + protected T addAnnotationToClassifier(final AnnotableAndModifiable annotable, + final String annotationName, final String annotationParameter, final Class classOfCorrespondingObject, + final String className) throws Throwable { + final ICompilationUnit cu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, + this.getCurrentTestProject()); + final IType type = cu.getType(className); + final int offset = CompilationUnitManipulatorHelper.getOffsetForAddingAnntationToClass(type); + final String composedName = "@" + annotationName + + (annotationParameter != null ? "(\"" + annotationParameter + "\")" : "") + + java.lang.System.lineSeparator(); + final InsertEdit insertEdit = new InsertEdit(offset, composedName); + editCompilationUnit(cu, insertEdit); + final Iterable eObjectsByType = getCorrespondingEObjects(annotable, classOfCorrespondingObject); + return claimOne(eObjectsByType); + } + + // add Annotation via the framework + protected T addAnnotationToField(final String fieldName, final String annotationName, + final String annotationParameter, final Class classOfCorrespondingObject, final String className) + throws Throwable { + final ICompilationUnit cu = CompilationUnitManipulatorHelper.findICompilationUnitWithClassName(className, + this.getCurrentTestProject()); + final IType type = cu.getType(className); + final int offset = CompilationUnitManipulatorHelper.getOffsetForAddingAnntationToField(type, fieldName); + final String composedName = "@" + annotationName + + (annotationParameter != null ? "(\"" + annotationParameter + "\")" : "") + + java.lang.System.lineSeparator(); + final InsertEdit insertEdit = new InsertEdit(offset, composedName); + editCompilationUnit(cu, insertEdit); + final Field jaMoPPField = this.getJaMoPPFieldFromClass(cu, fieldName); + final Iterable eObjectsByType = getCorrespondingEObjects(jaMoPPField, classOfCorrespondingObject); + return claimOne(eObjectsByType); + } + + protected void assertCorrespondingSEFF(final ResourceDemandingSEFF correspondingSeff, String methodName) + throws Throwable { + final ClassMethod jaMoPPMethod = claimOne(getCorrespondingEObjects(correspondingSeff, ClassMethod.class)); + assertEquals(jaMoPPMethod.getName(), methodName); + } + + protected void assertOperationInterface(final Repository repo, final OperationInterface opIf, + final String expectedName) { + assertTrue(null != opIf, "The created operation interface is null"); + assertEquals(opIf.getEntityName(), expectedName, + "OperationInterface name does not equals the expected interface Name."); + assertEquals(repo.getId(), opIf.getRepository__Interface().getId(), + "The created operation interface is not in the repository"); + } + + public ICompilationUnit addMethodToCompilationUnit(final String compilationUnitName, final String methodString, + final IProject currentTestProject) throws JavaModelException { + final ICompilationUnit cu = CompilationUnitManipulatorHelper + .findICompilationUnitWithClassName(compilationUnitName, currentTestProject); + final IType firstType = cu.getAllTypes()[0]; + final int offset = CompilationUnitManipulatorHelper.getOffsetForClassifierManipulation(firstType); + final InsertEdit insertEdit = new InsertEdit(offset, methodString); + editCompilationUnit(cu, insertEdit); + return cu; + } + +} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/BlockingProgressMonitor.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/BlockingProgressMonitor.java new file mode 100644 index 000000000..4ef8b104e --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/BlockingProgressMonitor.java @@ -0,0 +1,84 @@ +package tools.vitruv.applications.pcmjava.javaeditor.util; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Function; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; + +public class BlockingProgressMonitor extends NullProgressMonitor { + private static final int DEFAULT_TIMEOUT_MS = 500; + + private final Semaphore semaphore = new Semaphore(0); + + public BlockingProgressMonitor() { + super(); + } + + @Override + public void done() { + super.done(); + semaphore.release(); + } + + @Override + public void setCanceled(boolean cancelled) { + super.setCanceled(cancelled); + if (cancelled) { + semaphore.release(); + } + } + + public void waitForCompletion() { + try { + semaphore.tryAcquire(DEFAULT_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public static void performSynchronous(Consumer action) { + BlockingProgressMonitor monitor = new BlockingProgressMonitor(); + action.accept(monitor); + monitor.waitForCompletion(); + } + + public static void acceptSynchronousThrowing(ThrowingConsumer action) throws E { + BlockingProgressMonitor monitor = new BlockingProgressMonitor(); + try { + action.accept(monitor); + } catch (Exception exception) { + throw exception; + } + monitor.waitForCompletion(); + } + + public static R performSynchronous(Function action) { + BlockingProgressMonitor monitor = new BlockingProgressMonitor(); + R result = action.apply(monitor); + monitor.waitForCompletion(); + return result; + } + + public static R applySynchronousThrowing(ThrowingFunction action) throws E { + BlockingProgressMonitor monitor = new BlockingProgressMonitor(); + R result = null; + try { + result = action.apply(monitor); + } catch (Exception e) { + throw e; + } + monitor.waitForCompletion(); + return result; + } + + public static interface ThrowingConsumer { + void accept(T t) throws E; + } + + public static interface ThrowingFunction { + R apply(T t) throws E; + } +} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaEditorManipulationUtil.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaEditorManipulationUtil.java new file mode 100644 index 000000000..844968f90 --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaEditorManipulationUtil.java @@ -0,0 +1,222 @@ +package tools.vitruv.applications.pcmjava.javaeditor.util; + +import static org.eclipse.emf.common.util.URI.createPlatformResourceURI; +import static tools.vitruv.applications.pcmjava.javaeditor.util.BlockingProgressMonitor.acceptSynchronousThrowing; +import static tools.vitruv.applications.pcmjava.javaeditor.util.BlockingProgressMonitor.applySynchronousThrowing; + +import java.nio.file.Path; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; +import org.eclipse.jdt.internal.core.manipulation.StubUtility; +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringContribution; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.text.edits.InsertEdit; +import org.eclipse.text.edits.TextEdit; +import org.emftext.language.java.classifiers.Classifier; +import org.emftext.language.java.classifiers.ConcreteClassifier; +import org.emftext.language.java.containers.CompilationUnit; +import org.emftext.language.java.containers.JavaRoot; +import org.emftext.language.java.containers.Package; +import org.junit.jupiter.api.function.ThrowingConsumer; + +import edu.kit.ipd.sdq.commons.util.org.eclipse.emf.common.util.URIUtil; + +public class JavaEditorManipulationUtil { + private static final String SRC_FOLDER = "src"; + + private final JavaEditorView javaEditorView; + private final Path projectPath; + private IPackageFragmentRoot rootPackageFragment; + + JavaEditorManipulationUtil(JavaEditorView javaEditorView, Path projectPath) { + this.javaEditorView = javaEditorView; + this.projectPath = projectPath; + } + + public void createClass(String name, Package containingPackage, ThrowingConsumer initialization) throws CoreException { + createCompilationUnit(name, "class", containingPackage, initialization); + } + + public void createInterface(String name, Package containingPackage, ThrowingConsumer initialization) throws CoreException { + createCompilationUnit(name, "interface", containingPackage, initialization); + } + + private void createCompilationUnit(String name, String type, Package containingPackage, ThrowingConsumer initialization) throws CoreException { + IPackageFragment packageFragment = getPackageFragment(containingPackage); + ICompilationUnit compilationUnit = createEmptyCompilationUnit(packageFragment, type, name); + if (initialization != null) { + try { + initialization.accept(compilationUnit); + } + catch (Throwable t) { + throw new IllegalStateException(t); + } + } + javaEditorView.reloadResource(getFileUri(compilationUnit)); + } + + public ICompilationUnit claimCompilationUnit(String name, Package containingPackage) throws CoreException { + IPackageFragment packageFragment = getPackageFragment(containingPackage); + for (IJavaElement javaElement : packageFragment.getChildren()) { + if (javaElement instanceof ICompilationUnit && javaElement.getElementName().equals(name + ".java")) { + return (ICompilationUnit)javaElement; + } + } + throw new IllegalStateException("Could not find class " + name + " in package " + containingPackage); + } + + public void editCompilationUnit(final ICompilationUnit compilationUnit, final TextEdit... edits) throws JavaModelException { + URI originalUri = getFileUri(compilationUnit); + editCompilationUnitInternal(compilationUnit, edits); + URI changedUri = getFileUri(compilationUnit); + if (originalUri != changedUri) { + javaEditorView.moveResource(originalUri, changedUri); + } + javaEditorView.reloadResource(changedUri); + } + + /** + * Modifies the compilation unit without notifying the java editor view about resource changes. + */ + private void editCompilationUnitInternal(final ICompilationUnit compilationUnit, final TextEdit... edits) throws JavaModelException { + acceptSynchronousThrowing(monitor -> compilationUnit.becomeWorkingCopy(monitor)); + for (final TextEdit edit : edits) { + acceptSynchronousThrowing(monitor -> compilationUnit.applyTextEdit(edit, monitor)); + } + saveCompilationUnit(compilationUnit); + } + + private void saveCompilationUnit(ICompilationUnit compilationUnit) throws JavaModelException { + acceptSynchronousThrowing(monitor -> compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, monitor)); + acceptSynchronousThrowing(monitor -> compilationUnit.commitWorkingCopy(true, monitor)); + compilationUnit.discardWorkingCopy(); + acceptSynchronousThrowing(monitor -> compilationUnit.save(monitor, true)); + } + + public void renamePackage(final Package packageToRename, final String newName) throws CoreException { + final Resource resource = packageToRename.eResource(); + URI oldLocation = resource.getURI(); + final IFile iFile = getIFileForUri(resource.getURI(), projectPath); + IPath iPath = iFile.getProjectRelativePath(); + iPath = iPath.removeLastSegments(1); + final String newQualifiedName = packageToRename.getNamespacesAsString() + newName; + final IFolder iFolder = iFile.getProject().getFolder(iPath); + final IJavaElement javaPackage = JavaCore.create(iFolder); + String packageFile = String.join("/", packageToRename.getNamespaces()); + packageFile = packageFile + "/" + newName + "/package-info.java"; + refactorRenameJavaElement(newQualifiedName, javaPackage, IJavaRefactorings.RENAME_PACKAGE); + javaEditorView.moveResource(oldLocation, URIUtil.createFileURI(projectPath.resolve(SRC_FOLDER).resolve(packageFile).toFile())); + } + + public void addImportToCompilationUnit(ICompilationUnit compilationUnit, ICompilationUnit compilationUnitToImport, String classifierToImport) throws JavaModelException { + acceptSynchronousThrowing(monitor -> compilationUnit.becomeWorkingCopy(monitor)); + final String namespace = compilationUnitToImport.getType(classifierToImport).getFullyQualifiedName(); + acceptSynchronousThrowing(monitor -> compilationUnit.createImport(namespace, null, monitor)); + saveCompilationUnit(compilationUnit); + } + + private void refactorRenameJavaElement(final String newName, final IJavaElement iJavaElement, + final String refactorRenameActionName) throws CoreException { + final RefactoringContribution refacContrib = RefactoringCore + .getRefactoringContribution(refactorRenameActionName); + final RefactoringStatus status = new RefactoringStatus(); + final RenameJavaElementDescriptor desc = (RenameJavaElementDescriptor) refacContrib.createDescriptor(); + desc.setUpdateReferences(true); + desc.setJavaElement(iJavaElement); + desc.setNewName(newName); + final Refactoring refactoring = desc.createRefactoring(status); + acceptSynchronousThrowing(monitor -> refactoring.checkInitialConditions(monitor)); + acceptSynchronousThrowing(monitor -> refactoring.checkFinalConditions(monitor)); + Change change = applySynchronousThrowing(monitor -> refactoring.createChange(monitor)); + acceptSynchronousThrowing(monitor -> change.perform(monitor)); + } + + private T getJaMoPPRootForURI(final URI uri) { + final Resource resource = new ResourceSetImpl().getResource(uri, true); + // unchecked is OK for the test. + @SuppressWarnings("unchecked") + final T javaRoot = (T) resource.getContents().get(0); + return javaRoot; + } + + protected ConcreteClassifier getJaMoPPClassifierForURI(final URI uri) { + final CompilationUnit cu = this.getJaMoPPRootForURI(uri); + final Classifier jaMoPPClassifier = cu.getClassifiers().get(0); + return (ConcreteClassifier) jaMoPPClassifier; + } + + private ICompilationUnit createEmptyCompilationUnit(IPackageFragment packageFragment, String typeName, String name) throws JavaModelException { + String lineDelimiter = StubUtility.getLineDelimiterUsed(packageFragment.getJavaProject()); + ICompilationUnit compilationUnit = applySynchronousThrowing(monitor -> packageFragment.createCompilationUnit(name + ".java", "", false, null)); + InsertEdit edit = new InsertEdit(0, "package " + packageFragment.getElementName() + ";" + lineDelimiter + + lineDelimiter + "public " + typeName + " " + name + " { }"); + editCompilationUnitInternal(compilationUnit, edit); + return compilationUnit; + } + + private static IFile getIFileForUri(URI uri, Path projectPath) { + if (uri.isPlatform()) { + return URIUtil.getIFileForEMFUri(uri); + } + URI base = URIUtil.createFileURI(projectPath.toFile()); + String path = uri.deresolve(base).path(); + path = path.substring(path.indexOf("/") + 1); + URI platformUri = createPlatformResourceURI(projectPath.getFileName().resolve(path).normalize() + "/", + true); + return getIFileForUri(platformUri, projectPath); + } + + private URI getUriForElementInPackage(IPackageFragment packageFragment, String elementName) { + String uriString = packageFragment.getResource().getFullPath().toString() + "/" + elementName + ".java"; + return URI.createPlatformResourceURI(uriString, true); + } + + private URI getFileUri(ICompilationUnit compilationUnit) throws JavaModelException { + String[] namespace = compilationUnit.getPackageDeclarations()[0].getElementName().split("\\."); + Path path = projectPath.resolve(SRC_FOLDER); + for (String partialNamespace : namespace) { + path = path.resolve(partialNamespace); + } + return URIUtil.createFileURI(path.resolve(compilationUnit.getElementName()).toFile()); + } + + private IPackageFragmentRoot getRootPackage() throws CoreException { + if (rootPackageFragment != null) { + return rootPackageFragment; + } + + IFolder sourceFolder = javaEditorView.getEclipseProject().getFolder(SRC_FOLDER); + if (!sourceFolder.exists()) { + acceptSynchronousThrowing(monitor -> sourceFolder.create(true, true, monitor)); + } + rootPackageFragment = javaEditorView.getJavaProject().getPackageFragmentRoot(sourceFolder); + return rootPackageFragment; + } + + private IPackageFragment getPackageFragment(Package somePackage) throws CoreException { + String packageNamespace = somePackage.getNamespacesAsString() + somePackage.getName(); + for (IJavaElement javaElement : getRootPackage().getChildren()) { + if (javaElement instanceof IPackageFragment && javaElement.getElementName().equals(packageNamespace)) { + return (IPackageFragment)javaElement; + } + } + throw new IllegalStateException("No package fragment found for JaMoPP package " + somePackage); + } +} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaEditorView.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaEditorView.java new file mode 100644 index 000000000..c644e63f5 --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaEditorView.java @@ -0,0 +1,191 @@ +package tools.vitruv.applications.pcmjava.javaeditor.util; + +import static tools.vitruv.applications.pcmjava.javaeditor.util.BlockingProgressMonitor.acceptSynchronousThrowing; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +import org.apache.log4j.Logger; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; +import org.eclipse.jdt.core.IJavaProject; + +import edu.kit.ipd.sdq.commons.util.org.eclipse.core.resources.IProjectUtil; +import tools.vitruv.applications.pcmjava.javaeditor.java2pcm.legacy.Java2PcmTransformationTest; +import tools.vitruv.change.composite.description.PropagatedChange; +import tools.vitruv.framework.views.CommittableView; +import tools.vitruv.framework.views.View; +import tools.vitruv.framework.views.ViewSelection; +import tools.vitruv.framework.views.ViewSelector; +import tools.vitruv.framework.views.ViewType; +import tools.vitruv.framework.views.changederivation.StateBasedChangeResolutionStrategy; + +public class JavaEditorView implements CommittableView { + private static final Logger logger = Logger.getLogger(Java2PcmTransformationTest.class); + + private final Path projectFolder; + private CommittableView view; + private IProject eclipseProject; + private IJavaProject javaProject; + + public JavaEditorView(Path projectFolder, View view) { + this.projectFolder = projectFolder; + this.view = view.withChangeDerivingTrait(); + createJavaProject(); + } + + public IProject getEclipseProject() { + return eclipseProject; + } + + public IJavaProject getJavaProject() { + return javaProject; + } + + public JavaEditorManipulationUtil getManipulationUtil() { + return new JavaEditorManipulationUtil(this, projectFolder); + } + + @Override + public Collection getRootObjects() { + return view.getRootObjects(); + } + + @Override + public boolean isModified() { + return view.isModified(); + } + + @Override + public boolean isOutdated() { + return view.isOutdated(); + } + + @Override + public void update() { + try { + closeJavaProject(); + } catch (CoreException e) { + logger.error("Failed to close Java project", e); + } + view.update(); + createJavaProject(); + } + + private void createJavaProject() { + String projectName = projectFolder.getFileName().toString(); + eclipseProject = IProjectUtil.getWorkspaceProject(projectName); + if (!eclipseProject.exists()) { + eclipseProject = IProjectUtil.createProjectAt(projectName, projectFolder); + } + javaProject = IProjectUtil.configureAsJavaProject(eclipseProject); + } + + @Override + public boolean isClosed() { + return view.isClosed(); + } + + @Override + public void registerRoot(EObject object, URI persistAt) { + view.registerRoot(object, persistAt); + } + + @Override + public void moveRoot(EObject object, URI newLocation) { + view.moveRoot(object, newLocation); + } + + /** + * Reloads a resource at the given location. + * + * @param location is the location of the resource. + */ + public void reloadResource(URI location) { + // TODO: this is just a hack to circumvent missing support from the View + // interface. The resources of the element should not be accessed directly, so + // for the long-term we need to evaluate whether we want to add the here + // implemented functionality to the View interface. + Resource oldResource = getRootObjects().stream().map(it -> it.eResource()) + .filter(r -> r.getURI().equals(location)).findAny().orElse(null); + if (oldResource == null) { + Resource resource = new ResourceSetImpl().getResource(location, true); + for (EObject root : resource.getContents()) { + view.registerRoot(root, location); + } + } else { + oldResource.unload(); + try { + oldResource.load(null); + } catch (IOException e) { + logger.error("Failed to load resource at " + location, e); + } + } + } + + /** + * Moves a resource from the old to the new location and reloads its content. + * + * @param oldLocation is the old location. + * @param newLocation is the new location. + */ + public void moveResource(URI oldLocation, URI newLocation) { + // TODO: this is just a hack to circumvent missing support from the View + // interface. The resources of the element should not be accessed directly, so + // for the long-term we need to evaluate whether we want to add the here + // implemented functionality to the View interface. + Optional existingResource = getRootObjects().stream().map(it -> it.eResource()) + .filter(r -> r.getURI().equals(oldLocation)).findAny(); + existingResource.ifPresent(resource -> { + resource.setURI(newLocation); + reloadResource(newLocation); + }); + } + + @Override + public ViewSelection getSelection() { + return view.getSelection(); + } + + @Override + public ViewType getViewType() { + return view.getViewType(); + } + + @Override + public CommittableView withChangeRecordingTrait() { + return view.withChangeRecordingTrait(); + } + + @Override + public CommittableView withChangeDerivingTrait(StateBasedChangeResolutionStrategy changeResolutionStrategy) { + return view; + } + + @Override + public void close() throws Exception { + closeJavaProject(); + view.close(); + } + + private void closeJavaProject() throws CoreException { + if (eclipseProject == null) { + return; + } + acceptSynchronousThrowing(monitor -> eclipseProject.close(monitor)); + eclipseProject = null; + javaProject = null; + } + + @Override + public List commitChanges() { + return view.commitChanges(); + } +} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaPcmViewFactory.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaPcmViewFactory.java new file mode 100644 index 000000000..9df77d5dc --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaPcmViewFactory.java @@ -0,0 +1,73 @@ +package tools.vitruv.applications.pcmjava.javaeditor.util; + +import java.nio.file.Path; +import java.util.List; +import java.util.function.Consumer; + +import org.eclipse.core.runtime.CoreException; +import org.emftext.language.java.containers.CompilationUnit; +import org.emftext.language.java.containers.Package; +import org.junit.jupiter.api.function.ThrowingConsumer; +import org.palladiosimulator.pcm.repository.Repository; +import org.palladiosimulator.pcm.system.System; + +import tools.vitruv.framework.views.CommittableView; +import tools.vitruv.framework.views.View; +import tools.vitruv.framework.views.ViewProvider; +import tools.vitruv.testutils.TestViewFactory; + +public class JavaPcmViewFactory extends TestViewFactory { + private final Path javaProjectFolder; + + public JavaPcmViewFactory(Path javaProjectFolder, ViewProvider viewProvider) { + super(viewProvider); + this.javaProjectFolder = javaProjectFolder; + } + + private View createJavaView() { + return createViewOfElements("Java packages and classes", List.of(Package.class, CompilationUnit.class)); + } + + private JavaEditorView createJavaEditorView() { + View javaView = createJavaView(); + return new JavaEditorView(javaProjectFolder, javaView); + } + + private View createPcmView() { + return createViewOfElements("PCM", List.of(Repository.class, System.class)); + } + + public void changeJavaView(Consumer modelModification) throws Exception { + changeViewRecordingChanges(createJavaView(), modelModification); + } + + /** + * Changes the Java view containing all Java packages and classes as root + * elements according to the given modification function. Derives the performed + * changes, commits the recorded changes, and closes the view afterwards. + */ + public void changeJavaEditorView(ThrowingConsumer modelModification) throws Exception { + JavaEditorView javaEditorView = createJavaEditorView(); + try { + modelModification.accept(javaEditorView); + } catch (CoreException e) { + throw e; + } catch (Throwable e) { + throw new IllegalStateException(e); + } + javaEditorView.commitChanges(); + javaEditorView.close(); + } + + /** + * Validates the Java view containing all packages and classes by applying the + * validation function and closes the view afterwards. + */ + public void validateJavaView(Consumer viewValidation) throws Exception { + validateView(createJavaView(), viewValidation); + } + + public void validatePcmView(Consumer viewValidation) throws Exception { + validateView(createPcmView(), viewValidation); + } +} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaQueryUtil.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaQueryUtil.java new file mode 100644 index 000000000..404073e3d --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaQueryUtil.java @@ -0,0 +1,21 @@ +package tools.vitruv.applications.pcmjava.javaeditor.util; + +import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.claimOne; + +import java.util.stream.Collectors; + +import org.emftext.language.java.containers.Package; + +import tools.vitruv.framework.views.View; + +public class JavaQueryUtil { + public static final String DATATYPES_PACKAGE = "datatypes"; + public static final String CONTRACTS_PACKAGE = "contracts"; + + private JavaQueryUtil() { + } + + public static Package claimPackage(View view, String name) { + return claimOne(view.getRootObjects(Package.class).stream().filter(it -> name.equals(it.getName())).collect(Collectors.toList())); + } +} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaTextEditFactory.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaTextEditFactory.java new file mode 100644 index 000000000..0d3ba3d37 --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/JavaTextEditFactory.java @@ -0,0 +1,169 @@ +package tools.vitruv.applications.pcmjava.javaeditor.util; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.ILocalVariable; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.text.edits.InsertEdit; +import org.eclipse.text.edits.ReplaceEdit; +import org.eclipse.text.edits.TextEdit; + +/** + * Factory method to encapsulate all kinds of editing operations directly on the + * Java source code. + */ +public class JavaTextEditFactory { + public enum Visibility { + PUBLIC("public "), PRIVATE("private "), PROTECTED(""); + + private String codeRepresentation; + + public String getCodeRepresentation() { + return this.codeRepresentation; + } + + private Visibility(String codeRepresentation) { + this.codeRepresentation = codeRepresentation; + } + } + + private JavaTextEditFactory() { + } + + // === COMPILATION UNIT === + + public static TextEdit renameCompilationUnit(ICompilationUnit compilationUnit, String previousName, String newName) + throws JavaModelException { + int offset = compilationUnit.getBuffer().getContents().indexOf(previousName); + return new ReplaceEdit(offset, previousName.length(), newName); + // TODO: resource URI is not adjusted to new name + } + + public static TextEdit addImplementsRelation(IType implementingType, String interfaceName) + throws JavaModelException { + String newSource = " implements " + interfaceName; + int offset = implementingType.getSourceRange().getOffset(); + int firstBracket = implementingType.getSource().indexOf("{"); + offset = offset + firstBracket - 1; + return new InsertEdit(offset, newSource); + } + + // === METHOD === + + public static TextEdit addMethodWithEmptyBody(IType type, Visibility visibility, String returnType, + String methodName) throws JavaModelException { + String methodBlock = "\n\t" + visibility.getCodeRepresentation() + returnType + " " + methodName + "() {\n\t}\n"; + int offset = getOffsetForClassifierManipulation(type); + return new InsertEdit(offset, methodBlock); + } + + public static TextEdit addMethodSignature(IType type, String returnType, String methodName) + throws JavaModelException { + String methodSignature = "\n" + returnType + " " + methodName + "();\n"; + int offset = getOffsetForClassifierManipulation(type); + return new InsertEdit(offset, methodSignature); + } + + public static TextEdit renameMethod(IType type, String oldMethodName, String newMethodName) + throws JavaModelException { + IMethod iMethod = getMethodByName(type, oldMethodName); + int offset = iMethod.getNameRange().getOffset(); + int length = iMethod.getNameRange().getLength(); + return new ReplaceEdit(offset, length, newMethodName); + } + + public static TextEdit changeReturnTypeOfMethod(IType type, String methodName, String newReturnType) + throws JavaModelException { + IMethod iMethod = getMethodByName(type, methodName); + int offset = iMethod.getSourceRange().getOffset(); + String oldReturnType = iMethod.getSource().split(" ")[0]; + int returnTypeLength = oldReturnType.length(); + return new ReplaceEdit(offset, returnTypeLength, newReturnType); + } + + // === METHOD PARAMETER === + + public static TextEdit addMethodParameter(IType type, String methodName, String parameterName, String parameterType) + throws JavaModelException { + IMethod iMethod = getMethodByName(type, methodName); + String parameterString = parameterType + " " + parameterName; + int offset = iMethod.getSourceRange().getOffset() + iMethod.getSourceRange().getLength() - 2; + return new InsertEdit(offset, parameterString); + } + + public static TextEdit renameMethodParameter(IType type, String methodName, String oldParameterName, + String newParameterName) throws JavaModelException { + IMethod iMethod = getMethodByName(type, methodName); + ILocalVariable parameter = getParameterByName(iMethod, oldParameterName); + String typeName = parameter.getSource().split(" ")[0]; + String paramName = parameter.getSource().split(" ")[1]; + int offset = parameter.getSourceRange().getOffset() + typeName.length() + 1; + int length = paramName.length(); + return new ReplaceEdit(offset, length, newParameterName); + } + + public static TextEdit changeParameterType(IType type, String methodName, String parameterName, String newType) + throws JavaModelException { + IMethod iMethod = getMethodByName(type, methodName); + ILocalVariable parameter = getParameterByName(iMethod, parameterName); + int offset = parameter.getSourceRange().getOffset(); + int length = parameter.getSource().split(" ")[0].length(); + return new ReplaceEdit(offset, length, newType); + } + + // === FIELDS === + + public static TextEdit addField(IType type, Visibility visibility, String fieldName, String fieldType) + throws JavaModelException { + int offset = getOffsetForClassifierManipulation(type); + String fieldStr = visibility.getCodeRepresentation() + fieldType + " " + fieldName + ";"; + return new InsertEdit(offset, fieldStr); + } + + public static TextEdit renameField(IType type, String previousName, String newName) throws JavaModelException { + IField fieldToRename = type.getField(previousName); + String fieldToRenameString = fieldToRename.getSource(); + String fieldToRenameType = fieldToRenameString.split(" ")[1]; + String fieldToRenameName = fieldToRenameString.split(" ")[2]; + int offset = fieldToRename.getSourceRange().getOffset() + fieldToRenameString.indexOf(fieldToRenameType) + + fieldToRenameType.length() + 1; + int lengthToDelete = fieldToRenameName.length(); + return new ReplaceEdit(offset, lengthToDelete, newName + ";"); + } + + public static TextEdit changeTypeOfField(IType type, String fieldName, String newType) throws JavaModelException { + IField fieldToRename = type.getField(fieldName); + String fieldSrc = fieldToRename.getSource(); + String fieldType = fieldSrc.split(" ")[1]; + int offset = fieldToRename.getSourceRange().getOffset() + fieldSrc.indexOf(fieldType); + int lengthToDelete = fieldType.length(); + return new ReplaceEdit(offset, lengthToDelete, newType); + } + + // === Helpers === + + private static int getOffsetForClassifierManipulation(IType firstType) throws JavaModelException { + int posOfFirstBracket = firstType.getCompilationUnit().getSource().indexOf("{"); + return posOfFirstBracket + 1; + } + + private static IMethod getMethodByName(IType type, String methodName) throws JavaModelException { + for (IMethod method : type.getMethods()) { + if (method.getElementName().equals(methodName)) { + return method; + } + } + throw new IllegalStateException("Method " + methodName + " not found in type " + type); + } + + private static ILocalVariable getParameterByName(IMethod iMethod, String parameterName) throws JavaModelException { + for (ILocalVariable localVariable : iMethod.getParameters()) { + if (localVariable.getElementName().equals(parameterName)) { + return localVariable; + } + } + throw new IllegalStateException("Old parameter with name " + parameterName + " not found"); + } +} diff --git a/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/PcmQueryUtil.java b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/PcmQueryUtil.java new file mode 100644 index 000000000..d348e1a86 --- /dev/null +++ b/tests/tools.vitruv.applications.pcmjava.javaeditor.tests/src/tools/vitruv/applications/pcmjava/javaeditor/util/PcmQueryUtil.java @@ -0,0 +1,57 @@ +package tools.vitruv.applications.pcmjava.javaeditor.util; + +import static edu.kit.ipd.sdq.commons.util.java.lang.IterableUtil.claimOne; + +import java.util.Collection; +import java.util.stream.Collectors; + +import org.palladiosimulator.pcm.core.entity.NamedElement; +import org.palladiosimulator.pcm.repository.DataType; +import org.palladiosimulator.pcm.repository.Interface; +import org.palladiosimulator.pcm.repository.Repository; +import org.palladiosimulator.pcm.repository.RepositoryComponent; +import org.palladiosimulator.pcm.system.System; + +import tools.vitruv.framework.views.View; + +public class PcmQueryUtil { + private PcmQueryUtil() { + } + + public static Repository claimSingleRepository(View view) { + return claimOne(view.getRootObjects(Repository.class)); + } + + public static System claimSingleSystem(View view) { + return claimOne(view.getRootObjects(System.class)); + } + + public static Repository claimPcmRepository(View view, String repositoryName) { + return claimOne(view.getRootObjects(Repository.class).stream() + .filter(it -> repositoryName.equals(it.getEntityName())).collect(Collectors.toList())); + } + + public static T claimComponent(Repository repository, String componentName, + Class componentType) { + return claimNamedElement(repository.getComponents__Repository(), componentName, componentType); + } + + public static T claimInterface(Repository repository, String interfaceName, + Class interfaceType) { + return claimNamedElement(repository.getInterfaces__Repository(), interfaceName, interfaceType); + } + + public static T claimDataType(Repository repository, String dataTypeName, + Class dataTypeType) { + return claimNamedElement(repository.getDataTypes__Repository(), dataTypeName, dataTypeType); + } + + public static T claimNamedElement(Collection elements, String name) { + return claimOne(elements.stream().filter(it -> name.equals(it.getEntityName())).collect(Collectors.toList())); + } + + public static T claimNamedElement(Collection elements, String name, Class type) { + return claimOne(elements.stream().filter(type::isInstance).map(type::cast) + .filter(it -> name.equals(it.getEntityName())).collect(Collectors.toList())); + } +} diff --git a/tests/tools.vitruv.applications.pcmjava.tests/src/tools/vitruv/applications/pcmjava/pcm2java/Pcm2JavaTestUtils.java b/tests/tools.vitruv.applications.pcmjava.tests/src/tools/vitruv/applications/pcmjava/pcm2java/Pcm2JavaTestUtils.java index f0033b437..9c5859c41 100644 --- a/tests/tools.vitruv.applications.pcmjava.tests/src/tools/vitruv/applications/pcmjava/pcm2java/Pcm2JavaTestUtils.java +++ b/tests/tools.vitruv.applications.pcmjava.tests/src/tools/vitruv/applications/pcmjava/pcm2java/Pcm2JavaTestUtils.java @@ -25,6 +25,10 @@ public final class Pcm2JavaTestUtils { public static final String ASSEMBLY_CONTEXT_NAME = "assemblyContext"; public static final String COMPOSITE_COMPONENT_NAME = "TestCompositeComponent"; public static final String COLLECTION_DATA_TYPE_NAME = "TestCollectionDatatype"; + + public static final String IMPLEMENTING_CLASS_SUFFIX = "Impl"; + + private static final String PROVIDES_INTERFACE = "_provides_"; // private ctor for util class private Pcm2JavaTestUtils() { @@ -55,4 +59,8 @@ public static System createSystem(final String systemName) throws Throwable { system.setEntityName(systemName); return system; } + + public static String providesInterfaceName(String componentName, String interfaceName) { + return componentName + PROVIDES_INTERFACE + interfaceName; + } }