Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Standalone solution for loading a model out of a String using Xtext (instead of ParserHelper that depends on Junit/@test)
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.UUID;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.xtext.example.mydsl.MmlStandaloneSetup;
import org.xtext.example.mydsl.mml.MMLModel;
public class MMLLoader {
public static void main(String[] args) throws IOException {
/*
* example of MML file
*/
String content = "datainput \"foo15.csv\"\n"
+ "mlframework scikit-learn\n"
+ "algorithm DT\n"
+ "TrainingTest { pourcentageTraining 70 }\n"
+ "recall\n"
+ "";
MMLModel mml = new MMLLoader().loadModel(content);
// validaing the POC (we can traverse the model)
System.err.println("resource" + mml);
System.err.println(mml.getInput() + " " + mml.getValidation());
}
public MMLModel loadModel(String content) {
try {
// first write the content into an MML file
File temp = File.createTempFile("mmlfile" + UUID.randomUUID(), ".mml");
URI uri = URI.createFileURI(temp.getAbsolutePath());
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
bw.write(content);
bw.close();
// second load the resource
MmlStandaloneSetup.doSetup();
Resource res = new ResourceSetImpl().getResource(uri, true);
MMLModel mml = (MMLModel) res.getContents().get(0);
return mml;
}
catch (IOException e) {
System.err.println("Error loading MML model");
return null ;
}
}
}
@acherm

This comment has been minimized.

Copy link
Owner Author

acherm commented Mar 8, 2019

ParserHelper is a nice solution, but depends on @RunWith(XtextRunner)
So outside @Test methods, you cannot use it since dependency injection does not apply.

A workaround is to manually resolve dependency injection (as above).
It is also the solution I am usually relying on as part of the MDE/DSL/SPL course at University of Rennes 1: https://github.com/acherm/teaching-MDE-IL1819/blob/master/VideoGenTransformer/src/VideoGenHelper.xtend
Another solution is to edit .mwe2 file and generate a "Main" class:

language = StandardLanguage {
			name = "org.xtext.example.mydsl.Mml"
			fileExtensions = "mml"
...			
			generator = {
		        generateJavaMain = true 
		    }			
			
		} 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.