Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • anders_blomdell/labcomm
  • klaren/labcomm
  • tommyo/labcomm
  • erikj/labcomm
  • sven/labcomm
5 results
Show changes
Showing
with 2165 additions and 0 deletions
#dummy script to test the static part
# run labcomm compilation
java -jar ../../compiler/labcomm2014_compiler.jar --java=gen --javapackage=gen simple.lc
# compile example programs
javac -cp .:gen:../../lib/java/labcomm2014.jar test/StaticEncoder.java
javac -cp .:gen:../../lib/java/labcomm2014.jar test/StaticDecoder.java
# run example programs
java -cp .:gen:../../lib/java//labcomm2014.jar test.StaticEncoder encoded_data
java -cp .:gen:../../lib/java//labcomm2014.jar test.StaticDecoder encoded_data
#dummy script to test the on-the-fly compilation
javac -cp .:../../compiler/labcomm2014_compiler.jar:../../lib/java/labcomm2014.jar:../../lib/tools/beaver.jar:../../lib/tools/beaver-rt.jar:../../lib/tools/jastadd2.jar:../../lib/tools/JFlex.jar:../../lib/tools/proj.jar test/TestLabcommGen.java
javac test/HandlerContext.java
java -cp .:../../compiler/labcomm2014_compiler.jar:../../lib/java/labcomm2014.jar:../../lib/tools/beaver.jar:../../lib/tools/beaver-rt.jar:../../lib/tools/jastadd2.jar:../../lib/tools/JFlex.jar:../../lib/tools/proj.jar test.TestLabcommGen simple.lc handlers2.txt encoded_data
package test;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.CharBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import se.lth.control.labcomm2014.Decoder;
import se.lth.control.labcomm2014.DecoderChannel;
import se.lth.control.labcomm2014.Encoder;
import se.lth.control.labcomm2014.EncoderChannel;
import se.lth.control.labcomm2014.compiler.LabCommParser;
import se.lth.control.labcomm2014.compiler.LabCommScanner;
import se.lth.control.labcomm2014.compiler.Program;
import beaver.Parser.Exception;
public class DynamicPart {
private static final String TYPE_NAME_FOO = "foo_t";
private static final String SAMPLE_NAME_FOO = "foo";
private static final String SAMPLE_NAME_BAR = "bar";
static final String handlerClassName= "HandlerContainer";
static class HandlerSrc {
private String sampleName;
private String param;
private String body;
private final String proto = "public void handle_";
public HandlerSrc(String sampleName, String param, String body) {
this.sampleName = sampleName;
this.param = param;
this.body = body;
}
public String getSrc() {
String res = proto+sampleName+"("+param+")"+body;
return res;
}
}
public void doTest(InRAMCompiler irc, String iFile, String oFile) {
HandlerContext ctxt = new HandlerContext();
System.out.println("*** reading file "+iFile);
decodeTest(irc, ctxt, iFile, SAMPLE_NAME_FOO, SAMPLE_NAME_BAR);
System.out.println("*** writing "+oFile);
encodeTest(irc, ctxt, oFile);
}
/**
* @param args
*/
public static void main(String[] args) {
/* input data: */
String labcommStr = readLabcommDecl(args[0]);
String srcStr = readHandlerDecl(args[1]);
/*Map<sample name, handler code>*/
HashMap <String, String> handlers = new HashMap<String, String>();
generateHandlers(srcStr, handlers);
// System.out.println("*** Generated handler source:");
handlers.keySet();
// for (String n : handlers.keySet()) {
// System.out.println(n+":");
// System.out.println(handlers.get(n));
// }
InRAMCompiler irc = generateCode(labcommStr, handlers);
if(irc != null) {
String iFile = args[2];
String oFile = args[3];
new DynamicPart().doTest(irc, iFile, oFile);
}
}
public static void generateHandlers(String srcStr, HashMap<String,String> handlers) {
int pos = 0;
while(pos < srcStr.length()) {
int nameEnd = srcStr.indexOf(':', pos);
if(nameEnd <0) break;
String name = srcStr.substring(pos,nameEnd);
pos=nameEnd+1;
String par = "";
final String handler_decl = "handler(";
if(srcStr.startsWith(handler_decl, pos)) {
int endPar = srcStr.indexOf(')', pos);
par = srcStr.substring(pos+handler_decl.length(), endPar);
pos = endPar+1;
} else {
System.out.println("expeced handler decl:\n"+srcStr.substring(pos));
}
int bodyEnd = srcStr.indexOf("}###", pos); // HERE BE DRAGONS! a bit brittle
String body = srcStr.substring(pos, bodyEnd+1);
pos = bodyEnd+5;
HandlerSrc s = new HandlerSrc(name, par, body);
final String genSrc = s.getSrc();
handlers.put(name,genSrc);
}
}
public static String readHandlerDecl(String decl) {
FileReader fr;
int len=0;;
CharBuffer buf = CharBuffer.allocate(1024);
try {
fr = new FileReader(decl);
len = fr.read(buf);
buf.rewind();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
String srcStr = buf.toString().substring(0, len);
return srcStr;
}
private static String readLabcommDecl(String lcfile) {
FileReader fr;
int len=0;;
CharBuffer buf = CharBuffer.allocate(1024);
try {
fr = new FileReader(lcfile);
len = fr.read(buf);
// buf.append((char) 0x04);
buf.rewind();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
String labcommStr = buf.toString().substring(0, len-1);
return labcommStr;
}
public static InRAMCompiler generateCode(String lcDecl, HashMap<String, String> handlers) {
Specification ast = null;
InputStream in = new ByteArrayInputStream(lcDecl.getBytes());
LabCommScanner scanner = new LabCommScanner(in);
LabCommParser parser = new LabCommParser();
Collection errors = new LinkedList();
InRAMCompiler irc = null;
try {
Specification p = (Specification)parser.parse(scanner);
p.errorCheck(errors);
if (errors.isEmpty()) {
ast = p;
} else {
System.out.println("*** Errors:");
for (Iterator iter = errors.iterator(); iter.hasNext(); ) {
String s = (String)iter.next();
System.out.println(s);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (ast != null) {
irc = handleAst(ast, handlers);
} else {
System.err.println("compilation failed");
}
return irc;
}
/** generate labcomm code and compile handlers
*
* @param lcAST - the AST of the labcomm declaration
* @param handlers - a map <name, source> of handlers for the types in ast
* @return an InRAMCompiler object containing the generated clases
*/
private static InRAMCompiler handleAst(Specification lcAST, HashMap<String, String> handlers) {
Map<String, String> genCode = new HashMap<String, String>();
try {
lcAST.J_gen(genCode, "labcomm.generated", 2014);
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("Generated labcomm code:");
InRAMCompiler irc = new InRAMCompilerJavax("labcomm.generated", TestLabcommGen.class.getClassLoader());
StringBuilder handlerClass = new StringBuilder();
StringBuilder handlerMethods = new StringBuilder();
handlerClass.append("package labcomm.generated;\n");
handlerClass.append("public class "+handlerClassName+" implements ");
String handlerAttributes = "Object context;\n";
String handlerConstr = "public "+handlerClassName+"(){super();}\n";
String handlerConstrCtxt = "public "+handlerClassName+"(Object context){ this.context=context;}\n";
Iterator<String> i = genCode.keySet().iterator();
try {
while(i.hasNext()){
final String sampleName = i.next();
final String src = genCode.get(sampleName);
String handleM = handlers.get(sampleName);
if(handleM != null) {
handlerClass.append(sampleName+".Handler");
if(i.hasNext()) {
handlerClass.append(", ");
}
handlerMethods.append(handleM);
handlerMethods.append("\n");
}
// System.out.println("***"+sampleName+"\n"+src);
irc.compile(sampleName, src); // while iterating, compile the labcomm generated code
}
handlerClass.append("{\n");
handlerClass.append(handlerAttributes);
handlerClass.append(handlerConstr);
handlerClass.append(handlerConstrCtxt);
handlerClass.append(handlerMethods.toString());
handlerClass.append("}\n");
System.out.println("-------------------------------------");
final String handlerSrc = handlerClass.toString();
System.out.println(handlerSrc);
irc.compile(handlerClassName, handlerSrc); // compile the generated handler class
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println("================================");
return irc;
}
/** test method
*/
private void decodeTest(InRAMCompiler irc, HandlerContext ctxt, String tmpFile, String... sampleNames) {
try {
FileInputStream in = new FileInputStream(tmpFile);
DecoderChannel dec = new DecoderChannel(in);
Class handlerClass = irc.load(handlerClassName);
Constructor hcc = handlerClass.getDeclaredConstructor(Object.class);
Object handler = hcc.newInstance(ctxt);
for (String sampleName : sampleNames) {
System.out.println("registering handler for "+sampleName);
Class sampleClass = irc.load(sampleName);
Class handlerInterface = irc.load(sampleName+"$Handler");
Method reg = sampleClass.getDeclaredMethod("register", Decoder.class, handlerInterface);
reg.invoke(sampleClass, dec, handler);
}
try{
System.out.println("*** decoding:");
dec.run();
} catch(EOFException e) {
System.out.println("*** reached EOF ***");
}
in.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
/** test encoding
*/
private void encodeTest(InRAMCompiler irc, HandlerContext ctxt, String tmpFile) {
try {
Class fc = irc.load(SAMPLE_NAME_FOO);
Class bc = irc.load(SAMPLE_NAME_BAR);
Class ft; // hack for both cases with and w/o typedef
try {
ft = irc.load(TYPE_NAME_FOO);
} catch (ClassNotFoundException e) {
System.out.println("** encodeTest: defaulting to sample==type");
ft = fc;
}
/* create sample class and instance objects */
Object fv = ft.newInstance();
Field x = ft.getField("x");
Field y = ft.getField("y");
Field z = ft.getField("z");
x.setInt(fv, ctxt.x);
y.setInt(fv, ctxt.y);
z.setInt(fv, ctxt.z);
FileOutputStream out = new FileOutputStream(tmpFile);
EncoderChannel enc = new EncoderChannel(out);
/* register and send foo */
Method regFoo = fc.getDeclaredMethod("register", Encoder.class);
regFoo.invoke(fc, enc);
Method doEncodeFoo = fc.getDeclaredMethod("encode", Encoder.class, ft);
doEncodeFoo.invoke(fc, enc, fv);
/* register and send bar (NB! uses primitive type int) */
Method regBar = bc.getDeclaredMethod("register", Encoder.class);
regBar.invoke(bc, enc);
Method doEncodeBar = bc.getDeclaredMethod("encode", Encoder.class, Integer.TYPE);
doEncodeBar.invoke(bc, enc, ctxt.bar);
out.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
/** dummy test creating instances of sample and handler, and calling handle*/
private static void dummyTest(InRAMCompiler irc) {
try {
Class hc = irc.load(handlerClassName);
Constructor hcc = hc.getDeclaredConstructor(Object.class);
// Object h = hc.newInstance();
Object h = hcc.newInstance(new HandlerContext());
Class ft = irc.load(TYPE_NAME_FOO);
Object f = ft.newInstance();
Field x = ft.getDeclaredField("x");
Field y = ft.getDeclaredField("y");
Field z = ft.getDeclaredField("z");
x.setInt(f, 10);
y.setInt(f, 11);
z.setInt(f, 12);
Method m;
try {
m = hc.getDeclaredMethod("handle_"+SAMPLE_NAME_FOO, ft);
m.invoke(h, f);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package test;
public class HandlerContext {
public final String str="HandlerContext";
public int x, y, z, bar;
}
package test;
import java.lang.reflect.InvocationTargetException;
public interface InRAMCompiler {
/**
* Delete a class from the RAM storage, and destroy its ClassLoader, to
* allow it to be unloaded (and later replaced).
* @param className - the class to be unloaded. pkgName (as given to the constructor) is added to the name.
*/
public void deleteClass(String className);
public void compile(String name, String srcStr)
throws ClassNotFoundException, IllegalArgumentException,
SecurityException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException;
/**
* Load className.class out of cache
* @param className
* @return the class object
* @throws ClassNotFoundException
*/
public Class<?> load(String className) throws ClassNotFoundException;
}
package test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
/**
* On-the-fly, incremental, all-in-RAM compilation (no disk files used).
* Based on an example by Piotr Kobzda at
* http://groups.google.com/group/pl.co...7010d1cce043d0
*
* Each class is compiled in its own compilation unit, and newer
* classes can call or reference older classes.
*
* Written and debugged against Java 1.6.0 Beta 2 build 86, in Eclipse
* 3.2 Jim Goodwin July 25 2006
*
* Adapted to jdk 1.6.0_11 and adapted with more class loader delegation for
* working with custom class loaders (e.g., OSGi) by Sven Robertz
*/
public class InRAMCompilerJavax implements InRAMCompiler {
private boolean debug;
// Source for both test classes. They go in package
// "just.generated"
private ClassLoader loader;
private DiagnosticCollector<JavaFileObject> diagnostics;
private JavaCompiler compiler;
private RAMFileManager jfm;
private Map<String, JavaFileObject> output;
private ClassLoader providedClassLoader;
private String pkgName; //package for the generated classes
// private String getClassPath()
// {
// ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// URL[] urls = ((URLClassLoader) classLoader).getURLs();
// StringBuilder buf = new StringBuilder(1000);
// buf.append(".");
// String separator = System.getProperty("path.separator");
// for (URL url : urls) {
// buf.append(separator).append(url.getFile());
// }
// return buf.toString();
// }
public static void main(String[] args) throws Exception {
InRAMCompiler irc = new InRAMCompilerJavax("just.generated", null);
final String SRC_HelloIf = "package just.generated;\n"
+ "public class HelloIf {\n"
+ " public static class Foo {\n"
+ " public interface Bar {\n"
+ " public String foo();\n"
+ " }\n"
+ " }\n"
+ "}\n";
final String SRC_Hello1 = "package just.generated;\n"
+ "public class Hello1 {\n"
+ " public static void main(String... args) {\n"
+ " System.out.println(new Hello2()); \n" + "}}\n";
final String SRC_Hello2 = "package just.generated;\n"
+ "public class Hello2 implements HelloIf.Foo.Bar{\n"
+ " public String foo() { return \"foo\";}\n"
+ " public String toString() {\n"
+ " return \"hello!\"+foo();\n}}\n";
irc.compile("HelloIf", SRC_HelloIf);
irc.compile("Hello2", SRC_Hello2);
irc.compile("Hello1", SRC_Hello1);
Class<?> c = irc.load("Hello1");
// Run the 'main' method of the Hello class.
c.getMethod("main", String[].class).invoke(null,
new Object[] { new String[0] });
}
/**
*
* @param pkgName - The package for the generated classes. The source code must only contain classes in this package.
* @param cl - An optional (i.e., may be null) classloader that is also searched
*/
public InRAMCompilerJavax(String pkgName, ClassLoader cl) {
this.pkgName = pkgName;
providedClassLoader = cl;
compiler = ToolProvider.getSystemJavaCompiler();
// A map of from class names to the RAMJavaFileObject that holds
// the compiled-code for that class. This is the cache of
// compiled classes.
output = new HashMap<String, JavaFileObject>();
createNewClassLoader(providedClassLoader);
}
/**
*
* @param pkgName - The package for the generated classes. The source code must only contain classes in this package.
* @param cl - An optional (i.e., may be null) classloader that is also searched
*
* @param debug - set to true to turn on debug output
*/
public InRAMCompilerJavax(String pkgName, ClassLoader cl, boolean debug) {
this(pkgName, cl);
this.debug = debug;
}
/* (non-Javadoc)
* @see se.lth.cs.sven.rosettaTest.cc.InRAMCompiler#deleteClass(java.lang.String)
*/
public void deleteClass(String className) {
output.remove(pkgName+"."+className);
// System.out.println("\nstored classes: " + output.keySet());
createNewClassLoader(providedClassLoader);
}
/**
* Create a new class loader, possibly replacing the existing one.
* This method is called by the constructor, and from deleteClass, to
* allow unloading of generated classes.
* @param cl
*/
private void createNewClassLoader(ClassLoader cl) {
// A loader that searches our cache first.
loader = new RAMClassLoader(output, cl);
diagnostics = new DiagnosticCollector<JavaFileObject>();
// Create a JavaFileManager which uses our DiagnosticCollector,
// and creates a new RAMJavaFileObject for the class, and
// registers it in our cache
StandardJavaFileManager sjfm = compiler.getStandardFileManager(diagnostics, null, null);
jfm = new RAMFileManager(sjfm, output, loader);
}
/*
* Help routine to convert a string to a URI.
*/
static URI toURI(String name) {
try {
return new URI(name);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see se.lth.cs.sven.rosettaTest.cc.InRAMCompiler#compile(java.lang.String, java.lang.String)
*/
public void compile(String name, String srcStr) throws ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// TODO Auto-generated method stub
// Create source file objects
SourceJavaFileObject src = new SourceJavaFileObject(name,
srcStr);
// Compile source code. call() causes it to run.
// Compiler options
// String myCP = getClassPath()+":/home/sven/eclipse/workspace_sven_test_3.4/RosettaOSGi-API/bin";
// System.out.println("classpath: "+myCP);
List<String> options = new ArrayList<String>();
// options.add("-classpath");
// options.add(myCP);
// options.add(getClassPath());
CompilationTask task = compiler.getTask(null, jfm,
diagnostics, options, null, Arrays.asList(src));
jfm.isCompiling(true);
if (!task.call()) {
for (Diagnostic<?> dm : diagnostics.getDiagnostics())
System.err.println(dm);
throw new RuntimeException("Compilation of task "+name+" failed");
}
jfm.isCompiling(false);
// Traces the classes now found in the cache
if(debug) {
System.out.println("\nInRAMCompiler: generated classes = " + output.keySet());
}
}
/* (non-Javadoc)
* @see se.lth.cs.sven.rosettaTest.cc.InRAMCompiler#load(java.lang.String)
*/
public Class<?> load(String className) throws ClassNotFoundException {
jfm.isCompiling(false);
Class<?> c = Class.forName(pkgName+"."+className, false,
loader);
return c;
}
/*
* A JavaFileObject class for source code, that just uses a String for
* the source code.
*/
private class SourceJavaFileObject extends SimpleJavaFileObject {
private final String classText;
SourceJavaFileObject(String className, final String classText) {
super(InRAMCompilerJavax.toURI(className + ".java"),
Kind.SOURCE);
this.classText = classText;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
throws IOException, IllegalStateException,
UnsupportedOperationException {
return classText;
}
}
/*
* A JavaFileManager that presents the contents of the cache as a file
* system to the compiler. To do this, it must do four things:
*
* It remembers our special loader and returns it from getClassLoader()
*
* It maintains our cache, adding class "files" to it when the compiler
* calls getJavaFileForOutput
*
* It implements list() to add the classes in our cache to the result
* when the compiler is asking for the classPath. This is the key
trick:
* it is what makes it possible for the second compilation task to
* compile a call to a class from the first task.
*
* It implements inferBinaryName to give the right answer for cached
* classes.
*/
private class RAMFileManager extends
ForwardingJavaFileManager<StandardJavaFileManager> {
private final Map<String, JavaFileObject> output;
private final ClassLoader ldr;
public RAMFileManager(StandardJavaFileManager sjfm,
Map<String, JavaFileObject> output, ClassLoader ldr) {
super(sjfm);
this.output = output;
this.ldr = ldr;
}
public JavaFileObject getJavaFileForOutput(Location location,
String name, Kind kind, FileObject sibling)
throws IOException {
JavaFileObject jfo = new RAMJavaFileObject(name, kind);
output.put(name, jfo);
return jfo;
}
public ClassLoader getClassLoader(JavaFileManager.Location
location) {
return ldr;
}
@Override
public String inferBinaryName(Location loc, JavaFileObject jfo) {
// System.out.println("RAMFileManager.inferBinaryName:"+loc+", "+jfo);
String result;
if (loc == StandardLocation.CLASS_PATH
&& jfo instanceof RAMJavaFileObject)
result = jfo.getName();
else
result = super.inferBinaryName(loc, jfo);
return result;
}
private boolean restrictPackage=true;
public void isCompiling(boolean b) {
restrictPackage = !b;
}
@Override
public Iterable<JavaFileObject> list(Location loc, String pkg,
Set<Kind> kind, boolean recurse) throws IOException {
Iterable<JavaFileObject> result = super.list(loc, pkg, kind,
recurse);
if (loc == StandardLocation.CLASS_PATH
&& (!restrictPackage || pkg.equals("just.generated"))
&& kind.contains(JavaFileObject.Kind.CLASS)) {
ArrayList<JavaFileObject> temp = new ArrayList<JavaFileObject>(
3);
for (JavaFileObject jfo : result)
temp.add(jfo);
for (Entry<String, JavaFileObject> entry : output
.entrySet()) {
temp.add(entry.getValue());
}
result = temp;
} else {
result = super.list(loc, pkg, kind, recurse);
}
return result;
}
}
/**
* A JavaFileObject that uses RAM instead of disk to store the file. It
* gets written to by the compiler, and read from by the loader.
*/
private class RAMJavaFileObject extends SimpleJavaFileObject {
ByteArrayOutputStream baos;
RAMJavaFileObject(String name, Kind kind) {
super(InRAMCompilerJavax.toURI(name), kind);
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
throws IOException, IllegalStateException,
UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public InputStream openInputStream() throws IOException,
IllegalStateException, UnsupportedOperationException {
return new ByteArrayInputStream(baos.toByteArray());
}
@Override
public OutputStream openOutputStream() throws IOException,
IllegalStateException, UnsupportedOperationException {
return baos = new ByteArrayOutputStream();
}
}
/**
* A class loader that loads what's in the cache by preference, and if
* it can't find the class there, loads from the standard parent.
*
* It is important that everything in the demo use the same loader, so
* we pass this to the JavaFileManager as well as calling it directly.
*/
private final class RAMClassLoader extends ClassLoader {
private final Map<String, JavaFileObject> output;
private ClassLoader classLoader;
RAMClassLoader(Map<String, JavaFileObject> output, ClassLoader cl) {
this.output = output;
this.classLoader = cl;
if(debug) {
testGetResources();
}
}
private void testGetResources() {
Package[] ps = getPackages();
for (Package package1 : ps) {
System.out.println(package1.getName());
}
}
@Override
protected Class<?> findClass(String name)
throws ClassNotFoundException {
JavaFileObject jfo = output.get(name);
try {
//XXX This is a hack! Look in "parent" class loader first, to find correct Service instances.
if(classLoader != null) {
if(debug) {
System.out.println("RAMClassLoader.findClass: getResource (package): "+classLoader.getResource("se/lth/cs/sven/rosettaTest"));
System.out.println("RAMClassLoader.findClass: getResource: "+classLoader.getResource("se/lth/cs/sven/rosettaTest/Constraint.class"));
}
try {
Class<?> c = classLoader.loadClass(name);
if(c != null) {
return c;
}
} catch( ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
if (jfo != null) {
byte[] bytes = ((RAMJavaFileObject) jfo).baos.toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
} catch(Exception e) {
e.printStackTrace();
}
return super.findClass(name);
}
}
}
package test;
import gen.foo;
import gen.bar;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import se.lth.control.labcomm2014.DecoderChannel;
public class StaticDecoder implements foo.Handler, bar.Handler
{
DecoderChannel decoder;
public StaticDecoder(InputStream in) throws Exception {
decoder = new DecoderChannel(in);
foo.register(decoder, this);
bar.register(decoder, this);
}
public void run() throws Exception {
try {
System.out.println("Running decoder.");
decoder.run();
} catch (java.io.EOFException e) {
System.out.println("Decoder reached end of file.");
}
}
public void handle_foo(foo d) throws java.io.IOException {
System.out.println("Got foo, x="+d.x+", y="+d.y+", z="+d.z);
}
public void handle_bar(int d) throws java.io.IOException {
System.out.println("Got bar: "+d);
}
public static void main(String[] arg) throws Exception {
FileInputStream fis = new FileInputStream(new File(arg[0]));
StaticDecoder dec = new StaticDecoder(fis);
dec.run();
fis.close();
}
}
package test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import se.lth.control.labcomm2014.EncoderChannel;
import gen.foo;
import gen.bar;
public class StaticEncoder {
EncoderChannel encoder;
public StaticEncoder(OutputStream out)
throws Exception
{
encoder = new EncoderChannel(out);
foo.register(encoder);
bar.register(encoder);
}
public void doEncode() throws java.io.IOException {
foo f = new foo();
f.x = 17;
f.y = 42;
f.z = 37;
int b = 13;
System.out.println("Encoding foo, x="+f.x+", y="+f.y+", z="+f.z);
foo.encode(encoder, f);
System.out.println("Encoding bar: "+b);
bar.encode(encoder, b);
}
public static void main(String[] arg) throws Exception {
FileOutputStream fos = new FileOutputStream(arg[0]);
StaticEncoder enc = new StaticEncoder(fos);
enc.doEncode();
fos.close();
}
}
package test;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.CharBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
public class TestHandlerGen {
static class HandlerSrc {
private String sampleName;
private String param;
private String body;
private final String proto = "public void handle_";
public HandlerSrc(String sampleName, String param, String body) {
this.sampleName = sampleName;
this.param = param;
this.body = body;
}
public String getSrc() {
String res = proto+sampleName+"("+param+")"+body;
return res;
}
}
/**
* @param args
*/
public static void main(String[] args) {
/* input data: */
FileReader fr;
int len=0;;
CharBuffer buf = CharBuffer.allocate(1024);
try {
fr = new FileReader(args[0]);
len = fr.read(buf);
buf.rewind();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
String srcStr = buf.toString().substring(0, len);
/* read declarations */
int pos = 0;
while(pos < srcStr.length()) {
System.out.println("--------");
int nameEnd = srcStr.indexOf(':', pos);
String name = srcStr.substring(pos,nameEnd);
System.out.println("Name="+name);
pos=nameEnd+1;
String par = "";
final String handler_decl = "handler(";
if(srcStr.startsWith(handler_decl, pos)) {
int endPar = srcStr.indexOf(')', pos);
par = srcStr.substring(pos+handler_decl.length(), endPar);
System.out.println("param="+par);
pos = endPar+1;
} else {
System.out.println("expeced handler decl:");
}
int bodyEnd = srcStr.indexOf('}', pos); // HERE BE DRAGONS! too brittle
System.out.println("pos="+pos+", bodyEnd="+bodyEnd);
String body = srcStr.substring(pos, bodyEnd+1);
pos = bodyEnd+2;
System.out.println("body:");
System.out.println(body);
System.out.println("**** generates:");
HandlerSrc s = new HandlerSrc(name, par, body);
System.out.println(s.getSrc());
}
}
}
package test;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.CharBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import se.lth.control.labcomm2014.Decoder;
import se.lth.control.labcomm2014.DecoderChannel;
import se.lth.control.labcomm2014.Encoder;
import se.lth.control.labcomm2014.EncoderChannel;
import AST.Parser;
import AST.Scanner;
import AST.Specification;
import beaver.Parser.Exception;
public class TestCompiler {
private static final String BAR = "bar";
private static final String FOO = "foo";
/**
* @param args
*/
public static void main(String[] args) {
/* input data: */
FileReader fr;
int len=0;;
CharBuffer buf = CharBuffer.allocate(1024);
try {
fr = new FileReader(args[0]);
len = fr.read(buf);
buf.rewind();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
String labcommStr = buf.toString().substring(0, len-1);
HashMap <String, String> handlers = new HashMap<String, String>();
handlers.put(FOO, "public void handle_"+FOO+"("+FOO+" value) {\nSystem.out.println(value.x);\nSystem.out.println(value.y);\nSystem.out.println(value.z);}");
handlers.put(BAR, "public void handle_"+BAR+"(int value) {System.out.println(value);}");
InRAMCompiler irc = generateCode(labcommStr, handlers);
if(irc != null) {
System.out.println("*** Testing instantiation and invocation of Handler ");
dummyTest(irc);
// String tmpFile = "/tmp/lcctest";
String tmpFile = args[1];
System.out.println("*** Testing writing and reading file "+tmpFile);
encodeTest(irc, tmpFile);
decodeTest(irc, tmpFile);
}
}
private static void decodeTest(InRAMCompiler irc, String tmpFile) {
try {
FileInputStream in = new FileInputStream(tmpFile);
DecoderChannel dec = new DecoderChannel(in);
Class fc = irc.load(FOO);
Class hc = irc.load("gen_"+FOO+"Handler");
Class hi = irc.load(FOO+"$Handler");
Object h = hc.newInstance();
Method reg = fc.getDeclaredMethod("register", Decoder.class, hi);
reg.invoke(fc, dec, h);
dec.runOne();
in.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
private static void encodeTest(InRAMCompiler irc, String tmpFile) {
Class<?> hc;
try {
hc = irc.load("gen_"+FOO+"Handler");
Object h = hc.newInstance();
Class fc = irc.load(FOO);
Object f = fc.newInstance();
Field x = fc.getDeclaredField("x");
Field y = fc.getDeclaredField("y");
Field z = fc.getDeclaredField("z");
x.setInt(f, 10);
y.setInt(f, 11);
z.setInt(f, 12);
FileOutputStream out = new FileOutputStream(tmpFile);
EncoderChannel enc = new EncoderChannel(out);
Method reg = fc.getDeclaredMethod("register", Encoder.class);
reg.invoke(fc, enc);
Method doEncode = fc.getDeclaredMethod("encode", Encoder.class, fc);
doEncode.invoke(fc, enc, f);
out.close();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static InRAMCompiler generateCode(String lcDecl, HashMap<String, String> handlers) {
Specification ast = null;
InputStream in = new ByteArrayInputStream(lcDecl.getBytes());
Scanner scanner = new Scanner(in);
Parser parser = new Parser();
Collection errors = new LinkedList();
InRAMCompiler irc = null;
try {
Specification p = (Specification)parser.parse(scanner);
p.errorCheck(errors);
if (errors.isEmpty()) {
ast = p;
} else {
System.out.println("*** Errors:");
for (Iterator iter = errors.iterator(); iter.hasNext(); ) {
String s = (String)iter.next();
System.out.println(s);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (ast != null) {
irc = handleAst(ast, handlers);
} else {
System.err.println("compilation failed");
}
return irc;
}
/* dummy test creating instances of sample and handler, and calling handle*/
private static void dummyTest(InRAMCompiler irc) {
try {
Class hc = irc.load("gen_"+FOO+"Handler");
Object h = hc.newInstance();
Class fc = irc.load(FOO);
Object f = fc.newInstance();
Field x = fc.getDeclaredField("x");
Field y = fc.getDeclaredField("y");
Field z = fc.getDeclaredField("z");
x.setInt(f, 10);
y.setInt(f, 11);
z.setInt(f, 12);
Method m;
try {
m = hc.getDeclaredMethod("handle_"+FOO, fc);
m.invoke(h, f);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/** generate labcomm code and compile handlers
*
* @param lcAST - the AST of the labcomm declaration
* @param handlers - a map <name, source> of handlers for the types in ast
* @return an InRAMCompiler object containing the generated clases
*/
private static InRAMCompiler handleAst(Specification lcAST, HashMap<String, String> handlers) {
Map<String, String> genCode = new HashMap<String, String>();
try {
lcAST.J_gen(genCode, "labcomm.generated", 2013);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Generated labcomm code:");
InRAMCompiler irc = new InRAMCompilerJavax("labcomm.generated", null);
Iterator<String> i = genCode.keySet().iterator();
while(i.hasNext()){
final String sampleName = i.next();
final String src = genCode.get(sampleName);
System.out.println("***"+sampleName+"\n"+src);
StringBuilder sb = new StringBuilder();
sb.append("package labcomm.generated;\n");
sb.append("public class gen_"+sampleName+"Handler implements "+sampleName+".Handler {\n");
sb.append(handlers.get(sampleName));
sb.append("}\n");
System.out.println("-------------------------------------");
System.out.println(sb.toString());
try {
irc.compile(sampleName, src);
irc.compile("gen_"+sampleName+"Handler", sb.toString());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println("================================");
}
return irc;
}
}
package test;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.CharBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import se.lth.control.labcomm2014.Decoder;
import se.lth.control.labcomm2014.DecoderChannel;
import se.lth.control.labcomm2014.Encoder;
import se.lth.control.labcomm2014.EncoderChannel;
import se.lth.control.labcomm2014.compiler.LabCommParser;
import se.lth.control.labcomm2014.compiler.LabCommScanner;
import se.lth.control.labcomm2014.compiler.Program;
import beaver.Parser.Exception;
public class TestLabcommGen {
private static final String TYPE_NAME_FOO = "foo_t";
private static final String SAMPLE_NAME_FOO = "foo";
private static final String SAMPLE_NAME_BAR = "bar";
static final String handlerClassName= "HandlerContainer";
static class HandlerSrc {
private String sampleName;
private String param;
private String body;
private final String proto = "public void handle_";
public HandlerSrc(String sampleName, String param, String body) {
this.sampleName = sampleName;
this.param = param;
this.body = body;
}
public String getSrc() {
String res = proto+sampleName+"("+param+")"+body;
return res;
}
}
/**
* @param args
*/
public static void main(String[] args) {
/* input data: */
String labcommStr = readLabcommDecl(args[0]);
String srcStr = readHandlerDecl(args[1]);
/*Map<sample name, handler code>*/
HashMap <String, String> handlers = new HashMap<String, String>();
generateHandlers(srcStr, handlers);
System.out.println("*** Generated handler source:");
handlers.keySet();
for (String n : handlers.keySet()) {
System.out.println(n+":");
System.out.println(handlers.get(n));
}
InRAMCompiler irc = generateCode(labcommStr, handlers);
if(irc != null) {
System.out.println("*** Testing instantiation and invocation of Handler ");
//dummyTest(irc);
String tmpFile = args[2];
System.out.println("*** Testing writing and reading file "+tmpFile);
encodeTest(irc, tmpFile);
decodeTest(irc, tmpFile, SAMPLE_NAME_FOO, SAMPLE_NAME_BAR);
}
}
public static void generateHandlers(String srcStr, HashMap<String,String> handlers) {
int pos = 0;
while(pos < srcStr.length()) {
// System.out.println("--------");
int nameEnd = srcStr.indexOf(':', pos);
if(nameEnd <0) break;
String name = srcStr.substring(pos,nameEnd);
// System.out.println("Name="+name);
pos=nameEnd+1;
String par = "";
final String handler_decl = "handler(";
if(srcStr.startsWith(handler_decl, pos)) {
int endPar = srcStr.indexOf(')', pos);
par = srcStr.substring(pos+handler_decl.length(), endPar);
// System.out.println("param="+par);
pos = endPar+1;
} else {
System.out.println("expeced handler decl:\n"+srcStr.substring(pos));
}
int bodyEnd = srcStr.indexOf("}###", pos); // HERE BE DRAGONS! a bit brittle
String body = srcStr.substring(pos, bodyEnd+1);
pos = bodyEnd+5;
// System.out.println("body:");
// System.out.println(body);
// System.out.println("**** generates:");
HandlerSrc s = new HandlerSrc(name, par, body);
final String genSrc = s.getSrc();
// System.out.println(genSrc);
handlers.put(name,genSrc);
}
}
public static String readHandlerDecl(String decl) {
FileReader fr;
int len=0;;
CharBuffer buf = CharBuffer.allocate(1024);
try {
fr = new FileReader(decl);
len = fr.read(buf);
buf.rewind();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
String srcStr = buf.toString().substring(0, len);
return srcStr;
}
private static String readLabcommDecl(String lcfile) {
FileReader fr;
int len=0;;
CharBuffer buf = CharBuffer.allocate(1024);
try {
fr = new FileReader(lcfile);
len = fr.read(buf);
// buf.append((char) 0x04);
buf.rewind();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
String labcommStr = buf.toString().substring(0, len-1);
return labcommStr;
}
public static InRAMCompiler generateCode(String lcDecl, HashMap<String, String> handlers) {
Specification ast = null;
InputStream in = new ByteArrayInputStream(lcDecl.getBytes());
LabCommScanner scanner = new LabCommScanner(in);
LabCommParser parser = new LabCommParser();
Collection errors = new LinkedList();
InRAMCompiler irc = null;
try {
Specification p = (Specification)parser.parse(scanner);
p.errorCheck(errors);
if (errors.isEmpty()) {
ast = p;
} else {
System.out.println("*** Errors:");
for (Iterator iter = errors.iterator(); iter.hasNext(); ) {
String s = (String)iter.next();
System.out.println(s);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (ast != null) {
irc = handleAst(ast, handlers);
} else {
System.err.println("compilation failed");
}
return irc;
}
/** generate labcomm code and compile handlers
*
* @param lcAST - the AST of the labcomm declaration
* @param handlers - a map <name, source> of handlers for the types in ast
* @return an InRAMCompiler object containing the generated clases
*/
private static InRAMCompiler handleAst(Specification lcAST, HashMap<String, String> handlers) {
Map<String, String> genCode = new HashMap<String, String>();
try {
lcAST.J_gen(genCode, "labcomm.generated", 2014);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Generated labcomm code:");
InRAMCompiler irc = new InRAMCompilerJavax("labcomm.generated", TestLabcommGen.class.getClassLoader(), true);
StringBuilder handlerClass = new StringBuilder();
StringBuilder handlerMethods = new StringBuilder();
handlerClass.append("package labcomm.generated;\n");
handlerClass.append("import test.TestLabcommGen;\n");
handlerClass.append("public class "+handlerClassName+" implements ");
String handlerAttributes = "Object context;\n";
String handlerConstr = "public "+handlerClassName+"(){ super();}\n";
String handlerConstrCtxt = "public "+handlerClassName+"(Object context){ this.context=context;}\n";
Iterator<String> i = genCode.keySet().iterator();
try {
while(i.hasNext()){
final String sampleName = i.next();
System.out.println("sample: "+sampleName);
final String src = genCode.get(sampleName);
String hctmp = handlers.get(sampleName);
if(hctmp != null) {
handlerClass.append(sampleName+".Handler");
if(i.hasNext()) {
handlerClass.append(", ");
}
handlerMethods.append(hctmp);
handlerMethods.append("\n");
}
//System.out.println("FOOOO:"+sampleName+"++++"+hctmp);
//System.out.println("GOOO: "+sampleName+"----"+handlerMethods);
System.out.println("***"+sampleName+"\n"+src);
irc.compile(sampleName, src); // while iterating, compile the labcomm generated code
}
handlerClass.append("{\n");
if(handlerAttributes != null)
handlerClass.append(handlerAttributes);
if(handlerConstr != null)
handlerClass.append(handlerConstr);
if(handlerConstrCtxt != null)
handlerClass.append(handlerConstrCtxt);
if(handlerMethods != null)
handlerClass.append(handlerMethods.toString());
handlerClass.append("}\n");
System.out.println("--- generated code to compile -------"+ handlerClassName);
final String handlerSrc = handlerClass.toString();
System.out.println(handlerSrc);
irc.compile(handlerClassName, handlerSrc); // compile the generated handler class
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println("================================");
return irc;
}
/** generate labcomm code and compile handlers. Version for separate handler classes
*
* @param lcAST - the AST of the labcomm declaration
* @param handlers - a map <name, source> of handlers for the types in ast
* @return an InRAMCompiler object containing the generated clases
*/
private static InRAMCompiler handleAstSeparate(Specification lcAST, HashMap<String, String> handlers) {
Map<String, String> genCode = new HashMap<String, String>();
try {
lcAST.J_gen(genCode, "labcomm.generated", 2013);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Generated labcomm code:");
InRAMCompiler irc = new InRAMCompilerJavax("labcomm.generated", null);
Iterator<String> i = genCode.keySet().iterator();
while(i.hasNext()){
final String sampleName = i.next();
final String src = genCode.get(sampleName);
System.out.println("***"+sampleName+"\n"+src);
StringBuilder sb = new StringBuilder();
sb.append("package labcomm.generated;\n");
sb.append("public class gen_"+sampleName+"Handler implements "+sampleName+".Handler {\n");
sb.append(handlers.get(sampleName));
sb.append("}\n");
System.out.println("--- foo -----------------------------");
System.out.println(sb.toString());
try {
irc.compile(sampleName, src);
irc.compile("gen_"+sampleName+"Handler", sb.toString());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println("================================");
}
return irc;
}
/** test method
*/
private static void decodeTest(InRAMCompiler irc, String tmpFile, String... sampleNames) {
try {
FileInputStream in = new FileInputStream(tmpFile);
DecoderChannel dec = new DecoderChannel(in);
Class handlerClass = irc.load(handlerClassName);
Constructor hcc = handlerClass.getDeclaredConstructor(Object.class);
// Object handler = handlerClass.newInstance();
HandlerContext ctxt = new HandlerContext();
Object handler = hcc.newInstance(ctxt);
for (String sampleName : sampleNames) {
System.out.println("registering handler for "+sampleName);
Class sampleClass = irc.load(sampleName);
Class handlerInterface = irc.load(sampleName+"$Handler");
Method reg = sampleClass.getDeclaredMethod("register", Decoder.class, handlerInterface);
reg.invoke(sampleClass, dec, handler);
}
try{
System.out.println("*** decoding:");
dec.run();
} catch(EOFException e) {
System.out.println("*** reached EOF ***");
}
in.close();
System.out.println("ctxt.x = "+ctxt.x);
System.out.println("ctxt.y = "+ctxt.y);
System.out.println("ctxt.z = "+ctxt.z);
} catch (Throwable e) {
e.printStackTrace();
}
}
/** test encoding
*/
private static void encodeTest(InRAMCompiler irc, String tmpFile) {
try {
Class ft;
Class fc = irc.load(SAMPLE_NAME_FOO);
Class bc = irc.load(SAMPLE_NAME_BAR);
try {
ft = irc.load(TYPE_NAME_FOO);
} catch (ClassNotFoundException e) {
System.out.println("encodeTest: defaulting to ft == fc");
ft = fc;
}
/* create sample class and instance objects */
Object f = ft.newInstance();
Field x = ft.getDeclaredField("x");
Field y = ft.getDeclaredField("y");
Field z = ft.getDeclaredField("z");
x.setInt(f, 10);
y.setInt(f, 11);
z.setInt(f, 12);
FileOutputStream out = new FileOutputStream(tmpFile);
EncoderChannel enc = new EncoderChannel(out);
/* register and send foo */
Method regFoo = fc.getDeclaredMethod("register", Encoder.class);
regFoo.invoke(fc, enc);
Method doEncodeFoo = fc.getDeclaredMethod("encode", Encoder.class, ft);
doEncodeFoo.invoke(fc, enc, f);
/* register and send bar (NB! uses primitive type int) */
Method regBar = bc.getDeclaredMethod("register", Encoder.class);
regBar.invoke(bc, enc);
Method doEncodeBar = bc.getDeclaredMethod("encode", Encoder.class, Integer.TYPE);
doEncodeBar.invoke(bc, enc, 42);
out.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
/** dummy test creating instances of sample and handler, and calling handle*/
private static void dummyTest(InRAMCompiler irc) {
try {
Class hc = irc.load(handlerClassName);
Constructor hcc = hc.getDeclaredConstructor(Object.class);
// Object h = hc.newInstance();
Object h = hcc.newInstance(new HandlerContext());
Class fc = irc.load(SAMPLE_NAME_FOO);
Object f = fc.newInstance();
Field x = fc.getDeclaredField("x");
Field y = fc.getDeclaredField("y");
Field z = fc.getDeclaredField("z");
x.setInt(f, 10);
y.setInt(f, 11);
z.setInt(f, 12);
Method m;
try {
m = hc.getDeclaredMethod("handle_"+SAMPLE_NAME_FOO, fc);
m.invoke(h, f);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/** test method
*/
private static void decodeTestSeparate(InRAMCompiler irc, String tmpFile, String... sampleNames) {
try {
FileInputStream in = new FileInputStream(tmpFile);
DecoderChannel dec = new DecoderChannel(in);
for (String sampleName : sampleNames) {
System.out.println("registering handler for "+sampleName);
Class sampleClass = irc.load(sampleName);
Class handlerClass = irc.load("gen_"+sampleName+"Handler");
Class handlerInterface = irc.load(sampleName+"$Handler");
Object handler = handlerClass.newInstance();
Method reg = sampleClass.getDeclaredMethod("register", Decoder.class, handlerInterface);
reg.invoke(sampleClass, dec, handler);
}
try{
System.out.println("*** decoding:");
dec.run();
} catch(EOFException e) {
System.out.println("*** reached EOF ***");
}
in.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
/** dummy test creating instances of sample and handler, and calling handle*/
private static void dummyTestSeparate(InRAMCompiler irc) {
try {
Class hc = irc.load("gen_"+SAMPLE_NAME_FOO+"Handler");
Object h = hc.newInstance();
Class fc = irc.load(SAMPLE_NAME_FOO);
Object f = fc.newInstance();
Field x = fc.getDeclaredField("x");
Field y = fc.getDeclaredField("y");
Field z = fc.getDeclaredField("z");
x.setInt(f, 10);
y.setInt(f, 11);
z.setInt(f, 12);
Method m;
try {
m = hc.getDeclaredMethod("handle_"+SAMPLE_NAME_FOO, fc);
m.invoke(h, f);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#dummy script to test the on-the-fly compilation
javac -cp .:../../compiler/labcomm2014_compiler.jar:../../lib/java/labcomm2014.jar:../../lib/tools/beaver.jar:../../lib/tools/beaver-rt.jar:../../lib/tools/jastadd2.jar:../../lib/tools/JFlex.jar:../../lib/tools/proj.jar test/TestLabcommGen.java
javac test/HandlerContext.java
java -cp .:../../compiler/labcomm2014_compiler.jar:../../lib/java/labcomm2014.jar:../../lib/tools/beaver.jar:../../lib/tools/beaver-rt.jar:../../lib/tools/jastadd2.jar:../../lib/tools/JFlex.jar:../../lib/tools/proj.jar test.TestLabcommGen simple_type.lc handlers_type.txt encoded_data
LCDIR=../..
LABCOMM_JAR=../../compiler/labcomm2014_compiler.jar
LABCOMM=java -jar $(LABCOMM_JAR)
CLASSPATH=.:${LCDIR}/lib/java/labcomm2014.jar
JAVA_PKG=labcommTCPtest
SAMPLENAME=foo
LCLIBDIR=${LCDIR}/lib/c
LCFILE=jg
AUX=enc.c dec.c
TLCFILE=turtle1
TAUX=turtle_enc.c turtle_dec.c
${JAVA_PKG}/gen/foo.java: ${LCFILE}.lc
${LABCOMM} --javapackage=${JAVA_PKG}.gen --java=${JAVA_PKG}/gen $<
${JAVA_PKG}/gen/${SAMPLENAME}.class: ${JAVA_PKG}/gen/${SAMPLENAME}.java
javac -cp ${CLASSPATH} $<
${JAVA_PKG}/server/TestServer.class: ${JAVA_PKG}/server/TestServer.java ${JAVA_PKG}/gen/${SAMPLENAME}.class
javac -cp ${CLASSPATH} $<
${JAVA_PKG}/client/TestClient.class: ${JAVA_PKG}/client/TestClient.java ${JAVA_PKG}/gen/${SAMPLENAME}.class
javac -cp ${CLASSPATH} $<
.PHONY: runjavaserver
runjavaserver : ${JAVA_PKG}/server/TestServer.class
java -cp ${CLASSPATH} $(<:.class=)
.PHONY: runjavaclient
runjavaclient : ${JAVA_PKG}/client/TestClient.class
java -cp ${CLASSPATH} $(<:.class=)
client: client.c ${LCFILE}.c ${AUX} ${AUX:.c=.h}
${CC} -o $@ client.c ${AUX} ${LCFILE}.c -I${LCLIBDIR} -L${LCLIBDIR} -llabcomm
testserver: testserver.c ${LCFILE}.c ${AUX} ${AUX:.c=.h}
${CC} -o $@ testserver.c ${AUX} ${LCFILE}.c -I${LCLIBDIR} -L${LCLIBDIR} -llabcomm
turtleclient: turtleclient.c ${TLCFILE}.c ${TAUX} ${TAUX:.c=.h}
${CC} -o $@ turtleclient.c ${TAUX} ${TLCFILE}.c -I${LCLIBDIR} -L${LCLIBDIR} -llabcomm
${LCFILE}.c : ${LCFILE}.lc
${LABCOMM} -C ${LCFILE}.lc
${TLCFILE}.c : ${TLCFILE}.lc
${LABCOMM} -C ${TLCFILE}.lc
all: client testserver ${JAVA_PKG}/server/TestServer.class ${JAVA_PKG}/client/TestClient.class turtleclient
.PHONY: clean
clean :
rm -f ${LCFILE}.c ${LCFILE}.h client testserver turtleclient
rm -f ${JAVA_PKG}/server/*.class ${JAVA_PKG}/client/*.class
rm -f ${JAVA_PKG}/gen/*
.PHONY: distclean
distclean: clean
.PHONY: runclient
runclient : client
LD_LIBRARY_PATH=${LCLIBDIR} ./$< localhost 9999
.PHONY: runserver
runserver : testserver
LD_LIBRARY_PATH=${LCLIBDIR} ./$< 9999
.PHONY: runtclient
runtclient : turtleclient
LD_LIBRARY_PATH=${LCLIBDIR} ./$< localhost 8082
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "dec.h"
#include "enc.h"
void error(const char *msg)
{
perror(msg);
exit(0);
}
void do_labcomm(int sockfd)
{
void *enc = enc_init(sockfd);
void *dec = dec_init(sockfd, enc);
dec_run(dec);
dec_cleanup(dec);
enc_cleanup(enc);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
do_labcomm(sockfd);
close(sockfd);
return 0;
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<GCDocument color="-1" dimTicks="25" dpwsInterface="" dpwsPort="-1" height="599" horizontalScrollBar="1" modifiable="1" name="Client" saveVersion="7" scale="1.0" simulationMode="1" socketHost="" socketIsServer="0" socketPort="-1" socketSendMode="Changed" threadSpeed="40" tokenLuminance="0" verticalScrollBar="1" viewPositionX="0" viewPositionY="0" width="490" x="358" y="-1">
<LabCommObject height="60" isSocketServer="0" name="LabComm" socketHost="127.0.0.1" socketPort="9999" specification="sample struct {&#10; double b;&#10; int c;&#10; int d;&#10; string e;&#10; boolean f;&#10; short g;&#10; long h;&#10; float i;&#10;} foo;&#10;&#10;//sample int bar;&#10;" width="60" x="50" y="300"/>
<GCInitialStep actionBlockVisible="1" actionText="P b = LabComm.foo.b;" fileName="" height="70" id="d518e8b8-6b49-4af4-abcc-ec8024853580" name="" useIcon="0" width="200" x="140" y="65"/>
<IntegerVariable constant="0" exp="" height="45" initialValue="" name="b" updated="0" value="437" width="65" x="380" y="70"/>
</GCDocument>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <labcomm_fd_reader.h>
#include <labcomm_default_error_handler.h>
#include <labcomm_default_memory.h>
#include <labcomm_default_scheduler.h>
#include <stdio.h>
#include "jg.h"
static struct labcomm_encoder *encoder;
static void handle_foo(jg_foo *v, void *context) {
printf("got foo: b=%f, e=%s, f=%d\n", v->b, v->e, v->f);
v->d = v->d+1;
labcomm_encode_jg_foo(encoder, v);
usleep(500000);
v->d = v->d+1;
labcomm_encode_jg_foo(encoder, v);
}
struct labcomm_decoder *dec_init(int fd, struct labcomm_encoder *e) {
struct labcomm_decoder *decoder;
encoder = e;
void *context = NULL;
decoder = labcomm_decoder_new(labcomm_fd_reader_new(
labcomm_default_memory, fd, 1),
labcomm_default_error_handler,
labcomm_default_memory,
labcomm_default_scheduler);
if (!decoder) {
printf("Failed to allocate decoder %s:%d\n", __FUNCTION__, __LINE__);
return (void *)0;
}
labcomm_decoder_register_jg_foo(decoder, handle_foo, context);
return decoder;
}
void dec_run(struct labcomm_decoder *decoder) {
printf("Decoding:\n");
labcomm_decoder_run(decoder);
printf("--- End Of File ---:\n");
}
void dec_cleanup(struct labcomm_decoder *decoder) {
labcomm_decoder_free(decoder);
}
#include <labcomm_fd_reader.h>
#include <labcomm_default_error_handler.h>
#include <labcomm_default_memory.h>
#include <labcomm_default_scheduler.h>
#include <stdio.h>
struct labcomm_decoder * dec_init(int fd, struct labcomm_encoder *e) ;
void dec_run(struct labcomm_decoder *decoder) ;
void dec_cleanup(struct labcomm_decoder *decoder) ;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <labcomm_fd_writer.h>
#include <labcomm_default_error_handler.h>
#include <labcomm_default_memory.h>
#include <labcomm_default_scheduler.h>
#include "jg.h"
#include <stdio.h>
struct labcomm_encoder *enc_init( int fd) {
struct labcomm_encoder *encoder;
encoder = labcomm_encoder_new(labcomm_fd_writer_new(
labcomm_default_memory, fd, 1),
labcomm_default_error_handler,
labcomm_default_memory,
labcomm_default_scheduler);
labcomm_encoder_register_jg_foo(encoder);
return encoder;
}
void enc_run(struct labcomm_encoder *encoder, jg_foo *v) {
#if 0
jg_foo v;
v.b = 17.17;
v.c = 1742;
v.d = 4217;
v.e = "hello";
v.f = 17;
v.g = 42;
v.h = 2;
v.i = 42.42;
#endif
usleep(500000);
v->b += 42;
v->h += 42000000;
labcomm_encode_jg_foo(encoder, v);
}
void enc_cleanup(struct labcomm_encoder *encoder) {
labcomm_encoder_free(encoder);
}
#include <labcomm_fd_writer.h>
#include <labcomm_default_error_handler.h>
#include <labcomm_default_memory.h>
#include <labcomm_default_scheduler.h>
#include "jg.h"
struct labcomm_encoder *enc_init(int fd) ;
void enc_run(struct labcomm_encoder *encoder, jg_foo *v) ;
void enc_cleanup(struct labcomm_encoder *encoder) ;
sample struct {
double b;
int c;
int d;
string e;
boolean f;
short g;
long h;
float i;
} foo;