Java Code Examples for org.eclipse.emf.ecore.resource.ResourceSet#getResource()

The following examples show how to use org.eclipse.emf.ecore.resource.ResourceSet#getResource() . 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: AbstractReferenceUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected List<URI> loadReferringResources(ResourceSet resourceSet, Iterable<URI> referringResourceURIs,
		StatusWrapper status, IProgressMonitor monitor) {
	List<URI> unloadableResources = null;
	for (URI referringResourceURI : referringResourceURIs) {
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		Resource referringResource = resourceSet.getResource(referringResourceURI, true);
		if (referringResource == null) {
			status.add(ERROR, "Could not load referring resource ", referringResourceURI);
			if (unloadableResources == null)
				unloadableResources = newArrayList();
			unloadableResources.add(referringResourceURI);
		}
	}
	return unloadableResources == null ? Collections.<URI> emptyList() : unloadableResources;
}
 
Example 2
Source File: XtendBatchCompiler.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected ResourceSet loadXtendFiles(final ResourceSet resourceSet) {
	encodingProvider.setDefaultEncoding(getFileEncoding());
	final NameBasedFilter nameBasedFilter = new NameBasedFilter();
	nameBasedFilter.setExtension(fileExtensionProvider.getPrimaryFileExtension());
	PathTraverser pathTraverser = new PathTraverser();
	List<String> sourcePathDirectories = getSourcePathDirectories();
	Multimap<String, URI> pathes = pathTraverser.resolvePathes(sourcePathDirectories, new Predicate<URI>() {
		@Override
		public boolean apply(URI input) {
			boolean matches = nameBasedFilter.matches(input);
			return matches;
		}
	});
	for (String src : pathes.keySet()) {
		for (URI uri : pathes.get(src)) {
			if (log.isDebugEnabled()) {
				log.debug("load xtend file '" + uri + "'");
			}
			resourceSet.getResource(uri, true);
		}
	}
	return resourceSet;
}
 
Example 3
Source File: ProjectCacheInvalidationPluginTest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Performs the given {@code updateOperation} on the loaded AST of the given {@code packageJsonFile} and saves it to
 * disk.
 */
private void updatePackageJsonFile(IFile packageJsonFile, Consumer<JSONObject> updateOperation)
		throws CoreException {
	final IProject project = packageJsonFile.getProject();
	final ResourceSet resourceSet = resourceSetProvider.get(project);

	// read and parse package.json contents
	final String path = packageJsonFile.getFullPath().toString();
	final URI uri = URI.createPlatformResourceURI(path, true);
	final Resource resource = resourceSet.getResource(uri, true);

	final JSONObject root = PackageJSONTestUtils.getPackageJSONRoot(resource);
	updateOperation.accept(root);

	try {
		resource.save(null);
	} catch (IOException e) {
		throw new WrappedException("Failed to save package.json resource at " + resource.getURI().toString() + ".",
				e);
	}
	packageJsonFile.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
}
 
Example 4
Source File: AbstractXbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected JvmType findKnownTopLevelType(Class<?> rawType, Notifier context) {
	if (rawType.isArray()) {
		throw new IllegalArgumentException(rawType.getCanonicalName());
	}
	if (rawType.isPrimitive()) {
		throw new IllegalArgumentException(rawType.getName());
	}
	ResourceSet resourceSet = EcoreUtil2.getResourceSet(context);
	if (resourceSet == null) {
		return null;
	}
	Resource typeResource = resourceSet.getResource(URIHelperConstants.OBJECTS_URI.appendSegment(rawType.getName()), true);
	List<EObject> resourceContents = typeResource.getContents();
	if (resourceContents.isEmpty())
		return null;
	JvmType type = (JvmType) resourceContents.get(0);
	return type;
}
 
Example 5
Source File: BuildInstruction.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void handleChangedContents(Delta delta, IProject aProject, ResourceSet resourceSet) throws CoreException {
	// TODO: we will run out of memory here if the number of deltas is large enough
	Resource resource = resourceSet.getResource(delta.getUri(), true);
	if (shouldGenerate(resource, aProject)) {
		try {
			compositeGenerator.doGenerate(resource, access);
		} catch (RuntimeException e) {
			if (e instanceof GeneratorException) {
				N4JSActivator
						.getInstance()
						.getLog()
						.log(new Status(IStatus.ERROR, N4JSActivator.getInstance().getBundle().getSymbolicName(), e
								.getMessage(), e.getCause()));
			}
			if (e.getCause() instanceof CoreException) {
				throw (CoreException) e.getCause();
			}
			throw e;
		}
	}
}
 
