Java Code Examples for org.eclipse.xtext.resource.XtextResourceSet#createResource()

The following examples show how to use org.eclipse.xtext.resource.XtextResourceSet#createResource() . 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: XtextGrammarReconcilationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSimple() throws Exception {
	// this fails see bug #252181
	String model = "grammar foo with org.eclipse.xtext.common.Terminals Honolulu : name=ID;";

	// load grammar model
	XtextResourceSet rs = get(XtextResourceSet.class);
	Resource resource = rs.createResource(URI.createURI("foo.xtext"), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	resource.load(new StringInputStream(model), null);
	Grammar object = (Grammar) resource.getContents().get(0);

	// modify first rule
	object.getRules().get(0).setName("HONOLULU");

	// save
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	resource.save(out, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
	String result = new String(out.toByteArray());

	// check
	assertFalse(model.equals(result));
	String expectedModel = LineDelimiters.toPlatform("grammar foo with org.eclipse.xtext.common.Terminals\n\nHONOLULU:\n	name=ID;");
	assertEquals(expectedModel, result);
}
 
Example 2
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 3
Source File: LiveShadowedAllContainerStateTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testContainsURI() {
	String fileExtension = fep.getPrimaryFileExtension();
	XtextResourceSet xtextResourceSet1 = rsp.get();
	xtextResourceSet1.createResource(URI.createURI("/a/x." + fileExtension));
	xtextResourceSet1.createResource(URI.createURI("/b/x1." + fileExtension));
	ResourceSetBasedResourceDescriptions liveState = new ResourceSetBasedResourceDescriptions();
	liveState.setContext(xtextResourceSet1);
	liveState.setRegistry(registry);
	Multimap<String, URI> container2Uris = ArrayListMultimap.create();
	container2Uris.put("a", URI.createURI("/a/x." + fileExtension));
	container2Uris.put("a", URI.createURI("/a/y." + fileExtension));
	container2Uris.put("b", URI.createURI("/b/x1." + fileExtension));
	container2Uris.put("b", URI.createURI("/b/x2." + fileExtension));
	IAllContainersState containersState = containerStateProvider.get(liveState,
			new FakeAllContainerState(container2Uris));
	assertTrue(containersState.containsURI("a", URI.createURI("/a/x." + fileExtension)));
	assertTrue(containersState.containsURI("a", URI.createURI("/a/y." + fileExtension)));
	assertFalse(containersState.containsURI("b", URI.createURI("/a/x." + fileExtension)));
	assertFalse(containersState.containsURI("b", URI.createURI("/a/y." + fileExtension)));
	assertTrue(containersState.containsURI("b", URI.createURI("/b/x1." + fileExtension)));
	assertTrue(containersState.containsURI("b", URI.createURI("/b/x2." + fileExtension)));
	assertFalse(containersState.containsURI("a", URI.createURI("/b/x1." + fileExtension)));
	assertFalse(containersState.containsURI("a", URI.createURI("/b/x2." + fileExtension)));
}
 
Example 4
Source File: PartialParserTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void compareWithNewResource(XtextResource resource, String model, int offset, int length, String newText,
		String fileName) throws IOException {
	resource.update(offset, length, newText);
	XtextResourceSet secondResourceSet = getResourceSet();
	XtextResource newResource = (XtextResource) secondResourceSet.createResource(URI.createURI(fileName));
	String newModel = new StringBuilder(model).replace(offset, offset + length, newText).toString();
	assertEquals(newModel, resource.getParseResult().getRootNode().getText());
	newResource.load(new StringInputStream(newModel), null);
	assertEquals(newResource.getContents().size(), resource.getContents().size());
	EcoreUtil.resolveAll(resource);
	EcoreUtil.resolveAll(newResource);
	for(int i = 0; i < resource.getContents().size(); i++) {
		assertEquals(EmfFormatter.objToStr(newResource.getContents().get(i)), EmfFormatter.objToStr(resource.getContents().get(i)));
	}
	assertEqualNodes(newResource, resource);
}
 
Example 5
Source File: AbstractHierarchyBuilderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected ResourceSet createResourceSet(@Extension final AbstractHierarchyBuilderTest.HierarchyBuilderTestConfiguration configuration) {
  try {
    final XtextResourceSet resourceSet = this.resourceSetProvider.get();
    for (final Pair<String, String> model : configuration.models) {
      {
        final Resource resource = resourceSet.createResource(URI.createURI(model.getKey()));
        String _value = model.getValue();
        LazyStringInputStream _lazyStringInputStream = new LazyStringInputStream(_value, "UTF-8");
        resource.load(_lazyStringInputStream, null);
        this._validationTestHelper.assertNoIssues(resource);
      }
    }
    return resourceSet;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 6
Source File: AbstractXtendContentAssistBugTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public XtextResource getResourceFor(InputStream stream) {
	try {
		XtextResourceSet set = get(XtextResourceSet.class);
		XtextResource result = (XtextResource) set.createResource(URI.createURI("Test." + testHelper.getFileExtension()));
		result.load(stream, null);
		initializeTypeProvider(result);
		return result;
	} catch(Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 7
Source File: AbstractXtendTestCase.java    From xtext-xtend with 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 8
Source File: CompilationTestHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * same as {@link #resourceSet(Pair...)} but without actually loading the created resources.
 */
@SuppressWarnings("unchecked")
public ResourceSet unLoadedResourceSet(Pair<String,? extends CharSequence> ...resources ) throws IOException {
	XtextResourceSet result = resourceSetProvider.get();
	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?");
	}
	return result;
}
 
Example 9
Source File: XtendValidationTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testBug378211_NoException() throws Exception{
  	String model = "@Data class Foo { int id  def }";
  	XtextResourceSet set = getResourceSet();
String fileName = getFileName(model);
Resource resource = set.createResource(URI.createURI(fileName + ".xtend"));
resource.load(new StringInputStream(model), null);
  	helper.validate(resource.getContents().get(0));
  }
 
Example 10
Source File: AbstractContentAssistTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public XtextResource getResourceFor(InputStream stream) {
	try {
		XtextResourceSet set = resourceSetProvider.get();
		initializeTypeProvider(set);
		Resource result = set.createResource(URI.createURI("Test." + fileExtensionProvider.getPrimaryFileExtension()));
		result.load(stream, null);
		return (XtextResource) result;
	} catch (IOException e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example 11
Source File: AbstractContentAssistTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@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 12
Source File: FindReferencesTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public XtextResource getResourceFor(InputStream stream) {
	try {
		XtextResourceSet set = get(XtextResourceSet.class);
		set.setClasspathURIContext(JavaCore.create(project));
		XtextResource result = (XtextResource) set.createResource(URI.createURI("Test." + fileExtension));
		result.load(stream, null);
		return result;
	} catch(Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 13
Source File: CrossContainmentTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testCrossContainment_01() {
	XtextResourceSet resourceSet = get(XtextResourceSet.class);
	resourceSet.setClasspathURIContext(getClass());
	Resource resource = resourceSet.createResource(URI.createFileURI("container.xmi"));
	Resource childResource = resourceSet.createResource(URI.createFileURI("child.xmi"));
	CrossResourceContainerManyChildren container = PartialParsingTestUtilFactory.eINSTANCE.createCrossResourceContainerManyChildren();
	resource.getContents().add(container);
	Grammar grammar = XtextFactory.eINSTANCE.createGrammar();
	childResource.getContents().add(grammar);
	assertNull(grammar.eContainer());
	container.getChildren().add(grammar);
	assertSame(container, grammar.eContainer());
	assertSame(childResource, grammar.eResource());
	assertSame(resource, container.eResource());
}
 
Example 14
Source File: ScriptEngineImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private XExpression parseScriptIntoXTextEObject(String scriptAsString) throws ScriptParsingException {
    XtextResourceSet resourceSet = getResourceSet();
    Resource resource = resourceSet.createResource(computeUnusedUri(resourceSet)); // IS-A XtextResource
    try {
        resource.load(new StringInputStream(scriptAsString, StandardCharsets.UTF_8.name()),
                resourceSet.getLoadOptions());
    } catch (IOException e) {
        throw new ScriptParsingException(
                "Unexpected IOException; from close() of a String-based ByteArrayInputStream, no real I/O; how is that possible???",
                scriptAsString, e);
    }

    List<Diagnostic> errors = resource.getErrors();
    if (errors.size() != 0) {
        throw new ScriptParsingException("Failed to parse expression (due to managed SyntaxError/s)",
                scriptAsString).addDiagnosticErrors(errors);
    }

    EList<EObject> contents = resource.getContents();

    if (!contents.isEmpty()) {
        Iterable<Issue> validationErrors = getValidationErrors(contents.get(0));
        if (!validationErrors.iterator().hasNext()) {
            return (XExpression) contents.get(0);
        } else {
            throw new ScriptParsingException("Failed to parse expression (due to managed ValidationError/s)",
                    scriptAsString).addValidationIssues(validationErrors);
        }
    } else {
        return null;
    }
}
 
Example 15
Source File: AbstractXtendTestCase.java    From xtext-xtend with 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 16
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 17
Source File: ScriptEngineImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private XExpression parseScriptIntoXTextEObject(String scriptAsString) throws ScriptParsingException {
    XtextResourceSet resourceSet = getResourceSet();
    Resource resource = resourceSet.createResource(computeUnusedUri(resourceSet)); // IS-A XtextResource
    try {
        resource.load(new StringInputStream(scriptAsString, StandardCharsets.UTF_8.name()),
                resourceSet.getLoadOptions());
    } catch (IOException e) {
        throw new ScriptParsingException(
                "Unexpected IOException; from close() of a String-based ByteArrayInputStream, no real I/O; how is that possible???",
                scriptAsString, e);
    }

    List<Diagnostic> errors = resource.getErrors();
    if (!errors.isEmpty()) {
        throw new ScriptParsingException("Failed to parse expression (due to managed SyntaxError/s)",
                scriptAsString).addDiagnosticErrors(errors);
    }

    EList<EObject> contents = resource.getContents();

    if (!contents.isEmpty()) {
        Iterable<Issue> validationErrors = getValidationErrors(contents.get(0));
        if (!validationErrors.iterator().hasNext()) {
            return (XExpression) contents.get(0);
        } else {
            throw new ScriptParsingException("Failed to parse expression (due to managed ValidationError/s)",
                    scriptAsString).addValidationIssues(validationErrors);
        }
    } else {
        return null;
    }
}
 
Example 18
Source File: Bug318343Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	with(LangATestLanguageStandaloneSetup.class);
	globalScopeProvider = get(DefaultGlobalScopeProvider.class);
	XtextResourceSet xtextResourceSet = get(XtextResourceSet.class);
	resource1 = xtextResourceSet.createResource(URI.createFileURI(new File("uri1.langatestlanguage").getAbsolutePath()));
	resource2 = xtextResourceSet.createResource(URI.createFileURI(new File("uri2.langatestlanguage").getAbsolutePath()));
	resource1.load(new StringInputStream("type t1"),null);
	resource2.load(new StringInputStream("type t2"),null);
}
 
Example 19
Source File: WorkspaceEncodingProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testWorkspaceDefaultEncoding () {
	XtextResourceSet resourceSet = resourceSetProvider.get();
	XtextResource resource = (XtextResource) resourceSet.createResource(URI.createURI("platform:/resource/WorkspaceEncodingProviderTest/test1.xtextgrammar"));
	assertEquals(defaultEncoding, resource.getEncoding());
}
 
Example 20
Source File: AbstractXtextTestUtil.java    From dsl-devkit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a resource with the given URI and content.
 *
 * @param uri
 *          to associate the model with
 * @param content
 *          String representation of the create a resource from
 * @return {@link XtextResource} created
 * @throws IOException
 *           may be thrown when trying to load the given content
 */
protected final XtextResource getResource(final URI uri, final String content) throws IOException {
  StringInputStream instanceStream = new StringInputStream(content);
  XtextResourceSet rs = getResourceSet();
  XtextResource resource = (XtextResource) rs.createResource(uri);
  rs.getResources().add(resource);
  resource.load(instanceStream, null);
  EcoreUtil.resolveAll(resource);
  return resource;
}