Java Code Examples for org.eclipse.emf.ecore.resource.Resource#load()

The following examples show how to use org.eclipse.emf.ecore.resource.Resource#load() . 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: LazyStandaloneSetup.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void addRegisterEcoreFile(String fileName) throws IllegalArgumentException, SecurityException {
    Resource res = resourceSet.getResource(createURI(fileName), true);
    if (res == null) {
        throw new ConfigurationException("Couldn't find resource under  " + fileName);
    }
    if (!res.isLoaded()) {
        try {
            res.load(null);
        } catch (IOException e) {
            throw new ConfigurationException("Couldn't load resource under  " + fileName + " : " + e.getMessage());
        }
    }
    List<EObject> result = res.getContents();
    for (EObject object : result) {
        if (object instanceof EPackage) {
            registerPackage(fileName, object);
        }
        for (final TreeIterator<EObject> it = object.eAllContents(); it.hasNext();) {
            EObject child = it.next();
            if (child instanceof EPackage) {
                registerPackage(fileName, child);
            }
        }
    }
}
 
Example 2
Source File: YangPackageImpl.java    From yang-design-studio with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Laods the package and any sub-packages from their serialized form.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public void loadPackage()
{
  if (isLoaded) return;
  isLoaded = true;

  URL url = getClass().getResource(packageFilename);
  if (url == null)
  {
    throw new RuntimeException("Missing serialized package: " + packageFilename);
  }
  URI uri = URI.createURI(url.toString());
  Resource resource = new EcoreResourceFactoryImpl().createResource(uri);
  try
  {
    resource.load(null);
  }
  catch (IOException exception)
  {
    throw new WrappedException(exception);
  }
  initializeFromLoadedEPackage(this, (EPackage)resource.getContents().get(0));
  createResource(eNS_URI);
}
 
Example 3
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 4
Source File: ExternalContentSupportTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testCreateResource_03() throws IOException {
	String grammarInstead = "grammar org.foo.bar with org.eclipse.xtext.common.Terminals\n" +
			"generate something 'http://something'\n" +
			"Model: name=ID;";
	XtextResourceSet resourceSet = get(XtextResourceSet.class);
	resourceSet.setClasspathURIContext(getClass());
	URI original = URI.createURI("classpath:/org/eclipse/xtext/Xtext.xtext");
	URI normalized = resourceSet.getURIConverter().normalize(original);
	uriToContent.put(normalized, grammarInstead);
	support.configureResourceSet(resourceSet, this);
	Resource resource = resourceSet.createResource(original);
	assertNotNull(resource);
	assertFalse(resource.isLoaded());
	resource.load(Collections.emptyMap());
	assertEquals(1, resource.getContents().size());
	assertEquals("org.foo.bar", ((Grammar) resource.getContents().get(0)).getName());
}
 
Example 5
Source File: ExpressionBuilderImpl.java    From sarl with Apache License 2.0 6 votes vote down vote up
static JvmParameterizedTypeReference parseType(Notifier context, String typeName, AbstractBuilder caller) {
	ResourceSet resourceSet = toResource(context).getResourceSet();
	URI uri = caller.computeUnusedUri(resourceSet);
	Resource resource = caller.getResourceFactory().createResource(uri);
	resourceSet.getResources().add(resource);
	try (StringInputStream is = new StringInputStream(generateTypenameCode(typeName))) {
		resource.load(is, null);
		SarlScript script = resource.getContents().isEmpty() ? null : (SarlScript) resource.getContents().get(0);
		SarlEvent topElement = (SarlEvent) script.getXtendTypes().get(0);
		SarlField member = (SarlField) topElement.getMembers().get(0);
		JvmTypeReference reference = member.getType();
		if (reference instanceof JvmParameterizedTypeReference) {
			final JvmParameterizedTypeReference pref = (JvmParameterizedTypeReference) reference;
			if (!pref.getArguments().isEmpty()) {
				EcoreUtil2.resolveAll(resource);
				return pref;
			}
		}
	} catch (Exception exception) {
		throw new TypeNotPresentException(typeName, exception);
	} finally {
		resourceSet.getResources().remove(resource);
	}
	throw new TypeNotPresentException(typeName, null);
}
 
