Source

protocol-example / makejava.py

Full commit
"""
Templates for the generation of Java message packing code 
"""
import string
arg_tpl = string.Template("""${type} ${argname}""")
write_tpl = string.Template("""        daos.write${wtype}(${argname});""")
packer_tpl = string.Template("""
public static final byte[] pack${name}(${args}) {
    try
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final DataOutputStream daos = new DataOutputStream(baos);
        daos.writeByte(${type});
${writers}
        final byte[] data = baos.toByteArray();
        baos.close();
        daos.close();
        return data;
    } catch (Exception e) {
        e.printStackTrace();
    }    
    return null;
}
""")

protocol_tpl = string.Template("""

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

public class Protocol${name} {
    public static String VERSION = "${version}";
    ${methods}
}
""")

def mkjava(*messages):
    """Create java code for packing the given messages
    into byte arrays ready to send over the wire"""
    out = []
    for message in messages:
        args = []
        writers = []
        for token in message.tokens:
            jtype = token.javaname[0]
            args.append(arg_tpl.substitute(type=token.javaname, argname=token.name))
            if jtype == "String":
                wtype = "UTF"
            else:
                wtype = token.javaname.capitalize()
            writers.append(write_tpl.substitute(wtype=wtype, argname=token.name))
        
        out.append(packer_tpl.substitute(args=",".join(args), 
                                        writers="\n".join(writers), 
                                        type=message.type,
                                        name=message.name.capitalize()))
    return("\n\n".join(out))

def javaprotocol(protocol):
    name = str(protocol.version).replace('.', '')
    return 'Protocol' + name, protocol_tpl.substitute(name=name,
                            version=protocol.version,
                            methods=mkjava(*protocol.messages()))