I am working on a project that will have several Java classes that are very similar to each other, and that I would like to generate from XML files. What I would like to be able to do is change the Eclipse build process to do something like this:
- Compile the code generator
- Run the code generator, converting the XML to Java
- Compile the rest of the project
I could do this all manually but I would prefer to be able to have Eclipse do it all for me.
Example
I want to be able to take a source XML file that looks like this:
<command-list>
<command name="DATE" />
<command name="GROUP">
<capability "READER" />
<argument "groupname" />
</command>
<command name="ARTICLE">
<capability "READER" />
<argument "message-id" optional="true" />
</command>
</command-list>
and have it give me something similar to the following (in separate files as appropriate):
public class Date extends Command {
public ResponseCode execute() {
Server srv = getServer();
srv.send("DATE");
return srv.getResponse();
}
}
public class Group extends Command {
public ResponseCode execute() {
Server srv = getServer();
if (srv.hasCapability(Capabilities.READER) == false) {
Log.debug("Attempting non-available capability: READER");
}
String groupname = getArgument("groupname");
if (groupname == null) {
throw new InvalidArgumentException("Require groupname");
}
String command = "GROUP";
if (groupname != null) command += " " + groupname;
srv.send(command);
return srv.getResponse();
}
}
public class Article extends Command {
public ResponseCode execute() {
Server srv = getServer();
if (srv.hasCapability(Capabilities.READER) == false) {
Log.debug("Attempting non-available capability: READER");
}
String messageId = getArgument("messageId");
String command = "ARTICLE";
if (messageId != null) command += " " + messageId;
srv.send(command);
return srv.getResponse();
}
}
This is exactly what the JET component in the Model to Text (M2T) project was made for. In fact, you can even create the project, .classpath and any other files you need with JET.
Jet templates are as follows. Note that these templates must be named exactly as shown.
/templates/main.jet
/templates/classpath.jet
/templates/project.jet
/templates/class.jet
and using this model:
gives a complete java project named com.lacqui.commands containing three java files:
and this: