org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl Java Examples

The following examples show how to use org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Main.java    From ArduinoML-kernel with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static String xmi2NativeArduino(String xmiPath) throws IOException{
       // register ArduinoML
	ResourceSet resourceSet = new ResourceSetImpl();
    Map<String, Object> packageRegistry = resourceSet.getPackageRegistry();
       packageRegistry.put(arduinoML.ArduinoMLPackage.eNS_URI, arduinoML.ArduinoMLPackage.eINSTANCE);
	
       // load the xmi file
	XMIResource resource = new XMIResourceImpl(URI.createURI("file:"+xmiPath));
	resource.load(null);
	
	// get the root of the model
	App app = (App) resource.getContents().get(0);
	
	// Launch the visitor on the root
	ArduinoMLSwitchPrinter visitor = new ArduinoMLSwitchPrinter();
	return visitor.doSwitch(app);
}
 
Example #2
Source File: FactoryImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Entry<ComponentFactory> createService ( final UserInformation userInformation, final String configurationId, final BundleContext context, final Map<String, String> parameters ) throws Exception
{
    final ConfigurationDataHelper cfg = new ConfigurationDataHelper ( parameters );
    final String xml = cfg.getStringNonEmpty ( "configuration" );

    final XMIResource xmi = new XMIResourceImpl ();
    final Map<?, ?> options = new HashMap<Object, Object> ();
    final InputSource is = new InputSource ( new StringReader ( xml ) );
    xmi.load ( is, options );

    final Object c = EcoreUtil.getObjectByType ( xmi.getContents (), ParserPackage.Literals.COMPONENT );
    if ( ! ( c instanceof Component ) )
    {
        throw new RuntimeException ( String.format ( "Configuration did not contain an object of type %s", Component.class.getName () ) );
    }

    final ComponentFactoryWrapper wrapper = new ComponentFactoryWrapper ( this.executor, (Component)c );

    final Dictionary<String, ?> properties = new Hashtable<> ();
    final ServiceRegistration<ComponentFactory> handle = context.registerService ( ComponentFactory.class, wrapper, properties );

    return new Entry<ComponentFactory> ( configurationId, wrapper, handle );
}
 
Example #3
Source File: EcoreResourceDescriptionManagerTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testNestedPackage() throws Exception {
	Resource resource = new XMIResourceImpl();
	EPackage parent = EcoreFactory.eINSTANCE.createEPackage();
	parent.setName("parent");
	parent.setNsURI("http://parent");
	EPackage child = EcoreFactory.eINSTANCE.createEPackage();
	child.setName("child");
	child.setNsURI("http://child");
	EClass eClass = EcoreFactory.eINSTANCE.createEClass();
	eClass.setName("Test");
	child.getEClassifiers().add(eClass);
	parent.getESubpackages().add(child);
	resource.getContents().add(parent);
	Map<QualifiedName, IEObjectDescription> index = createIndex(resource);
	checkEntry(index, parent, false, "parent");
	checkEntry(index, child, false, "parent", "child");
	checkEntry(index, eClass, false, "parent", "child", "Test");
	checkEntry(index, parent, true, "http://parent");
	checkEntry(index, child, true, "http://child");
	checkEntry(index, eClass, true, "http://child", "Test");
	assertEquals(6,index.size());
}
 
Example #4
Source File: SCTResourceTest.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testParsingOnLoad() throws Exception {
	File tmpFile = File.createTempFile("SCTResource", "test.test");
	tmpFile.deleteOnExit();
	URI uri = URI.createFileURI(tmpFile.getPath().toString());
	Resource resource = new XMIResourceImpl(uri);
	Statechart statechart = createStatechart("internal: event Event1");
	resource.getContents().add(statechart);
	Transition transition = createTransition("Event1 [true] / 3 * 3");
	resource.getContents().add(transition);
	resource.save(Collections.EMPTY_MAP);

	res.setURI(uri);
	res.load(Collections.EMPTY_MAP);
	statechart = (Statechart) res.getContents().get(0);
	transition = (Transition) res.getContents().get(1);

	assertEquals("" + res.getErrors(), 0, res.getErrors().size());
	ReactionTrigger trigger = (ReactionTrigger) transition.getTrigger();
	RegularEventSpec eventSpec = (RegularEventSpec) trigger.getTriggers().get(0);
	ElementReferenceExpression expression = (ElementReferenceExpression) eventSpec.getEvent();
	EventDefinition reference = (EventDefinition) expression.getReference();
	assertNotNull(reference);
	assertEquals("Event1", reference.getName());
}
 
Example #5
Source File: EcoreResourceDescriptionManagerTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testMissingMiddleName() {
	Resource resource = new XMIResourceImpl();
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	ePackage.setName("test");
	ePackage.setNsURI("http://test");
	EClass unnamedEClass = EcoreFactory.eINSTANCE.createEClass();
	EAttribute eAttribute = EcoreFactory.eINSTANCE.createEAttribute();
	eAttribute.setName("test");
	unnamedEClass.getEStructuralFeatures().add(eAttribute);
	ePackage.getEClassifiers().add(unnamedEClass);
	resource.getContents().add(ePackage);
	Map<QualifiedName, IEObjectDescription> index = createIndex(resource);
	checkEntry(index, ePackage, false, "test");
	checkEntry(index, ePackage, true, "http://test");
	assertEquals(2,index.size());
	
	unnamedEClass.setName("Test");
	index = createIndex(resource);
	checkEntry(index, ePackage, false, "test");
	checkEntry(index, ePackage, true, "http://test");
	checkEntry(index, unnamedEClass, false, "test", "Test");
	checkEntry(index, unnamedEClass, true, "http://test", "Test");
	checkEntry(index, eAttribute, false, "test", "Test", "test");
	checkEntry(index, eAttribute, true, "http://test", "Test", "test");
	assertEquals(6,index.size());
}
 
Example #6
Source File: M2DocTestUtils.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new {@link DocumentTemplate} with the given {@link DocumentTemplate#getBody() body}. The body is linked to {@link XWPFRun}.
 * 
 * @param body
 *            the {@link Block}
 * @return a new {@link DocumentTemplate}
 */
@SuppressWarnings("resource")
public static DocumentTemplate createDocumentTemplate(Block body) {
    final DocumentTemplate res = TemplatePackage.eINSTANCE.getTemplateFactory().createDocumentTemplate();
    final Resource r = new XMIResourceImpl();
    r.getContents().add(res);

    final XWPFDocument document = new XWPFDocument();
    res.setDocument(document);
    res.setBody(body);

    final XWPFParagraph paragraph = document.createParagraph();

    linkRuns(paragraph, body);

    return res;
}
 
Example #7
Source File: GenericResourceDescriptionManagerTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testCreateDeltaAndIsAffected() {
	GenericResourceDescriptionManager manager = getEmfResourceDescriptionsManager();
	EClass eClass = EcoreFactory.eINSTANCE.createEClass();
	eClass.setName("Test");
	eClass.getESuperTypes().add(EcorePackage.Literals.EPACKAGE);
	Resource resource = new XMIResourceImpl(URI.createFileURI("test.ecore"));
	resource.getContents().add(eClass);

	EPackage copyOfEPackage = EcoreUtil.copy(EcorePackage.eINSTANCE);
	Resource ecoreResource = new XMIResourceImpl(URI.createURI(copyOfEPackage.getNsURI()));
	ecoreResource.getContents().add(copyOfEPackage);
	
	IResourceDescription oldDescription = new CopiedResourceDescription(manager.getResourceDescription(ecoreResource));
	oldDescription.getExportedObjects();
	copyOfEPackage.setName("ecore_new");
	IResourceDescription newDescription = manager.getResourceDescription(ecoreResource);
	
	Delta delta = manager.createDelta(oldDescription, newDescription);
	assertTrue(delta.haveEObjectDescriptionsChanged());
	
	IResourceDescription referrerDescription = manager.getResourceDescription(resource);
	assertTrue(manager.isAffected(delta, referrerDescription));
}
 
Example #8
Source File: NewGenerationWizard.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor.
 */
public NewGenerationWizard() {
    generation = GenconfPackage.eINSTANCE.getGenconfFactory().createGeneration();
    final Resource resource = new XMIResourceImpl();
    final ResourceSet rs = new ResourceSetImpl();
    rs.getResources().add(resource);
    resource.getContents().add(generation);
    TransactionalEditingDomain.Factory.INSTANCE.createEditingDomain(rs);
}
 
Example #9
Source File: DiagramFileStoreTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private Pool aPoolInAResourceWithUUID(final String uuid) throws IOException {
    final XMIResourceImpl xmiResourceImpl = new XMIResourceImpl();
    final Pool pool = aPool().build();
    xmiResourceImpl.getContents().add(pool);
    xmiResourceImpl.setID(pool, uuid);
    return pool;
}
 
Example #10
Source File: StextResourceFactory.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Resource createResource(URI uri) {
	String domainID = DomainRegistry.determineDomainID(uri);
	if (domainID == null || DomainRegistry.getDomain(domainID) == null) {
		return new XMIResourceImpl(uri);
	}
	IDomain domain = DomainRegistry.getDomain(domainID);
	Injector injector = getInjector(domain);
	Resource resource = injector.getInstance(Resource.class);
	ResourceSet set = new ResourceSetImpl();
	set.getResources().add(resource);
	resource.setURI(uri);
	return resource;
}
 
Example #11
Source File: TransientContainerReferencesTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testCrossResourceContainment() throws Exception {
	Element parent = CrossContainmentFactory.eINSTANCE.createElement();
	Element child = CrossContainmentFactory.eINSTANCE.createElement();
	parent.getContainment().add(child);
	Resource resource0 = new XMIResourceImpl(URI.createFileURI("test0.xmi"));
	resource0.getContents().add(parent);
	DefaultTransientValueService defaultTransientValueService = new DefaultTransientValueService();
	assertTrue(defaultTransientValueService.isTransient(child, CrossContainmentPackage.Literals.ELEMENT__CONTAINER, 0));
	Resource resource1 =new XMIResourceImpl(URI.createFileURI("test0.xmi"));
	resource1.getContents().add(child);
	assertEquals(parent, child.getContainer());
	assertFalse(defaultTransientValueService.isTransient(child, CrossContainmentPackage.Literals.ELEMENT__CONTAINER, 0));
}
 
Example #12
Source File: ResourceSetReferencingResourceSetTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private Resource getResource(String resourceURI, String references) {
	XMIResourceImpl res = new XMIResourceImpl();
	res.setURI(URI.createURI(resourceURI));
	EcoreFactory f = EcoreFactory.eINSTANCE;
	EClass class1 = f.createEClass();
	res.getContents().add(class1);
	class1.setName("mytype");
	if (references!=null) {
		EClass referencedProxy = f.createEClass();
		String fragment = res.getURIFragment(class1);
		((InternalEObject)referencedProxy).eSetProxyURI(URI.createURI(references).appendFragment(fragment));
		class1.getESuperTypes().add(referencedProxy);
	}
	return res;
}
 
Example #13
Source File: GenericUnloaderTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected EPackage createExample() {
	ResourceSetImpl resourceSet = new ResourceSetImpl();
	Resource resource = new XMIResourceImpl(URI.createURI("test"));
	resourceSet.getResources().add(resource);
	EPackage root = EcoreFactory.eINSTANCE.createEPackage();
	resource.getContents().add(root);
	EClass child = EcoreFactory.eINSTANCE.createEClass();
	root.getEClassifiers().add(child);
	return root;
}
 
Example #14
Source File: InjectableValidatorTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testWrongResource() throws Exception {
	Main main = LangATestLanguageFactory.eINSTANCE.createMain();
	XMIResource xmiResource = new XMIResourceImpl();
	xmiResource.getContents().add(main);
	assertTrue(languageSpecificValidator.validate(main, new BasicDiagnostic(), null));
	assertTrue(languageSpecificValidator.validate(main, new BasicDiagnostic(), context));
	context.put(AbstractInjectableValidator.CURRENT_LANGUAGE_NAME, xtextResource.getLanguageName());
	assertFalse(languageSpecificValidator.validate(main, new BasicDiagnostic(), context));

	context.clear();
	assertFalse(languageAgnosticValidator.validate(main, new BasicDiagnostic(), null));
	assertFalse(languageAgnosticValidator.validate(main, new BasicDiagnostic(), context));
	context.put(AbstractInjectableValidator.CURRENT_LANGUAGE_NAME, xtextResource.getLanguageName());
	assertFalse(languageAgnosticValidator.validate(main, new BasicDiagnostic(), context));
}
 
Example #15
Source File: AbstractTemplatesTestSuite.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param testFolder
 *            the test folder path
 * @throws IOException
 *             if the tested template can't be read
 * @throws DocumentParserException
 *             if the tested template can't be parsed
 */
public AbstractTemplatesTestSuite(String testFolder) throws IOException, DocumentParserException {
    MyDslPackage.eINSTANCE.getName();// make sure MyDsl is loaded (XText)
    UMLPackage.eINSTANCE.getName(); // make sure UML2 is loaded
    this.testFolderPath = testFolder.replaceAll("\\\\", "/");
    final URI genconfURI = getGenconfURI(new File(testFolderPath));
    if (URIConverter.INSTANCE.exists(genconfURI, Collections.EMPTY_MAP)) {
        final ResourceSet rs = getResourceSetForGenconf();
        generation = getGeneration(genconfURI, rs);
    } else {
        generation = GenconfFactory.eINSTANCE.createGeneration();
        Resource r = new XMIResourceImpl(genconfURI);
        r.getContents().add(generation);
    }
    final URI templateURI = getTemplateURI(new File(testFolderPath));
    setTemplateFileName(generation, URI.decode(templateURI.deresolve(genconfURI).toString()));
    final List<Exception> exceptions = new ArrayList<>();
    resourceSetForModels = getResourceSetForModel(exceptions);
    queryEnvironment = GenconfUtils.getQueryEnvironment(resourceSetForModels, generation);
    new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration();
    documentTemplate = M2DocUtils.parse(resourceSetForModels.getURIConverter(), templateURI, queryEnvironment,
            new ClassProvider(this.getClass().getClassLoader()), new BasicMonitor());
    for (Exception e : exceptions) {
        final XWPFRun run = M2DocUtils.getOrCreateFirstRun(documentTemplate.getDocument());
        documentTemplate.getBody().getValidationMessages()
                .add(new TemplateValidationMessage(ValidationMessageLevel.ERROR, e.getMessage(), run));
    }
    variables = GenconfUtils.getVariables(generation, resourceSetForModels);
}
 
Example #16
Source File: EcoreResourceDescriptionManagerTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testMissingName() {
	Resource resource = new XMIResourceImpl();
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	ePackage.setNsURI("http://test");
	EClass eClass = EcoreFactory.eINSTANCE.createEClass();
	eClass.setName("Test");
	ePackage.getEClassifiers().add(eClass);
	resource.getContents().add(ePackage);
	Map<QualifiedName, IEObjectDescription> index = createIndex(resource);
	checkEntry(index, ePackage, true, "http://test");
	checkEntry(index, eClass, true, "http://test", "Test");
	assertEquals(2,index.size());
}
 
Example #17
Source File: EcoreResourceDescriptionManagerTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testMissingNsURI() {
	Resource resource = new XMIResourceImpl();
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	ePackage.setName("test");
	EClass eClass = EcoreFactory.eINSTANCE.createEClass();
	eClass.setName("Test");
	ePackage.getEClassifiers().add(eClass);
	resource.getContents().add(ePackage);
	Map<QualifiedName, IEObjectDescription> index = createIndex(resource);
	checkEntry(index, ePackage, false, "test");
	checkEntry(index, eClass, false, "test", "Test");
	assertEquals(2,index.size());
}
 
Example #18
Source File: ParserDriverProcessor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private String makeXml ( final Component component ) throws IOException
{
    final XMIResourceImpl xmi = new XMIResourceImpl ();
    xmi.getContents ().add ( EcoreUtil.copy ( component ) );

    final StringWriter writer = new StringWriter ();
    xmi.save ( writer, null );
    return writer.toString ();
}
 
Example #19
Source File: UserDataMapper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Reads the TModule stored in the given IEObjectDescription.
 */
public static TModule getDeserializedModuleFromDescription(IEObjectDescription eObjectDescription, URI uri) {
	final String serializedData = eObjectDescription.getUserData(USER_DATA_KEY_SERIALIZED_SCRIPT);
	if (Strings.isNullOrEmpty(serializedData)) {
		return null;
	}
	final XMIResource xres = new XMIResourceImpl(uri);
	try {
		final boolean binary = !serializedData.startsWith("<");
		final ByteArrayInputStream bais = new ByteArrayInputStream(
				binary ? Base64.getDecoder().decode(serializedData)
						: serializedData.getBytes(TRANSFORMATION_CHARSET_NAME));
		xres.load(bais, getOptions(uri, binary));
	} catch (Exception e) {
		LOGGER.warn("error deserializing module from IEObjectDescription: " + uri); //$NON-NLS-1$
		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("error deserializing module from IEObjectDescription=" + eObjectDescription
					+ ": " + uri, e); //$NON-NLS-1$
		}
		// fail safe, because not uncommon (serialized data might have been created with an old version of the N4JS
		// IDE, so the format could be out of date (after an update of the IDE))
		return null;
	}
	final List<EObject> contents = xres.getContents();
	if (contents.isEmpty() || !(contents.get(0) instanceof TModule)) {
		return null;
	}
	final TModule module = (TModule) contents.get(0);
	xres.getContents().clear();

	final String astMD5 = eObjectDescription.getUserData(USER_DATA_KEY_AST_MD5);
	module.setAstMD5(astMD5);

	return module;
}
 
Example #20
Source File: UserDataMapper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * <b>ONLY INTENDED FOR TESTS OR DEBUGGING. DON'T USE IN PRODUCTION CODE.</b>
 * <p>
 * Same as {@link #getDeserializedModuleFromDescription(IEObjectDescription, URI)}, but always returns the module as
 * an XMI-serialized string. If no module is found, returns null.
 */
public static String getDeserializedModuleFromDescriptionAsString(IEObjectDescription eObjectDescription,
		URI uri) throws IOException {
	final TModule module = getDeserializedModuleFromDescription(eObjectDescription, uri);
	if (module == null) {
		return null;
	}
	final XMIResource resourceForUserData = new XMIResourceImpl(uri);
	resourceForUserData.getContents().add(module);
	final ByteArrayOutputStream baos = new ByteArrayOutputStream();
	resourceForUserData.save(baos, getOptions(uri, false));
	return baos.toString(TRANSFORMATION_CHARSET_NAME);
}
 
Example #21
Source File: UserDataMapper.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Serializes an exported script (or other {@link EObject}) stored in given resource content at index 1, and stores
 * that in a map under key {@link #USER_DATA_KEY_SERIALIZED_SCRIPT}.
 */
public static Map<String, String> createUserData(final TModule exportedModule) throws IOException,
		UnsupportedEncodingException {
	if (exportedModule.isPreLinkingPhase()) {
		throw new AssertionError("Module may not be from the preLinkingPhase");
	}
	// TODO GH-230 consider disallowing serializing reconciled modules to index with fail-fast
	// if (exportedModule.isReconciled()) {
	// throw new IllegalArgumentException("module must not be reconciled");
	// }
	final Resource originalResourceUncasted = exportedModule.eResource();
	if (!(originalResourceUncasted instanceof N4JSResource)) {
		throw new IllegalArgumentException("module must be contained in an N4JSResource");
	}
	final N4JSResource originalResource = (N4JSResource) originalResourceUncasted;

	// resolve resource (i.e. resolve lazy cross-references, resolve DeferredTypeRefs, etc.)
	originalResource.performPostProcessing();
	if (EcoreUtilN4.hasUnresolvedProxies(exportedModule) || TypeUtils.containsDeferredTypeRefs(exportedModule)) {
		// don't write invalid TModule to index
		// TODO GHOLD-193 reconsider handling of this error case
		// 2016-05-11: keeping fail-safe behavior for now (in place at least since end of 2014).
		// Fail-fast behavior not possible, because common case (e.g. typo in an identifier in the source code, that
		// leads to an unresolvable proxy in the TModule)
		return createTimestampUserData(exportedModule);
	}

	// add copy -- EObjects can only be contained in a single resource, and
	// we do not want to mess up the original resource
	URI resourceURI = originalResource.getURI();
	XMIResource resourceForUserData = new XMIResourceImpl(resourceURI);

	resourceForUserData.getContents().add(TypeUtils.copyWithProxies(exportedModule));

	ByteArrayOutputStream baos = new ByteArrayOutputStream();

	resourceForUserData.save(baos, getOptions(resourceURI, BINARY));

	String serializedScript = BINARY ? Base64.getEncoder().encodeToString(baos.toByteArray())
			: baos.toString(TRANSFORMATION_CHARSET_NAME);

	final HashMap<String, String> ret = new HashMap<>();
	ret.put(USER_DATA_KEY_SERIALIZED_SCRIPT, serializedScript);

	final String astMD5 = exportedModule.getAstMD5();
	if (astMD5 != null) {
		ret.put(USER_DATA_KEY_AST_MD5, astMD5);
	}

	if (exportedModule.isMainModule()) {
		ret.put(N4JSResourceDescriptionStrategy.MAIN_MODULE_KEY, Boolean.toString(exportedModule.isMainModule()));
	}

	// in case of filling file store fingerprint to keep filled type updated by the incremental builder.
	// required to trigger rebuilds even if only minor changes happened to the content.
	if (exportedModule.isStaticPolyfillModule()) {
		final String contentHash = Integer.toHexString(originalResource.getParseResult().getRootNode().hashCode());
		ret.put(USER_DATA_KEY_STATIC_POLYFILL_CONTENTHASH, contentHash);
	}
	return ret;
}
 
Example #22
Source File: DefaultReferenceDescriptionTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testSpecialReferences() {
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	ePackage.setName("test");
	ePackage.setNsPrefix("test");
	ePackage.setNsURI("test");

	EClass eClass = EcoreFactory.eINSTANCE.createEClass();
	eClass.setName("Test");
	eClass.getESuperTypes().add(EcorePackage.Literals.EPACKAGE);
	ePackage.getEClassifiers().add(eClass);

	EReference eReference1 = EcoreFactory.eINSTANCE.createEReference();
	eReference1.setContainment(false);
	eReference1.setName("onlyExportedRef");
	eReference1.setEType(EcorePackage.Literals.EPACKAGE);
	eClass.getEStructuralFeatures().add(eReference1);

	EReference eReference2 = EcoreFactory.eINSTANCE.createEReference();
	eReference2.setContainment(true);
	eReference2.setName("containmentRef");
	eReference2.setEType(EcorePackage.Literals.EPACKAGE);
	eClass.getEStructuralFeatures().add(eReference2);

	EReference eReference3 = EcoreFactory.eINSTANCE.createEReference();
	eReference3.setContainment(false);
	eReference3.setTransient(true);
	eReference3.setName("transientRef");
	eReference3.setEType(EcorePackage.Literals.EPACKAGE);
	eClass.getEStructuralFeatures().add(eReference3);

	EReference eReference4 = EcoreFactory.eINSTANCE.createEReference();
	eReference4.setContainment(false);
	eReference4.setVolatile(true);
	eReference4.setName("volatileRef");
	eReference4.setEType(EcorePackage.Literals.EPACKAGE);
	eClass.getEStructuralFeatures().add(eReference4);

	EReference eReference5 = EcoreFactory.eINSTANCE.createEReference();
	eReference5.setContainment(false);
	eReference5.setDerived(true);
	eReference5.setName("derivedRef");
	eReference5.setEType(EcorePackage.Literals.EPACKAGE);
	eClass.getEStructuralFeatures().add(eReference5);

	EObject object = ePackage.getEFactoryInstance().create(eClass);
	object.eSet(EcorePackage.Literals.ENAMED_ELEMENT__NAME, "testname");
	object.eSet(eReference1, EcorePackage.eINSTANCE);
	object.eSet(eReference2, ePackage.getEFactoryInstance().create(eClass));
	object.eSet(eReference3, EcorePackage.eINSTANCE);
	object.eSet(eReference4, EcorePackage.eINSTANCE);
	object.eSet(eReference5, EcorePackage.eINSTANCE);

	Resource testResource = new XMIResourceImpl(URI.createPlatformResourceURI("test.ecore", true));
	testResource.getContents().add(object);
	IResourceDescription resourceDescription = createResourceDescription(testResource);
	assertEquals("Only one external reference expected", 1, size(resourceDescription.getReferenceDescriptions()));
	IReferenceDescription referenceDescription = resourceDescription.getReferenceDescriptions().iterator().next();
	assertEquals(-1, referenceDescription.getIndexInList());
	assertEquals(EcoreUtil.getURI(object), referenceDescription.getSourceEObjectUri());
	assertEquals(eReference1, referenceDescription.getEReference());
	assertEquals(EcoreUtil.getURI(EcorePackage.eINSTANCE), referenceDescription.getTargetEObjectUri());
	assertEquals(EcoreUtil.getURI(object), referenceDescription.getContainerEObjectURI());
}
 
Example #23
Source File: DefaultReferenceDescriptionTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testCrossResourceContainment() {
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	ePackage.setName("test");
	ePackage.setNsPrefix("test");
	ePackage.setNsURI("test");

	EClass eClass = EcoreFactory.eINSTANCE.createEClass();
	eClass.setName("Test");
	ePackage.getEClassifiers().add(eClass);
	
	EAttribute nameAttribute = EcoreFactory.eINSTANCE.createEAttribute();
	nameAttribute.setName("name");
	nameAttribute.setID(true);
	nameAttribute.setEType(EcorePackage.Literals.ESTRING);
	eClass.getEStructuralFeatures().add(nameAttribute);

	EReference containmentRef = EcoreFactory.eINSTANCE.createEReference();
	containmentRef.setContainment(true);
	containmentRef.setName("crossResourceContainment");
	containmentRef.setEType(eClass);
	containmentRef.setResolveProxies(true);
	eClass.getEStructuralFeatures().add(containmentRef);
	
	EReference containerRef = EcoreFactory.eINSTANCE.createEReference();
	containerRef.setName("containerRef");
	containerRef.setEType(eClass);
	containerRef.setResolveProxies(true);
	containerRef.setEOpposite(containmentRef);
	containmentRef.setEOpposite(containerRef);
	eClass.getEStructuralFeatures().add(containerRef);

	EObject container = ePackage.getEFactoryInstance().create(eClass);
	EObject child = ePackage.getEFactoryInstance().create(eClass);
	
	Resource containerResource = new XMIResourceImpl(URI.createPlatformResourceURI("container.ecore", true));
	Resource childResource = new XMIResourceImpl(URI.createPlatformResourceURI("child.ecore", true));
	ResourceSet resourceSet = new ResourceSetImpl();
	resourceSet.getResources().add(containerResource);
	resourceSet.getResources().add(childResource);
	
	containerResource.getContents().add(container);
	childResource.getContents().add(child);
	
	container.eSet(containmentRef, child);
	assertTrue(container.eResource() != child.eResource());
	
	{ 
		IResourceDescription containerDescription = createResourceDescription(containerResource);
		IReferenceDescription onlyContainerElement = Iterables.getOnlyElement(containerDescription.getReferenceDescriptions());
		assertEquals(-1, onlyContainerElement.getIndexInList());
		assertEquals(EcoreUtil.getURI(container), onlyContainerElement.getSourceEObjectUri());
		assertEquals(containmentRef, onlyContainerElement.getEReference());
		assertEquals(EcoreUtil.getURI(child), onlyContainerElement.getTargetEObjectUri());
	}
	{
		IResourceDescription childDescription = createResourceDescription(childResource);
		IReferenceDescription onlyChildElement = Iterables.getOnlyElement(childDescription.getReferenceDescriptions());
		assertEquals(-1, onlyChildElement.getIndexInList());
		assertEquals(EcoreUtil.getURI(child), onlyChildElement.getSourceEObjectUri());
		assertEquals(containerRef, onlyChildElement.getEReference());
		assertEquals(EcoreUtil.getURI(container), onlyChildElement.getTargetEObjectUri());
	}
}