Java Code Examples for org.eclipse.emf.ecore.resource.impl.ResourceSetImpl

The following are top voted examples for showing how to use org.eclipse.emf.ecore.resource.impl.ResourceSetImpl. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: neoscada   File: ArduinoDriverImpl.java   View source code 7 votes vote down vote up
@Override
public Profile getProfile ()
{
    if ( this.profile == null )
    {
        final ResourceSet rs = new ResourceSetImpl ();
        final Resource r = rs.createResource ( URI.createURI ( DEFAULT_URI ) );
        try
        {
            r.load ( null );
        }
        catch ( final IOException e )
        {
            throw new RuntimeException ( e );
        }
        this.profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
        if ( this.profile == null )
        {
            throw new IllegalStateException ( String.format ( "Resource loaded from %s does not contain an object of type %s", DEFAULT_URI, Profile.class.getName () ) );
        }
    }

    return this.profile;
}
 
Example 2
Project: MBSE-Vacation-Manager   File: Validate.java   View source code 6 votes vote down vote up
public Validate()
{
	Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
    Map<String, Object> m = reg.getExtensionToFactoryMap();
    m.put("calender", new XMIResourceFactoryImpl());
    

	ResourceSet rs = new ResourceSetImpl();
	Resource r = rs.getResource(URI.createFileURI("model/mynew.calender"), true);
	
	EObject root = r.getContents().get(0);
	
	Iterator<EObject> i = r.getAllContents();
	while(i.hasNext())
		System.out.println(i.next());
}
 
Example 3
Project: gemoc-studio-modeldebugging   File: GemocSequentialPropertyTester.java   View source code 6 votes vote down vote up
protected boolean isModel(IAdaptable receiver){
	IFile modelFile = (IFile)(receiver).getAdapter(IFile.class);
	if(modelFile !=null){
		ResourceSet rs = new ResourceSetImpl();
		URI modelURI = URI.createURI("platform:/resource/"+modelFile.getFullPath().toString());
		try{
			Resource resource = rs.getResource(modelURI, true);
		if (resource != null) {
			return true;
		}
		} catch (Exception e){
			// not a valid model, simply ignore
			return false;
		}
	}
	return false;
}
 
Example 4
Project: gemoc-studio-modeldebugging   File: CreateDSAWizardContextActionDSAK3.java   View source code 6 votes vote down vote up
private GenModel loadGenmodel(String path) {
	try {
		if (!EPackage.Registry.INSTANCE.containsKey(GenModelPackage.eNS_URI))
			EPackage.Registry.INSTANCE.put(GenModelPackage.eNS_URI, GenModelPackage.eINSTANCE);

		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("genmodel", new XMIResourceFactoryImpl());

		ResourceSet rs = new ResourceSetImpl();
		URI uri = URI.createURI(path);
		Resource pkg = rs.getResource(uri, true);

		return (GenModel) pkg.getContents().get(0);
	} catch (Exception e) {
		// ...
	}

	return null;
}
 
Example 5
Project: gemoc-studio-modeldebugging   File: CreateDSAProposal.java   View source code 6 votes vote down vote up
private GenModel loadGenmodel(String path) {
	try {
		if (!EPackage.Registry.INSTANCE.containsKey(GenModelPackage.eNS_URI))
			EPackage.Registry.INSTANCE.put(GenModelPackage.eNS_URI, GenModelPackage.eINSTANCE);

		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("genmodel", new XMIResourceFactoryImpl());

		ResourceSet rs = new ResourceSetImpl();
		URI uri = URI.createURI(path);
		Resource pkg = rs.getResource(uri, true);

		return (GenModel) pkg.getContents().get(0);
	} catch (Exception e) {
		// ...
	}

	return null;
}
 
Example 6
Project: neoscada   File: ChartConfiguratorView.java   View source code 6 votes vote down vote up
public void setChartConfiguration ( final Chart chart )
{
    if ( chart == null )
    {
        this.viewer.setInput ( null );
    }
    else
    {
        if ( chart.eResource () == null )
        {
            final ResourceSetImpl rs = new ResourceSetImpl ();
            final Resource r = rs.createResource ( URI.createURI ( "urn:dummy" ) );
            r.getContents ().add ( chart );
        }

        if ( chart.eResource ().getURI () == null )
        {
            chart.eResource ().setURI ( URI.createURI ( "urn:dummy" ) );
        }

        this.viewer.setInput ( chart.eResource () );
    }
}
 
