Last active
June 29, 2021 08:00
-
-
Save acherm/bf7896a81d8db2c3726e82e8d4d921ec to your computer and use it in GitHub Desktop.
Standalone solution for loading a model out of a String using Xtext (instead of ParserHelper that depends on Junit/@test)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: