Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2012 itemis AG (http://www.itemis.eu) and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html /
  
  package org.eclipse.xtext.xbase.compiler;
  
 import static com.google.common.collect.Lists.*;
 import static com.google.common.collect.Maps.*;
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 
 import  org.eclipse.emf.common.util.URI;
 import  org.eclipse.emf.ecore.resource.Resource;
 import  org.eclipse.emf.ecore.resource.ResourceSet;
 import  org.eclipse.xtext.EcoreUtil2;
 import  org.eclipse.xtext.generator.IGenerator;
 import  org.eclipse.xtext.generator.IOutputConfigurationProvider;
 import  org.eclipse.xtext.generator.OutputConfiguration;
 import  org.eclipse.xtext.junit4.TemporaryFolder;
 import  org.eclipse.xtext.resource.FileExtensionProvider;
 import  org.eclipse.xtext.resource.IResourceDescription;
 import  org.eclipse.xtext.resource.IResourceServiceProvider;
 import  org.eclipse.xtext.resource.XtextResource;
 import  org.eclipse.xtext.resource.XtextResourceSet;
 import  org.eclipse.xtext.resource.impl.ResourceDescriptionsData;
 import  org.eclipse.xtext.util.CancelIndicator;
 import  org.eclipse.xtext.util.Files;
 import  org.eclipse.xtext.util.IAcceptor;
 import  org.eclipse.xtext.validation.CheckMode;
 import  org.eclipse.xtext.validation.Issue;
 import  org.eclipse.xtext.xbase.file.ProjectConfig;
 import  org.eclipse.xtext.xbase.file.RuntimeWorkspaceConfigProvider;
 import  org.eclipse.xtext.xbase.file.WorkspaceConfig;
 import  org.eclipse.xtext.xbase.lib.IterableExtensions;
 import  org.eclipse.xtext.xbase.lib.Pair;
 import  org.junit.Assert;
 
 import  com.google.inject.Inject;
 import  com.google.inject.Provider;

A utility class for testing Xtext languages that compile to Java code. It's designed to be used as an injected extension in unit tests written in Xtend. Example:

Author(s):
Sven Efftinge
Since:
2.7
RunWith:
XtextRunner)
InjectWith:
MyLanguageInjectorProvider) class CompilerTest {
Rule:
@Inject public TemporaryFolder temporaryFolder
Inject:
extension CompilationTestHelper
Test:
def void myTest() { ''' // DSL code Foo bla '''.assertCompilesTo(''' class Foo { String bla } ''' } }
Noextend:
This class is not intended to be subclassed by clients.
 
 public class CompilationTestHelper {
 	
 	public final static String PROJECT_NAME = "myProject";
 	
 	@Inject private TemporaryFolder temporaryFolder;
 	
 	@Inject private OnTheFlyJavaCompiler javaCompiler;
 	
 	@Inject private Provider<XtextResourceSet> resourceSetProvider;
 	
 	@Inject private FileExtensionProvider extensionProvider;
 
 	@Inject private IOutputConfigurationProvider outputConfigurationProvider;
 	
 	@Inject private Provider<ResultresultProvider;
 
 	private RuntimeWorkspaceConfigProvider configProvider;
 
 	@Inject
	private void setWorkspaceConfig(RuntimeWorkspaceConfigProvider configProvider) {
		this. = configProvider;
	}

creates a fresh temp directory and sets it as the workspace root.
	public void configureFreshWorkspace() {
		File tempDir = createFreshTempDir();
		WorkspaceConfig config = new WorkspaceConfig(tempDir.getAbsolutePath());
		ProjectConfig projectConfig = new ProjectConfig();
		projectConfig.addSourceFolderMapping("src""src-gen");
		config.addProjectConfig(projectConfig);
		.setWorkspaceConfig(config);
	}
	protected String getSourceFolderPath() {
		return "/"++"/src";
	}
	protected File createFreshTempDir() {
		try {
			return .newFolder();
catch (IOException e) {
			throw new AssertionError(e);
		}
	}

Add the class path entries of the given classes to the java compiler's class path.
	public void setJavaCompilerClassPath(Class<?> ...classes) {
		for (Class<?> clazz : classes) {
		}
	}

Asserts that the expected code is generated for the given source. Assumes that

Parameters:
source some valid source code written in the language under test
expected the expected Java source code.
Throws:
IOException if the resource loading fails
	public void assertCompilesTo(CharSequence sourcefinal CharSequence expectedthrows IOException {
		final boolean[] called = {false};
		compile(sourcenew IAcceptor<CompilationTestHelper.Result>() {
			public void accept(Result r) {
				Assert.assertEquals(expected.toString(), r.getSingleGeneratedCode());
				called[0] = true;
			}
		});
		Assert.assertTrue("Nothing was generated but the expectation was :\n"+expectedcalled[0]);
	}

Parses, validates and compiles the given source. Calls the given acceptor for each resource which is generated from the source.

Parameters:
source some code written in the language under test.
acceptor gets called once for each file generated in IGenerator
Throws:
IOException if the resource loading fails
	@SuppressWarnings("unchecked")
	public void compile(CharSequence source, IAcceptor<Resultacceptorthrows IOException {
		String fileName = "MyFile."+.getPrimaryFileExtension();
		compile(resourceSet(new Pair<StringCharSequence>(fileNamesource)), acceptor);
	}

Parses, validates and compiles the given source. Calls the given acceptor for each resource which is generated from the source.

Parameters:
resourceSet - the ResourceSet to use
acceptor gets called once for each file generated in IGenerator
	public void compile(final ResourceSet resourceSet, IAcceptor<Resultacceptor) {
		try {
			List<Resource> resourcesToCheck = newArrayList(resourceSet.getResources());
			Result result = .get();
			result.setResources(resourcesToCheck);
			result.setResourceSet(resourceSet);
			result.doGenerate();
			acceptor.accept(result);
catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	protected Iterable<? extends OutputConfiguration> getOutputConfigurations() {
		return .getOutputConfigurations();
	}

creates a fresh resource set with the given resources

Parameters:
resources - pairs of file names and their contents
Returns:
a ResourceSet, containing the given resources.
Throws:
IOException if the resource loading fails
	public ResourceSet resourceSet(Pair<String,? extends CharSequence> ...resources ) throws IOException {
		XtextResourceSet result = .get();
		for (Pair<String, ? extends CharSequenceentry : 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?");
			resource.load(newHashMap());
		}
		return result;
	}

Physically copies the given files to the currently used worksapce root (a temporary folder).

Parameters:
workspacefilePath the workspace relative path
contents the file contents
	public URI copyToWorkspace(String workspacefilePathCharSequence contents) {
		File workspaceRoot = new File(this..getWorkspaceConfig().getAbsoluteFileSystemPath());
		File fullPath = new File(workspaceRoot.getAbsolutePath()+"/"+workspacefilePath);
		if (fullPath.exists()) {
			fullPath.delete();
else {
			mkDir(fullPath.getParentFile());
		}
		URI uri = URI.createFileURI(fullPath.getAbsolutePath());
		Files.writeStringIntoFile(uri.toFileString(), contents.toString());
		return uri;
	}
	private void mkDir(File file) {
		if (!file.getParentFile().exists()) {
		}
		if (!file.exists()) {
			file.mkdir();
		}
	}

same as resourceSet(Pair...) but without actually loading the created resources.
	public ResourceSet unLoadedResourceSet(Pair<String,? extends CharSequence> ...resources ) throws IOException {
		XtextResourceSet result = .get();
		for (Pair<String, ? extends CharSequenceentry : 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;
	}

A result contains information about various aspects of a compiled piece of code.

Noextend:
This class is not intended to be subclassed by clients.
Noinstantiate:
This class is not intended to be instantiated by clients.
	public static class Result {
		@Inject private IResourceServiceProvider.Registry serviceRegistry;
		private ResourceSet resourceSet;
		private List<Resource> sources;
		private Map<String,OutputConfiguration> outputConfigurations;
		protected void setResourceSet(ResourceSet resourceSet) {
			this. = resourceSet;
		}
		protected void setResources(List<Resource> sources) {
			this. = sources;
		}
		protected void setJavaCompiler(OnTheFlyJavaCompiler javaCompiler) {
			this. = javaCompiler;
		}
		protected void setOutputConfigurations(Iterable<? extends OutputConfiguration> outputConfiguration) {
			for (OutputConfiguration conf : outputConfiguration) {
				.put(conf.getName(), conf);
			}
		}
		private ResourceDescriptionsData index;
		private List<Issue> allErrorsAndWarnings;

Ensures validation has happened and returns any errors and warnings

Returns:
errors and warnings contained in the currently processed sources
		public List<Issue> getErrorsAndWarnings() {
		}

Ensures compilation has happened and returns any generated and compiled Java classes.

Returns:
the compiled Java classes
		}

Ensures compilation has happened and returns the class loader including compiled classes.

Returns:
the class loader after the compilation happend
			return ;
		}

Ensures generation happened and returns a map of the generated Java source files.

Returns:
a map of the generated Java source files, where the key is the qualified class name and the value the generated Java code.
		}

convenience method. Same as getGeneratedCode().get(typeName)
		public String getGeneratedCode(String typeName) {
			return getGeneratedCode().get(typeName);
		}

Convenience method for the common case, that only one file is generated.
			if (.getTextFiles().size() == 1)
			String separator = System.getProperty("line.separator");
			if (separator == null)
				separator = "\n";
			Collections.sort(filesnew Comparator<GeneratedFile>() {
				public int compare(GeneratedFile o1,
					return o1.getPath().toString().compareTo(o2.getPath().toString());
				}
			});
			StringBuilder result = new StringBuilder("MULTIPLE FILES WERE GENERATED"+separator+separator);
			int i = 1;
			for (GeneratedFile filefiles) {
				result.append("File "+i+" : "+file.getPath().toString()+separator+separator);
				result.append(file.getContents()).append(separator);
				i++;
			}
			return result.toString();
		}

Returns:
the resource set used in this compilation process
		public ResourceSet getResourceSet() {
			return ;
		}

Convenience method for single generated Java classes
		public Class<?> getCompiledClass() {
			return IterableExtensions.head(getCompiledClasses().values());
		}

Convenience method for single generated Java classes
		public Class<?> getCompiledClass(String className) {
			return getCompiledClasses().get(className);
		}

Returns:
all generated resources. the key is the file path and the value denotes the generated text.
				result.put(f.getPath().toString(), f.getContents());
			}
			return result;
		}
		protected void doIndex() {
			if ( == null) {
				// indexing
				List<IResourceDescription> descriptions = newArrayList();
				for (Resource resource : ) {
					IResourceServiceProvider serviceProvider = .getResourceServiceProvider(resource.getURI());
					IResourceDescription description = serviceProvider.getResourceDescriptionManager().getResourceDescription(resource);
					descriptions.add(description);
				}
				 = new ResourceDescriptionsData(descriptions);
				ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData();
			}
		}
		protected void doLinking() {
			for (Resource resource : ) {
				EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl);
			}
		}
		protected void doValidation() {
			if ( == null) {
				// validation
				for (Resource resource : ) {
					if (resource instanceof XtextResource) {
						XtextResource xtextResource = (XtextResource) resource;
						List<Issue> issues = xtextResource.getResourceServiceProvider().getResourceValidator().validate(xtextResource, CheckMode.ALL, CancelIndicator.NullImpl);
						for (Issue issue : issues) {
						}
					}
				}
			}
		}
		protected void doGenerate() {
			if ( == null) {
				.setOutputConfigurations();
				for (Resource resource : ) {
					if (resource instanceof XtextResource) {
						XtextResource xtextResource = (XtextResource) resource;
						IGenerator generator = xtextResource.getResourceServiceProvider().get(IGenerator.class);
						if (generator != null) {
							generator.doGenerate(xtextResource);
						}
					}
				}
				for (final GeneratedFile e : .getTextFiles()) {
					if (e.getJavaClassName() != null) {
					}
				}
			}
		}
		protected void doCompile() {
			if ( == null || ==null) {
				try {
					org.eclipse.xtext.util.Pair<ClassLoaderMap<StringClass<?>>> compilationResult = .internalCompileToClasses(getGeneratedCode());
					this. = compilationResult.getFirst();
					this. = compilationResult.getSecond();
catch (IllegalArgumentException e) {
					throw new AssertionError(e);
				}
			}
		}
	}
New to GrepCode? Check out our FAQ X