Example 7
Project: neoscada   File: ChartHelper.java   View source code 6 votes vote down vote up
public static Chart loadConfiguraton ( final String configurationUri )
{
    if ( configurationUri == null || configurationUri.isEmpty () )
    {
        return null;
    }

    // load
    ChartPackage.eINSTANCE.eClass ();

    final ResourceSet resourceSet = new ResourceSetImpl ();

    resourceSet.getResourceFactoryRegistry ().getExtensionToFactoryMap ().put ( "*", new XMIResourceFactoryImpl () ); //$NON-NLS-1$

    final Resource resource = resourceSet.getResource ( URI.createURI ( configurationUri ), true );

    for ( final EObject o : resource.getContents () )
    {
        if ( o instanceof Chart )
        {
            return (Chart)o;
        }
    }
    return null;
}
 
Example 8
Project: neoscada   File: DetailViewImpl.java   View source code 6 votes vote down vote up
private void load ()
{
    logger.info ( "Loading: {}", this.uri ); //$NON-NLS-1$

    final ResourceSet resourceSet = new ResourceSetImpl ();

    resourceSet.getResourceFactoryRegistry ().getExtensionToFactoryMap ().put ( "*", new XMIResourceFactoryImpl () ); //$NON-NLS-1$

    final URI file = URI.createURI ( this.uri );
    final Resource resource = resourceSet.getResource ( file, true );

    for ( final EObject o : resource.getContents () )
    {
        if ( o instanceof View )
        {
            createView ( (View)o );
        }
    }
}
 
Example 9
Project: neoscada   File: ServerHostImpl.java   View source code 6 votes vote down vote up
public Collection<? extends ServerDescriptor> startServer ( final URI exporterFileUri, final String locationLabel ) throws CoreException
{
    final ResourceSetImpl resourceSet = new ResourceSetImpl ();

    resourceSet.getResourceFactoryRegistry ().getExtensionToFactoryMap ().put ( "*", new ExporterResourceFactoryImpl () );

    final Resource resource = resourceSet.createResource ( exporterFileUri );
    try
    {
        resource.load ( null );
    }
    catch ( final IOException e )
    {
        throw new CoreException ( StatusHelper.convertStatus ( HivesPlugin.PLUGIN_ID, "Failed to load configuration", e ) );
    }

    final DocumentRoot root = (DocumentRoot)EcoreUtil.getObjectByType ( resource.getContents (), ExporterPackage.Literals.DOCUMENT_ROOT );
    if ( root == null )
    {
        throw new CoreException ( new Status ( IStatus.ERROR, HivesPlugin.PLUGIN_ID, "Failed to locate exporter configuration in: " + exporterFileUri ) );
    }
    return startServer ( root, locationLabel );
}
 
Example 10
Project: neoscada   File: ParserDriverImpl.java   View source code 6 votes vote down vote up
/**
 * @generated NOT
 */
@Override
public Profile getProfile ()
{
    if ( this.profile == null )
    {
        final ResourceSet rs = new ResourceSetImpl ();
        final Resource r = rs.createResource ( URI.createURI ( DEFAULT_URI ), "org.eclipse.scada.configuration.world.osgi.profile" );
        try
        {
            r.load ( null );
        }
        catch ( final IOException e )
        {
            throw new RuntimeException ( e );
        }
        this.profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
        if ( this.profile == null )
        {
            throw new IllegalStateException ( String.format ( "Resource loaded from %s does not contain an object of type %s", DEFAULT_URI, Profile.class.getName () ) );
        }
    }

    return this.profile;
}
 
Example 11
Project: neoscada   File: DriverApplicationImpl.java   View source code 6 votes vote down vote up
/**
 * @generated NOT
 */
@Override
public Profile getProfile ()
{
    if ( this.profile == null )
    {
        final ResourceSet rs = new ResourceSetImpl ();
        final Resource r = rs.createResource ( URI.createURI ( DEFAULT_URI ), "org.eclipse.scada.configuration.world.osgi.profile" );
        try
        {
            r.load ( null );
        }
        catch ( final IOException e )
        {
            throw new RuntimeException ( e );
        }
        this.profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
        if ( this.profile == null )
        {
            throw new IllegalStateException ( String.format ( "Resource loaded from %s does not contain an object of type %s", DEFAULT_URI, Profile.class.getName () ) );
        }
    }

    return this.profile;
}
 
Example 12
Project: neoscada   File: CommonPackageHandler.java   View source code 6 votes vote down vote up
/**
 * Inject the CA bootstrap property to the profile
 *
 * @param file
 *            the profile.xml file in the package target
 * @throws IOException
 */