Example 6
Source File: DuplicateResourceAwareFileSetupContext.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Resource load(final ResourceSet resourceSet, final URI uri, final InputStream input) throws IOException {
	final Injector injector = IXtInjectorProvider.INSTANCE.getInjector(context.get(XpectJavaModel.class), uri);
	final Resource resource = injector.getInstance(IResourceFactory.class).createResource(uri);
	final Resource existingResousce = from(resourceSet.getResources())
			.firstMatch(r -> r.getURI().equals(resource.getURI())).orNull();
	if (null != existingResousce) {
		// remove the existing one
		resourceSet.getResources().remove(existingResousce);
	}
	resourceSet.getResources().add(resource);
	try {
		resource.load(input, null);
	} finally {
		if (input != null)
			input.close();
	}
	return resource;
}
 
Example 7
Source File: XSDRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
public IStatus isXSDFileValid(final File file) {
    Resource resource = null;
    final String filePath = file.getAbsolutePath();
    try {
        final XSDResourceFactoryImpl factory = new XSDResourceFactoryImpl();
        resource = factory.createResource(URI.createFileURI(filePath));
        resource.load(Collections.EMPTY_MAP);
        final XSDSchema schema = (XSDSchema) resource.getContents().get(0);
        if (schema.getTargetNamespace() == null) {
            return new Status(IStatus.ERROR, XMLPlugin.PLUGIN_ID, Messages.missingATargetNamespace);
        }
    } catch (final Exception ex) {
        return new Status(IStatus.ERROR, XMLPlugin.PLUGIN_ID,
                "An xsd file seems corrupted in your workspace (" + filePath + ").\n" + ex.getMessage(), ex);
    } finally {
        if (resource != null) {
            resource.unload();
        }
    }
    return Status.OK_STATUS;
}
 
Example 8
Source File: SerializerImpl.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected DesignValues read( InputStream is ) throws IOException
{
	ModelXMLProcessor xmlProcessor = new ModelXMLProcessor( );
	Resource resource = xmlProcessor.createResource( URI
			.createFileURI( "test.designValue" ) ); //$NON-NLS-1$ 

	try
	{
		Map options = new HashMap( );
		options.put( XMLResource.OPTION_ENCODING, "UTF-8" ); //$NON-NLS-1$

		resource.load( is, options );
	}
	catch ( IOException ex )
	{
		throw ex;
	}
	DocumentRoot docRoot = (DocumentRoot) resource.getContents( ).get( 0 );
	return docRoot.getDesignValues( );
}
 
Example 9
Source File: DefaultResourceDescription2Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testBrokenLink() throws Exception {
	XtextResourceSet rs = get(XtextResourceSet.class);
	Resource res1 = rs.createResource(URI.createURI("foo.langatestlanguage"));
	res1.load(new StringInputStream("type Foo"), null);
	
	XtextResource res2 = (XtextResource) rs.createResource(URI.createURI("bar.langatestlanguage"));
	res2.load(new StringInputStream("import 'foo.langatestlanguage'" +
	"type Bar extends Baz"), null);
	
	EcoreUtil.resolveAll(res2);
	Iterable<QualifiedName> names = res2.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(res2).getImportedNames();
	assertEquals(QualifiedName.create("baz"),names.iterator().next());
}
 
Example 10
Source File: InferredJvmModelShadowingJavaLinkingTests.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected XtendClass classFile(String fileName, String content) throws Exception {
	Resource resource = resourceSet.createResource(URI.createURI(fileName + ".xtend"));
	resource.load(new StringInputStream(content), null);
	EObject root = resource.getContents().get(0);
	assertTrue(root instanceof XtendFile);
	return (XtendClass) ((XtendFile) root).getXtendTypes().get(0);
}
 
