Java Code Examples for org.eclipse.xtext.resource.XtextResource#load()

The following examples show how to use org.eclipse.xtext.resource.XtextResource#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: DirtyStateResourceDescriptionTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
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 2
Source File: AbstractContentAssistTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public final XtextResource getResourceFor(InputStream stream) {
	try {
		final StringBuilder content = new StringBuilder();
		try (final InputStreamReader reader = new InputStreamReader(stream)) {
			final BufferedReader breader = new BufferedReader(reader);
			String line = breader.readLine();
			while (line != null) {
				content.append(line);
				content.append(getLineSeparator());
				line = breader.readLine();
			}
		}
		final WorkbenchTestHelper helper = helper();
		final String strContent = content.toString();
		final IFile file = helper.createFile(helper.generateFilename(), strContent);
		final XtextResource resource = (XtextResource) helper.getResourceSet().createResource(helper.uri(file));
		try (InputStream is = new StringInputStream(strContent)) {
			resource.load(is, null);
		}
		return resource;
	} catch(Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 3
Source File: Bug297909Test.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testReconcileDocument() throws Exception {
	Injector injector = doGetSetup().createInjectorAndDoEMFRegistration();
	XtextDocument document = injector.getInstance(XtextDocument.class);
	document.setValidationJob(new Job("Job") {
		@Override
		protected IStatus run(IProgressMonitor monitor) {
			return Status.OK_STATUS;
		}
	});
	XtextResource resource = injector.getInstance(XtextResource.class);
	XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
	resourceSet.getResources().add(resource);
	resource.load(new StringInputStream(""), Collections.singletonMap(XtextResource.OPTION_ENCODING, Charset.defaultCharset().name()));
	document.setInput(resource);
	document.set("abstract rules firstRule");
	XtextDocumentReconcileStrategy strategy = injector.getInstance(XtextDocumentReconcileStrategy.class);
	strategy.setDocument(document);
	strategy.setResource(resource);
	try {
		strategy.reconcile(new ReconcilerReplaceRegion(0, document.getLength(), document.get()));
		fail("Expected ParseException");
	} catch(ParseException expected) {
		assertTrue(expected.getMessage().contains("Make sure the EPackage has been registered"));
	}
}
 
Example 4
Source File: TemporaryResourceProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public <Result> Result useTemporaryResource(
		ResourceSet resourceSet, Grammar language, 
		AbstractRule rootRule, String content, IUnitOfWork<Result, XtextResource> runnable) {
	XtextResource resource = languageRegistry.createTemporaryResourceIn(language, resourceSet);
	if (rootRule != null)
		PartialParser.assignRootRule(resource, (ParserRule) rootRule);
	try {
		resource.load(new StringInputStream(content, resource.getEncoding()), null);
		return runnable.exec(resource);
	} catch(Exception e) {
		throw new RuntimeException(e);
	} finally {
		if (resource != null) {
			if (resource.isLoaded())
				resource.unload();
			resourceSet.getResources().remove(resource);
		}
	}
}
 
Example 5
Source File: DotEditorUtils.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private static XtextResource doGetResource(Injector injector,
		InputStream in, URI uri) throws Exception {
	XtextResourceSet rs = injector.getInstance(XtextResourceSet.class);
	rs.setClasspathURIContext(DotEditorUtils.class);
	XtextResource resource = (XtextResource) injector
			.getInstance(IResourceFactory.class).createResource(uri);
	rs.getResources().add(resource);
	resource.load(in, null);
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource)
				.resolveLazyCrossReferences(CancelIndicator.NullImpl);
	} else {
		EcoreUtil.resolveAll(resource);
	}
	return resource;
}
 
Example 6
Source File: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testBug_266807() throws Exception {
  final XtextResourceSet rs = this.<XtextResourceSet>get(XtextResourceSet.class);
  rs.setClasspathURIContext(this.getClass());
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("classpath:/");
  String _replace = this.getClass().getPackage().getName().replace(Character.valueOf('.').charValue(), Character.valueOf('/').charValue());
  _builder.append(_replace);
  _builder.append("/Test.xtext");
  Resource _createResource = rs.createResource(
    URI.createURI(_builder.toString()), 
    ContentHandler.UNSPECIFIED_CONTENT_TYPE);
  final XtextResource resource = ((XtextResource) _createResource);
  resource.load(null);
  EList<Resource.Diagnostic> _errors = resource.getErrors();
  for (final Resource.Diagnostic d : _errors) {
    Assert.fail(d.getMessage());
  }
}
 
Example 7
Source File: FormatterFacadeTest.java    From sarl with 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 8
Source File: DefaultReferenceDescriptionTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testgetReferenceDescriptionForMultiValue() throws Exception {
	with(new LangATestLanguageStandaloneSetup());
	XtextResource targetResource = getResource("type C type D", "bar.langatestlanguage");
	EObject typeC = targetResource.getContents().get(0).eContents().get(0);
	EObject typeD = targetResource.getContents().get(0).eContents().get(1);
	XtextResource resource = (XtextResource) targetResource.getResourceSet().createResource(URI.createURI("foo.langatestlanguage"));
	resource.load(new StringInputStream("type A implements B,C,D type B"), null);
	EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl);
	IResourceDescription resDesc = resource.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(resource);
	Iterable<IReferenceDescription> descriptions = resDesc.getReferenceDescriptions();
	Collection<IReferenceDescription> collection = Lists.newArrayList(descriptions);
	assertEquals(2,collection.size());
	Iterator<IReferenceDescription> iterator = descriptions.iterator();
	IReferenceDescription refDesc1 = iterator.next();
	IReferenceDescription refDesc2 = iterator.next();
	Main m = (Main) resource.getParseResult().getRootASTElement();
	assertEquals(m.getTypes().get(0),resource.getResourceSet().getEObject(refDesc1.getSourceEObjectUri(),false));
	assertEquals(typeC,resource.getResourceSet().getEObject(refDesc1.getTargetEObjectUri(),false));
	assertEquals(1,refDesc1.getIndexInList());
	assertEquals(LangATestLanguagePackage.Literals.TYPE__IMPLEMENTS,refDesc1.getEReference());
	assertEquals(m.getTypes().get(0),resource.getResourceSet().getEObject(refDesc2.getSourceEObjectUri(),false));
	assertEquals(typeD,resource.getResourceSet().getEObject(refDesc2.getTargetEObjectUri(),false));
	assertEquals(2,refDesc2.getIndexInList());
	assertEquals(LangATestLanguagePackage.Literals.TYPE__IMPLEMENTS,refDesc2.getEReference());
}
 
Example 9
Source File: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public XtextResource doGetResource(final InputStream in, final URI uri) throws Exception {
  XtextResourceSet rs = this.<XtextResourceSet>get(XtextResourceSet.class);
  rs.setClasspathURIContext(this.getClass());
  Resource _createResource = this.getResourceFactory().createResource(uri);
  final XtextResource resource = ((XtextResource) _createResource);
  rs.getResources().add(resource);
  XtextLinker linker = new XtextLinker() {
    @Override
    protected Xtext2EcoreTransformer createTransformer(final Grammar grammar, final IDiagnosticConsumer consumer) {
      Xtext2EcoreTransformer result = super.createTransformer(grammar, consumer);
      ErrorAcceptor _errorAcceptor = result.getErrorAcceptor();
      Xtext2EcoreTransformerTest.MyErrorAcceptor _myErrorAcceptor = new Xtext2EcoreTransformerTest.MyErrorAcceptor(_errorAcceptor, Xtext2EcoreTransformerTest.this.errorAcceptorMock);
      result.setErrorAcceptor(_myErrorAcceptor);
      return result;
    }
  };
  ILinker _linker = resource.getLinker();
  linker.setScopeProvider(((XtextLinker) _linker).getScopeProvider());
  ILinker _linker_1 = resource.getLinker();
  linker.setLinkingService(((Linker) _linker_1).getLinkingService());
  ILinker _linker_2 = resource.getLinker();
  linker.setLinkingHelper(((Linker) _linker_2).getLinkingHelper());
  XtextLinker.PackageRemover _packageRemover = new XtextLinker.PackageRemover();
  linker.setPackageRemover(_packageRemover);
  LinkingDiagnosticMessageProvider _linkingDiagnosticMessageProvider = new LinkingDiagnosticMessageProvider();
  linker.setDiagnosticMessageProvider(_linkingDiagnosticMessageProvider);
  OnChangeEvictingCache _onChangeEvictingCache = new OnChangeEvictingCache();
  linker.setCache(_onChangeEvictingCache);
  resource.setLinker(linker);
  resource.load(in, null);
  return resource;
}
 
Example 10
Source File: ParserTestHelper.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public XtextResource getResourceFromStream(InputStream in) throws IOException {
	XtextResourceSet rs = resourceSet.get();
	rs.setClasspathURIContext(getClass());
	URI uri = URI.createURI("mytestmodel."+fileExtension);
	XtextResource resource = createResource(uri);
	rs.getResources().add(resource);
	resource.load(in, null);
	return resource;
}
 
Example 11
Source File: AbstractXbaseContentAssistTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public final XtextResource getResourceFor(InputStream stream) {
	try {
		XtextResource result = (XtextResource) getResourceSet().createResource(URI.createURI("Test." + fileExtension));
		result.load(stream, null);
		return result;
	} catch(Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 12
Source File: EncodingTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSaveUtfToUtf() throws Exception {
	XtextResource resource = createXtextResource();
	resource.load(new ByteArrayInputStream(utfBytes), utfOptions);
	ByteArrayOutputStream utfSaveStream = new ByteArrayOutputStream();
	resource.save(utfSaveStream, null);
	utfSaveStream.close();
	byte[] savedUtfBytes = utfSaveStream.toByteArray();
	assertTrue(Arrays.equals(utfBytes, savedUtfBytes));
}
 
Example 13
Source File: AbstractHyperlinkingTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public XtextResource getResourceFor(InputStream stream) {
	try {
		XtextResource result = (XtextResource) getResourceSet().createResource(URI.createURI("Test." + fileExtension));
		result.load(stream, null);
		return result;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 14
Source File: EncodingTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSaveIsoToIso() throws Exception {
	XtextResource resource = createXtextResource();
	resource.load(new ByteArrayInputStream(isoBytes), isoOptions);
	ByteArrayOutputStream isoSaveStream = new ByteArrayOutputStream();
	resource.save(isoSaveStream, null);
	isoSaveStream.close();
	byte[] savedIsoBytes = isoSaveStream.toByteArray();
	assertTrue(Arrays.equals(isoBytes, savedIsoBytes));
}
 
Example 15
Source File: AbstractXtextTests.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected XtextResource doGetResource(InputStream in, URI uri) throws Exception {
	XtextResourceSet rs = get(XtextResourceSet.class);
	rs.setClasspathURIContext(getClass());
	XtextResource resource = (XtextResource) getResourceFactory().createResource(uri);
	rs.getResources().add(resource);
	resource.load(in, null);
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource).resolveLazyCrossReferences(CancelIndicator.NullImpl);
	} else {
		EcoreUtil.resolveAll(resource);
	}
	return resource;
}
 
Example 16
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 17
Source File: HighlightingTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void highlight(String model) {
	try {
		XtextResource resource = resourceProvider.createResource();
		resource.load(new StringInputStream(model), null);
		highlighter.provideHighlightingFor(resource, this, CancelIndicator.NullImpl);
		Assert.assertTrue(expectedRegions.toString(), expectedRegions.isEmpty());
	} catch(Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 18
Source File: AbstractXtextTests.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected XtextResource doGetResource(InputStream in, URI uri) throws Exception {
	XtextResourceSet rs = get(XtextResourceSet.class);
	rs.setClasspathURIContext(getClass());
	XtextResource resource = (XtextResource) getResourceFactory().createResource(uri);
	rs.getResources().add(resource);
	resource.load(in, null);
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource).resolveLazyCrossReferences(CancelIndicator.NullImpl);
	} else {
		EcoreUtil.resolveAll(resource);
	}
	return resource;
}
 
Example 19
Source File: Xtext2EcoreTransformerTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public XtextResource doGetResource(InputStream in, URI uri) throws Exception {
	XtextResourceSet rs = get(XtextResourceSet.class);
	Map<URI, URI> uriMap = rs.getURIConverter().getURIMap();
	uriMap.put(URI.createPlatformPluginURI("org.eclipse.xtext/", false), URI.createURI("classpath:/"));
	uriMap.put(URI.createPlatformPluginURI("org.eclipse.xtext.xbase/", false), URI.createURI("classpath:/"));
	uriMap.put(URI.createPlatformPluginURI("org.eclipse.xtext.common.types/", false), URI.createURI("classpath:/"));
	uriMap.put(URI.createPlatformPluginURI("org.eclipse.emf.ecore/", false), URI.createURI("classpath:/"));
	uriMap.put(URI.createPlatformResourceURI("org.eclipse.xtext.xbase/", false), URI.createURI("classpath:/"));
	uriMap.put(URI.createPlatformResourceURI("org.eclipse.emf.ecore/", false), URI.createURI("classpath:/"));
	uriMap.put(URI.createPlatformResourceURI("org.eclipse.xtext.common.types/", false),
			URI.createURI("classpath:/"));
	rs.setClasspathURIContext(getClass());
	XtextResource resource = ((XtextResource) getResourceFactory().createResource(uri));
	rs.getResources().add(resource);
	XtextLinker linker = new XtextLinker() {
		@Override
		protected Xtext2EcoreTransformer createTransformer(Grammar grammar, IDiagnosticConsumer consumer) {
			Xtext2EcoreTransformer result = super.createTransformer(grammar, consumer);
			result.setErrorAcceptor(new Xtext2EcoreTransformerTest.MyErrorAcceptor(result.getErrorAcceptor(),
					Xtext2EcoreTransformerTest.this.errorAcceptorMock));
			return result;
		}
	};
	linker.setScopeProvider(((XtextLinker) resource.getLinker()).getScopeProvider());
	linker.setLinkingService(((Linker) resource.getLinker()).getLinkingService());
	linker.setLinkingHelper(((Linker) resource.getLinker()).getLinkingHelper());
	linker.setPackageRemover(new XtextLinker.PackageRemover());
	linker.setDiagnosticMessageProvider(new LinkingDiagnosticMessageProvider());
	linker.setCache(new OnChangeEvictingCache());
	resource.setLinker(linker);
	resource.load(in, null);
	return resource;
}
 
Example 20
Source File: DefaultResourceDescription2Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testValidExternalLink() 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 Foo"), null);
	
	EcoreUtil.resolveAll(res2);
	Iterable<QualifiedName> names = res2.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(res2).getImportedNames();
	assertEquals(QualifiedName.create("foo"),names.iterator().next());
}