Example 6
Source File: TxtUMLToUML2.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
public static Model loadExportedModel(URI uri) throws WrappedException {
	ResourceSet resSet = new ResourceSetImpl();
	Resource resource = resSet.getResource(uri, true);
	Model model = null;
	if (resource.getContents().size() != 0)
		model = (Model) resource.getContents().get(0);
	return model;
}
 
Example 7
Source File: TestImportBPMN2.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public void testImportBPMN2WithUnknownDiagramNS() throws Exception {
    URL bpmnResource = FileLocator.toFileURL(getClass().getResource("standardProcess_badNameSpace.bpmn")); //$NON-NLS-1$
    BPMNToProc bpmnToProc = new BPMNToProc(bpmnResource.getFile());
    destFile = bpmnToProc.createDiagram(bpmnResource, new NullProgressMonitor());

    ResourceSet resourceSet = new ResourceSetImpl();
    Resource resource = resourceSet.getResource(toEMFURI(destFile), true);
    MainProcess mainProcess = (MainProcess) resource.getContents().get(0);

    checkContent(mainProcess, 4, 14, 3, 0, 1, null);
    resource.unload();
}
 
Example 8
Source File: AbstractBuilder.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Compute a unused URI for a synthetic resource.
 * @param resourceSet the resource set in which the resource should be located.
 * @return the uri.
 */
@Pure
protected URI computeUnusedUri(ResourceSet resourceSet) {
	String name = "__synthetic";
	for (int i = 0; i < Integer.MAX_VALUE; ++i) {
		URI syntheticUri = URI.createURI(name + i + "." + getScriptFileExtension());
		if (resourceSet.getResource(syntheticUri, false) == null) {
			return syntheticUri;
		}
	}
	throw new IllegalStateException();
}
 
Example 9
Source File: AbstractLibraryGlobalScopeProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected Iterable<IEObjectDescription> getDescriptions(Resource context, URI uri) {
	List<IEObjectDescription> result = Lists.newArrayList();
	ResourceSet set = new ResourceSetImpl();
	Resource resource = set.getResource(uri, true);
	IResourceServiceProvider resourceServiceProvider = serviceProviderRegistry.getResourceServiceProvider(uri);
	if (resourceServiceProvider == null) {
		Iterables.addAll(result, Scopes.scopedElementsFor(Lists.newArrayList(resource.getAllContents())));
	} else {
		IResourceDescription resourceDescription = resourceServiceProvider.getResourceDescriptionManager()
				.getResourceDescription(resource);
		Iterables.addAll(result, resourceDescription.getExportedObjects());
	}
	resource.unload();
	return result;
}
 
Example 10
Source File: ResourceHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected URI computeUnusedUri(ResourceSet resourceSet) {
	String name = "__synthetic";
	for (int i = 0; i < Integer.MAX_VALUE; i++) {
		URI syntheticUri = URI.createURI(name + i + "." + fileExtension);
		if (resourceSet.getResource(syntheticUri, false) == null)
			return syntheticUri;
	}
	throw new IllegalStateException();
}
 
Example 11
Source File: JvmTypesAwareDirtyStateEditorSupport.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void processDelta(IResourceDescription.Delta delta, Resource context, List<Resource> result) {
	super.processDelta(delta, context, result);
	ResourceSet resourceSet = context.getResourceSet();
	if(delta.getNew() != null){
		Iterable<IEObjectDescription> exportedJvmTypes = delta.getNew().getExportedObjectsByType(TypesPackage.Literals.JVM_GENERIC_TYPE);
		for(IEObjectDescription jvmTypeDesc : exportedJvmTypes){
			URI uriToJvmType = URIHelperConstants.OBJECTS_URI.appendSegment(jvmTypeDesc.getQualifiedName().toString());
			Resource jvmResourceInResourceSet = resourceSet.getResource(uriToJvmType, false);
			if(jvmResourceInResourceSet != null)
				result.add(jvmResourceInResourceSet);
		}
	}
}
 
Example 12
Source File: TestImportBPMN2.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public void testImportBPMN2WithOMG_ns() throws Exception {
    URL bpmnResource = FileLocator.toFileURL(getClass().getResource("testimport.bpmn")); //$NON-NLS-1$
    BPMNToProc bpmnToProc = new BPMNToProc(bpmnResource.getFile());
    destFile = bpmnToProc.createDiagram(bpmnResource, new NullProgressMonitor());

    ResourceSet resourceSet = new ResourceSetImpl();
    Resource resource = resourceSet.getResource(toEMFURI(destFile), true);
    MainProcess mainProcess = (MainProcess) resource.getContents().get(0);

    checkContent(mainProcess, 2, 4, 0, 0, 0, null);
    resource.unload();
}
 