protected void patchProfile ( final String appName, final File file ) throws IOException
{
    final ResourceSet rs = new ResourceSetImpl ();
    final Resource r = rs.createResource ( URI.createFileURI ( file.toString () ) );
    r.load ( null );

    final Profile profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
    Profiles.addSystemProperty ( profile, "org.eclipse.scada.ca.file.provisionJsonUrl", "file:///usr/share/eclipsescada/ca.bootstrap/bootstrap." + appName + ".json" );
    r.save ( null );
}
 
Example 13
Project: neoscada   File: ModelLoader.java   View source code 6 votes vote down vote up
public T load ( final URI uri, final String contentTypeId ) throws IOException
{
    final ResourceSet rs = new ResourceSetImpl ();
    final Resource r = rs.createResource ( uri, contentTypeId );
    r.load ( null );

    for ( final Object o : r.getContents () )
    {
        if ( this.clazz.isAssignableFrom ( o.getClass () ) )
        {
            return this.clazz.cast ( o );
        }
    }

    throw new IllegalStateException ( String.format ( "Model %s does not contain an object of type %s", uri, this.clazz ) );
}
 
Example 14
Project: neoscada   File: DaveDriverImpl.java   View source code 6 votes vote down vote up
/**
 * @generated NOT
 */
@Override
public Profile getProfile ()
{
    if ( this.profile == null )
    {
        final ResourceSet rs = new ResourceSetImpl ();
        final Resource r = rs.createResource ( URI.createURI ( DEFAULT_URI ), "org.eclipse.scada.configuration.world.osgi.profile" );
        try
        {
            r.load ( null );
        }
        catch ( final IOException e )
        {
            throw new RuntimeException ( e );
        }
        this.profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
        if ( this.profile == null )
        {
            throw new IllegalStateException ( String.format ( "Resource loaded from %s does not contain an object of type %s", DEFAULT_URI, Profile.class.getName () ) );
        }
    }

    return this.profile;
}
 
Example 15
Project: neoscada   File: ModbusDriverImpl.java   View source code 6 votes vote down vote up
@Override
public Profile getProfile ()
{
    if ( this.profile == null )
    {
        final ResourceSet rs = new ResourceSetImpl ();
        final Resource r = rs.createResource ( URI.createURI ( DEFAULT_URI ), "org.eclipse.scada.configuration.world.osgi.profile" );
        try
        {
            r.load ( null );
        }
        catch ( final IOException e )
        {
            throw new RuntimeException ( e );
        }
        this.profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
        if ( this.profile == null )
        {
            throw new IllegalStateException ( String.format ( "Resource loaded from %s does not contain an object of type %s", DEFAULT_URI, Profile.class.getName () ) );
        }
    }

    return this.profile;
}
 
Example 16
Project: neoscada   File: DefaultValueArchiveServerImpl.java   View source code 6 votes vote down vote up
@Override
public Profile getProfile ()
{
    if ( this.profile == null )
    {
        final ResourceSet rs = new ResourceSetImpl ();
        final Resource r = rs.createResource ( URI.createURI ( DEFAULT_URI ), "org.eclipse.scada.configuration.world.osgi.profile" );
        try
        {
            r.load ( null );
        }
        catch ( final IOException e )
        {
            throw new RuntimeException ( e );
        }
        this.profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
        if ( this.profile == null )
        {
            throw new IllegalStateException ( String.format ( "Resource loaded from %s does not contain an object of type %s", DEFAULT_URI, Profile.class.getName () ) );
        }
    }

    return this.profile;
}
 
Example 17
Project: neoscada   File: DefaultMasterServerImpl.java   View source code 6 votes vote down vote up
@Override
public Profile getProfile ()
{
    if ( this.profile == null )
    {
        final ResourceSet rs = new ResourceSetImpl ();
        final Resource r = rs.createResource ( URI.createURI ( DEFAULT_URI ), "org.eclipse.scada.configuration.world.osgi.profile" );
        try
        {
            r.load ( null );
        }
        catch ( final IOException e )
        {
            throw new RuntimeException ( e );
        }
        this.profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
        if ( this.profile == null )
        {
            throw new IllegalStateException ( String.format ( "Resource loaded from %s does not contain an object of type %s", DEFAULT_URI, Profile.class.getName () ) );
        }
    }

    return this.profile;
}
 
Example 18
Project: neoscada   File: Hive.java   View source code 6 votes vote down vote up
private static RootType parse ( final URI uri ) throws IOException
{
    final ResourceSet rs = new ResourceSetImpl ();
    rs.getResourceFactoryRegistry ().getExtensionToFactoryMap ().put ( "*", new ConfigurationResourceFactoryImpl () );

    final Resource r = rs.createResource ( uri );
    r.load ( null );

    final DocumentRoot doc = (DocumentRoot)EcoreUtil.getObjectByType ( r.getContents (), ConfigurationPackage.Literals.DOCUMENT_ROOT );
    if ( doc == null )
    {
        return null;
    }
    else
    {
        return doc.getRoot ();
    }
}
 
