Skip to main content

Greenbox: Consuming Metamodel as XML

Posted by edgars on July 13, 2006 at 11:37 AM PDT

As Alexandre Gomes told on JavaOne2006 "Greenbox is a lot of ideas", besides ideas, it have a lot of very easy instruments to generate source really easy.


Creating a Metamoldel serializer for XML

To do that is quite easy, you have a interface available since 2002 on framework, its name is IXmlMetamodel. Then I did an implementation using XStream tool, which you can see in the following code:

public class MetamodelMarshaller implements IXmlMetamodel {
protected XStream xml;
private static MetamodelMarshaller me;
private MetamodelMarshaller() {
// setting the alias for classes and attributes
xml = new XStream();
xml.alias("class", net.java.dev.greenbox.base.Clazz.class);
xml.alias("attribute", net.java.dev.greenbox.base.Attribute.class);
xml.alias("method", net.java.dev.greenbox.base.Method.class);
xml.aliasField("package", net.java.dev.greenbox.base.Clazz.class,"packageName");
xml.aliasField("name", net.java.dev.greenbox.base.Clazz.class,"className");
}
public static MetamodelMarshaller getInstance() {

if (null == me) {

me = new MetamodelMarshaller();
}
return me;
}

public String getMetamodelAsXml(Object objeto) {
return xml.toXML(objeto);
}

public Object loadMetamodel(String xmlString) {
return xml.fromXML(xmlString);
}

}

Now, we will build a simple main method on Java Class to use it and generate a ValueObject pattern:

public static void main(String[] args) {
  StringBuffer xml = loadXMLFromFile();
  Clazz clazz = (Clazz) MetamodelMarshaller.getInstance ().loadMetamodel(xml.toString());
  clazz.setMethods(decorateMethods(clazz));
  GreenboxContext  ctx = new GreenboxContext();
  ctx.declareVariable("class",clazz);
  try {
   System.out.println(ClassGeneratorBase.getInstance().generateSourceByTemplateName(clazz,"vo",ctx));
  } catch (Exception e) {
    e.printStackTrace();
}

This will print a complete Java Value Object pattern implementation source.


Look that we have some errors on source, this I know, is just to call your atention to GreenboxContext usage, when you declare it on the object ctx, this will be generated in output too.

If you want this example, feel you free to send an email to edgarsilva (nospam) gmail.com

cya