package dk.itu.kasper.Macros; import java.lang.reflect.*; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.Reader; import java.io.StringReader; import java.io.IOException; public class MacroExpander { private MacroExpander nextExpander=null; public MacroExpander(){ nextExpander = null; } public MacroExpander(MacroExpander next){ nextExpander = next; } public String undefined(String name, String[] args){ if ( nextExpander != null ) return nextExpander.expand( name, args ); return "*** " + name + " could not be expanded ***"; } public void process(String input, PrintStream out){ process( new StringReader( input ), out ); } public void process(Reader input, PrintStream out){ try{ MacroProcessor mp = new MacroProcessor( input , out ); mp.setExpander( this ); mp.process(); }catch(IOException e){ out.print( "***MacroProcessing Failed***" ); } } protected String process(String s){ ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream( out ); this.process( s, ps ); return out.toString(); } String expand(String name, String[] args){ final Class[] argTypes = new Class[]{String[].class}; String expansion; try{ Method m = this.getClass().getMethod( name , argTypes ); expansion = (String)m.invoke( this , new Object[]{args} ); }catch(NoSuchMethodException no){ expansion = undefined( name, args ); }catch(InvocationTargetException in){ expansion = "'" + name + " invocation error: " + in.getCause() + "'"; }catch(Exception e){ expansion = "Macro "+ name + " failed'"+e+"'"; } return expansion; } }