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 File: FormatterSerializerIntegrationTest.java    From xtext-core with 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 #2
Source File: BPMNImportExportTest.java    From bonita-studio with 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 #3
Source File: SCTBuilder.java    From statecharts with 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 #4
Source File: Storage2UriMapperJdtImplTest.java    From xtext-eclipse with 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 #5
Source File: PapyrusModelCreatorTest.java    From txtUML with 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 #6
Source File: SerializerImpl.java    From birt with 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 #7
Source File: ChartHelper.java    From neoscada with 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 #8
Source File: DetailViewImpl.java    From neoscada with 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 #9
Source File: RenameRefactoringIntegrationTest.java    From xtext-eclipse with 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 #10
Source File: CheckResourceUtil.java    From dsl-devkit with 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 #11
Source File: XtextComparisonExpressionLoaderTest.java    From bonita-studio with 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 #12
Source File: CustomClassAwareEcoreGenerator.java    From dsl-devkit with 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 #13
Source File: ServerHostImpl.java    From neoscada with 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 #14
Source File: Main.java    From ArduinoML-kernel with 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 #15
Source File: ReleaseUtils.java    From bonita-studio with 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 #16
Source File: ExtendedLanguageConfig.java    From dsl-devkit with 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 #17
Source File: DefaultSimulationEngineFactory.java    From statecharts with 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 #18
Source File: FindingsTemplateService.java    From elexis-3-core with 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 #19
Source File: SerializerImpl.java    From birt with 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 #20
Source File: DaveDriverImpl.java    From neoscada with 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 #21
Source File: BpmnDeployer.java    From fixflow with 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 #22
Source File: EmfXmiSerializer.java    From Knowage-Server with 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 #23
Source File: DefaultValueArchiveServerImpl.java    From neoscada with 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 #24
Source File: SerializerImpl.java    From birt with 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 #25
Source File: ModelWriter.java    From orcas with 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 #26
Source File: Hive.java    From neoscada with 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 #27
Source File: ClasspathBasedConstructorScopeTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	factory = new ClasspathTypeProviderFactory(getClass().getClassLoader(), null);
	resourceSet = new ResourceSetImpl();
	typeScope = new ClasspathBasedTypeScope(factory.createTypeProvider(resourceSet), new IQualifiedNameConverter.DefaultImpl(), Predicates.<IEObjectDescription>alwaysTrue());
	constructorScope = new ClasspathBasedConstructorScope(typeScope);
}
 
Example #28
Source File: GenModelLoader.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public static GeneratorModel load(IFile file) {
	Resource resource = null;
	URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
	resource = new ResourceSetImpl().getResource(uri, true);
	if (resource == null || resource.getContents().size() == 0 || resource.getErrors().size() > 0)
		return null;
	final GeneratorModel model = (GeneratorModel) resource.getContents().get(0);
	return model;
}
 
Example #29
Source File: JdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	resourceSet = new ResourceSetImpl();
	projectProvider = new MockJavaProjectProvider();
	typeProvider = new JdtTypeProvider(projectProvider.getJavaProject(resourceSet), resourceSet);
	elementFinder = new JavaElementFinder();
	elementFinder.setProjectProvider(projectProvider);
}
 
Example #30
Source File: IndexedJvmTypeAccess.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public EObject getIndexedJvmType(URI javaObjectURI, ResourceSet resourceSet, boolean throwShadowedException) throws UnknownNestedTypeException {
	if (resourceSet != null) {
		URI withoutFragment = javaObjectURI.trimFragment();
		if (resourceSet instanceof ResourceSetImpl) {
			// if the resource uri is already available in the resource set, try to find it directly
			Map<URI, Resource> resourceMap = ((ResourceSetImpl) resourceSet).getURIResourceMap();
			if (resourceMap != null && resourceMap.containsKey(withoutFragment)) {
				EObject result = resourceSet.getEObject(javaObjectURI, true);
				if (result != null) {
					return result;
				}
			}
		}
		String fqn = withoutFragment.segment(withoutFragment.segmentCount() - 1);
		final String base = fqn;
		Iterator<String> variants = innerClassNameVariants.variantsFor(base);
		EObject jvmType = null;
		while (jvmType == null && variants.hasNext()) {
			fqn = variants.next();
			List<String> fqnSegments = Strings.split(fqn, '.');
			QualifiedName qualifiedName = QualifiedName.create(fqnSegments);
			jvmType = getIndexedJvmType(qualifiedName, javaObjectURI.fragment(), resourceSet, throwShadowedException);
		}
		return jvmType;
	}
	return null;
}