Example 19
Project: greycat-idea-plugin   File: PrettyPrinter.java   View source code 6 votes vote down vote up
protected ResourceSet getEcoreModel(File ecorefile) {

        ResourceSetImpl rs = new ResourceSetImpl();
        Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        try {
            URI fileUri = URI.createFileURI(ecorefile.getCanonicalPath());
            Resource resource = rs.createResource(fileUri);
            resource.load(null);
            EcoreUtil.resolveAll(resource);
            rs.getResources().add(resource);
            EcoreUtil.resolveAll(rs);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return rs;
    }
 
Example 20
Project: JavaGraph   File: EcoreResource.java   View source code 6 votes vote down vote up
public EcoreResource(File typeTarget, File instanceTarget) {
    this.m_resourceSet = new ResourceSetImpl();
    this.m_resourceSet.getResourceFactoryRegistry()
        .getExtensionToFactoryMap()
        .put("*", new XMIResourceFactoryImpl());

    this.m_typeFile = typeTarget;
    this.m_instanceFile = instanceTarget;

    if (this.m_typeFile == this.m_instanceFile || this.m_typeFile == null
        || this.m_instanceFile == null) {
        this.relPath = "";
    } else {
        this.relPath =
            groove.io.Util.getRelativePath(new File(this.m_instanceFile.getAbsoluteFile()
                .getParent()), this.m_typeFile.getAbsoluteFile())
                .toString();
    }
}
 
Example 21
Project: TOSCA-Studio   File: ExtensionsManager.java   View source code 6 votes vote down vote up
public static void createExtendedTosca() {
	ResourceSet resSet = new ResourceSetImpl();
	URI modelURI = URI
			.createURI("file:/C:/Users/schallit/workspace-tosca2/plugins/org.eclipse.cmf.occi.tosca.extended/model/extendedTosca.occie");
	resource = resSet.createResource(modelURI);
	Extension extension = OCCIFactory.eINSTANCE.createExtension();
	extension.setDescription("Extended TOSCA");
	extension.setScheme("http://org.occi/extendedTosca#");
	extension.setName("extendedTosca");
	Extension toscaExtension = OcciHelper.loadExtension("http://org.occi/tosca#");
	extension.getImport().add(extensionsPerName.get("core"));
	extension.getImport().add(extensionsPerName.get("infrastructure"));
	extension.getImport().add(extensionsPerName.get("platform"));
	extension.getImport().add(extensionsPerName.get("sla"));
	extension.getImport().add(toscaExtension);
	copy(toscaExtension);
	extensionsPerName.replace("tosca", toscaExtension);
	resource.getContents().add(extension);
	extensionsPerName.put("extendedTosca", extension);
	currentExtensionToBeBuild = extension;
}
 
Example 22
Project: TOSCA-Studio   File: ConfigManager.java   View source code 6 votes vote down vote up
public static void createConfiguration(String path) {
	String name = convertPathToConfigName(path);
	ResourceSet resSet = new ResourceSetImpl();
	URI modelURI = URI
			.createURI("file:/C:/Users/schallit/workspace-tosca2/plugins/org.eclipse.cmf.occi.tosca.examples/" + name + ".extendedTosca");
	resource = resSet.createResource(modelURI);
	Configuration configuration = OCCIFactory.eINSTANCE.createConfiguration();
	configuration.getUse().add(OcciHelper.loadExtension("http://schemas.ogf.org/occi/core#"));
	configuration.getUse().add(OcciHelper.loadExtension("http://schemas.ogf.org/occi/infrastructure#"));
	configuration.getUse().add(OcciHelper.loadExtension("http://schemas.ogf.org/occi/platform#"));
	configuration.getUse().add(OcciHelper.loadExtension("http://schemas.ogf.org/occi/sla#"));
	configuration.getUse().add(OcciHelper.loadExtension("http://org.occi/tosca#"));
	configuration.getUse().add(OcciHelper.loadExtension("http://org.occi/extendedTosca#"));
	resource.getContents().add(configuration);
	currentConfiguration = configuration;
}
 
Example 23
Project: Tarski   File: EcoreUtilities.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public static void saveResources(final List<EObject> root, final URI uri) {
  final ResourceSet resourceSet = new ResourceSetImpl();
  resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
      .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMLResourceFactoryImpl());
  final Resource resource = resourceSet.createResource(uri);
  resource.getContents().addAll(root);

  final Map options = new HashMap();
  options.put(XMLResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE);
  try {
    resource.save(options);
  } catch (final IOException e) {
    e.printStackTrace();
  }
}
 
Example 24
Project: OCCI-Studio   File: DesignerGeneratorAction.java   View source code 6 votes vote down vote up
private IProject generateDesignProject(String occieLocation, String designName, String designProjectName,
		final IProgressMonitor monitor) throws CoreException, IOException {

	// Load the ecore file.
	String ecoreLocation = occieLocation.replace(".occie", ".ecore");
	URI ecoreURI = URI.createFileURI(ecoreLocation);
	// Create a new resource set.
	ResourceSet resourceSet = new ResourceSetImpl();
	// Load the OCCI resource.
	org.eclipse.emf.ecore.resource.Resource resource = resourceSet.getResource(ecoreURI, true);
	// Return the first element.
	EPackage ePackage = (EPackage) resource.getContents().get(0);

	String extensionScheme = Occi2Ecore.convertEcoreNamespace2OcciScheme(ePackage.getNsURI());

	// Register the ePackage to avoid an error when trying to open the generated
	// .odesign file,
	EPackage.Registry.INSTANCE.put(ePackage.getNsURI(), ePackage);

	
	URI occieURI = URI.createFileURI(occieLocation);
	
	/*
	 * Create design project
	 */
	IProject project = DesignerGeneratorUtils.genDesignProject(designProjectName, designName, extensionScheme,
			new ProgressMonitorDialog(shell));

	/*
	 * Create design model
	 */
	org.eclipse.cmf.occi.core.gen.design.main.Generate generator = new org.eclipse.cmf.occi.core.gen.design.main.Generate(
			occieURI, project.getFolder("description").getLocation().toFile(), new ArrayList<String>());
	generator.doGenerate(BasicMonitor.toMonitor(monitor));
	project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
	return project;
}
 
Example 25
Project: OCCI-Studio   File: RegisterOCCIExtensionAction.java   View source code 6 votes vote down vote up
/**
 * @see IActionDelegate#run(IAction)
 */
public void run(IAction action) {
	if (selection != null) {
		IFile selectedFile = (IFile) ((IStructuredSelection) selection)
				.getFirstElement();

		// Use a platform:/resource/ URI
		URI uri = URI.createPlatformResourceURI(selectedFile.getFullPath().toString(), true);

		ResourceSet rs = new ResourceSetImpl();
		Resource r = rs.getResource(uri, true);

		Extension extension = (Extension) r.getContents().get(0);
		OcciRegistry.getInstance().registerExtension(extension.getScheme(),
				uri.toString());
		closeOtherSessions(selectedFile.getProject());
		MessageDialog.openInformation(shell,
				Messages.RegisterExtensionAction_ExtRegistration,
				Messages.RegisterExtensionAction_RegisteredExtension
						+ extension.getScheme());
	}
}
 
Example 26
Project: SurveyDSL   File: SurveyGenerator.java   View source code 6 votes vote down vote up
private static Survey loadSurveyModel(String modulePath) {
	// Initialize the model
	QueryITPackage.eINSTANCE.eClass();

	Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
	Map<String, Object> m = reg.getExtensionToFactoryMap();
	m.put("xmi", new XMIResourceFactoryImpl());
	m.put("ecore", new EcoreResourceFactoryImpl());

	// Obtain a new resource set
	ResourceSet resSet = new ResourceSetImpl();

	// Get the resource
	//Resource resource = resSet.getResource(URI.createFileURI(modulePath), true);
	Resource resource = resSet.getResource(URI.createURI(modulePath), true);

	// Get the first model element and cast it to the right type, in my
	// example everything is included in this first node
	Survey s = (Survey) resource.getContents().get(0);

	return s;
}
 
Example 27
Project: termsuite-ui   File: WorkspaceUtil.java   View source code 6 votes vote down vote up
public static void saveResource(EObject emfObject, Path path) {
		// Obtain a new resource set
		ResourceSet resSet = new ResourceSetImpl();
		Resource resource = resSet
				.createResource(URI.createFileURI(path.toString()));
		// Get the first model element and cast it to the right type, in my
		// example everything is hierarchical included in this first node
		
//		if (emfObject instanceof EPipeline) {
//			resource.getContents().add(((EPipeline) emfObject).getTaggerConfig());
//		}
		resource.getContents().add(emfObject);

		// now save the content.
		Map<String, Object> options = Maps.newHashMap();
//		options.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, false);
		try {
			resource.save(options);
		} catch (IOException e) {
			throw new TermSuiteException("Could not save resource " + emfObject.getClass().getSimpleName(), e);
		}
	}
 