Example 13
Source File: EmfResourceRenameStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void createDeclarationUpdates(String newName, ResourceSet resourceSet,
		IRefactoringUpdateAcceptor updateAcceptor) {
	Resource targetResource = resourceSet.getResource(getTargetElementOriginalURI().trimFragment(), false);
	EcoreUtil.resolveAll(targetResource);
	applyDeclarationChange(newName, resourceSet);
	try {
		changeUtil.addSaveAsUpdate(targetResource, updateAcceptor);
	} catch (IOException exc) {
		updateAcceptor.getRefactoringStatus().add(ERROR, exc.getMessage());
	} finally {
		revertDeclarationChange(resourceSet);
	}
}
 
Example 14
Source File: WizardGeneratorHelperPluginTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Edits the AST of a package.json file by inserting a new required runtime library and asserts the resulting
 * serialized package.json contents.
 */
@Test
public void testInsertRequiredRuntimeLibraries() throws CoreException {
	final IProject testProject = ProjectTestsUtils.createJSProject(TEST_PROJECT_NAME);

	final ResourceSet resourceSet = this.resourceSetProvider.get();
	final XtextResource packageJson = (XtextResource) resourceSet.getResource(
			URI.createPlatformResourceURI(TEST_PROJECT_NAME + "/" + IN4JSProject.PACKAGE_JSON, true),
			true);

	// add required runtime library
	generatorHelper.applyJSONModifications(packageJson,
			Arrays.asList(
					PackageJsonModificationProvider.insertRequiredRuntimeLibraries(Arrays.asList("req-lib"))));

	Assert.assertEquals("Formatted document matches expectations after inserting another project dependency.",
			WizardGeneratorHelperTestExpectations.ONE_REQUIRED_RUNTIME_LIBRARIES,
			getPackageJsonContents(testProject));

	// add another required runtime library
	generatorHelper.applyJSONModifications(packageJson,
			Arrays.asList(
					PackageJsonModificationProvider.insertRequiredRuntimeLibraries(Arrays.asList("req-lib-2"))));

	Assert.assertEquals("Formatted document matches expectations after inserting another project dependency.",
			WizardGeneratorHelperTestExpectations.TWO_REQUIRED_RUNTIME_LIBRARIES,
			getPackageJsonContents(testProject));
}
 
Example 15
Source File: AbstractLiveContainerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected URI computeUnusedUri(ResourceSet resourceSet) {
	String name = "__synthetic";
	for (int i = 0; i < Integer.MAX_VALUE; i++) {
		URI syntheticUri = URI.createURI(name + i + "." + parser.fileExtension);
		syntheticUri = resourceSet.getURIConverter().normalize(syntheticUri);
		if (resourceSet.getResource(syntheticUri, false) == null)
			return syntheticUri;
	}
	throw new IllegalStateException();
}
 
Example 16
Source File: PackageJSONTestHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Loads the given project description file (using {@link Resource}) and applies
 * {@code projectDescriptionAdjustments} to the {@link JSONObject} to be found in the root of the given
 * {@code package.json} project description file.
 *
 * After the adjustments have been applied, the resource is saved.
 */
public void updateProjectDescription(IFile projectDescriptionFile,
		Consumer<JSONObject> projectDescriptionAdjustments) throws IOException {
	final URI uri = URI.createPlatformResourceURI(projectDescriptionFile.getFullPath().toString(), true);
	final ResourceSet resourceSet = getInjector().getInstance(IResourceSetProvider.class)
			.get(projectDescriptionFile.getProject());
	final Resource resource = resourceSet.getResource(uri, true);

	final JSONObject root = PackageJSONTestUtils.getPackageJSONRoot(resource);
	projectDescriptionAdjustments.accept(root);
	resource.save(null);
}
 