Example 11
Source File: ExtensionsEditor.java    From ifml-editor with MIT License 5 votes vote down vote up
/**
 * Handles what to do with changed resources on activation.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void handleChangedResources() {
	if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
		if (isDirty()) {
			changedResources.addAll(editingDomain.getResourceSet().getResources());
		}
		editingDomain.getCommandStack().flush();

		updateProblemIndication = false;
		for (Resource resource : changedResources) {
			if (resource.isLoaded()) {
				resource.unload();
				try {
					resource.load(Collections.EMPTY_MAP);
				}
				catch (IOException exception) {
					if (!resourceToDiagnosticMap.containsKey(resource)) {
						resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
					}
				}
			}
		}

		if (AdapterFactoryEditingDomain.isStale(editorSelection)) {
			setSelection(StructuredSelection.EMPTY);
		}

		updateProblemIndication = true;
		updateProblemIndication();
	}
}
 
Example 12
Source File: VisualInterfaceEditor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Handles what to do with changed resources on activation.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void handleChangedResources ()
{
    if ( !changedResources.isEmpty () && ( !isDirty () || handleDirtyConflict () ) )
    {
        if ( isDirty () )
        {
            changedResources.addAll ( editingDomain.getResourceSet ().getResources () );
        }
        editingDomain.getCommandStack ().flush ();

        updateProblemIndication = false;
        for ( Resource resource : changedResources )
        {
            if ( resource.isLoaded () )
            {
                resource.unload ();
                try
                {
                    resource.load ( Collections.EMPTY_MAP );
                }
                catch ( IOException exception )
                {
                    if ( !resourceToDiagnosticMap.containsKey ( resource ) )
                    {
                        resourceToDiagnosticMap.put ( resource, analyzeResourceProblems ( resource, exception ) );
                    }
                }
            }
        }

        if ( AdapterFactoryEditingDomain.isStale ( editorSelection ) )
        {
            setSelection ( StructuredSelection.EMPTY );
        }

        updateProblemIndication = true;
        updateProblemIndication ();
    }
}
 
Example 13
Source File: CompilationTestHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * creates a fresh resource set with the given resources
 * 
 * @param resources - pairs of file names and their contents 
 * @return a ResourceSet, containing the given resources.
 * @throws IOException if the resource loading fails 
 */
public ResourceSet resourceSet(@SuppressWarnings("unchecked") Pair<String,? extends CharSequence> ...resources ) throws IOException {
	XtextResourceSet result = newResourceSetWithUTF8Encoding();
	FileProjectConfig projectConfig = new FileProjectConfig(new File(workspaceRoot,PROJECT_NAME), PROJECT_NAME);
	projectConfig.addSourceFolder("src");
	ProjectConfigAdapter.install(result, projectConfig);
	for (Pair<String, ? extends CharSequence> entry : resources) {
		URI uri = copyToWorkspace(getSourceFolderPath()+"/"+entry.getKey(), entry.getValue());
		Resource resource = result.createResource(uri);
		if (resource == null)
			throw new IllegalStateException("Couldn't create resource for URI "+uri+". Resource.Factory not registered?");
		resource.load(result.getLoadOptions());
	}
	return result;
}
 
Example 14
Source File: JvmModelTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Resource newResource(CharSequence input) throws IOException {
	XtextResourceSet resourceSet = resourceSetProvider.get();
	Resource resource = resourceSet.createResource(URI.createURI("Test.___xbase"));
	resource.load(new StringInputStream(input.toString()), null);
	return resource;
}
 
Example 15
Source File: NewAgentTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore("only for debugging purpose")
public void xtextParsing() throws Exception {
	IFile file = helper().createFile("test_" + UUID.randomUUID() + ".sarl", multilineString(
			"package io.sarl.eclipse.tests.wizards",
			"agent FooAgent0 { }"));
	Resource resource = helper().getResourceFor(file);
	resource.load(null);
	System.out.println(EmfFormatter.objToStr(resource.getContents().get(0)));
}
 
Example 16
Source File: RepositoriesContentHandlerV1.java    From ADT_Frontend with MIT License 5 votes vote down vote up
@Override
public IRepositories deserialize(IMessageBody body, Class<? extends IRepositories> dataType) {
	try {
		InputStream content = body.getContent();
		Resource resource = new AbapgitrepositoriesResourceFactoryImpl().createResource(this.virtualResourceUri);
		resource.load(content, null);
		IRepositories repos = loadEmf(resource);
		return repos;
	} catch (IOException e) {
		throw new ContentHandlerException("Error parsing repositories", e); //$NON-NLS-1$
	}
}
 
Example 17
Source File: CrossflowEditor.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Handles what to do with changed resources on activation.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void handleChangedResources() {
	if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
		ResourceSet resourceSet = editingDomain.getResourceSet();
		if (isDirty()) {
			changedResources.addAll(resourceSet.getResources());
		}
		editingDomain.getCommandStack().flush();

		updateProblemIndication = false;
		for (Resource resource : changedResources) {
			if (resource.isLoaded()) {
				resource.unload();
				try {
					resource.load(resourceSet.getLoadOptions());
				}
				catch (IOException exception) {
					if (!resourceToDiagnosticMap.containsKey(resource)) {
						resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
					}
				}
			}
		}

		if (AdapterFactoryEditingDomain.isStale(editorSelection)) {
			setSelection(StructuredSelection.EMPTY);
		}

		updateProblemIndication = true;
		updateProblemIndication();
	}
}
 
Example 18
Source File: ResolveLazyComponent.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
public void invoke(IWorkflowContext ctx) {
	Set<String> names = ctx.getSlotNames();
	for (String slotName : names) {

		Object slotContent = ctx.get(slotName);
		if (slotContent instanceof Iterable) {
			Iterator<?> iter = ((Iterable<?>) slotContent).iterator();
			while (iter.hasNext()) {
				Object o = iter.next();
				if (o instanceof Resource) {
					Resource r = ((Resource) o);
					if(!r.isLoaded())
						try {
							r.load(null);
						} catch (IOException e) {
							throw new RuntimeException("Error loading slot "+ slotName, e);
						} 

					if(r instanceof LazyLinkingResource)
						ctx.put(slotName, r.getContents());
				}
			}
		}

	}

}
 
Example 19
Source File: DelegatingReferenceFinderTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected Resource loadResource(String pathName, String content) throws IOException {
	Resource resource = resourceSet.createResource(URI.createFileURI(pathName));
	resource.load(new StringInputStream(content), null);
	assertTrue(resource.getErrors().isEmpty());
	return resource;
}
 
Example 20
Source File: JBPM3ToProc.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
@Override
public File createDiagram(final URL sourceURL, final IProgressMonitor progressMonitor) throws Exception {
    progressMonitor.beginTask(Messages.importFromJBPM, IProgressMonitor.UNKNOWN);
    URI sourceJBPMUri = URI.createURI(sourceURL.toURI().toString());
    final URI gpdFileName = sourceJBPMUri.trimSegments(1).appendSegment("gpd.xml");

    // copy files
    final File tmpDir = new File(ProjectUtil.getBonitaStudioWorkFolder(), "importJBPMtemp");
    tmpDir.mkdirs();

    final File processDefFile = new File(tmpDir, "processdefinition.xml");
    try (final InputStream is = FileLocator.toFileURL(new java.net.URI(sourceJBPMUri.toString()).toURL()).openStream();
            final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            FileOutputStream out = new FileOutputStream(processDefFile);) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            line = line.replace("urn:jbpm.org:jpdl-3.2", "");
            out.write(line.getBytes());
        }
    }

    final File gpdFileTmp = new File(tmpDir, "gpd.xml");
    try (FileOutputStream out = new FileOutputStream(gpdFileTmp);
            final InputStream src = new java.net.URL(gpdFileName.toString()).openStream();) {
        FileUtil.copy(src, out);
    }
    progressMonitor.worked(1);

    // Update URIs
    sourceJBPMUri = URI.createURI(processDefFile.toURI().toString());

    // parse resource
    final Resource resource = new jpdl32ResourceFactoryImpl().createResource(sourceJBPMUri);
    final Map<String, String> options = new HashMap<String, String>();
    options.put(jpdl32ResourceImpl.NO_NAMESPACE_SCHEMA_LOCATION, Boolean.TRUE.toString());
    resource.load(options);
    final DocumentRoot docRoot = (DocumentRoot) resource.getContents().get(0);
    final ProcessDefinitionType processDef = docRoot.getProcessDefinition();
    final String diagramName = sourceJBPMUri.lastSegment();
    progressMonitor.worked(1);

    // parse GPD
    try {

        final URI gpd = gpdFileName; // TODO test
        final URL gpdUrl = FileLocator.toFileURL(new URL(gpd.toString()));
        final File gpdFile = new File(gpdUrl.getFile());
        if (gpdFile.exists()) {
            populateLocationMap(gpdFile);
        }
    } catch (final IOException ex) {
        BonitaStudioLog.log("Could not use gpd for " + sourceJBPMUri.toString());
    }
    progressMonitor.worked(1);

    builder = new ProcBuilder(progressMonitor);
    result = File.createTempFile(diagramName, ".proc");
    result.deleteOnExit();
    builder.createDiagram(diagramName, diagramName, "1.0", result);
    try {
        importFromJBPM(processDef);
        gpdFileTmp.delete();
        processDefFile.delete();
        tmpDir.delete();
        builder.done();
        return result;
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
    return null;

}