Skip to main content



      Home
Home » Modeling » EMF » Issue Generating Java Code Programmatically from Ecore Model Using Gen Model(Issue Generating Java Code Programmatically from Ecore Model Using Gen Model)
Issue Generating Java Code Programmatically from Ecore Model Using Gen Model [message #1867392] Mon, 24 June 2024 12:48 Go to next message
Eclipse UserFriend
Hello,

I have written the following code to programmatically create a GenModel and generate Java code from an Ecore model. While the code successfully generates the GenModel file (e.g., Family.genmodel), it does not generate the Java code as expected.

Could someone help identify what might be missing or incorrect in my code?

Any help or guidance would be greatly appreciated!

Here is the code:
 
package com.example.codegen.codeGenerator;

import org.eclipse.emf.codegen.ecore.generator.Generator;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.eclipse.emf.codegen.ecore.genmodel.GenModelFactory;
import org.eclipse.emf.codegen.ecore.genmodel.GenModelPackage;
import org.eclipse.emf.codegen.ecore.genmodel.generator.GenBaseGeneratorAdapter;
import org.eclipse.emf.codegen.ecore.genmodel.generator.GenModelGeneratorAdapterFactory;
import org.eclipse.emf.common.util.BasicMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceFactoryImpl;

import java.io.File;
import java.io.IOException;
import java.util.Collections;


public class CodeGenerator {

    public static void main(String[] args) {

        String ecorePath = "/Users/adielt./Documents/demo/src/main/resources/model/Family.ecore";
        String genModelPath = "/Users/adielt./Documents/demo/src/main/resources/codegen/Family.genmodel";
        String outputDirectory = "/Users/adielt./Documents/demo/src/main/java";
        String modelName = "Family";

        // Verify and load the .ecore file
        ResourceSet resourceSet = createResourceSet();
        Resource ecoreResource = loadEcoreModel(resourceSet, ecorePath);
        if (ecoreResource == null) return;

        // Create and configure the GenModel
        GenModel genModel = createGenModel(ecoreResource, outputDirectory, modelName);
        saveGenModel(resourceSet, genModel, genModelPath);

        // Load the saved GenModel
        GenModel loadedGenModel = loadGenModel(resourceSet, genModelPath);
        if (loadedGenModel == null) return;

        // Generate the code
        generateCode(loadedGenModel, outputDirectory);
    }

    private static ResourceSet createResourceSet() {
        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("genmodel", new XMLResourceFactoryImpl());
        return resourceSet;
    }

    private static Resource loadEcoreModel(ResourceSet resourceSet, String ecorePath) {
        System.out.println("Loading the Ecore file...");
        URI ecoreURI = URI.createFileURI(ecorePath);
        Resource ecoreResource = resourceSet.getResource(ecoreURI, true);
        try {
            ecoreResource.load(null);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        if (ecoreResource.getContents().isEmpty()) {
            System.err.println("Error: The Ecore file does not contain any packages.");
            return null;
        }

        System.out.println("Ecore file loaded successfully.");
        return ecoreResource;
    }

    private static GenModel createGenModel(Resource ecoreResource, String outputDirectory, String modelName) {
        EPackage ePackage = (EPackage) ecoreResource.getContents().get(0);
        GenModel genModel = GenModelFactory.eINSTANCE.createGenModel();
        genModel.initialize(Collections.singleton(ePackage));
        genModel.setModelName(modelName);
        genModel.setModelDirectory(outputDirectory.replace("\\", "/"));
        genModel.setCanGenerate(true);
        genModel.setValidateModel(true);

        System.out.println("GenModel configuration completed.");
        return genModel;
    }

    private static void saveGenModel(ResourceSet resourceSet, GenModel genModel, String genModelPath) {
        URI genModelURI = URI.createFileURI(genModelPath);
        Resource genModelResource = resourceSet.createResource(genModelURI);
        genModelResource.getContents().add(genModel);
        try {
            genModelResource.save(null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("GenModel saved successfully.");
    }

    private static GenModel loadGenModel(ResourceSet resourceSet, String genModelPath) {
        System.out.println("Loading the saved GenModel...");
        URI genModelURI = URI.createFileURI(genModelPath);
        Resource genModelResource = resourceSet.getResource(genModelURI, true);
        try {
            genModelResource.load(null);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        if (genModelResource.getContents().isEmpty()) {
            System.err.println("Error: The saved GenModel does not contain any data.");
            return null;
        }

        System.out.println("Saved GenModel loaded successfully.");
        return (GenModel) genModelResource.getContents().get(0);
    }

    private static void generateCode(GenModel genModel, String outputDirectory) {
        genModel.reconcile();
        genModel.setCanGenerate(true);
        genModel.setValidateModel(true);
        genModel.setForceOverwrite(true);

        Generator generator = new Generator();
        generator.setInput(genModel);
        generator.getAdapterFactoryDescriptorRegistry().addDescriptor(GenModelPackage.eNS_URI, GenModelGeneratorAdapterFactory.DESCRIPTOR);

        // Generate the MODEL_PROJECT_TYPE code
        System.out.println("Starting MODEL_PROJECT_TYPE generation...");
        generator.generate(genModel, GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE, new BasicMonitor.Printing(System.out));
        System.out.println("MODEL_PROJECT_TYPE generation completed.");

        // Verify if the files have been generated
        File generatedDir = new File(outputDirectory);
        File[] generatedFiles = generatedDir.listFiles();
        if (generatedFiles != null && generatedFiles.length > 0) {
            System.out.println("Java code generated successfully in the directory: " + outputDirectory);
            for (File file : generatedFiles) {
                System.out.println("Generated: " + file.getAbsolutePath());
            }
        } else {
            System.err.println("Error: No files generated in the output directory.");
        }
    }

    public static String getFileExtension(String fullName) {
        String fileName = new File(fullName).getName();
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
    }
}

Re: Issue Generating Java Code Programmatically from Ecore Model Using Gen Model [message #1867398 is a reply to message #1867392] Mon, 24 June 2024 17:20 Go to previous messageGo to next message
Eclipse UserFriend
You should really look at what the IDE does and compare what you produce like this versus what's produced doing this in the IDE.
Re: Issue Generating Java Code Programmatically from Ecore Model Using Gen Model [message #1867401 is a reply to message #1867398] Mon, 24 June 2024 17:21 Go to previous messageGo to next message
Eclipse UserFriend
E.g., I don't see anything that sets the GenPackage's base package.
Re: Issue Generating Java Code Programmatically from Ecore Model Using Gen Model [message #1867413 is a reply to message #1867401] Tue, 25 June 2024 03:35 Go to previous messageGo to next message
Eclipse UserFriend
Dear Ed Merks,

First, thank you for your quick reply and your advice on setting the GenPackage's base package.

I have included the following code to set the GenPackage:
private static void setGenPackageBasePackage(GenModel genModel, String basePackage) {
    for (GenPackage genPackage : genModel.getGenPackages()) {
        genPackage.setBasePackage(basePackage);
    }
}


I am using Eclipse IDE and expecting the generated code to be placed in the outputDirectory I have specified.

When I run this code, the only thing generated is the GenModel file. Apart from that, nothing happens, except an output ("MODEL_PROJECT_TYPE generation completed.
Java code generated successfully in the directory:
/Users/adielt./Documents/demo/src/main/java
") in the console. I have also tried to refresh the tool, but still, no Java code is generated.
Re: Issue Generating Java Code Programmatically from Ecore Model Using Gen Model [message #1867416 is a reply to message #1867413] Tue, 25 June 2024 06:00 Go to previous messageGo to next message
Eclipse UserFriend
It would be good to use the debugger to see what it is happening to find perhaps what missing information might be causing it to skip generating things, e.g., a breakpoint in org.eclipse.emf.codegen.ecore.generator.Generator.canGenerate(Object, Object) to see why/when it returns false versus true.
Re: Issue Generating Java Code Programmatically from Ecore Model Using Gen Model [message #1867419 is a reply to message #1867416] Tue, 25 June 2024 06:03 Go to previous messageGo to next message
Eclipse UserFriend
In the editors, it does this, so perhaps that's important too:

editingDomain.getResourceSet().getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap(true));
Re: Issue Generating Java Code Programmatically from Ecore Model Using Gen Model [message #1868205 is a reply to message #1867419] Mon, 15 July 2024 07:42 Go to previous message
Eclipse UserFriend
Sorry for the delayed response. If you still need help, the Eclipse QVTd JUnit tests synthesize *.ecore, *.genmodel, .project, MANIFEST.MF and then use genmodel to synthesize *.java which is compiled and tested. Ensuring that the synthesis uses consistent installed/development/synthesized files requires classpath and ResourceSet configuration care. Ensuring that that the synthesized project is IDE compatible requires everything to be created BEFORE the project is opened; there are perhaps IDE bugs in regards to a failure to refresh if you create files 'late'.

The root of the tests is https://git.eclipse.org/c/mmt/org.eclipse.qvtd.git/tree/tests/org.eclipse.qvtd.xtext.qvtrelation.tests/src/org/eclipse/qvtd/xtext/qvtrelation/tests/QVTrCompilerTests.java
Previous Topic:Generating EMOF from XMI vs Ecore
Next Topic:[CDO] commit in EmbeddedRepositoryExample
Goto Forum:
  


Current Time: Sun Aug 31 07:57:25 EDT 2025

Powered by FUDForum. Page generated in 0.16502 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top