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

The following examples show how to use org.eclipse.emf.ecore.resource.impl.ResourceSetImpl. 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 Project: neoscada   Author: eclipse   File: ChartHelper.java    License: Eclipse Public License 1.0 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 #2
Source Project: neoscada   Author: eclipse   File: DetailViewImpl.java    License: Eclipse Public License 1.0 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 #3
Source Project: bonita-studio   Author: bonitasoft   File: XtextComparisonExpressionLoaderTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
@Ignore("I wasn't able to mock what is required AND can't make failing the test with the known bug... sometimes it seems to work")
public void testValidationWithUTF8() {
    final ComparisonExpressionValidator comparisonExpressionValidator = new ComparisonExpressionValidator();
    final ComparisonExpressionValidator spy = Mockito.spy(comparisonExpressionValidator);
    Mockito.doReturn(new ResourceSetImpl()).when(spy).getContextResourceSet();
    final Injector injector = ConditionModelActivator.getInstance().getInjector(ConditionModelActivator.ORG_BONITASOFT_STUDIO_CONDITION_CONDITIONMODEL);
    final XtextComparisonExpressionLoader xtextComparisonExpressionLoader = Mockito
            .spy(new XtextComparisonExpressionLoader(injector.getInstance(ConditionModelGlobalScopeProvider.class),
                    new ModelSearch(Collections::emptyList), new ProjectXtextResourceProvider(injector)));
    Mockito.doReturn(xtextComparisonExpressionLoader).when(spy).getXtextExpressionLoader(Mockito.any(Injector.class),
            any(IModelSearch.class));
    Mockito.doReturn(Collections.singletonList("管理者")).when(xtextComparisonExpressionLoader).getAccessibleReferences(Mockito.any(EObject.class));
    spy.setInputExpression(createNewComparisonExpression(""));

    final IStatus validate = spy.validate("管理者 == \"test\"");
    Assert.assertTrue(validate.isOK());
}
 
Example #4
Source Project: dsl-devkit   Author: dsldevkit   File: CustomClassAwareEcoreGenerator.java    License: Eclipse Public License 1.0 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 #5
Source Project: birt   Author: eclipse   File: SerializerImpl.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void write( Chart cModel, OutputStream os ) throws IOException
{
	// REMOVE ANY TRANSIENT RUNTIME SERIES
	cModel.clearSections( IConstants.RUN_TIME );

	// Create and setup local ResourceSet
	ResourceSet rsChart = new ResourceSetImpl( );
	rsChart.getResourceFactoryRegistry( )
			.getExtensionToFactoryMap( )
			.put( "chart", new ModelResourceFactoryImpl( ) ); //$NON-NLS-1$

	// Create resources to represent the disk files to be used to store the
	// models
	Resource rChart = rsChart.createResource( URI.createFileURI( "test.chart" ) ); //$NON-NLS-1$

	// Add the chart to the resource
	rChart.getContents( ).add( cModel );

	Map<String, Object> options = new HashMap<String, Object>( );
	options.put( XMLResource.OPTION_ENCODING, "UTF-8" ); //$NON-NLS-1$

	// Save the resource to disk
	rChart.save( os, options );
}
 
Example #6
Source Project: neoscada   Author: eclipse   File: ServerHostImpl.java    License: Eclipse Public License 1.0 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 #7
Source Project: xtext-core   Author: eclipse   File: FormatterSerializerIntegrationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testFormatterIntegrationWithSerializer() {
  try {
    final Resource resource = this.factory.createResource(URI.createURI("dummy.ext"));
    new ResourceSetImpl().getResources().add(resource);
    final IDList model = FormattertestlanguageFactory.eINSTANCE.createIDList();
    EList<String> _ids = model.getIds();
    _ids.add("foo");
    EList<EObject> _contents = resource.getContents();
    _contents.add(model);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    BufferedOutputStream _bufferedOutputStream = new BufferedOutputStream(out);
    resource.save(_bufferedOutputStream, Collections.<Object, Object>emptyMap());
    Assert.assertEquals("idlist  foo", out.toString());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #8
Source Project: bonita-studio   Author: bonitasoft   File: ReleaseUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** Extract the namespace URI from a model file using EMF Resource loading. */
public static String getNamespaceURI_Registry(URI modelURI) {
	final ResourceSet resourceSet = new ResourceSetImpl();

	// register delegating package registry
	final PackageRegistry registry = new PackageRegistry(
		resourceSet.getPackageRegistry());
	resourceSet.setPackageRegistry(registry);

	final Resource resource = resourceSet.createResource(modelURI);
	try {
		resource.load(null);
	} catch (final Exception e) {
		// loading should fail here
	}

	return registry.getNsURI();
}
 
Example #9
Source Project: statecharts   Author: Yakindu   File: DefaultSimulationEngineFactory.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected ExecutionContext restore(String context, Statechart statechart) {
	try {
		ResourceSet set = new ResourceSetImpl();
		Resource resource = set.createResource(URI.createURI("snapshot.xmi"));
		if (resource == null)
			return null;
		set.getResources().add(resource);
		resource.load(new URIConverter.ReadableInputStream(context, "UTF_8"), Collections.emptyMap());
		IDomain domain = DomainRegistry.getDomain(statechart);
		Injector injector = domain.getInjector(IDomain.FEATURE_SIMULATION);
		ITypeSystem typeSystem = injector.getInstance(ITypeSystem.class);
		if (typeSystem instanceof AbstractTypeSystem) {
			set.getResources().add(((AbstractTypeSystem) typeSystem).getResource());
		}
		EcoreUtil.resolveAll(resource);
		ExecutionContext result = (ExecutionContext) resource.getContents().get(0);
		result.setSnapshot(true);
		return result;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #10
Source Project: elexis-3-core   Author: elexis   File: FindingsTemplateService.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private String createXMI(FindingsTemplates findingsTemplates){
	Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
	Map<String, Object> m = reg.getExtensionToFactoryMap();
	m.put("xmi", new XMIResourceFactoryImpl());
	ResourceSet resSet = new ResourceSetImpl();
	Resource resource = resSet.createResource(URI.createURI("findingsTemplate.xml"));
	resource.getContents().add(findingsTemplates);
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	
	try {
		resource.save(os, Collections.EMPTY_MAP);
		os.flush();
		String aString = new String(os.toByteArray(), "UTF-8");
		os.close();
		return aString;
	} catch (IOException e) {
		LoggerFactory.getLogger(FindingsTemplateService.class).error("", e);
	}
	return null;
}
 
Example #11
Source Project: neoscada   Author: eclipse   File: DaveDriverImpl.java    License: Eclipse Public License 1.0 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
Source Project: fixflow   Author: fixteam   File: BpmnDeployer.java    License: Apache License 2.0 6 votes vote down vote up
private ResourceSet getResourceSet() {
	// TODO Auto-generated method stub
	ResourceSet resourceSet = new ResourceSetImpl();
	(EPackage.Registry.INSTANCE).put("http://www.omg.org/spec/BPMN/20100524/MODEL", Bpmn2Package.eINSTANCE);
	(EPackage.Registry.INSTANCE).put("http://www.founderfix.com/fixflow", FixFlowPackage.eINSTANCE);
	(EPackage.Registry.INSTANCE).put("http://www.omg.org/spec/DD/20100524/DI", DiPackage.eINSTANCE);
	(EPackage.Registry.INSTANCE).put("http://www.omg.org/spec/DD/20100524/DC", DcPackage.eINSTANCE);
	(EPackage.Registry.INSTANCE).put("http://www.omg.org/spec/BPMN/20100524/DI", BpmnDiPackage.eINSTANCE);
	FixFlowPackage.eINSTANCE.eClass();

	FixFlowPackage xxxPackage = FixFlowPackage.eINSTANCE;
	EPackage.Registry.INSTANCE.put(xxxPackage.getNsURI(), xxxPackage);
	Bpmn2ResourceFactoryImpl ddd = new Bpmn2ResourceFactoryImpl();
	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("fixflow", ddd);

	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn", ddd);

	resourceSet.getPackageRegistry().put(xxxPackage.getNsURI(), xxxPackage);

	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("bpmn", ddd);
	
	return resourceSet;
}
 
Example #13
Source Project: neoscada   Author: eclipse   File: DefaultValueArchiveServerImpl.java    License: Eclipse Public License 1.0 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 #14
Source Project: neoscada   Author: eclipse   File: Hive.java    License: Eclipse Public License 1.0 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 #15
Source Project: Knowage-Server   Author: KnowageLabs   File: EmfXmiSerializer.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void serialize(Model model, OutputStream outputStream) {

	// Create a resource set.
	ResourceSet resourceSet = new ResourceSetImpl();

	// Register the default resource factory -- only needed for stand-alone!
	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());

	// Get the URI of the model file.
	// URI uri = URI.createFileURI(new File("mylibrary.xmi").getAbsolutePath());
	URI uri = URI.createURI(KNOWAGE_MODEL_URI);

	// Create a resource for this file.
	Resource resource = resourceSet.createResource(uri);

	// Add the book and writer objects to the contents.
	resource.getContents().add(model);
	// Save the contents of the resource to the file system.
	try {
		// resource.save(Collections.EMPTY_MAP);
		resource.save(outputStream, Collections.EMPTY_MAP);
	} catch (IOException e) {
		throw new RuntimeException("Impossible to serialize model [" + model.getName() + "]", e);
	}
}
 
Example #16
Source Project: bonita-studio   Author: bonitasoft   File: BPMNImportExportTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void checkGraphic(final String fileName, final MainProcess mainProcess) throws IOException {
    final URL bpmnResource = FileLocator.toFileURL(BPMNImportExportTest.class.getResource(fileName));
    final ResourceSet resourceSet1 = new ResourceSetImpl();
    final Resource resource1 = resourceSet1.createResource(BPMNTestUtil.toEMFURI(new File(bpmnResource.getFile())));
    resource1.load(Collections.emptyMap());
    new File(resource1.getURI().toFileString()).deleteOnExit();

    final Diagram diagramFor = ModelHelper.getDiagramFor(mainProcess);
    DiagramEditPart dep;
    try {
        dep = OffscreenEditPartFactory.getInstance().createDiagramEditPart(diagramFor,
                PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
    } catch (final Exception ex) {
        dep = OffscreenEditPartFactory.getInstance().createDiagramEditPart(diagramFor,
                PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
    }
    final MainProcessEditPart mped = (MainProcessEditPart) dep;

    checkAllEditPartsAreVisible(mped);
}
 
Example #17
Source Project: dsl-devkit   Author: dsldevkit   File: CheckResourceUtil.java    License: Eclipse Public License 1.0 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 #18
Source Project: statecharts   Author: Yakindu   File: SCTBuilder.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <TYPE extends EObject> TYPE loadFromResource(IResource res) {
	URI uri = URI.createPlatformResourceURI(res.getFullPath().toString(), true);
	ResourceSet set = new ResourceSetImpl();
	Resource emfResource = null;
	try {
		emfResource = set.getResource(uri, true);
	} catch (WrappedException e) {
		Platform.getLog(BuilderActivator.getDefault().getBundle()).log(new Status(IStatus.WARNING,
				GeneratorActivator.PLUGIN_ID, "Resource " + uri + " can not be loaded by builder", e));
		return null;
	}
	if (emfResource.getErrors().size() > 0 || emfResource.getContents().size() == 0)
		return null;
	return (TYPE) emfResource.getContents().get(0);
}
 
Example #19
Source Project: dsl-devkit   Author: dsldevkit   File: ExtendedLanguageConfig.java    License: Eclipse Public License 1.0 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 #20
Source Project: birt   Author: eclipse   File: SerializerImpl.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Chart read( InputStream is ) throws IOException
{
	// Create and setup local ResourceSet
	ResourceSet rsChart = new ResourceSetImpl( );
	rsChart.getResourceFactoryRegistry( )
			.getExtensionToFactoryMap( )
			.put( "chart", new ModelResourceFactoryImpl( ) ); //$NON-NLS-1$

	// Create resources to represent the disk files to be used to store the
	// models
	Resource rChart = rsChart.createResource( URI.createFileURI( "test.chart" ) ); //$NON-NLS-1$

	Map<String, Object> options = new HashMap<String, Object>( );
	options.put( XMLResource.OPTION_ENCODING, "UTF-8" ); //$NON-NLS-1$

	rChart.load( is, options );
	return (Chart) rChart.getContents( ).get( 0 );
}
 
Example #21
Source Project: orcas   Author: opitzconsulting   File: ModelWriter.java    License: Apache License 2.0 6 votes vote down vote up
public static String getSkriptXml( Model pModel )
{
  Resource.Factory.Registry lRegistry = Resource.Factory.Registry.INSTANCE;
  Map<String,Object> lMap = lRegistry.getExtensionToFactoryMap();
  lMap.put( "xml", new XMLResourceFactoryImpl() );

  ResourceSet lResourceSet = new ResourceSetImpl();
  Resource lResource = lResourceSet.createResource( URI.createFileURI( "*.xml" ) );

  ((XMLResource)lResource).getDefaultSaveOptions();

  lResource.getContents().add( pModel );
  try
  {
    ByteArrayOutputStream lByteArrayOutputStream = new ByteArrayOutputStream();
    lResource.save( lByteArrayOutputStream, Collections.EMPTY_MAP );

    return new String( lByteArrayOutputStream.toByteArray() );
  }
  catch( IOException e )
  {
    throw new RuntimeException( e );
  }
}
 
Example #22
Source Project: birt   Author: eclipse   File: SerializerImpl.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Chart read( URI uri ) throws IOException
{
	// Create and setup local ResourceSet
	ResourceSet rsChart = new ResourceSetImpl( );
	rsChart.getResourceFactoryRegistry( )
			.getExtensionToFactoryMap( )
			.put( "chart", new ModelResourceFactoryImpl( ) ); //$NON-NLS-1$

	// Create resources to represent the disk files to be used to store the
	// models
	Resource rChart = null;

	rChart = rsChart.createResource( uri );

	Map<String, Object> options = new HashMap<String, Object>( );
	options.put( XMLResource.OPTION_ENCODING, "UTF-8" ); //$NON-NLS-1$

	rChart.load( options );
	return (Chart) rChart.getContents( ).get( 0 );
}
 
Example #23
Source Project: ArduinoML-kernel   Author: mosser   File: Main.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void ArduinoML2xmi(String modelPath, String destinationPath) throws IOException{
       // register ArduinoML
	ResourceSet resources = new ResourceSetImpl();
    Map<String, Object> packageRegistry = resources.getPackageRegistry();
       packageRegistry.put(arduinoML.ArduinoMLPackage.eNS_URI, arduinoML.ArduinoMLPackage.eINSTANCE);
	
	// load ArduinoML dependencies 
	Injector injector = new ArduinoMLStandaloneSetup().createInjectorAndDoEMFRegistration();
	XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
	
	// load the dsl file and parse it
	URI uri = URI.createURI(modelPath);
	Resource xtextResource = resourceSet.getResource(uri, true);
	EcoreUtil.resolveAll(xtextResource);
	Resource xmiResource = resourceSet.createResource(URI.createURI(destinationPath));
	// add the root (often forgotten)
	xmiResource.getContents().add(xtextResource.getContents().get(0));
	
	xmiResource.save(null);
}
 
Example #24
Source Project: xtext-eclipse   Author: eclipse   File: RenameRefactoringIntegrationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testRefFromOtherNonXtextLanguage() throws Exception {
	ResourceSet resourceSet = new ResourceSetImpl();
	EObject elementB = resourceSet.getEObject(uriB, true);
	String xmiFileName = "otherLanguageFile.referring_xmi";
	Resource referringResource = resourceSet.createResource(URI.createPlatformResourceURI(TEST_PROJECT + "/"
			+ xmiFileName, true));
	Reference ref = ReferringFactory.eINSTANCE.createReference();
	ref.setReferenced(elementB);
	referringResource.getContents().add(ref);
	referringResource.save(null);
	project.refreshLocal(IResource.DEPTH_INFINITE, null);
	IFile referringXmiFile = project.getFile(xmiFileName);
	String originalContent = fileToString(referringXmiFile);
	doRename();
	assertEquals(originalContent.replaceAll("#B", "#C"), fileToString(referringXmiFile));
}
 
Example #25
Source Project: xtext-eclipse   Author: eclipse   File: Storage2UriMapperJdtImplTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug463258_01() throws Exception {
	IJavaProject project = createJavaProject("foo");
	IFile file = project.getProject().getFile("foo.jar");
	file.create(jarInputStream(new TextFile("foo/bar.notindexed", "//empty")), true, monitor());
	addJarToClasspath(project, file);
	
	Storage2UriMapperJavaImpl impl = getStorage2UriMapper();
	IPackageFragmentRoot root = project.getPackageFragmentRoot(file);
	IPackageFragment foo = root.getPackageFragment("foo");
	JarEntryFile fileInJar = new JarEntryFile("bar.notindexed");
	fileInJar.setParent(foo);
	
	URI uri = impl.getUri(fileInJar);
	assertEquals("archive:platform:/resource/foo/foo.jar!/foo/bar.notindexed", uri.toString());
	
	try (InputStream stream = new ResourceSetImpl().getURIConverter().createInputStream(uri)) {
		byte[] bytes = ByteStreams.toByteArray(stream);
		assertEquals("//empty", new String(bytes));
	}
}
 
Example #26
Source Project: txtUML   Author: ELTE-Soft   File: PapyrusModelCreatorTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void createUMLFile(URI uri, String modelname){
	Model model = UMLFactory.eINSTANCE.createModel();
       
	model.setName(modelname);

   	ResourceSet resourceSet = new ResourceSetImpl();
 		resourceSet.getPackageRegistry().put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
       
       resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(
 				UMLResource.FILE_EXTENSION,
 				UMLResource.Factory.INSTANCE
 			);
       
       Resource modelResource = resourceSet.createResource(uri);
       modelResource.getContents().add(model);
       try {
		modelResource.save(null);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #27
Source Project: graphical-lsp   Author: eclipsesource   File: WorkflowModelServerAccess.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public ResourceSet setupResourceSet() {
	ResourceSet resourceSet = new ResourceSetImpl();
	resourceSet.getPackageRegistry().put(CoffeePackage.eINSTANCE.getNsURI(), CoffeePackage.eINSTANCE);
	resourceSet.getPackageRegistry().put(WfnotationPackage.eINSTANCE.getNsURI(), WfnotationPackage.eINSTANCE);
	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
	return resourceSet;
}
 
Example #28
Source Project: kieker   Author: kieker-monitoring   File: MetaModelHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Saves the given meta model project to the given file.
 * 
 * @param file
 *            The file in which the project will be stored.
 * @param project
 *            The meta model project.
 * 
 * @throws IOException
 *             If something went wrong during the saving.
 */
public static final void saveProjectToFile(final File file, final MIProject project) throws IOException {
	// Create a resource and put the given project into it
	final ResourceSet resourceSet = new ResourceSetImpl();
	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
	final Resource resource = resourceSet.createResource(URI.createFileURI(file.getAbsolutePath()));
	resource.getContents().add(project);

	// Make sure that the controller uses utf8 instead of ascii.
	final Map<String, String> options = new HashMap<String, String>(); // NOPMD (no concurrent access)
	options.put(XMLResource.OPTION_ENCODING, "UTF-8");

	// Now try to save the resource
	resource.save(options);
}
 
Example #29
Source Project: n4js   Author: eclipse   File: XcoreReader.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private ResourceSet getResourceSet() {
	if (!injectors.isEmpty()) {
		ResourceSet instance = injectors.get(0).getInstance(
				ResourceSet.class);
		return instance;
	}
	return new ResourceSetImpl();
}
 
Example #30
Source Project: txtUML   Author: ELTE-Soft   File: ModelMapProvider.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param directory
 *            Directory of the saved mapping.
 * @param filename
 *            File name of the saved mapping (without extension).
 * @throws ModelMapException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws ClassNotFoundException
 */
public ModelMapProvider(URI directory, String filename) throws ModelMapException {
	uriFragmentMapper = new URIFragmentMapper(directory, filename);

	ResourceSet resourceSet = new ResourceSetImpl();
	UMLResourcesUtil.init(resourceSet);
	URI modelURI = URI.createURI(uriFragmentMapper.getModelPath());
	if (modelURI == null) {
		throw new ModelMapException(CANNOT_LOAD_MODEL);
	}
	resource = resourceSet.getResource(modelURI, true);
	if (resource == null) {
		throw new ModelMapException(CANNOT_LOAD_MODEL);
	}
}