Java Code Examples for org.eclipse.xtext.resource.XtextResourceSet

The following examples show how to use org.eclipse.xtext.resource.XtextResourceSet. These examples are extracted from open source projects. 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: sarl   Source File: FormatterFacadeTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertResourceContentFormat(String source, String expected) throws IOException {
	final ResourceSet resourceSet = new XtextResourceSet();
	final URI createURI = URI.createURI("synthetic://to-be-formatted.sarl"); //$NON-NLS-1$
	final XtextResource resource = (XtextResource) this.resourceFactory.createResource(createURI);
	resourceSet.getResources().add(resource);
	try (StringInputStream stringInputStream = new StringInputStream(source)) {
		resource.load(stringInputStream, Collections.emptyMap());
	}
	this.facade.format(resource);
	final String actual; 
	try (ByteArrayOutputStream stringOutputStream = new ByteArrayOutputStream()) {
		resource.save(stringOutputStream, Collections.emptyMap());
		stringOutputStream.flush();
		actual = stringOutputStream.toString();
	}
	assertEquals(expected, actual);
}
 
Example 2
Source Project: xtext-core   Source File: XtextFormatterTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testXtextFormatting() throws IOException {
	String path = getClass().getPackage().getName().replace('.', '/');
	URI u = URI.createURI("classpath:/" + path + "/XtextFormatterMessy.xtext");
	XtextResourceSet resourceSet = new XtextResourceSet();
	resourceSet.setClasspathURIContext(getClass());
	Resource r = resourceSet.getResource(u, true);
	// System.out.println(r.getWarnings());
	// System.out.println(r.getErrors());
	ByteArrayOutputStream formatted = new ByteArrayOutputStream();
	r.save(formatted, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
	// System.out.println(EmfFormatter.listToStr(r.getContents()));
	// System.out.println(formatted.toString());

	URI expectedURI = URI.createURI("classpath:/" + path + "/XtextFormatterExpected.xtext");
	XtextResource expectedResource = (XtextResource) resourceSet.getResource(expectedURI, true);
	String expected = expectedResource.getParseResult().getRootNode().getText();
	assertEquals(expected.replaceAll(System.lineSeparator(), "\n"), 
	    formatted.toString().replaceAll(System.lineSeparator(), "\n"));
}
 
Example 3
private XtextResource parse(final String doc) {
  try {
    String _primaryFileExtension = this.fileExtension.getPrimaryFileExtension();
    String _plus = ("dummy." + _primaryFileExtension);
    final URI uri = URI.createURI(_plus);
    Resource _createResource = this.resFactory.createResource(uri);
    final XtextResource res = ((XtextResource) _createResource);
    EList<Resource> _resources = new XtextResourceSet().getResources();
    _resources.add(res);
    if ((this.entryPoint != null)) {
      res.setEntryPoint(this.entryPoint);
    }
    StringInputStream _stringInputStream = new StringInputStream(doc);
    res.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
    this.validator.assertNoErrors(res);
    return res;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 4
Source Project: n4js   Source File: XStatefulIncrementalBuilder.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void removeGeneratedFiles(URI source, XSource2GeneratedMapping source2GeneratedMapping) {
	Map<URI, String> outputConfigMap = source2GeneratedMapping.deleteSourceAndGetOutputConfigs(source);
	IResourceServiceProvider serviceProvider = context.getResourceServiceProvider(source);
	IContextualOutputConfigurationProvider2 outputConfigurationProvider = serviceProvider
			.get(IContextualOutputConfigurationProvider2.class);
	XtextResourceSet resourceSet = request.getResourceSet();
	Set<OutputConfiguration> outputConfigs = outputConfigurationProvider.getOutputConfigurations(resourceSet);
	Map<String, OutputConfiguration> outputConfigsMap = Maps.uniqueIndex(outputConfigs,
			OutputConfiguration::getName);
	URIConverter uriConverter = resourceSet.getURIConverter();
	for (URI generated : outputConfigMap.keySet()) {
		OutputConfiguration config = outputConfigsMap.get(outputConfigMap.get(generated));
		if (config != null && config.isCleanUpDerivedResources()) {
			try {
				uriConverter.delete(generated, CollectionLiterals.emptyMap());
				request.setResultDeleteFile(generated);
			} catch (IOException e) {
				Exceptions.sneakyThrow(e);
			}
		}
	}
}
 
Example 5
Source Project: n4js   Source File: XIncrementalBuilder.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Run the build.
 * <p>
 * Cancellation behavior: does not throw exception but returns with a partial result.
 */
public XBuildResult build(XBuildRequest request, IResourceClusteringPolicy clusteringPolicy) {

	ResourceDescriptionsData resDescrsCopy = request.getState().getResourceDescriptions().copy();
	XSource2GeneratedMapping fileMappingsCopy = request.getState().getFileMappings().copy();
	XIndexState oldState = new XIndexState(resDescrsCopy, fileMappingsCopy);

	XtextResourceSet resourceSet = request.getResourceSet();
	XBuildContext context = new XBuildContext(languagesRegistry::getResourceServiceProvider,
			resourceSet, oldState, clusteringPolicy, request.getCancelIndicator());

	XStatefulIncrementalBuilder builder = provider.get();
	builder.setContext(context);
	builder.setRequest(request);

	return builder.launch();
}
 
Example 6
public ClassLoader getClassLoader(ResourceSet resourceSet) {
	if (resourceSet instanceof XtextResourceSet) {
		XtextResourceSet xtextResourceSet = (XtextResourceSet) resourceSet;
		Object ctx = xtextResourceSet.getClasspathURIContext();
		if (ctx != null) {
	        if (ctx instanceof Class<?>) {
	            return ((Class<?>)ctx).getClassLoader();
	        }
	        if (!(ctx instanceof ClassLoader)) {
	        	return ctx.getClass().getClassLoader();
	        }
	        return (ClassLoader) ctx;
		}
	}
	return classLoader;
}
 
Example 7
Source Project: xtext-core   Source File: SerializationUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static String getCompleteContent(XtextResource xr) throws IOException, UnsupportedEncodingException {
	XtextResourceSet resourceSet = (XtextResourceSet) xr.getResourceSet();
	URIConverter uriConverter = resourceSet.getURIConverter();
	URI uri = xr.getURI();
	String encoding = xr.getEncoding();

	InputStream inputStream = null;

	try {
		inputStream = uriConverter.createInputStream(uri);

		return getCompleteContent(encoding, inputStream);
	} finally {
		tryClose(inputStream, null);
	}
}
 
Example 8
Source Project: xtext-xtend   Source File: FormatterFacade.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public String format(final String xtendCode) {
  try {
    final XtextResourceSet resourceSet = new XtextResourceSet();
    Resource _createResource = this.resourceFactory.createResource(URI.createURI("synthetic://to-be-formatted.xtend"));
    final XtextResource resource = ((XtextResource) _createResource);
    EList<Resource> _resources = resourceSet.getResources();
    _resources.add(resource);
    StringInputStream _stringInputStream = new StringInputStream(xtendCode);
    resource.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
    final ITextRegionAccess regionAccess = this.regionAccessBuilder.get().forNodeModel(resource).create();
    FormatterRequest _formatterRequest = new FormatterRequest();
    final Procedure1<FormatterRequest> _function = (FormatterRequest it) -> {
      it.setAllowIdentityEdits(false);
      it.setTextRegionAccess(regionAccess);
      it.setPreferences(TypedPreferenceValues.castOrWrap(this.cfgProvider.getPreferenceValues(resource)));
    };
    FormatterRequest request = ObjectExtensions.<FormatterRequest>operator_doubleArrow(_formatterRequest, _function);
    List<ITextReplacement> replacements = this.formatter.format(request);
    return regionAccess.getRewriter().renderToString(replacements);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 9
public XtextResource parse(final String fileName, final CharSequence model) {
  try {
    XtextResource _xblockexpression = null;
    {
      final XtextResourceSet rs = this.resourceSetProvider.get();
      Resource _createResource = rs.createResource(URI.createURI((fileName + ".xtend")));
      final XtextResource r = ((XtextResource) _createResource);
      String _string = model.toString();
      StringInputStream _stringInputStream = new StringInputStream(_string);
      r.load(_stringInputStream, Collections.<Object, Object>unmodifiableMap(CollectionLiterals.<Object, Object>newHashMap()));
      _xblockexpression = r;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 10
@Override
public XtextResourceSet getInitializedResourceSet() {
	XtextResourceSet resourceSet = new XtextResourceSet() {
		@Override
		public Resource createResource(URI uri) {
			Resource result = getResource(uri, false);
			if (result == null)
				return super.createResource(uri);
			return result;
		}
	};
	injector.injectMembers(resourceSet);
	resourceSet.eAdapters().add(new AllContainerAdapter(resourceSet));
	return resourceSet;
}
 
Example 11
Source Project: xtext-core   Source File: UriBasedReader.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void setClasspathURIContext(Object class1) {
	final XtextResourceSet resourceSet = new XtextResourceSet();
	resourceSet.setClasspathURIContext(class1);
	setResourceSetProvider(new Provider<ResourceSet>() {
		
		@Override
		public ResourceSet get() {
			return resourceSet;
		}
	});
}
 
Example 12
Source Project: n4js   Source File: ECMA6TestSuiteForJSX.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Script doParse(String code, URI uri, XtextResourceSet resourceSet, Analyser analyser) throws Exception {

	if (isStrictModeTestCase(code)) {
		uri = uri.trimFileExtension().appendFileExtension("n4jsx");
	} else {
		uri = uri.trimFileExtension().appendFileExtension("jsx");
	}
	// ensure code contains JSX syntax to fail in case of wrong
	// configuration
	if (!analyser.isNegative()) {
		code = code + "\nvar x42 = <div/>\n";
	}
	return parserN4JS.parse(code, uri, resourceSet);
}
 
Example 13
Source Project: n4js   Source File: ECMA5TestSuiteForJSX.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Script doParse(String code, URI uri, XtextResourceSet resourceSet, Analyser analyser) throws Exception {
	if (isStrictModeTestCase(code)) {
		uri = uri.trimFileExtension().appendFileExtension("n4jsx");
	} else {
		uri = uri.trimFileExtension().appendFileExtension("jsx");
	}
	// ensure code contains JSX syntax to fail in case of wrong
	// configuration
	if (!analyser.isNegative()) {
		code = code + "\nvar x42 = <div/>\n";
	}
	return parserN4JS.parse(code, uri, resourceSet);
}
 
Example 14
protected final XtextResourceSet getResourceSet() {
	XtextResourceSet resourceSet = get(XtextResourceSet.class);
	IJvmTypeProvider.Factory typeProviderFactory = new JdtTypeProviderFactory(this);
	typeProviderFactory.findOrCreateTypeProvider(resourceSet);
	resourceSet.setClasspathURIContext(getJavaProject(resourceSet));
	return resourceSet;
}
 
Example 15
Source Project: xtext-core   Source File: CrossRefTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testCrossReferenceValueConverter() throws Exception {
	Resource r = get(XtextResourceSet.class).createResource(URI.createURI("test." + getCurrentFileExtension()));
	Main main = LangATestLanguageFactory.eINSTANCE.createMain();
	Type ele = LangATestLanguageFactory.eINSTANCE.createType();
	r.getContents().add(main);
	main.getTypes().add(ele);
	ele.setName("type");
	ele.setExtends(ele);
	assertEquals("type ^type extends ^type", getSerializer().serialize(main));
}
 
Example 16
Source Project: n4js   Source File: XProjectManager.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** Create an empty resource set. */
protected XtextResourceSet createFreshResourceSet(ResourceDescriptionsData newIndex) {
	if (resourceSet == null) {
		resourceSet = createNewResourceSet(newIndex);
	} else {
		ChunkedResourceDescriptions resDescs = ChunkedResourceDescriptions.findInEmfObject(resourceSet);

		for (Entry<String, ResourceDescriptionsData> entry : fullIndex.entries()) {
			resDescs.setContainer(entry.getKey(), entry.getValue());
		}
		resDescs.setContainer(projectDescription.getName(), newIndex);
	}
	return resourceSet;
}
 
Example 17
Source Project: xtext-core   Source File: WorkspaceManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Return true if the given resource still exists.
 */
protected boolean exists(URI uri) {
	ProjectManager projectManager = getProjectManager(uri);
	if (projectManager != null) {
		XtextResourceSet rs = projectManager.getResourceSet();
		if (rs != null) {
			return rs.getURIConverter().exists(uri, null);
		}
	}
	return false;
}
 
Example 18
@Override
public XtextResource getResourceFor(InputStream stream) {
	XtextResourceSet resourceSet = resourceSetProvider.get();
	initializeTypeProvider(resourceSet);
	try {
		URI resourceUri = URI.createURI("Test." + fileExtensionProvider.getPrimaryFileExtension());
		Resource resource = resourceSet.createResource(resourceUri);
		resource.load(stream, null);
		return (XtextResource) resource;
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 19
Source Project: n4js   Source File: XBuildContext.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor.
 */
public XBuildContext(
		Function1<? super URI, ? extends IResourceServiceProvider> resourceServiceProviderProvider,
		XtextResourceSet resourceSet, XIndexState oldState,
		IResourceClusteringPolicy clusteringPolicy, CancelIndicator cancelIndicator) {
	this.resourceServiceProviderProvider = resourceServiceProviderProvider;
	this.resourceSet = resourceSet;
	this.oldState = oldState;
	this.clusteringPolicy = clusteringPolicy;
	this.cancelIndicator = cancelIndicator;
}
 
Example 20
Source Project: dsl-devkit   Source File: AbstractXtextTestUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public XtextResource getResourceFor(final InputStream stream) {
  XtextResourceSet rs = getResourceSet();
  XtextResource resource = (XtextResource) rs.createResource(getTestProjectManager().createTestSourceUri(getDefaultSourceName() + '.' + getFileExtension()));
  rs.getResources().add(resource);
  try {
    resource.load(stream, null);
  } catch (IOException e) {
    throw new WrappedException("Could not create XtextResource from input stream.", e);
  }
  EcoreUtil.resolveAll(resource);
  return resource;
}
 
Example 21
Source Project: xtext-xtend   Source File: AbstractXtendTestCase.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected XtendFile fileWithErrors(String string) throws Exception {
	XtextResourceSet set = getResourceSet();
	String fileName = getFileName(string);
	Resource resource = set.createResource(URI.createURI(fileName + ".xtend"));
	resource.load(new StringInputStream(string), null);
	assertTrue(resource.getErrors().toString(), resource.getErrors().size() > 0);
	XtendFile file = (XtendFile) resource.getContents().get(0);
	return file;
}
 
Example 22
Source Project: xtext-xtend   Source File: IndexingTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected XtextResource justLoad(String contents) throws IOException {
	XtextResourceSet set = getResourceSet();
	String fileName = getFileName(contents);
	Resource resource = set.createResource(URI.createURI(fileName + ".xtend"));
	resource.load(new StringInputStream(contents), null);
	return (XtextResource) resource;
}
 
Example 23
@Test
public void testResourcesAreInMap() {
  final XtextResourceSet rs = this.createEmptyResourceSet();
  Assert.assertEquals(0, rs.getURIResourceMap().size());
  final XtextResource resource = new XtextResource();
  resource.setURI(URI.createFileURI(new File("foo").getAbsolutePath()));
  EList<Resource> _resources = rs.getResources();
  _resources.add(resource);
  Assert.assertEquals(1, rs.getURIResourceMap().size());
  rs.getResources().remove(resource);
  Assert.assertTrue(resource.eAdapters().isEmpty());
  Assert.assertEquals(0, rs.getURIResourceMap().size());
}
 
Example 24
protected final XtextResourceSet getResourceSet() {
	XtextResourceSet resourceSet = get(XtextResourceSet.class);
	IJvmTypeProvider.Factory typeProviderFactory = new JdtTypeProviderFactory(this);
	typeProviderFactory.findOrCreateTypeProvider(resourceSet);
	resourceSet.setClasspathURIContext(getJavaProject(resourceSet));
	return resourceSet;
}
 
Example 25
Source Project: n4js   Source File: OpenFileContext.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected XtextResourceSet createResourceSet() {
	XtextResourceSet result = resourceSetProvider.get();
	ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(result, index);
	externalContentSupport.configureResourceSet(result, new OpenFileContentProvider());

	IAllContainersState allContainersState = new OpenFileAllContainersState(this);
	result.eAdapters().add(new DelegatingIAllContainerAdapter(allContainersState));

	return result;
}
 
Example 26
/** {@inheritDoc} */
@Override
protected BinaryClassFinder createBinaryClassFinder(final ClassLoader classLoader) {
  if (getResourceSet() instanceof XtextResourceSet) {
    Object context = ((XtextResourceSet) getResourceSet()).getClasspathURIContext();
    if (context instanceof Bundle) {
      Bundle bundle = (Bundle) context;
      return new BundleClassFinder(classLoader, bundle);
    }
  }
  return super.createBinaryClassFinder(classLoader);
}
 
Example 27
Source Project: xtext-xtend   Source File: XtendBatchCompiler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Performs the actual installation of the JvmTypeProvider.
 */
private void internalInstallJvmTypeProvider(ResourceSet resourceSet, File tmpClassDirectory, boolean skipIndexLookup) {
	Iterable<String> classPathEntries = concat(asList(tmpClassDirectory.toString()), getClassPathEntries(), getSourcePathDirectories());
	classPathEntries = filter(classPathEntries, new Predicate<String>() {
		@Override
		public boolean apply(String input) {
			return !Strings.isEmpty(input.trim());
		}
	});
	
	Iterable<File> classpath = transform(classPathEntries, TO_FILE);
	if (log.isDebugEnabled()) {
		log.debug("classpath used for Xtend compilation : " + classpath);
	}
	ClassLoader parentClassLoader;
	if (useCurrentClassLoaderAsParent) {
		parentClassLoader = currentClassLoader;
	} else {
		if (isEmpty(bootClassPath)) {
			parentClassLoader = ClassLoader.getSystemClassLoader().getParent();
		} else {
			Iterable<File> bootClassPathEntries = transform(getBootClassPathEntries(), TO_FILE);
			parentClassLoader = new AlternateJdkLoader(bootClassPathEntries);
		}
	}
	jvmTypesClassLoader = createClassLoader(classpath, parentClassLoader);
	new ClasspathTypeProvider(jvmTypesClassLoader, resourceSet, skipIndexLookup ? null : indexedJvmTypeAccess, null);
	((XtextResourceSet) resourceSet).setClasspathURIContext(jvmTypesClassLoader);

	// for annotation processing we need to have the compiler's classpath as a parent.
	annotationProcessingClassLoader = createClassLoader(classpath, currentClassLoader);
	resourceSet.eAdapters().add(new ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter(annotationProcessingClassLoader));
}
 
Example 28
@Override
public void setUp() throws Exception {
	super.setUp();
	if (ReusedTypeProviderTest.typeProvider == null) {
		String pathToSources = "/org/eclipse/xtext/common/types/testSetups";
		List<String> files = ReusedTypeProviderTest.readResource(pathToSources + "/files.list");
		ResourceDescriptionsData part = new ResourceDescriptionsData(Collections.emptySet());
		XtextResourceSet resourceSet = resourceSetProvider.get();
		ProjectDescription projectDesc = new ProjectDescription();
		projectDesc.setName("my-test-project");
		projectDesc.attachToEmfObject(resourceSet);
		ChunkedResourceDescriptions index = new ChunkedResourceDescriptions(Collections.emptyMap(), resourceSet);
		index.setContainer(projectDesc.getName(), part);
		resourceSet.setClasspathURIContext(ReusedTypeProviderTest.class.getClassLoader());

		typeProviderFactory.createTypeProvider(resourceSet);
		BuildRequest buildRequest = new BuildRequest();
		for (String file : files) {
			if (file != null) {
				String fullPath = pathToSources + "/" + file;
				URL url = ReusedTypeProviderTest.class.getResource(fullPath);
				buildRequest.getDirtyFiles().add(URI.createURI(url.toExternalForm()));
			}
		}
		buildRequest.setResourceSet(resourceSet);
		buildRequest.setState(new IndexState(part, new Source2GeneratedMapping()));
		builder.build(buildRequest, (URI it) -> {
			return resourceServiceProviderRegistry.getResourceServiceProvider(it);
		});
		ReusedTypeProviderTest.typeProvider = typeProviderFactory.findTypeProvider(resourceSet);
	}
}
 
Example 29
@Test public void testClasspathURIIsNormalized() {
	XtextResourceSet xtextResourceSet = new XtextResourceSet();
	xtextResourceSet.setClasspathURIContext(this);
	URI classpathURI = URI.createURI("classpath:/org/eclipse/xtext/XtextGrammarTestLanguage.ecore");
	Resource resource = xtextResourceSet.getResource(classpathURI, true);
	IResourceDescription ecoreResourceDescription = createResourceDescription(resource);
	assertNotSame(classpathURI, ecoreResourceDescription.getURI());
	assertEquals(xtextResourceSet.getURIConverter().normalize(classpathURI), ecoreResourceDescription.getURI());
}
 
Example 30
@Test public void testValidLocalLink() 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 Foo type Bar extends Foo"), null);
	
	EcoreUtil.resolveAll(res2);
	Iterable<QualifiedName> names = res2.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(res2).getImportedNames();
	assertFalse(names.iterator().hasNext());
}