Example 17
Source File: EMFFileStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected Resource doCreateEMFResource() {
    final URI uri = getResourceURI();
    try {
        final EditingDomain editingDomain = getParentStore().getEditingDomain(uri);
        final ResourceSet resourceSet = editingDomain.getResourceSet();
        if (getResource().exists()) {
            return resourceSet.getResource(uri, true);
        } else {
            return resourceSet.createResource(uri);
        }
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
    return null;
}
 
Example 18
Source File: ResourceStorageTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testUpstreamResourcesAreLoadedFromStorage() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package mypack");
    _builder.newLine();
    _builder.newLine();
    _builder.append("class MyClass {");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    this.helper.createFile("mypack/MyClass.xtend", _builder.toString());
    final IProject downStreamProject = WorkbenchTestHelper.createPluginProject("downstream", this.helper.getProject().getName());
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("package downstream");
    _builder_1.newLine();
    _builder_1.newLine();
    _builder_1.append("class SomeClass {");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.append("def void foo(mypack.MyClass myClass) {");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.append("}");
    _builder_1.newLine();
    _builder_1.append("}");
    _builder_1.newLine();
    final IFile downstreamFile = this.helper.createFileImpl("/downstream/src/downstream/SomeClass.xtend", _builder_1.toString());
    IResourcesSetupUtil.waitForBuild();
    final URI downstreamUri = this.uriMapper.getUri(downstreamFile);
    final ResourceSet resourceSet = this.resourceSetProvider.get(downStreamProject);
    SourceLevelURIsAdapter.setSourceLevelUris(resourceSet, Collections.<URI>unmodifiableList(CollectionLiterals.<URI>newArrayList(downstreamUri)));
    Resource _resource = resourceSet.getResource(downstreamUri, true);
    final StorageAwareResource downstreamResource = ((StorageAwareResource) _resource);
    EObject _get = downstreamResource.getContents().get(1);
    final JvmGenericType type = ((JvmGenericType) _get);
    final JvmType parameterType = IterableExtensions.<JvmFormalParameter>head(IterableExtensions.<JvmOperation>head(Iterables.<JvmOperation>filter(type.getMembers(), JvmOperation.class)).getParameters()).getParameterType().getType();
    Assert.assertNotNull(parameterType);
    Resource _eResource = parameterType.eResource();
    Assert.assertTrue(((StorageAwareResource) _eResource).isLoadedFromStorage());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 19
Source File: XMISymbolLoader.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
protected void load () throws Exception
{
    // register model
    VisualInterfacePackage.eINSTANCE.eClass ();

    this.symbol = null;

    final ResourceSet resourceSet = new ResourceSetImpl ();

    // set resource factory to XMI on extension map
    resourceSet.getResourceFactoryRegistry ().getExtensionToFactoryMap ().put ( "vi", FACTORY_INSTANCE ); //$NON-NLS-1$

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

    this.symbol = (Symbol)EcoreUtil.getObjectByType ( resource.getContents (), VisualInterfacePackage.Literals.SYMBOL );
}
 
Example 20
Source File: ExportFragment.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Get the export model that we have to process.
 *
 * @param grammar
 *          The grammar
 * @return The model
 */
private synchronized ExportModel getModel(final Grammar grammar) { // NOPMD NPathComplexity by wth on 24.11.10 08:22
  if (modelLoaded) {
    return model;
  }
  modelLoaded = true;
  Resource resource = grammar.eResource();
  if (resource == null) {
    return null;
  }

  final ResourceSet resourceSet = resource.getResourceSet();
  URI uri = null;
  if (getExportFileURI() != null) {
    uri = URI.createURI(getExportFileURI());
  } else {
    uri = grammar.eResource().getURI().trimFileExtension().appendFileExtension(EXPORT_FILE_EXTENSION);
  }
  try {
    resource = resourceSet.getResource(uri, true);
    final List<Issue> issues = VALIDATOR.validate(resource, LOGGER);

    for (final Issue issue : issues) {
      if (issue.isSyntaxError() || issue.getSeverity() == Severity.ERROR) {
        throw new WorkflowInterruptedException(NLS.bind(Messages.ExportFragment_EXPORT_ERRORS, uri));
      }
    }
    if (resource.getContents().size() == 0) {
      return null;
    }
    model = (ExportModel) resource.getContents().get(0);
    return model;
  } catch (final ClasspathUriResolutionException e) {
    // Resource does not exist.
    if (getExportFileURI() != null) {
      // Explicit file specified, but not found: stop the workflow.
      throw new WorkflowInterruptedException(NLS.bind(Messages.ExportFragment_NO_EXPORT_FILE, uri)); // NOPMD PreserveStackTrace by wth on 24.11.10 08:27
    }
    // No file found at implicit location: work with a null model, generating code that implements the default behavior.
    return null;
  }
}