Example 28
Project: xtext-core   File: LazyLinkingResourceTest.java   View source code 6 votes vote down vote up
@Test public void testResolveLazyCrossReferences_02() throws Exception {
	with(lazyLinkingTestLangaugeSetup());
	ResourceSetImpl rs = new ResourceSetImpl();
	final Resource res1 = rs.createResource(URI.createURI("file1.lazylinkingtestlanguage"));
	Resource res2 = rs.createResource(URI.createURI("file2.lazylinkingtestlanguage"));
	res1.load(new StringInputStream("type Foo { } type Baz { Foo Bar prop; } }"), null);
	res2.load(new StringInputStream("type Bar { }"), null);
	res1.eAdapters().add(notificationAlert);
	
	Model m = (Model) res1.getContents().get(0);
	Type t = m.getTypes().get(1);
	Property p = t.getProperties().get(0);
	final InternalEList<Type> types = (InternalEList<Type>) p.getType();
	assertEquals(2, types.size());
	for (Iterator<Type> it = types.basicIterator(); it.hasNext();) {
		final Type tt = it.next();
		assertTrue(tt.eIsProxy());
	}
	((LazyLinkingResource) res1).resolveLazyCrossReferences(CancelIndicator.NullImpl);
	assertFalse(types.basicGet(0).eIsProxy());
	assertTrue(types.basicGet(1).eIsProxy());
	res1.eAdapters().remove(notificationAlert);
   	EcoreUtil.resolveAll(res1);
	assertFalse(types.basicGet(0).eIsProxy());
	assertFalse(types.basicGet(1).eIsProxy());
}
 
Example 29
Project: benchmarx   File: MediniQVTFamiliesToPersonsConfig.java   View source code 6 votes vote down vote up
/**
 * Allows to save the current state of the source and target models
 * 
 * @param name : Filename 
 */
public void saveModels(String name) {
	ResourceSet set = new ResourceSetImpl();
	set.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
	URI srcURI = URI.createFileURI(RESULTPATH + "/" + name + "Family.xmi");
	URI trgURI = URI.createFileURI(RESULTPATH + "/" + name + "Person.xmi");
	Resource resSource = set.createResource(srcURI);
	Resource resTarget = set.createResource(trgURI);
	
	EObject colSource = EcoreUtil.copy(getSourceModel());
	EObject colTarget = EcoreUtil.copy(getTargetModel());
	
	resSource.getContents().add(colSource);
	resTarget.getContents().add(colTarget);
	
	try {
		resSource.save(null);
		resTarget.save(null);
	} catch (IOException e) {
		e.printStackTrace();
	}		
}
 
Example 30
Project: xtext-core   File: ResourceSetBasedResourceDescriptionsTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	resourceSet = new ResourceSetImpl();
	IQualifiedNameProvider qualifiedNameProvider = new IQualifiedNameProvider.AbstractImpl() {
		
		@Override
		public QualifiedName getFullyQualifiedName(EObject obj) {
			return QualifiedName.create(((ENamedElement) obj).getName());
		}

		@Override
		public QualifiedName apply(EObject from) {
			return QualifiedName.create(((ENamedElement) from).getName());
		}
		
	};
	resourceDescriptionManager = new DefaultResourceDescriptionManager();
	resourceDescriptionManager.setCache(IResourceScopeCache.NullImpl.INSTANCE);
	DefaultResourceDescriptionStrategy strategy = new DefaultResourceDescriptionStrategy();
	strategy.setQualifiedNameProvider(qualifiedNameProvider);
	resourceDescriptionManager.setStrategy(strategy);
	resDescs = new ResourceSetBasedResourceDescriptions();
	resDescs.setContext(resourceSet);
	resDescs.setRegistry(this);
	container = new ResourceDescriptionsBasedContainer(resDescs);
}
 
Example 31
Project: benchmarx   File: EMoflonFamiliesToPersons.java   View source code 6 votes vote down vote up
public void saveModels(String name) {
	ResourceSet set = new ResourceSetImpl();
	set.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
	URI srcURI = URI.createFileURI(RESULTPATH + "/" + name + "Family.xmi");
	URI trgURI = URI.createFileURI(RESULTPATH + "/" + name + "Person.xmi");
	Resource resSource = set.createResource(srcURI);
	Resource resTarget = set.createResource(trgURI);
	
	EObject colSource = EcoreUtil.copy(getSourceModel());
	EObject colTarget = EcoreUtil.copy(getTargetModel());
	
	resSource.getContents().add(colSource);
	resTarget.getContents().add(colTarget);
	
	try {
		resSource.save(null);
		resTarget.save(null);
	} catch (IOException e) {
		e.printStackTrace();
	}
	
}
 
Example 32
Project: haetae   File: ProgramPerformanceAnalyser.java   View source code 6 votes vote down vote up
public void visit(EOLModule program)
{
	ResourceSet resourceSet = new ResourceSetImpl();
	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
	Resource resource = resourceSet.createResource(URI.createFileURI(new File("test.xmi").getAbsolutePath()));
	resource.getContents().add(program);

	model = new InMemoryEmfModel("EOL",	program.eResource(), EolPackage.eINSTANCE);
	try {
		matchSelectPatterOne(program);
		matchSelectPatterTwo(program);
		matchSelectPatterThree(program);
		matchSelectPatterFour(program);
		matchSelectPatterFive(program);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 33
Project: library-training   File: NewChildTest.java   View source code 6 votes vote down vote up
/**
 * Check that referenced element type are in the registry
 */
@Test
public void checkMenuNewChildElementTypeIdRefs() {
	URI createPlatformPluginURI = URI.createPlatformPluginURI(NEW_CHILD_MENU_PATH, true);
	ResourceSetImpl resourceSetImpl = new ResourceSetImpl();
	Resource resource = resourceSetImpl.getResource(createPlatformPluginURI, true);

	TreeIterator<EObject> allContents = resource.getAllContents();
	while (allContents.hasNext()) {
		EObject eObject = (EObject) allContents.next();
		if (eObject instanceof CreationMenu) {
			String iconPath = ((CreationMenu) eObject).getIcon();
			 if (iconPath != null && !"".equals(iconPath)){
					try {
						Assert.assertNotNull("The icon "+iconPath+" can't be found", FileLocator.find(new URL(iconPath)));
					} catch (MalformedURLException e) {
						Assert.fail("The new child menu is refering to a malformed url "+iconPath);
					}
			 }
		}
	}
}
 
Example 34
Project: dsl-devkit   File: ExtendedLanguageConfig.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Registers all EPackages (transitively) referenced by registered GenModels prior to calling {@link LanguageConfig#setUri(String)}.
 */
@Override
public void setUri(final String uri) {
  ResourceSet rs = new ResourceSetImpl();
  Set<URI> result = Sets.newHashSet();
  @SuppressWarnings("deprecation")
  Map<String, URI> genModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
  for (Map.Entry<String, URI> entry : genModelLocationMap.entrySet()) {
    Resource resource = GenModelAccess.getGenModelResource(null, entry.getKey(), rs);
    if (resource != null) {
      for (EObject model : resource.getContents()) {
        if (model instanceof GenModel) {
          GenModel genModel = (GenModel) model;
          result.addAll(getReferencedEPackages(genModel));
        }
      }
    }
  }
  for (URI u : result) {
    addLoadedResource(u.toString());
  }
  super.setUri(uri);
}
 
Example 35
Project: dsl-devkit   File: CheckResourceUtil.java   View source code 6 votes vote down vote up
/**
 * Gets all available grammars.
 * <p>
 * The result contains no null entries.
 * </p>
 *
 * @return an iterator over all grammars in the workspace followed by all those in the registry.
 */
private Iterable<Grammar> allGrammars() {
  final ResourceSet resourceSetForResolve = new ResourceSetImpl();
  final Function<IEObjectDescription, Grammar> description2GrammarTransform = new Function<IEObjectDescription, Grammar>() {
    @Override
    public Grammar apply(final IEObjectDescription desc) {
      EObject obj = desc.getEObjectOrProxy();
      if (obj != null && obj.eIsProxy()) {
        obj = EcoreUtil.resolve(obj, resourceSetForResolve);
      }
      if (obj instanceof Grammar && !obj.eIsProxy()) {
        return (Grammar) obj;
      } else {
        return null;
      }

    }
  };

  final Iterable<IEObjectDescription> grammarDescriptorsFromIndex = Access.getIResourceDescriptions().get().getExportedObjectsByType(XtextPackage.Literals.GRAMMAR);
  return Iterables.concat(Iterables.filter(Iterables.transform(grammarDescriptorsFromIndex, description2GrammarTransform), Predicates.notNull()), allGrammarsFromRegistry());
}
 
Example 36
Project: M2Doc   File: ServerWithAuthentication.java   View source code 6 votes vote down vote up
@BeforeClass
public static void startCDOServer() throws IOException, CommitException {
    server = new CDOServer(true);
    server.start();
    IConnector connector = M2DocCDOUtils
            .getConnector(CDOServer.PROTOCOL + "://" + CDOServer.IP + ":" + CDOServer.PORT);
    CDOSession session = M2DocCDOUtils.openSession(connector, CDOServer.REPOSITORY_NAME, CDOServer.USER_NAME,
            CDOServer.PASSWORD);
    final CDOTransaction transaction = M2DocCDOUtils.openTransaction(session);
    final CDOResource resource = transaction.createResource("anydsl.ecore");
    final ResourceSet resourceSet = new ResourceSetImpl();
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
    final Resource anyDSLResource = resourceSet.getResource(URI.createFileURI("resources/anydsl.ecore"), true);
    resource.getContents().addAll(anyDSLResource.getContents());
    resource.save(null);
    transaction.commit();
    transaction.close();
    session.close();
    connector.close();

    if (!EMFPlugin.IS_ECLIPSE_RUNNING) {
        ConfigurationProviderService.getInstance().register(CONFIGURATION_PROVIDER);
        M2DocUtils.registerServicesConfigurator(SERVICES_CONFIGURATOR_DESCRIPTOR);
    }
}
 
Example 37
Project: dsl-devkit   File: CustomClassAwareEcoreGenerator.java   View source code 6 votes vote down vote up
/**
 * Registers the given source-paths in the generator.
 */
@Override
public void preInvoke() {
  ResourceSet resSet = new ResourceSetImpl();
  Resource resource = resSet.getResource(URI.createURI(genModel), true);
  for (EObject obj : resource.getContents()) {
    if (obj instanceof GenModel) {
      GenModel model = (GenModel) obj;
      addSourcePathForPlugin(model.getModelPluginID());
      for (GenPackage usedPackage : model.getUsedGenPackages()) {
        addSourcePathForPlugin(usedPackage.getGenModel().getModelPluginID());
      }
    }
  }
  LOGGER.info("Registered source path to discover custom classes: " + Joiner.on(", ").join(this.srcPaths));
}
 
Example 38
Project: xtext-core   File: SimpleNameScopeProviderTest.java   View source code 6 votes vote down vote up
@Test public void testGetAllContents() throws Exception {
	SyntheticModelAwareURIConverter models = new SyntheticModelAwareURIConverter();
	ResourceSetImpl rs = new ResourceSetImpl();
	rs.setURIConverter(models);

	models.addModel("foo.importuritestlanguage", "import 'bar.importuritestlanguage' type Foo");
	models.addModel("bar.importuritestlanguage", "type A type B type C");

	Resource resource = rs.getResource(URI.createURI("foo.importuritestlanguage"), true);
	
	IScope scope = getScopeProvider().getScope(((Main)resource.getContents().get(0)).getTypes().get(0), ImportedURIPackage.Literals.TYPE__EXTENDS);
	HashSet<IEObjectDescription> set = Sets.newHashSet(scope.getAllElements());
	assertEquals(4,set.size());
}
 
Example 39
Project: Vitruv   File: ResourceRepositoryImpl.java   View source code 6 votes vote down vote up
public ResourceRepositoryImpl(final File folder, final VitruvDomainRepository metamodelRepository,
        final ClassLoader classLoader) {
    this.metamodelRepository = metamodelRepository;
    this.folder = folder;

    this.resourceSet = new ResourceSetImpl();
    ResourceSetUtil.addExistingFactoriesToResourceSet(this.resourceSet);

    this.modelInstances = new HashMap<VURI, ModelInstance>();
    this.fileSystemHelper = new FileSystemHelper(this.folder);

    initializeUuidProviderAndResolver();
    this.domainToRecorder = new HashMap<VitruvDomain, AtomicEmfChangeRecorder>();

    initializeCorrespondenceModel();
    loadVURIsOfVSMUModelInstances();
}
 
Example 40
Project: Vitruv   File: Models.java   View source code 6 votes vote down vote up
public static Resource loadModel(URL modelURL) {

        ResourceSet resSet = new ResourceSetImpl();
        resSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION,
                new XMIResourceFactoryImpl());

        EcoreResourceFactoryImpl ecoreResFact = new EcoreResourceFactoryImpl();
        URI fileName = BasicTestCase.getURI(modelURL);
        LOGGER.info("Trying to load " + fileName);
        Resource ecoreRes = ecoreResFact.createResource(fileName);
        try {
            ecoreRes.load(null);
        } catch (IOException e) {
            fail("Could not load " + Files.EXAMPLEMODEL_ECORE.getFile() + ". Reason: " + e);
        }

        resSet.getResources().add(ecoreRes);

        return ecoreRes;
    }