Java Code Examples for org.eclipse.emf.ecore.util.EcoreUtil#resolveAll()

The following examples show how to use org.eclipse.emf.ecore.util.EcoreUtil#resolveAll() . 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
public void compile(String qualifiedName) throws IOException {
	ResourceSet set = injector.getInstance(ResourceSet.class);
	final String from = "src/" + qualifiedName.replace('.', '/') + ".xtend";
	final String to = "src-gen/" + qualifiedName.replace('.', '/') + ".java";

	Resource res = set.getResource(org.eclipse.emf.common.util.URI.createFileURI(from), true);
	EcoreUtil.resolveAll(res);
	if (!res.getErrors().isEmpty())
		throw new RuntimeException(res.getErrors().toString());
	final File file = new File(to);
	createFolders(file);
	FileWriter writer = new FileWriter(file);
	IXtendJvmAssociations associations = injector.getInstance(IXtendJvmAssociations.class);
	JvmModelGenerator generator = injector.getInstance(JvmModelGenerator.class);
	XtendFile xtendFile = (XtendFile)res.getContents().get(0);
	JvmGenericType inferredType = associations.getInferredType((XtendClass) xtendFile.getXtendTypes().get(0));
	GeneratorConfig config = injector.getInstance(IGeneratorConfigProvider.class).get(inferredType);
	CharSequence javaCode = generator.generateType(inferredType, config);
	writer.append(javaCode);
	writer.close();
	System.out.println("compiled " + from + " to " + to);
}
 
Example 2
Source Project: n4js   File: ExceptionAnalyser.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected List<Diagnostic> getScriptErrors(Script script) {
	EcoreUtil.resolveAll(script.eResource());
	List<Diagnostic> diagnostics = super.getScriptErrors(script);
	Iterator<TypableElement> typableASTNodes = Iterators.filter(EcoreUtil2.eAll(script), TypableElement.class);
	List<Diagnostic> result = Lists.<Diagnostic> newArrayList(Iterables.filter(diagnostics,
			ExceptionDiagnostic.class));
	while (typableASTNodes.hasNext()) {
		TypableElement typableASTNode = typableASTNodes.next();
		RuleEnvironment ruleEnvironment = RuleEnvironmentExtensions.newRuleEnvironment(typableASTNode);
		try {
			typeSystem.type(ruleEnvironment, typableASTNode);
		} catch (Throwable cause) {
			if (cause instanceof Exception) {
				result.add(new ExceptionDiagnostic((Exception) cause));
			} else {
				throw new RuntimeException(cause);
			}
		}
	}
	validator.validate(script.eResource(), CheckMode.ALL, CancelIndicator.NullImpl);
	return result;
}
 
Example 3
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 4
protected List<Pair<EObject, ICompositeNode>> detachNodeModel(EObject eObject) {
	EcoreUtil.resolveAll(eObject);
	List<Pair<EObject, ICompositeNode>> result = Lists.newArrayList();
	Iterator<Object> iterator = EcoreUtil.getAllContents(eObject.eResource(), false);
	while (iterator.hasNext()) {
		EObject object = (EObject) iterator.next();
		Iterator<Adapter> adapters = object.eAdapters().iterator();
		while (adapters.hasNext()) {
			Adapter adapter = adapters.next();
			if (adapter instanceof ICompositeNode) {
				adapters.remove();
				result.add(Tuples.create(object, (ICompositeNode) adapter));
				break;
			}
		}
	}
	return result;
}
 
Example 5
protected void compareWithFullParse(String model, int offset, int length, String newText) throws Exception {
	XtextResource resource = getResourceFromStringAndExpect(model, UNKNOWN_EXPECTATION);
	resource.update(offset, length, newText);
	String text = resource.getParseResult().getRootNode().getText();
	XtextResource newResource = getResourceFromStringAndExpect(text, UNKNOWN_EXPECTATION);
	assertEquals(text, resource.getContents().size(), newResource.getContents().size());
	EcoreUtil.resolveAll(resource);
	EcoreUtil.resolveAll(newResource);
	for(int i = 0; i < resource.getContents().size(); i++) {
		assertEquals(text, EmfFormatter.objToStr(newResource.getContents().get(i)), EmfFormatter.objToStr(resource.getContents().get(i)));
	}
	
	ICompositeNode rootNode = resource.getParseResult().getRootNode();
	ICompositeNode newRootNode = newResource.getParseResult().getRootNode();
	Iterator<INode> iterator = rootNode.getAsTreeIterable().iterator();
	Iterator<INode> newIterator = newRootNode.getAsTreeIterable().iterator();
	while(iterator.hasNext()) {
		assertTrue(newIterator.hasNext());
		assertEqualNodes(text, iterator.next(), newIterator.next());
	}
	assertFalse(iterator.hasNext());
	assertFalse(newIterator.hasNext());
}
 
Example 6
protected XtextResource doGetResource(InputStream in, URI uri) throws Exception {
	XtextResourceSet rs = get(XtextResourceSet.class);
	rs.setClasspathURIContext(getClasspathURIContext());
	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 7
@Test public void testCircularImports() {
	XtextResourceSet resourceSet = get(XtextResourceSet.class);
	resourceSet.setClasspathURIContext(getClass().getClassLoader());
	URI uri = URI.createURI("classpath:/org/eclipse/xtext/linking/01.importuritestlanguage");
	Resource res = resourceSet.getResource(uri, true);
	EcoreUtil.resolveAll(res);
	assertNotNull("res", res);
	assertFalse(res.getErrors().toString(), res.getErrors().isEmpty());
}
 
Example 8
@Test
public void testBug379019() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package testPackage");
    _builder.newLine();
    _builder.append("class Foo {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def error() {");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("val start = System::currentTimeMillis()");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("var time = System::currentTimeMillis() - start");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("time");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtendFile xtendFile = this.parseHelper.parse(_builder, this.getResourceSet());
    final XtendClass clazz = IterableExtensions.<XtendClass>head(Iterables.<XtendClass>filter(xtendFile.getXtendTypes(), XtendClass.class));
    final XtendMember function = IterableExtensions.<XtendMember>head(clazz.getMembers());
    final String signature = this.signatureProvider.getSignature(function);
    EcoreUtil.resolveAll(xtendFile);
    Assert.assertEquals("long error()", signature);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 9
@Override
public void processFile(String data) throws Exception {
	XtextResourceSet resourceSet = new XtextResourceSet();
	NoOpClassLoader classLoader = new NoOpClassLoader();
	resourceSet.setClasspathURIContext(classLoader);
	ClasspathTypeProviderFactory factory = new ClasspathTypeProviderFactory(classLoader, typeResourceServices);
	factory.createTypeProvider(resourceSet);
	EObject parsed = parseHelperNoJRE.parse(data, resourceSet);
	EcoreUtil.resolveAll(parsed);
	checkNoErrorsInValidator(data, (XtextResource) parsed.eResource());
}
 
Example 10
protected XtendFile getParsedXtendFile(final CharSequence contents) {
  try {
    final XtendFile file = this._parseHelper.parse(contents);
    final EList<Resource.Diagnostic> errors = file.eResource().getErrors();
    Assert.assertTrue(errors.toString(), errors.isEmpty());
    EcoreUtil.resolveAll(file);
    return file;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 11
protected JvmDeclaredType loadAndResolve(String name, boolean accessMembers, boolean accessAnnotations, boolean accessTypeParams, boolean accessParameter, boolean accessParameterNames) {
	JvmDeclaredType type = (JvmDeclaredType) getTypeProvider().findTypeByName(name);
	EcoreUtil.resolveAll(type.eResource());
	EcoreUtil.resolveAll(type.eResource().getResourceSet());
	Assert.assertNotNull(name, type);
	
	if (accessAnnotations) {
		type.getAnnotations();
	}
	
	if (accessMembers) {
		EList<JvmMember> members = type.getMembers();
		for (JvmMember member : members) {
			if (accessAnnotations) {
				member.getAnnotations();
			}
			if (member instanceof JvmExecutable) {
				JvmExecutable operation = (JvmExecutable) member;
				if (accessParameter) {
					EList<JvmFormalParameter> parameters = operation.getParameters();
					for (JvmFormalParameter jvmFormalParameter : parameters) {
						if (accessAnnotations) {
							jvmFormalParameter.getAnnotations();
						}
						if (accessParameterNames) {
							jvmFormalParameter.getName();
						}
					}
				}
			}
		}
	}
	return type;
}
 
Example 12
@Test public void testGenerics_2() throws Exception {
	// linking is ok but should trigger a validation error
	XExpression expression = expression("(null as testdata.GenericType1<? extends java.lang.StringBuffer>) += new StringBuffer", false);
	EcoreUtil.resolveAll(expression);
	List<Resource.Diagnostic> errors = expression.eResource().getErrors();
	assertEquals(errors.toString(), 1, errors.size());
	assertEquals("Type mismatch: type StringBuffer is not applicable at this location", errors.get(0).getMessage());
}
 
Example 13
@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 14
@Override
@Test public void testWithImports() throws Exception {
	SyntheticModelAwareURIConverter uriConverter = new SyntheticModelAwareURIConverter();
	XtextResourceSet resourceSet = get(XtextResourceSet.class);
	resourceSet.setURIConverter(uriConverter);
	
	uriConverter.addModel("a.ignorecaseimportstestlanguage", "a A {}");
	
	XtextResource resource = (XtextResource) getResourceFactory().createResource(URI.createURI("b.ignorecaseimportstestlanguage"));
	resourceSet.getResources().add(resource);
	resource.load(new StringInputStream("'a.ignorecaseimportstestlanguage' b A {}"), null);
	EcoreUtil.resolveAll(resource);
	assertTrue(resource.getErrors().toString(), resource.getErrors().isEmpty());
}
 
Example 15
@Test public void testReplaceResourceURIs() {
	XtextResourceSet xtextResourceSet = get(XtextResourceSet.class);
	xtextResourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl());
	xtextResourceSet.setClasspathURIContext(this);
	Resource grammarResource = xtextResourceSet.getResource(URI.createURI("classpath:/org/eclipse/xtext/generator/grammarAccess/GrammarAccessTestLanguage.xtext"), true);
	EcoreUtil.resolveAll(grammarResource);
	Grammar grammar = (Grammar) grammarResource.getContents().get(0);
	EPackage ePackage = grammar.getMetamodelDeclarations().get(0).getEPackage();
	assertFalse(ePackage.eResource().getURI().equals(URI.createURI(ePackage.getNsURI())));
	fragment.replaceResourceURIsWithNsURIs(grammar, xtextResourceSet);
	assertEquals(ePackage.eResource().getURI(), URI.createURI(ePackage.getNsURI()));
}
 
Example 16
@Test public void testDummy() {
	assertEquals(1, resource.getResourceSet().getResources().size());
	EcoreUtil.resolveAll(resource);
	assertEquals(101, resource.getResourceSet().getResources().size());
}
 
Example 17
Source Project: CogniCrypt   File: CrySLParser.java    License: Eclipse Public License 2.0 4 votes vote down vote up
public CrySLRule readRule(File ruleFile) {
	final String fileName = ruleFile.getName();
	final String extension = fileName.substring(fileName.lastIndexOf("."));
	if (!Constants.cryslFileEnding.equals(extension)) {
		return null;
	}
	final Resource resource = resourceSet.getResource(URI.createFileURI(ruleFile.getAbsolutePath()), true);// URI.createPlatformResourceURI(ruleFile.getFullPath().toPortableString(),
																																																					// true), true);
	EcoreUtil.resolveAll(resourceSet);
	final EObject eObject = resource.getContents().get(0);
	final Domainmodel dm = (Domainmodel) eObject;
	String curClass = dm.getJavaType().getQualifiedName();
	final EnsuresBlock ensure = dm.getEnsure();
	final Map<ParEqualsPredicate, SuperType> pre_preds = Maps.newHashMap();
	final DestroysBlock destroys = dm.getDestroy();

	Expression order = dm.getOrder();
	try {
		if (order instanceof Order) {
			validateOrder((Order) order);
		}
	}
	catch (ClassCastException ex) {
		Activator.getDefault().logError(ex.getMessage() + " in rule " + curClass + ".");
		return null;
	}

	if (destroys != null) {
		pre_preds.putAll(getKills(destroys.getPred()));
	}
	if (ensure != null) {
		pre_preds.putAll(getPredicates(ensure.getPred()));
	}

	this.smg = buildStateMachineGraph(order);
	final ForbiddenBlock forbEvent = dm.getForbEvent();
	this.forbiddenMethods = (forbEvent != null) ? getForbiddenMethods(forbEvent.getForb_methods()) : Lists.newArrayList();

	final List<ISLConstraint> constraints = (dm.getReqConstraints() != null) ? buildUpConstraints(dm.getReqConstraints().getReq()) : Lists.newArrayList();
	constraints.addAll(((dm.getRequire() != null) ? collectRequiredPredicates(dm.getRequire().getPred()) : Lists.newArrayList()));
	final List<Entry<String, String>> objects = getObjects(dm.getUsage());

	final List<CrySLPredicate> actPreds = Lists.newArrayList();

	for (final ParEqualsPredicate pred : pre_preds.keySet()) {
		final SuperType cond = pre_preds.get(pred);
		if (cond == null) {
			actPreds.add(pred.tobasicPredicate());
		} else {
			actPreds.add(new CrySLCondPredicate(pred.getBaseObject(), pred.getPredName(), pred.getParameters(), pred.isNegated(),
					getStatesForMethods(CrySLParserUtils.resolveAggregateToMethodeNames(cond))));
		}
	}
	final CrySLRule rule = new CrySLRule(curClass, objects, this.forbiddenMethods, this.smg, constraints, actPreds);

	return rule;
}
 
Example 18
@Override
protected void doLinking() {
	super.doLinking();
	if (isEagerLinking())
		EcoreUtil.resolveAll(this);
}
 
Example 19
protected Type resolve(Type type, String text, int offset, int length) {
	SyntheticLinkingSupport syntheticLinkingSupport = get(SyntheticLinkingSupport.class);
	syntheticLinkingSupport.createAndSetProxy(type, ImportedURIPackage.Literals.TYPE__EXTENDS, text, offset, length);
	EcoreUtil.resolveAll(type.eResource().getResourceSet());
	return type;
}
 
Example 20
protected void doTestNavigation(IUnitOfWork<URI, IFile> uriComputation, boolean expectFQN) throws Exception {
	IJavaProject project = JavaProjectSetupUtil.createJavaProject("importuriuitestlanguage.project");
	try {
		IFile first = project.getProject().getFile("src/first.importuriuitestlanguage");
		first.create(new StringInputStream("type ASimpleType"), true, null);
		
		ResourceSet resourceSet = resourceSetProvider.get(project.getProject());
		
		Resource resource = resourceFactory.createResource(URI.createURI("synthetic://second.importuriuitestlanguage"));
		resourceSet.getResources().add(resource);
		String model = "import '" + uriComputation.exec(first) + "' type MyType extends ASimpleType";
		resource.load(new StringInputStream(model), null);
		EcoreUtil.resolveAll(resource);
		Assert.assertTrue(resource.getErrors().isEmpty());
		
		IHyperlink[] hyperlinks = helper.createHyperlinksByOffset((XtextResource) resource, model.indexOf("SimpleType"), false);
		Assert.assertEquals(1, hyperlinks.length);
		IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
		Assert.assertNull(activePage.getActiveEditor());
		if (expectFQN) {
			Assert.assertEquals(URI.createURI(first.getLocationURI().toString()), ((XtextHyperlink)hyperlinks[0]).getURI().trimFragment());
		} else {
			Assert.assertEquals(URI.createPlatformResourceURI(first.getFullPath().toString(), true), ((XtextHyperlink)hyperlinks[0]).getURI().trimFragment());
		}
		hyperlinks[0].open();
		IEditorPart editor = activePage.getActiveEditor();
		Assert.assertNotNull(editor);
		IXtextDocument document = xtextDocumentUtil.getXtextDocument(editor);
		document.readOnly(new IUnitOfWork.Void<XtextResource>() {
			@Override
			public void process(XtextResource state) throws Exception {
				Assert.assertEquals("platform:/resource/importuriuitestlanguage.project/src/first.importuriuitestlanguage", state.getURI().toString());
			}
		});
		Assert.assertEquals("type ASimpleType", document.get());
		IEditorPart newPart = IDE.openEditor(activePage, first);
		Assert.assertEquals(1, activePage.getEditorReferences().length);
		Assert.assertEquals(editor, newPart);
	} finally {
		project.getProject().delete(true, null);
	}
}