You can subscribe to this list here.
2002 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(11) |
Nov
(97) |
Dec
(35) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2003 |
Jan
(12) |
Feb
(55) |
Mar
(21) |
Apr
(3) |
May
(7) |
Jun
(25) |
Jul
(108) |
Aug
(23) |
Sep
|
Oct
|
Nov
|
Dec
(4) |
2006 |
Jan
|
Feb
|
Mar
(6) |
Apr
(3) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2008 |
Jan
(13) |
Feb
|
Mar
(257) |
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(38) |
Dec
|
2009 |
Jan
|
Feb
(1) |
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2010 |
Jan
|
Feb
(63) |
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
(1) |
Oct
|
Nov
|
Dec
(1) |
2011 |
Jan
|
Feb
(1) |
Mar
|
Apr
(1) |
May
(1) |
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2012 |
Jan
|
Feb
(1) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <dr...@us...> - 2003-06-12 00:48:21
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/tools In directory sc8-pr-cvs1:/tmp/cvs-serv6675/src/org/webmacro/tools Modified Files: CheckTemplates.java EvalTemplates.java TemplateEvalAntTask.java WMTemplateAntTask.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: CheckTemplates.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/tools/CheckTemplates.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** CheckTemplates.java 12 Jun 2002 17:17:28 -0000 1.6 --- CheckTemplates.java 12 Jun 2003 00:47:48 -0000 1.7 *************** *** 1,13 **** package org.webmacro.tools; - import java.io.*; - import org.webmacro.Broker; import org.webmacro.WM; - import org.webmacro.engine.Block; import org.webmacro.engine.BuildContext; import org.webmacro.engine.Builder; import org.webmacro.engine.Parser; /** * CheckTemplates --- 1,14 ---- package org.webmacro.tools; import org.webmacro.Broker; import org.webmacro.WM; import org.webmacro.engine.BuildContext; import org.webmacro.engine.Builder; import org.webmacro.engine.Parser; + import java.io.FileReader; + import java.io.InputStreamReader; + import java.io.Reader; + /** * CheckTemplates *************** *** 18,51 **** */ ! public class CheckTemplates { ! private static Parser parser; ! private static Broker broker; ! public static void parseTemplate(String name, Reader in) { ! try { ! Builder bb = parser.parseBlock(name, in); ! bb.build(new BuildContext(broker)); ! } ! catch (Exception e) { ! System.err.println("Exception parsing template " + name + "\n" + e); ! } ! } ! public static void main(String[] args) throws Exception { ! if (!System.getProperties().containsKey("org.webmacro.LogLevel")) ! System.getProperties().setProperty("org.webmacro.LogLevel", "ERROR"); ! WM wm = new WM(); ! broker = wm.getBroker(); ! parser = (Parser) broker.get("parser", "wm"); ! if (args.length == 0) ! parseTemplate("Standard in", new InputStreamReader(System.in)); ! else { ! for (int i = 0; i < args.length; i++) ! parseTemplate(args[i], new FileReader(args[i])); ! } ! ; ! } } --- 19,58 ---- */ ! public class CheckTemplates ! { ! private static Parser parser; ! private static Broker broker; ! public static void parseTemplate (String name, Reader in) ! { ! try ! { ! Builder bb = parser.parseBlock(name, in); ! bb.build(new BuildContext(broker)); ! } ! catch (Exception e) ! { ! System.err.println("Exception parsing template " + name + "\n" + e); ! } ! } ! public static void main (String[] args) throws Exception ! { ! if (!System.getProperties().containsKey("org.webmacro.LogLevel")) ! System.getProperties().setProperty("org.webmacro.LogLevel", "ERROR"); ! WM wm = new WM(); ! broker = wm.getBroker(); ! parser = (Parser) broker.get("parser", "wm"); ! if (args.length == 0) ! parseTemplate("Standard in", new InputStreamReader(System.in)); ! else ! { ! for (int i = 0; i < args.length; i++) ! parseTemplate(args[i], new FileReader(args[i])); ! } ! ; ! } } Index: EvalTemplates.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/tools/EvalTemplates.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** EvalTemplates.java 21 Jul 2002 00:02:10 -0000 1.4 --- EvalTemplates.java 12 Jun 2003 00:47:48 -0000 1.5 *************** *** 1,3 **** --- 1,4 ---- package org.webmacro.tools; + import org.webmacro.Context; import org.webmacro.util.WMEval; *************** *** 17,85 **** */ ! public class EvalTemplates { ! ! private WMEval wm = new WMEval(); // constructs an encapsulation of WM ! /** ! * Evaluates a single template file argument. ! * Exceptions are reported to standard error, not thrown. ! */ ! public void run(String inputTemplate) { ! System.out.println("Template File=" + inputTemplate); ! try { ! wm.eval(wm.getNewContext(), inputTemplate, null, false, null); ! } ! catch (Exception e) { ! System.err.println("Unable to evaluate input."); ! e.printStackTrace(); ! } ! } ! /** ! * Evaluates a single template file argument. ! * Exceptions are reported to standard error, not thrown. ! * <p>This method provides programmer control ! * over the evaluation options. ! * @param inputTemplate A template in the resource path. ! * @param outFile An output file for the template output. If ! * null, the template must set the output. ! * @param append If true, output will be appended to existing file. ! * @param encoding The encoding to use on the output file, null allowed. ! */ ! public Context run(String inputTemplate, String outFile, boolean append, ! String encoding) { ! try { ! wm.eval(wm.getNewContext(), inputTemplate, outFile, append, encoding); ! return wm.getCurrentContext(); } ! catch (Exception e) { ! System.err.println("Unable to evaluate input."); ! e.printStackTrace(); ! return null; } - } ! /** ! * After a template has been run, this method ! * will return an object in the context by name. ! */ ! public Object getContextElement(String key) { ! Context context = wm.getCurrentContext(); ! return context.get(key); ! } ! /** ! * Normally this main is invoked from an ant task but it can ! * be invoked from any main launcher including ! * a command line. ! * @param args One or more file references to an input template file name. ! */ ! public static void main(String[] args) throws Exception { ! if (args == null) return; ! EvalTemplates ev = new EvalTemplates(); ! for (int i = 0; i < args.length; i++) { ! ev.run(args[i]); ! } ! } } --- 18,96 ---- */ ! public class EvalTemplates ! { ! private WMEval wm = new WMEval(); // constructs an encapsulation of WM ! /** ! * Evaluates a single template file argument. ! * Exceptions are reported to standard error, not thrown. ! */ ! public void run (String inputTemplate) ! { ! System.out.println("Template File=" + inputTemplate); ! try ! { ! wm.eval(wm.getNewContext(), inputTemplate, null, false, null); ! } ! catch (Exception e) ! { ! System.err.println("Unable to evaluate input."); ! e.printStackTrace(); ! } } ! ! /** ! * Evaluates a single template file argument. ! * Exceptions are reported to standard error, not thrown. ! * <p>This method provides programmer control ! * over the evaluation options. ! * @param inputTemplate A template in the resource path. ! * @param outFile An output file for the template output. If ! * null, the template must set the output. ! * @param append If true, output will be appended to existing file. ! * @param encoding The encoding to use on the output file, null allowed. ! */ ! public Context run (String inputTemplate, String outFile, boolean append, ! String encoding) ! { ! try ! { ! wm.eval(wm.getNewContext(), inputTemplate, outFile, append, encoding); ! return wm.getCurrentContext(); ! } ! catch (Exception e) ! { ! System.err.println("Unable to evaluate input."); ! e.printStackTrace(); ! return null; ! } } ! /** ! * After a template has been run, this method ! * will return an object in the context by name. ! */ ! public Object getContextElement (String key) ! { ! Context context = wm.getCurrentContext(); ! return context.get(key); ! } ! /** ! * Normally this main is invoked from an ant task but it can ! * be invoked from any main launcher including ! * a command line. ! * @param args One or more file references to an input template file name. ! */ ! public static void main (String[] args) throws Exception ! { ! if (args == null) return; ! EvalTemplates ev = new EvalTemplates(); ! for (int i = 0; i < args.length; i++) ! { ! ev.run(args[i]); ! } ! } } Index: TemplateEvalAntTask.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/tools/TemplateEvalAntTask.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** TemplateEvalAntTask.java 11 Jun 2002 17:43:23 -0000 1.2 --- TemplateEvalAntTask.java 12 Jun 2003 00:47:48 -0000 1.3 *************** *** 1,13 **** package org.webmacro.tools; ! public class TemplateEvalAntTask extends WMTemplateAntTask { ! public TemplateEvalAntTask() { ! super(); ! } ! protected String getMainClass() { ! return "org.webmacro.tools.EvalTemplates"; ! } } --- 1,16 ---- package org.webmacro.tools; ! public class TemplateEvalAntTask extends WMTemplateAntTask ! { ! public TemplateEvalAntTask () ! { ! super(); ! } ! protected String getMainClass () ! { ! return "org.webmacro.tools.EvalTemplates"; ! } } Index: WMTemplateAntTask.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/tools/WMTemplateAntTask.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** WMTemplateAntTask.java 11 Jun 2002 17:43:23 -0000 1.4 --- WMTemplateAntTask.java 12 Jun 2003 00:47:48 -0000 1.5 *************** *** 1,10 **** package org.webmacro.tools; ! import java.io.*; ! import java.util.*; ! import org.apache.tools.ant.*; ! import org.apache.tools.ant.taskdefs.*; ! import org.apache.tools.ant.types.*; /** --- 1,15 ---- package org.webmacro.tools; ! import org.apache.tools.ant.BuildException; ! import org.apache.tools.ant.DirectoryScanner; ! import org.apache.tools.ant.Task; ! import org.apache.tools.ant.taskdefs.Execute; ! import org.apache.tools.ant.types.CommandlineJava; ! import org.apache.tools.ant.types.FileSet; ! import org.apache.tools.ant.types.Path; ! import org.apache.tools.ant.types.Reference; ! import java.io.File; ! import java.util.Vector; /** *************** *** 14,86 **** */ ! public class WMTemplateAntTask extends Task { ! protected Vector filesets = new Vector(); ! private CommandlineJava cmdl = new CommandlineJava(); ! private Path compileClasspath; ! public void addFileset(FileSet set) { ! filesets.addElement(set); ! } ! public void setClasspath(Path classpath) { ! if (compileClasspath == null) { ! compileClasspath = classpath; ! } ! else { ! compileClasspath.append(classpath); ! } ! } ! public Path getClasspath() { ! return compileClasspath; ! } ! public Path createClasspath() { ! if (compileClasspath == null) { ! compileClasspath = new Path(project); ! } ! return compileClasspath.createPath(); ! } ! public void setClasspathRef(Reference r) { ! createClasspath().setRefid(r); ! } ! /** ! * Subclasses should override this ! * to supply their own template execution ! * vehicle. ! */ ! protected String getMainClass() { ! return "org.webmacro.tools.CheckTemplates"; ! } ! public WMTemplateAntTask() { ! cmdl.setVm("java"); ! cmdl.setClassname(getMainClass()); ! } ! public void execute() throws BuildException { ! for (int i = 0; i < filesets.size(); i++) { ! FileSet fs = (FileSet) filesets.elementAt(i); ! File fromDir = fs.getDir(project); ! DirectoryScanner ds = fs.getDirectoryScanner(project); ! String[] srcFiles = ds.getIncludedFiles(); ! for (int j = 0; j < srcFiles.length; j++) ! cmdl.createArgument() ! .setValue(new File(fromDir.getAbsolutePath(), srcFiles[j]) ! .getAbsolutePath()); ! } ! Path classpath = cmdl.createClasspath(project); ! classpath.append(getClasspath()); ! Execute.runCommand(this, cmdl.getCommandline()); ! } } --- 19,104 ---- */ ! public class WMTemplateAntTask extends Task ! { ! protected Vector filesets = new Vector(); ! private CommandlineJava cmdl = new CommandlineJava(); ! private Path compileClasspath; ! public void addFileset (FileSet set) ! { ! filesets.addElement(set); ! } ! public void setClasspath (Path classpath) ! { ! if (compileClasspath == null) ! { ! compileClasspath = classpath; ! } ! else ! { ! compileClasspath.append(classpath); ! } ! } ! public Path getClasspath () ! { ! return compileClasspath; ! } ! public Path createClasspath () ! { ! if (compileClasspath == null) ! { ! compileClasspath = new Path(project); ! } ! return compileClasspath.createPath(); ! } ! public void setClasspathRef (Reference r) ! { ! createClasspath().setRefid(r); ! } ! /** ! * Subclasses should override this ! * to supply their own template execution ! * vehicle. ! */ ! protected String getMainClass () ! { ! return "org.webmacro.tools.CheckTemplates"; ! } ! public WMTemplateAntTask () ! { ! cmdl.setVm("java"); ! cmdl.setClassname(getMainClass()); ! } ! public void execute () throws BuildException ! { ! for (int i = 0; i < filesets.size(); i++) ! { ! FileSet fs = (FileSet) filesets.elementAt(i); ! File fromDir = fs.getDir(project); ! DirectoryScanner ds = fs.getDirectoryScanner(project); ! String[] srcFiles = ds.getIncludedFiles(); ! for (int j = 0; j < srcFiles.length; j++) ! cmdl.createArgument() ! .setValue(new File(fromDir.getAbsolutePath(), srcFiles[j]) ! .getAbsolutePath()); ! } ! Path classpath = cmdl.createClasspath(project); ! classpath.append(getClasspath()); ! Execute.runCommand(this, cmdl.getCommandline()); ! } } |
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/profile In directory sc8-pr-cvs1:/tmp/cvs-serv6675/src/org/webmacro/profile Modified Files: CallGraph.java Profile.java ProfileCategory.java ProfileEvent.java ProfileSystem.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: CallGraph.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/profile/CallGraph.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** CallGraph.java 11 Jun 2002 17:43:22 -0000 1.6 --- CallGraph.java 12 Jun 2003 00:47:46 -0000 1.7 *************** *** 24,31 **** package org.webmacro.profile; - import java.util.*; - import org.webmacro.util.SimpleStack; /** * A CallGraph is a view of the events in a ProfileCategory. It --- 24,34 ---- package org.webmacro.profile; import org.webmacro.util.SimpleStack; + import java.util.Arrays; + import java.util.Comparator; + import java.util.HashMap; + import java.util.Iterator; + /** * A CallGraph is a view of the events in a ProfileCategory. It *************** *** 33,160 **** * the time is going in your application. */ ! public class CallGraph { ! private String name; ! private long duration; ! private int calls; ! private HashMap children; ! private CallGraph(String name) { ! this.name = name; ! duration = 0; ! calls = 0; ! children = new HashMap(); ! } ! final private static Comparator comparator = new Comparator() { ! final public int compare(Object a, Object b) { ! CallGraph ca = (CallGraph) a; ! CallGraph cb = (CallGraph) b; ! if (ca.duration < cb.duration) return 1; ! if (ca.duration > cb.duration) return -1; ! return 0; ! } ! }; ! /** ! * Construct a CallGraph representing the nodes in the supplied root ! */ ! public CallGraph(ProfileCategory root) { ! this(root.getName()); ! Profile[] profiles = root.getProfiles(); ! for (int i = 0; i < profiles.length; i++) { ! addProfile(profiles[i]); ! } ! } ! /** ! * Add the data from this profile to the call graph. ! */ ! private void addProfile(Profile p) { ! SimpleStack cgStack = new SimpleStack(); // rebuild invocation stack ! CallGraph cg = this; ! int depth = -1; // 0 is the first actual invocation, we are "above" that ! Iterator i = p.getEvents(); ! while (i.hasNext()) { ! ProfileEvent evt = (ProfileEvent) i.next(); ! int evtDepth = evt.depth; ! int evtDuration = evt.duration; ! // move to parent ! while (evtDepth <= depth) { ! cg = (CallGraph) cgStack.pop(); ! depth--; ! } ! // find child ! CallGraph child = (CallGraph) cg.children.get(evt.name); ! if (child == null) { ! child = new CallGraph(evt.name); ! cg.children.put(evt.name, child); ! } ! cgStack.push(cg); ! depth++; ! cg = child; ! // record statistics ! cg.calls++; ! cg.duration += evtDuration; ! } ! } ! public String toString() { ! return "CallGraph(" + name + ")"; ! } ! public String getName() { ! return name; ! } ! public CallGraph[] getChildren() { ! CallGraph[] ret = ! (CallGraph[]) children.values().toArray(new CallGraph[0]); ! Arrays.sort(ret, comparator); ! return ret; ! } ! public long getTime() { ! return duration; ! } ! public int getCalls() { ! return calls; ! } ! public String format() { ! StringBuffer buf = new StringBuffer(); ! format(buf, 0); ! return buf.toString(); ! } ! private static char[] _indentation = new char[0]; ! public void format(StringBuffer buf, int depth) { ! int indent = depth * 2; ! if (indent > _indentation.length) { ! _indentation = new char[indent * 2]; ! Arrays.fill(_indentation, ' '); ! } ! buf.append(_indentation, 0, indent); ! buf.append(name); ! buf.append(": "); ! buf.append(duration); ! buf.append(" ("); ! buf.append(calls); ! buf.append(", "); ! buf.append((double) duration / calls); ! buf.append(")\n"); ! CallGraph kids[] = getChildren(); ! for (int i = 0; i < kids.length; i++) { ! kids[i].format(buf, depth + 1); ! } ! } } --- 36,182 ---- * the time is going in your application. */ ! public class CallGraph ! { ! private String name; ! private long duration; ! private int calls; ! private HashMap children; ! private CallGraph (String name) ! { ! this.name = name; ! duration = 0; ! calls = 0; ! children = new HashMap(); ! } ! final private static Comparator comparator = new Comparator() ! { ! final public int compare (Object a, Object b) ! { ! CallGraph ca = (CallGraph) a; ! CallGraph cb = (CallGraph) b; ! if (ca.duration < cb.duration) return 1; ! if (ca.duration > cb.duration) return -1; ! return 0; ! } ! }; ! /** ! * Construct a CallGraph representing the nodes in the supplied root ! */ ! public CallGraph (ProfileCategory root) ! { ! this(root.getName()); ! Profile[] profiles = root.getProfiles(); ! for (int i = 0; i < profiles.length; i++) ! { ! addProfile(profiles[i]); ! } ! } ! /** ! * Add the data from this profile to the call graph. ! */ ! private void addProfile (Profile p) ! { ! SimpleStack cgStack = new SimpleStack(); // rebuild invocation stack ! CallGraph cg = this; ! int depth = -1; // 0 is the first actual invocation, we are "above" that ! Iterator i = p.getEvents(); ! while (i.hasNext()) ! { ! ProfileEvent evt = (ProfileEvent) i.next(); ! int evtDepth = evt.depth; ! int evtDuration = evt.duration; ! // move to parent ! while (evtDepth <= depth) ! { ! cg = (CallGraph) cgStack.pop(); ! depth--; ! } ! // find child ! CallGraph child = (CallGraph) cg.children.get(evt.name); ! if (child == null) ! { ! child = new CallGraph(evt.name); ! cg.children.put(evt.name, child); ! } ! cgStack.push(cg); ! depth++; ! cg = child; ! // record statistics ! cg.calls++; ! cg.duration += evtDuration; ! } ! } ! public String toString () ! { ! return "CallGraph(" + name + ")"; ! } ! public String getName () ! { ! return name; ! } ! public CallGraph[] getChildren () ! { ! CallGraph[] ret = ! (CallGraph[]) children.values().toArray(new CallGraph[0]); ! Arrays.sort(ret, comparator); ! return ret; ! } ! public long getTime () ! { ! return duration; ! } ! public int getCalls () ! { ! return calls; ! } ! public String format () ! { ! StringBuffer buf = new StringBuffer(); ! format(buf, 0); ! return buf.toString(); ! } ! private static char[] _indentation = new char[0]; ! public void format (StringBuffer buf, int depth) ! { ! int indent = depth * 2; ! if (indent > _indentation.length) ! { ! _indentation = new char[indent * 2]; ! Arrays.fill(_indentation, ' '); ! } ! buf.append(_indentation, 0, indent); ! buf.append(name); ! buf.append(": "); ! buf.append(duration); ! buf.append(" ("); ! buf.append(calls); ! buf.append(", "); ! buf.append((double) duration / calls); ! buf.append(")\n"); ! CallGraph kids[] = getChildren(); ! for (int i = 0; i < kids.length; i++) ! { ! kids[i].format(buf, depth + 1); ! } ! } } Index: Profile.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/profile/Profile.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Profile.java 11 Jun 2002 17:43:22 -0000 1.5 --- Profile.java 12 Jun 2003 00:47:46 -0000 1.6 *************** *** 24,301 **** package org.webmacro.profile; ! import java.util.*; ! final public class Profile { ! private String _qName[] = new String[64]; ! private long _qTime[] = new long[64]; ! private int _qPtr = 0; ! private ProfileEvent[] _eventBuffer = new ProfileEvent[32]; ! /** the ProfileCategory that controls us */ ! ProfileCategory _owner; ! /** ProfileCategory uses this to manage us */ ! protected long timestamp = 0; ! /** only our ProfileCategory should create new instances */ ! protected Profile(ProfileCategory owner) { ! _owner = owner; ! } ! /** ! * Retrieve a list of the events in this profile. The returned ! * iterator will cycle through the ProfileEvent objects that ! * were generated during the execution of this Profile. ! */ ! public Iterator getEvents() throws IllegalStateException { ! final int last = _qPtr; ! int next = -1; ! int lastOpen = -1; ! int depth = 0; ! final int numEvents = _qPtr / 2; ! ProfileEvent[] buf = _eventBuffer; ! if (buf.length < numEvents) { ! buf = new ProfileEvent[numEvents]; ! System.arraycopy(_eventBuffer, 0, buf, 0, _eventBuffer.length); ! _eventBuffer = buf; ! } ! try { ! for (int i = 0; i < last; i++) { ! String name = _qName[i]; ! long time = _qTime[i]; ! if (name != null) { ! // start a new event ! ProfileEvent wme = buf[++next]; ! if (wme == null) { ! wme = new ProfileEvent(); ! buf[next] = wme; ! } ! wme.name = name; ! wme.start = time; ! wme.duration = lastOpen; // tmp parent pointer ! wme.depth = depth++; ! lastOpen = next; ! } ! else { ! ProfileEvent wme = buf[lastOpen]; ! lastOpen = wme.duration; // a tmp parent pointer ! wme.duration = (int) (time - wme.start); ! depth--; } - } ! if ((depth != 0) || (next + 1 != numEvents)) { ! throw new Exception("Invalid stack state"); ! } ! return new Iterator() { ! int pos = 0; ! public boolean hasNext() { ! return (pos < numEvents); ! } ! public Object next() { ! return (_eventBuffer[pos++]); ! } ! public void remove() throws UnsupportedOperationException { ! throw new UnsupportedOperationException("Cannot remove"); ! } ! }; ! } ! catch (Exception e) { ! StringBuffer sb = new StringBuffer(); ! sb.append("Profile: start/stop timing call graph invalid:\n"); ! char[] indent = new char[_qPtr * 4]; ! Arrays.fill(indent, ' '); ! int mdepth = 0; ! for (int i = 0; i < _qPtr; i++) { ! if (_qName[i] != null) { ! sb.append(indent, 0, mdepth); ! sb.append(_qName[i]); ! sb.append("\n"); ! mdepth += 2; ! } ! else { ! mdepth -= 2; ! } ! if (mdepth > _qPtr / 2) { ! sb.append("AT THIS POINT MORE START TIMINGS THAN STOPS\n"); ! } ! if (mdepth < 0) { ! sb.append("AT THIS POINT MORE STOP TIMINGS THAN STARTS\n"); ! mdepth = 0; } ! } ! sb.append("NUMBER OF START TIMINGS NOT EQUAL NUMBER OF STOPS:" ! + "depth=" + depth + " " + "lastOpen=" + lastOpen + " " ! + "next=" + next + " " + "last=" + last + " " ! + "buf.length=" + buf.length); ! e.printStackTrace(); ! throw new IllegalStateException(sb.toString()); ! } ! } ! /** ! * This method resets the data structures for this Profile ! * so it can be re-used. Ordinarily only our controlling ! * category will call this method. ! */ ! protected void reset() { ! _qPtr = 0; ! } ! /** ! * Start timing an event called 'name'. You *MUST* call stop() ! * later in order to get valid results. ! */ ! public void startEvent(String name) { ! try { ! _qName[_qPtr] = name; ! } ! catch (ArrayIndexOutOfBoundsException e) { ! expand(); ! _qName[_qPtr] = name; ! } ! _qTime[_qPtr++] = time(); ! } ! /** ! * Stop timing the last event started. You *MUST* have called ! * start() prior to this in order to get coherent results. ! * @exception IllegalStateException if stopEvent called too many times ! */ ! public void stopEvent() { ! long time = time(); ! try { ! _qName[_qPtr] = null; ! } ! catch (ArrayIndexOutOfBoundsException e) { ! expand(); ! _qName[_qPtr] = null; ! } ! _qTime[_qPtr++] = time; ! } ! /** ! * Double the size of the arrays ! */ ! private void expand() { ! String tmpName[] = new String[_qPtr * 2]; ! System.arraycopy(_qName, 0, tmpName, 0, _qName.length); ! _qName = tmpName; ! long tmpTime[] = new long[_qPtr * 2]; ! System.arraycopy(_qTime, 0, tmpTime, 0, _qTime.length); ! _qTime = tmpTime; ! } ! /** ! * Get the current time as a long ! */ ! private long time() { ! return System.currentTimeMillis(); ! } ! /** ! * Terminate profiling, releasing any resources allocated to ! * this Profile and forwarding any collected statistics back ! * to the ProfileSystem. It is expected that implementations ! * will use this method to recycle the Profile objects ! * themselves for efficiency. ! */ ! public void destroy() { ! _owner.record(this); ! } ! public static void main(String arg[]) { ! try { ! Profile test = new Profile(null); ! test.startEvent("1"); ! Thread.sleep(5); ! test.startEvent("1.1"); ! Thread.sleep(5); ! test.startEvent("1.1.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! test.startEvent("1.2"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("1.3"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("2"); ! Thread.sleep(5); ! test.startEvent("2.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("2.2"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("3"); ! Thread.sleep(5); ! test.startEvent("3.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("3.2"); ! Thread.sleep(5); ! test.startEvent("3.2.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("3.2.2"); ! Thread.sleep(5); ! test.startEvent("3.2.2.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("4"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! Iterator i = test.getEvents(); ! int num = 0; ! while (i.hasNext()) { ! ProfileEvent wme = (ProfileEvent) i.next(); ! System.out.println(num++ + "\t" + wme.depth + "\t" + wme.name + "\t" ! + wme.start + "\t" + wme.duration); ! } ! } ! catch (Exception e) { ! e.printStackTrace(); ! } ! } } --- 24,336 ---- package org.webmacro.profile; ! import java.util.Arrays; ! import java.util.Iterator; ! final public class Profile ! { ! private String _qName[] = new String[64]; ! private long _qTime[] = new long[64]; ! private int _qPtr = 0; ! private ProfileEvent[] _eventBuffer = new ProfileEvent[32]; ! /** the ProfileCategory that controls us */ ! ProfileCategory _owner; ! /** ProfileCategory uses this to manage us */ ! protected long timestamp = 0; ! /** only our ProfileCategory should create new instances */ ! protected Profile (ProfileCategory owner) ! { ! _owner = owner; ! } ! /** ! * Retrieve a list of the events in this profile. The returned ! * iterator will cycle through the ProfileEvent objects that ! * were generated during the execution of this Profile. ! */ ! public Iterator getEvents () throws IllegalStateException ! { ! final int last = _qPtr; ! int next = -1; ! int lastOpen = -1; ! int depth = 0; ! final int numEvents = _qPtr / 2; ! ProfileEvent[] buf = _eventBuffer; ! if (buf.length < numEvents) ! { ! buf = new ProfileEvent[numEvents]; ! System.arraycopy(_eventBuffer, 0, buf, 0, _eventBuffer.length); ! _eventBuffer = buf; ! } ! try ! { ! for (int i = 0; i < last; i++) ! { ! String name = _qName[i]; ! long time = _qTime[i]; ! if (name != null) ! { ! // start a new event ! ProfileEvent wme = buf[++next]; ! if (wme == null) ! { ! wme = new ProfileEvent(); ! buf[next] = wme; ! } ! wme.name = name; ! wme.start = time; ! wme.duration = lastOpen; // tmp parent pointer ! wme.depth = depth++; ! lastOpen = next; ! } ! else ! { ! ProfileEvent wme = buf[lastOpen]; ! lastOpen = wme.duration; // a tmp parent pointer ! wme.duration = (int) (time - wme.start); ! depth--; ! } } ! if ((depth != 0) || (next + 1 != numEvents)) ! { ! throw new Exception("Invalid stack state"); ! } ! return new Iterator() ! { ! int pos = 0; ! public boolean hasNext () ! { ! return (pos < numEvents); ! } ! public Object next () ! { ! return (_eventBuffer[pos++]); ! } ! public void remove () throws UnsupportedOperationException ! { ! throw new UnsupportedOperationException("Cannot remove"); ! } ! }; ! } ! catch (Exception e) ! { ! StringBuffer sb = new StringBuffer(); ! sb.append("Profile: start/stop timing call graph invalid:\n"); ! char[] indent = new char[_qPtr * 4]; ! Arrays.fill(indent, ' '); ! int mdepth = 0; ! for (int i = 0; i < _qPtr; i++) ! { ! if (_qName[i] != null) ! { ! sb.append(indent, 0, mdepth); ! sb.append(_qName[i]); ! sb.append("\n"); ! mdepth += 2; ! } ! else ! { ! mdepth -= 2; ! } ! if (mdepth > _qPtr / 2) ! { ! sb.append("AT THIS POINT MORE START TIMINGS THAN STOPS\n"); ! } ! if (mdepth < 0) ! { ! sb.append("AT THIS POINT MORE STOP TIMINGS THAN STARTS\n"); ! mdepth = 0; ! } } ! sb.append("NUMBER OF START TIMINGS NOT EQUAL NUMBER OF STOPS:" ! + "depth=" + depth + " " + "lastOpen=" + lastOpen + " " ! + "next=" + next + " " + "last=" + last + " " ! + "buf.length=" + buf.length); ! e.printStackTrace(); ! throw new IllegalStateException(sb.toString()); ! } ! } ! /** ! * This method resets the data structures for this Profile ! * so it can be re-used. Ordinarily only our controlling ! * category will call this method. ! */ ! protected void reset () ! { ! _qPtr = 0; ! } ! /** ! * Start timing an event called 'name'. You *MUST* call stop() ! * later in order to get valid results. ! */ ! public void startEvent (String name) ! { ! try ! { ! _qName[_qPtr] = name; ! } ! catch (ArrayIndexOutOfBoundsException e) ! { ! expand(); ! _qName[_qPtr] = name; ! } ! _qTime[_qPtr++] = time(); ! } ! /** ! * Stop timing the last event started. You *MUST* have called ! * start() prior to this in order to get coherent results. ! * @exception IllegalStateException if stopEvent called too many times ! */ ! public void stopEvent () ! { ! long time = time(); ! try ! { ! _qName[_qPtr] = null; ! } ! catch (ArrayIndexOutOfBoundsException e) ! { ! expand(); ! _qName[_qPtr] = null; ! } ! _qTime[_qPtr++] = time; ! } ! /** ! * Double the size of the arrays ! */ ! private void expand () ! { ! String tmpName[] = new String[_qPtr * 2]; ! System.arraycopy(_qName, 0, tmpName, 0, _qName.length); ! _qName = tmpName; ! long tmpTime[] = new long[_qPtr * 2]; ! System.arraycopy(_qTime, 0, tmpTime, 0, _qTime.length); ! _qTime = tmpTime; ! } ! /** ! * Get the current time as a long ! */ ! private long time () ! { ! return System.currentTimeMillis(); ! } ! /** ! * Terminate profiling, releasing any resources allocated to ! * this Profile and forwarding any collected statistics back ! * to the ProfileSystem. It is expected that implementations ! * will use this method to recycle the Profile objects ! * themselves for efficiency. ! */ ! public void destroy () ! { ! _owner.record(this); ! } ! public static void main (String arg[]) ! { ! try ! { ! Profile test = new Profile(null); ! test.startEvent("1"); ! Thread.sleep(5); ! test.startEvent("1.1"); ! Thread.sleep(5); ! test.startEvent("1.1.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! test.startEvent("1.2"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("1.3"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("2"); ! Thread.sleep(5); ! test.startEvent("2.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("2.2"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("3"); ! Thread.sleep(5); ! test.startEvent("3.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("3.2"); ! Thread.sleep(5); ! test.startEvent("3.2.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("3.2.2"); ! Thread.sleep(5); ! test.startEvent("3.2.2.1"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! test.startEvent("4"); ! Thread.sleep(5); ! test.stopEvent(); ! Thread.sleep(5); ! Iterator i = test.getEvents(); ! int num = 0; ! while (i.hasNext()) ! { ! ProfileEvent wme = (ProfileEvent) i.next(); ! System.out.println(num++ + "\t" + wme.depth + "\t" + wme.name + "\t" ! + wme.start + "\t" + wme.duration); ! } ! } ! catch (Exception e) ! { ! e.printStackTrace(); ! } ! } } Index: ProfileCategory.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/profile/ProfileCategory.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** ProfileCategory.java 11 Jun 2002 17:43:22 -0000 1.7 --- ProfileCategory.java 12 Jun 2003 00:47:46 -0000 1.8 *************** *** 24,134 **** package org.webmacro.profile; - import java.util.*; - import org.webmacro.util.Pool; import org.webmacro.util.ScalablePool; /** * A ProfileCategory manages Profile objects for a category. */ ! public class ProfileCategory { ! private final Pool _pool = new ScalablePool(); ! private final LinkedList _profiles = new LinkedList(); ! private int _sharedProfiles = 0; ! private long _timestamp = 0; ! private long _sharedTimestamp = 0; ! private int _recordTime; ! private final int _samplingRate; ! private int _sampleCount = 0; ! private final String _name; ! /** ! * Record time is how long we are to record profiles. After the ! * specified amount of record time we will discard old profiles. ! */ ! protected ProfileCategory(String name, int samplingRate, int recordTime) { ! _name = name; ! _recordTime = recordTime; ! _samplingRate = samplingRate; ! } ! final public String getName() { ! return _name; ! } ! public String toString() { ! return "ProfileCategory(" ! + _name + "," + _recordTime + "," + _samplingRate + ")"; ! } ! /** ! * Instantiate a new Profile. If a null object is returned then ! * no profiling is to be done. The returned object will be the ! * root of a Profile stack trace. Call its start() and stop() ! * methods to record timing data. ! * <P> ! * Concurrency: this method is thread-safe. You may call it from ! * multiple threads. ! */ ! synchronized public Profile newProfile() { ! if ((_samplingRate == 0) || (++_sampleCount < _samplingRate)) { ! return null; ! } ! _sampleCount = 0; ! Profile p = (Profile) _pool.get(); ! if (p == null) { ! p = new Profile(this); ! } ! p.timestamp = System.currentTimeMillis(); ! return p; ! } ! /** ! * Add the profiler to the record queue, and clean out any ! * profilers that have been hanging around for too long. ! */ ! final synchronized protected void record(Profile p) { ! _profiles.add(p); ! cleanup(); ! } ! /** ! * Get the current Profiles ! */ ! final synchronized public Profile[] getProfiles() { ! _sharedTimestamp = System.currentTimeMillis(); ! cleanup(); ! return (Profile[]) _profiles.toArray(new Profile[0]); ! } ! /** ! * Eliminate any profilers that are too old, recycling any ! * that have not been shared with any other object. ! */ ! final private void cleanup() { ! if (_profiles.size() == 0) return; ! long cutoff = System.currentTimeMillis() - _recordTime; ! try { ! while (_timestamp < cutoff) { ! Profile wmp = (Profile) _profiles.getFirst(); ! _timestamp = wmp.timestamp; ! if (_timestamp < cutoff) { ! _profiles.removeFirst(); ! if (_timestamp > _sharedTimestamp) _pool.put(wmp); } ! } ! } ! catch (NoSuchElementException e) { ! // we emptied the list, ignore it ! } ! } } --- 24,149 ---- package org.webmacro.profile; import org.webmacro.util.Pool; import org.webmacro.util.ScalablePool; + import java.util.LinkedList; + import java.util.NoSuchElementException; + /** * A ProfileCategory manages Profile objects for a category. */ ! public class ProfileCategory ! { ! private final Pool _pool = new ScalablePool(); ! private final LinkedList _profiles = new LinkedList(); ! private int _sharedProfiles = 0; ! private long _timestamp = 0; ! private long _sharedTimestamp = 0; ! private int _recordTime; ! private final int _samplingRate; ! private int _sampleCount = 0; ! private final String _name; ! /** ! * Record time is how long we are to record profiles. After the ! * specified amount of record time we will discard old profiles. ! */ ! protected ProfileCategory (String name, int samplingRate, int recordTime) ! { ! _name = name; ! _recordTime = recordTime; ! _samplingRate = samplingRate; ! } ! final public String getName () ! { ! return _name; ! } ! public String toString () ! { ! return "ProfileCategory(" ! + _name + "," + _recordTime + "," + _samplingRate + ")"; ! } ! /** ! * Instantiate a new Profile. If a null object is returned then ! * no profiling is to be done. The returned object will be the ! * root of a Profile stack trace. Call its start() and stop() ! * methods to record timing data. ! * <P> ! * Concurrency: this method is thread-safe. You may call it from ! * multiple threads. ! */ ! synchronized public Profile newProfile () ! { ! if ((_samplingRate == 0) || (++_sampleCount < _samplingRate)) ! { ! return null; ! } ! _sampleCount = 0; ! Profile p = (Profile) _pool.get(); ! if (p == null) ! { ! p = new Profile(this); ! } ! p.timestamp = System.currentTimeMillis(); ! return p; ! } ! /** ! * Add the profiler to the record queue, and clean out any ! * profilers that have been hanging around for too long. ! */ ! final synchronized protected void record (Profile p) ! { ! _profiles.add(p); ! cleanup(); ! } ! /** ! * Get the current Profiles ! */ ! final synchronized public Profile[] getProfiles () ! { ! _sharedTimestamp = System.currentTimeMillis(); ! cleanup(); ! return (Profile[]) _profiles.toArray(new Profile[0]); ! } ! /** ! * Eliminate any profilers that are too old, recycling any ! * that have not been shared with any other object. ! */ ! final private void cleanup () ! { ! if (_profiles.size() == 0) return; ! long cutoff = System.currentTimeMillis() - _recordTime; ! try ! { ! while (_timestamp < cutoff) ! { ! Profile wmp = (Profile) _profiles.getFirst(); ! _timestamp = wmp.timestamp; ! if (_timestamp < cutoff) ! { ! _profiles.removeFirst(); ! if (_timestamp > _sharedTimestamp) _pool.put(wmp); ! } } ! } ! catch (NoSuchElementException e) ! { ! // we emptied the list, ignore it ! } ! } } Index: ProfileEvent.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/profile/ProfileEvent.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ProfileEvent.java 11 Jun 2002 17:43:22 -0000 1.6 --- ProfileEvent.java 12 Jun 2003 00:47:46 -0000 1.7 *************** *** 29,71 **** * when it started, and when it stopped. */ ! final public class ProfileEvent { ! /** ! * The name of this event ! */ ! public String name; ! /** ! * Milliseconds since Jan 1, 1970 that this event started ! */ ! public long start; ! /** ! * Milliseconds that this event lasted for ! */ ! public int duration; ! /** ! * How many levels down the "call stack" is this event? In other ! * words, how many events enclose it. ! */ ! public int depth; ! /** ! * Create a new profile event with null and 0 values ! */ ! public ProfileEvent() { ! this(null, 0, 0, 0); ! } ! /** ! * Create a new profile event with the supplied values ! */ ! public ProfileEvent(String name, int start, int duration, int depth) { ! this.name = name; ! this.start = start; ! this.duration = duration; ! this.depth = depth; ! } } --- 29,74 ---- * when it started, and when it stopped. */ ! final public class ProfileEvent ! { ! /** ! * The name of this event ! */ ! public String name; ! /** ! * Milliseconds since Jan 1, 1970 that this event started ! */ ! public long start; ! /** ! * Milliseconds that this event lasted for ! */ ! public int duration; ! /** ! * How many levels down the "call stack" is this event? In other ! * words, how many events enclose it. ! */ ! public int depth; ! /** ! * Create a new profile event with null and 0 values ! */ ! public ProfileEvent () ! { ! this(null, 0, 0, 0); ! } ! /** ! * Create a new profile event with the supplied values ! */ ! public ProfileEvent (String name, int start, int duration, int depth) ! { ! this.name = name; ! this.start = start; ! this.duration = duration; ! this.depth = depth; ! } } Index: ProfileSystem.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/profile/ProfileSystem.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** ProfileSystem.java 11 Jun 2002 17:43:22 -0000 1.7 --- ProfileSystem.java 12 Jun 2003 00:47:46 -0000 1.8 *************** *** 24,70 **** package org.webmacro.profile; ! import java.util.*; ! public class ProfileSystem { ! final private static ProfileSystem _instance = new ProfileSystem(); ! public static final ProfileSystem getInstance() { ! return _instance; ! } ! final private LinkedList _children = new LinkedList(); ! /** ! * Return a ProfileCategory for the category 'name'. If a null ! * is returned from this method then no profiling is being ! * done for the supplied name. ! */ ! public ProfileCategory newProfileCategory(String name, int rate, int time) { ! if (_children == null) return null; ! ProfileCategory child = new ProfileCategory(name, rate, time); ! _children.add(child); ! return child; ! } ! /** ! * Return an array of the ProfileCategory objects that are ! * being managed. This may return null if there is no ! * profiling being done. ! */ ! public ProfileCategory[] getProfileCategories() { ! if (_children == null) return null; ! return (ProfileCategory[]) _children.toArray(new ProfileCategory[0]); ! } ! /** ! * Shut down the profiling system. This method allows a profiling ! * system to save its settings to a file or database. It will be ! * called by the application when the application is about to ! * terminate the module containing the profiling system. ! */ ! public void destroy() { ! _children.clear(); ! } } --- 24,75 ---- package org.webmacro.profile; ! import java.util.LinkedList; ! public class ProfileSystem ! { ! final private static ProfileSystem _instance = new ProfileSystem(); ! public static final ProfileSystem getInstance () ! { ! return _instance; ! } ! final private LinkedList _children = new LinkedList(); ! /** ! * Return a ProfileCategory for the category 'name'. If a null ! * is returned from this method then no profiling is being ! * done for the supplied name. ! */ ! public ProfileCategory newProfileCategory (String name, int rate, int time) ! { ! if (_children == null) return null; ! ProfileCategory child = new ProfileCategory(name, rate, time); ! _children.add(child); ! return child; ! } ! /** ! * Return an array of the ProfileCategory objects that are ! * being managed. This may return null if there is no ! * profiling being done. ! */ ! public ProfileCategory[] getProfileCategories () ! { ! if (_children == null) return null; ! return (ProfileCategory[]) _children.toArray(new ProfileCategory[0]); ! } ! /** ! * Shut down the profiling system. This method allows a profiling ! * system to save its settings to a file or database. It will be ! * called by the application when the application is about to ! * terminate the module containing the profiling system. ! */ ! public void destroy () ! { ! _children.clear(); ! } } |
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/directive In directory sc8-pr-cvs1:/tmp/cvs-serv6675/src/org/webmacro/directive Modified Files: AlternateDirective.java ArgsHolder.java AttributeDirective.java BeanDirective.java CommentDirective.java CountDirective.java DefaultDirective.java Directive.java DirectiveArgs.java DirectiveBuilder.java DirectiveDescriptor.java DirectiveProvider.java DummyDirective.java EncodeDirective.java EscapeDirective.java ForeachDirective.java GlobalDirective.java IfDirective.java IncludeDirective.java MacroDirective.java ParamDirective.java ProfileDirective.java PropertyDirective.java SetDirective.java SetblockDirective.java SilenceDirective.java TextDirective.java TypeDirective.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: AlternateDirective.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/directive/AlternateDirective.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** AlternateDirective.java 11 Nov 2002 19:22:36 -0000 1.11 --- AlternateDirective.java 12 Jun 2003 00:47:44 -0000 1.12 *************** *** 19,34 **** * * See www.webmacro.org for more information on the WebMacro project. ! */ ! ! package org.webmacro.directive; ! ! import java.io.*; ! import java.util.*; ! ! import org.webmacro.*; ! import org.webmacro.engine.BuildContext; ! import org.webmacro.engine.BuildException; ! import org.webmacro.engine.Variable; ! /** * <b>#alternate</b><p> --- 19,36 ---- * * See www.webmacro.org for more information on the WebMacro project. ! */ ! ! package org.webmacro.directive; ! ! import org.webmacro.*; ! import org.webmacro.engine.BuildContext; ! import org.webmacro.engine.BuildException; ! import org.webmacro.engine.Variable; ! ! import java.io.IOException; ! import java.util.ArrayList; ! import java.util.Iterator; ! import java.util.List; ! /** * <b>#alternate</b><p> *************** *** 60,165 **** * is evaluated, it will have the value "blue", and so on through the list. When it gets * to the end of the list, it wraps back around to the beginning. ! */ ! public class AlternateDirective extends Directive { ! ! private static final int ALTERNATE_TARGET = 1; ! private static final int ALTERNATE_THROUGH = 2; ! private static final int ALTERNATE_LIST = 3; ! ! private Variable target; ! private Object list; ! ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LValueArg(ALTERNATE_TARGET), ! new KeywordArg(ALTERNATE_THROUGH, "through"), ! new RValueArg(ALTERNATE_LIST) ! }; ! ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor("alternate", null, myArgs, null); ! ! public static DirectiveDescriptor getDescriptor() { ! return myDescr; ! } ! ! public Object build(DirectiveBuilder builder, ! BuildContext bc) ! throws BuildException { ! try { ! target = (Variable) builder.getArg(ALTERNATE_TARGET, bc); ! } ! catch (ClassCastException e) { ! throw new NotVariableBuildException(myDescr.name, e); ! } ! list = builder.getArg(ALTERNATE_LIST, bc); ! return this; ! } ! ! public void write(FastWriter out, Context context) ! throws PropertyException, IOException { ! Object l = null; ! ! try { ! if (list instanceof Macro) ! l = ((Macro) list).evaluate(context); ! else ! l = list; ! ! Iterator itr = context.getBroker()._propertyOperators.getIterator(l); ! ! target.setValue(context, new IteratorAlternator(itr)); ! } ! catch (Exception e) { ! String warning = "#alternate: list argument is not a list: " + l; ! writeWarning(warning, context, out); ! return; ! } ! } ! ! public void accept(TemplateVisitor v) { ! v.beginDirective(myDescr.name); ! v.visitDirectiveArg("AlternateTarget", target); ! v.visitDirectiveArg("AlternateList", list); ! v.endDirective(); ! } ! ! } ! ! abstract class Alternator implements Macro { ! ! public abstract Object evaluate(Context context); ! ! public void write(FastWriter out, Context context) throws PropertyException, IOException { ! Object o = evaluate(context); ! if (o != null) ! out.write(o.toString()); ! } ! } ! ! class IteratorAlternator extends Alternator { ! ! private Iterator itr; ! private List list; ! private int index = -1; ! ! public IteratorAlternator(Iterator itr) { ! this.itr = itr; ! this.list = new ArrayList(); ! } ! ! public Object evaluate(Context context) { ! Object o; ! if (index == -1 && itr.hasNext()) { ! o = itr.next(); ! list.add(o); ! } ! else { ! index++; ! if (index == list.size()) ! index = 0; ! o = list.get(index); ! } ! return o; ! } } --- 62,183 ---- * is evaluated, it will have the value "blue", and so on through the list. When it gets * to the end of the list, it wraps back around to the beginning. ! */ ! public class AlternateDirective extends Directive ! { ! ! private static final int ALTERNATE_TARGET = 1; ! private static final int ALTERNATE_THROUGH = 2; ! private static final int ALTERNATE_LIST = 3; ! ! private Variable target; ! private Object list; ! ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LValueArg(ALTERNATE_TARGET), ! new KeywordArg(ALTERNATE_THROUGH, "through"), ! new RValueArg(ALTERNATE_LIST) ! }; ! ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor("alternate", null, myArgs, null); ! ! public static DirectiveDescriptor getDescriptor () ! { ! return myDescr; ! } ! ! public Object build (DirectiveBuilder builder, ! BuildContext bc) ! throws BuildException ! { ! try ! { ! target = (Variable) builder.getArg(ALTERNATE_TARGET, bc); ! } ! catch (ClassCastException e) ! { ! throw new NotVariableBuildException(myDescr.name, e); ! } ! list = builder.getArg(ALTERNATE_LIST, bc); ! return this; ! } ! ! public void write (FastWriter out, Context context) ! throws PropertyException, IOException ! { ! Object l = null; ! ! try ! { ! if (list instanceof Macro) ! l = ((Macro) list).evaluate(context); ! else ! l = list; ! ! Iterator itr = context.getBroker()._propertyOperators.getIterator(l); ! ! target.setValue(context, new IteratorAlternator(itr)); ! } ! catch (Exception e) ! { ! String warning = "#alternate: list argument is not a list: " + l; ! writeWarning(warning, context, out); ! return; ! } ! } ! ! public void accept (TemplateVisitor v) ! { ! v.beginDirective(myDescr.name); ! v.visitDirectiveArg("AlternateTarget", target); ! v.visitDirectiveArg("AlternateList", list); ! v.endDirective(); ! } ! ! } ! ! abstract class Alternator implements Macro ! { ! ! public abstract Object evaluate (Context context); ! ! public void write (FastWriter out, Context context) throws PropertyException, IOException ! { ! Object o = evaluate(context); ! if (o != null) ! out.write(o.toString()); ! } ! } ! ! class IteratorAlternator extends Alternator ! { ! ! private Iterator itr; ! private List list; ! private int index = -1; ! ! public IteratorAlternator (Iterator itr) ! { ! this.itr = itr; ! this.list = new ArrayList(); ! } ! ! public Object evaluate (Context context) ! { ! Object o; ! if (index == -1 && itr.hasNext()) ! { ! o = itr.next(); ! list.add(o); ! } ! else ! { ! index++; ! if (index == list.size()) ! index = 0; ! o = list.get(index); ! } ! return o; ! } } Index: ArgsHolder.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/directive/ArgsHolder.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** ArgsHolder.java 11 Jun 2002 17:43:20 -0000 1.7 --- ArgsHolder.java 12 Jun 2003 00:47:44 -0000 1.8 *************** *** 35,112 **** */ ! public final class ArgsHolder implements DirectiveArgs { ! // The argument descriptors for the arguments we hold ! private Directive.ArgDescriptor[] args; ! // The parser will call setArg(), and we'll store them here. For ! // each argument in the argument list, the corresponding argument data ! // will be in the same index into buildArgs. ! private Object[] buildArgs; ! public ArgsHolder(Directive.ArgDescriptor[] args) { ! this.args = args; ! buildArgs = new Object[args.length]; ! } ! private final int findArgIndex(int id) ! throws BuildException { ! for (int i = 0; i < args.length; i++) { ! if (args[i].id == id) ! return i; ! } ! throw new BuildException("Invalid argument ID " + id + " requested "); ! } ! /** ! * Get the argument at the specified <code>index</code>. This is different than getting ! * an argument by it's <code>id</code> ! */ ! public Object getExactArg(int idx) throws BuildException { ! return buildArgs[idx]; ! } ! /** ! * How many arguments does this ArgsHolder have? ! */ ! public final int getArgCount() { ! return buildArgs.length; ! } ! /** ! * Retrieve the argument whose id is the specified id. ! */ ! public final Object getArg(int id) ! throws BuildException { ! int index = findArgIndex(id); ! return buildArgs[index]; ! } ! /** ! * Retrieve the argument whose id is the specified id, and if it is a ! * Builder, build it with the specified build context. ! */ ! public final Object getArg(int id, BuildContext bc) ! throws BuildException { ! int index = findArgIndex(id); ! Object o = buildArgs[index]; ! return (o instanceof Builder) ! ? ((Builder) o).build(bc) ! : o; ! } ! /** ! * Set the argument whose id is the specified id. If the argument has ! * already been set, it is overwritten. Generally not used by directives, ! * only used by the parser. ! */ ! public final void setArg(int id, Object o) ! throws BuildException { ! int index = findArgIndex(id); ! buildArgs[index] = o; ! } } --- 35,121 ---- */ ! public final class ArgsHolder implements DirectiveArgs ! { ! // The argument descriptors for the arguments we hold ! private Directive.ArgDescriptor[] args; ! // The parser will call setArg(), and we'll store them here. For ! // each argument in the argument list, the corresponding argument data ! // will be in the same index into buildArgs. ! private Object[] buildArgs; ! public ArgsHolder (Directive.ArgDescriptor[] args) ! { ! this.args = args; ! buildArgs = new Object[args.length]; ! } ! private final int findArgIndex (int id) ! throws BuildException ! { ! for (int i = 0; i < args.length; i++) ! { ! if (args[i].id == id) ! return i; ! } ! throw new BuildException("Invalid argument ID " + id + " requested "); ! } ! /** ! * Get the argument at the specified <code>index</code>. This is different than getting ! * an argument by it's <code>id</code> ! */ ! public Object getExactArg (int idx) throws BuildException ! { ! return buildArgs[idx]; ! } ! /** ! * How many arguments does this ArgsHolder have? ! */ ! public final int getArgCount () ! { ! return buildArgs.length; ! } ! /** ! * Retrieve the argument whose id is the specified id. ! */ ! public final Object getArg (int id) ! throws BuildException ! { ! int index = findArgIndex(id); ! return buildArgs[index]; ! } ! /** ! * Retrieve the argument whose id is the specified id, and if it is a ! * Builder, build it with the specified build context. ! */ ! public final Object getArg (int id, BuildContext bc) ! throws BuildException ! { ! int index = findArgIndex(id); ! Object o = buildArgs[index]; ! return (o instanceof Builder) ! ? ((Builder) o).build(bc) ! : o; ! } ! /** ! * Set the argument whose id is the specified id. If the argument has ! * already been set, it is overwritten. Generally not used by directives, ! * only used by the parser. ! */ ! public final void setArg (int id, Object o) ! throws BuildException ! { ! int index = findArgIndex(id); ! buildArgs[index] = o; ! } } Index: AttributeDirective.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/directive/AttributeDirective.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** AttributeDirective.java 11 Jun 2002 17:43:20 -0000 1.7 --- AttributeDirective.java 12 Jun 2003 00:47:44 -0000 1.8 *************** *** 23,28 **** package org.webmacro.directive; - import java.io.*; - import org.webmacro.Context; import org.webmacro.FastWriter; --- 23,26 ---- *************** *** 32,35 **** --- 30,35 ---- import org.webmacro.engine.Variable; + import java.io.IOException; + /** * The #attribute directive allows you to set a template attribute such *************** *** 37,84 **** */ ! public class AttributeDirective extends Directive { ! private static final int ATTRIBUTE_TARGET = 1; ! private static final int ATTRIBUTE_RESULT = 2; ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LValueArg(ATTRIBUTE_TARGET), ! new AssignmentArg(), ! new RValueArg(ATTRIBUTE_RESULT) ! }; ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor(null, null, myArgs, null); ! public static DirectiveDescriptor getDescriptor() { ! return myDescr; ! } ! public Object build(DirectiveBuilder builder, ! BuildContext bc) ! throws BuildException { ! Variable target = null; ! try { ! target = (Variable) builder.getArg(ATTRIBUTE_TARGET, bc); ! Object result = builder.getArg(ATTRIBUTE_RESULT, bc); ! if (!target.isSimpleName()) ! throw new NotSimpleVariableBuildException(myDescr.name); ! target.setValue(bc, result); ! } ! catch (ClassCastException e) { ! throw new NotVariableBuildException(myDescr.name, e); ! } ! catch (PropertyException e) { ! throw new BuildException("#attribute: Exception setting variable " ! + target.toString(), e); ! } ! return null; ! } ! public void write(FastWriter out, Context context) ! throws PropertyException, IOException { ! } } --- 37,91 ---- */ ! public class AttributeDirective extends Directive ! { ! private static final int ATTRIBUTE_TARGET = 1; ! private static final int ATTRIBUTE_RESULT = 2; ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LValueArg(ATTRIBUTE_TARGET), ! new AssignmentArg(), ! new RValueArg(ATTRIBUTE_RESULT) ! }; ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor(null, null, myArgs, null); ! public static DirectiveDescriptor getDescriptor () ! { ! return myDescr; ! } ! public Object build (DirectiveBuilder builder, ! BuildContext bc) ! throws BuildException ! { ! Variable target = null; ! try ! { ! target = (Variable) builder.getArg(ATTRIBUTE_TARGET, bc); ! Object result = builder.getArg(ATTRIBUTE_RESULT, bc); ! if (!target.isSimpleName()) ! throw new NotSimpleVariableBuildException(myDescr.name); ! target.setValue(bc, result); ! } ! catch (ClassCastException e) ! { ! throw new NotVariableBuildException(myDescr.name, e); ! } ! catch (PropertyException e) ! { ! throw new BuildException("#attribute: Exception setting variable " ! + target.toString(), e); ! } ! return null; ! } ! public void write (FastWriter out, Context context) ! throws PropertyException, IOException ! { ! } } Index: BeanDirective.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/directive/BeanDirective.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** BeanDirective.java 20 Dec 2002 02:25:24 -0000 1.11 --- BeanDirective.java 12 Jun 2003 00:47:44 -0000 1.12 *************** *** 28,396 **** */ - import java.io.*; - import java.util.*; - import org.webmacro.*; import org.webmacro.engine.*; ! public class BeanDirective extends Directive { ! private static final int BEAN_TARGET = 1; ! private static final int BEAN_CLASS_NAME = 2; ! private static final int BEAN_SCOPE = 3; ! private static final int BEAN_SCOPE_GLOBAL = 4; ! private static final int BEAN_SCOPE_APPLICATION = 5; ! private static final int BEAN_SCOPE_SESSION = 6; ! private static final int BEAN_SCOPE_PAGE = 7; ! private static final int BEAN_INITARGS = 8; ! private static final int BEAN_INITARGS_VAL = 9; ! private static final int BEAN_TYPE_STATIC = 10; ! private static final int BEAN_ON_NEW = 11; ! private static final int BEAN_ON_NEW_BLOCK = 12; ! private static final UndefinedMacro UNDEF = UndefinedMacro.getInstance(); ! private static int[] BEAN_SCOPES = { ! BEAN_SCOPE_GLOBAL, BEAN_SCOPE_APPLICATION, ! BEAN_SCOPE_SESSION, BEAN_SCOPE_PAGE ! }; ! private Variable target; ! private String targetName; ! private String _className; ! private int scope; ! private boolean isStaticClass; ! private Object initArgObj; ! private Object[] initArgs; ! private Block onNewBlock; ! private Log _log; ! private List _impliedPackages; ! private List _allowedPackages; ! private Class _class; ! private BeanConf beanConf; ! private Broker _broker; ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LValueArg(BEAN_TARGET), ! new AssignmentArg(), ! new QuotedStringArg(BEAN_CLASS_NAME), ! new OptionalGroup(3), ! new KeywordArg(BEAN_SCOPE, "scope"), ! new AssignmentArg(), ! new SingleOptionChoice(5), ! new OptionalGroup(1), ! new KeywordArg(BEAN_SCOPE_GLOBAL, "global"), ! new OptionalGroup(1), ! new KeywordArg(BEAN_SCOPE_APPLICATION, "application"), ! new OptionalGroup(1), ! new KeywordArg(BEAN_SCOPE_SESSION, "session"), ! new OptionalGroup(1), ! new KeywordArg(BEAN_SCOPE_PAGE, "page"), ! new OptionalGroup(1), ! new KeywordArg(BEAN_TYPE_STATIC, "static"), ! new OptionalGroup(2), ! new KeywordArg(BEAN_INITARGS, "initArgs"), ! new RValueArg(BEAN_INITARGS_VAL), ! new OptionalGroup(2), ! new KeywordArg(BEAN_ON_NEW, "onNew"), ! new BlockArg(BEAN_ON_NEW_BLOCK) ! }; ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor("bean", null, myArgs, null); ! public static DirectiveDescriptor getDescriptor() { ! return myDescr; ! } ! public BeanDirective() { ! } ! public Object build(DirectiveBuilder builder, BuildContext bc) ! throws BuildException { ! _broker = bc.getBroker(); ! _log = _broker.getLog("directive"); ! // BeanConf object is created by the init method when this directive ! // is registered by the DirectiveProvider ! beanConf = (BeanConf) _broker.getBrokerLocal("BeanDirective.Conf"); ! if (beanConf == null) { ! throw new BuildException( ! "Error building the #bean directive. The directive has not been properly initialized!"); ! } ! try { ! target = (Variable) builder.getArg(BEAN_TARGET, bc); ! } ! catch (ClassCastException e) { ! throw new NotVariableBuildException(myDescr.name, e); ! } ! targetName = target.getName(); ! _className = (String) builder.getArg(BEAN_CLASS_NAME, bc); ! _class = classForName(_className); ! // check if bean is declared as static ! // this implies global scope and no constructor invocation ! isStaticClass = (builder.getArg(BEAN_TYPE_STATIC) != null); ! if (isStaticClass) ! scope = BEAN_SCOPE_GLOBAL; ! else { ! scope = getScope(builder, bc); ! // initArgs is only valid for non-static beans ! initArgObj = builder.getArg(BEAN_INITARGS_VAL); ! if (initArgObj instanceof Builder) ! initArgObj = ((Builder) initArgObj).build(bc); ! } ! onNewBlock = (Block) builder.getArg(BEAN_ON_NEW_BLOCK, bc); ! _log.debug("BeanDirective, target=" + target ! + ", className=" + _className + ", scope=" + scope ! + ", isStaticClass=" + isStaticClass + ", initArgs=" + initArgObj); ! return this; ! } ! public void write(FastWriter out, Context context) ! throws PropertyException, IOException { ! Map globalBeans = BeanConf.globalBeans; ! Map appBeans = beanConf.appBeans; ! boolean isNew = false; ! try { ! while (initArgObj instanceof Macro && initArgObj != UNDEF) ! initArgObj = ((Macro) initArgObj).evaluate(context); ! // store init args in array ! if (initArgObj == null || initArgObj.getClass().isArray()) { ! initArgs = (Object[]) initArgObj; ! } ! else { ! initArgs = new Object[] { initArgObj }; ! } ! Object o = null; ! Class c = null; ! switch (scope) { ! case BEAN_SCOPE_GLOBAL: ! synchronized (globalBeans) { ! o = globalBeans.get(targetName); ! if (o == null) { ! if (isStaticClass) { ! c = context.getBroker().classForName(_className); ! o = new org.webmacro.engine.StaticClassWrapper(c); ! } ! else { ! //c = Class.forName(_className); ! //o = c.newInstance(); ! o = instantiate(_className, initArgs); ! } ! isNew = true; ! globalBeans.put(targetName, o); ! } ! } ! break; ! case BEAN_SCOPE_APPLICATION: ! synchronized (appBeans) { ! o = appBeans.get(targetName); ! if (o == null) { ! o = instantiate(_className, initArgs); ! isNew = true; ! appBeans.put(targetName, o); ! } ! } ! break; ! case BEAN_SCOPE_SESSION: ! javax.servlet.http.HttpSession session = ! (javax.servlet.http.HttpSession) context.getProperty("Session"); ! //if (context instanceof WebContext){ ! if (session != null) { ! synchronized (session) { ! o = session.getAttribute(targetName); ! if (o == null) { ! o = instantiate(_className, initArgs); ! isNew = true; ! session.setAttribute(targetName, o); ! } ! } ! } ! else { ! PropertyException e = new PropertyException( ! "#bean usage error: session scope is only valid with servlets!"); ! _broker.getEvaluationExceptionHandler().evaluate( ! target, context, e); ! } ! break; ! default: ! // make "page" the default scope ! //case BEAN_SCOPE_PAGE: ! // NOTE: page beans always overwrite anything in the context ! // with the same name ! o = instantiate(_className, initArgs); ! isNew = true; ! if (o != null) { ! Class[] paramTypes = {Context.class}; ! try { ! java.lang.reflect.Method m = o.getClass().getMethod("init", paramTypes); ! if (m != null) { ! Object[] args = {context}; ! m.invoke(o, args); ! } ! } ! catch (Exception e) { // ignore ! } ! } ! break; ! } ! _log.debug("BeanDirective: Class " + _className + " loaded."); ! target.setValue(context, o); ! } ! catch (PropertyException e) { ! this._broker.getEvaluationExceptionHandler().evaluate(target, context, e); ! } ! catch (Exception e) { ! String errorText = "BeanDirective: Unable to load bean " + target + " of type " + _className; ! writeWarning(errorText, context, out); ! } ! if (isNew && onNewBlock != null) ! onNewBlock.write(out, context); ! } ! public void accept(TemplateVisitor v) { ! v.beginDirective(myDescr.name); ! v.visitDirectiveArg("BeanTarget", target); ! v.visitDirectiveArg("BeanClass", _className); ! v.visitDirectiveArg("BeanScope", new Integer(scope)); ! v.visitDirectiveArg("BeanIsStatic", new Boolean(isStaticClass)); ! v.visitDirectiveArg("BeanInitArgs", initArgs); ! v.endDirective(); ! } ! private Object instantiate(String className, Object[] args) ! throws Exception { ! Class c = classForName(className); ! return instantiate(c, args); ! } ! private Object instantiate(Class c, Object[] args) ! throws Exception { ! // @@@ FIXME(BG): either use lastException or don't record it ! Object o = null; ! if (args == null) { ! o = c.newInstance(); ! } ! else { ! Exception lastException = null; ! java.lang.reflect.Constructor[] cons = c.getConstructors(); ! for (int i = 0; i < cons.length; i++) { ! if (cons[i].getParameterTypes().length == args.length) { ! // try to instantiate using this constructor ! try { ! o = cons[i].newInstance(args); ! break; // if successful, we're done! ! } ! catch (Exception e) { ! lastException = e; ! } } ! } ! if (o == null) { ! throw new InstantiationException( ! "Unable to construct object of type " + c.getName() ! + " using the supplied arguments: " ! + java.util.Arrays.asList(args).toString()); ! } ! } ! return o; ! } ! private static int getScope(DirectiveBuilder builder, BuildContext bc) throws org.webmacro.engine.BuildException { ! int scope = -1; ! for (int i = 0; i < BEAN_SCOPES.length; i++) { ! scope = BEAN_SCOPES[i]; ! if (builder.getArg(scope) != null) break; ! } ! return scope; ! } ! public static void init(Broker b) { ! // get configuration parameters ! synchronized (b) { ! BeanConf bCfg = new BeanConf(b); ! b.setBrokerLocal("BeanDirective.Conf", bCfg); ! Log log = b.getLog("directive"); ! log.debug("BeanDirective initialization - impliedPackages: " + bCfg.impliedPackages); ! log.debug("BeanDirective initialization - allowedPackages: " + bCfg.allowedPackages); ! } ! } ! private Class classForName(String className) throws BuildException { ! Class c = null; ! Exception except = null; ! try { ! c = _broker.classForName(className); ! } ! catch (Exception cnfe) { ! except = cnfe; ! // try with implied packages prepended ! for (int i = 0; i < beanConf.impliedPackages.size(); i++) { ! String s = (String) beanConf.impliedPackages.get(i); ! try { ! c = _broker.classForName(s + "." + className); ! break; } ! catch (Exception cnfe2) { ! except = cnfe2; } ! } ! if (c == null) { ! throw new BuildException("Unable to load class " + className, except); ! } ! } ! if (!beanConf.allowedPackages.isEmpty()) { ! // check if class is in a permitted package ! String pkg = c.getPackage().getName(); ! if (!beanConf.allowedPackages.contains(pkg)) { ! throw new BuildException( ! "You are not permitted to load classes from this package (" + pkg ! + "). Check the \"BeanDirective.AllowedPackages\" parameter in the WebMacro.properties file."); ! } ! } ! return c; ! } } ! class BeanConf { ! static Map globalBeans = new HashMap(20); ! Map appBeans = new HashMap(20); ! List impliedPackages; ! List allowedPackages; ! public BeanConf(Broker b) { ! String s = b.getSetting("BeanDirective.ImpliedPackages"); ! impliedPackages = Arrays.asList(org.webmacro.servlet.TextTool.split(s, ",")); ! s = b.getSetting("BeanDirective.AllowedPackages"); ! allowedPackages = Arrays.asList(org.webmacro.servlet.TextTool.split(s, ",")); ! } ! public Map getGlobalBeans() { ! return globalBeans; ! } ! public Map getAppBeans() { ! return appBeans; ! } ! public List getImpliedPackages() { ! return impliedPackages; ! } ! public List getAllowedPackages() { ! return allowedPackages; ! } } --- 28,457 ---- */ import org.webmacro.*; import org.webmacro.engine.*; ! import java.io.IOException; ! import java.util.Arrays; ! import java.util.HashMap; ! import java.util.List; ! import java.util.Map; ! public class BeanDirective extends Directive ! { ! private static final int BEAN_TARGET = 1; ! private static final int BEAN_CLASS_NAME = 2; ! private static final int BEAN_SCOPE = 3; ! private static final int BEAN_SCOPE_GLOBAL = 4; ! private static final int BEAN_SCOPE_APPLICATION = 5; ! private static final int BEAN_SCOPE_SESSION = 6; ! private static final int BEAN_SCOPE_PAGE = 7; ! private static final int BEAN_INITARGS = 8; ! private static final int BEAN_INITARGS_VAL = 9; ! private static final int BEAN_TYPE_STATIC = 10; ! private static final int BEAN_ON_NEW = 11; ! private static final int BEAN_ON_NEW_BLOCK = 12; ! private static final UndefinedMacro UNDEF = UndefinedMacro.getInstance(); ! private static int[] BEAN_SCOPES = { ! BEAN_SCOPE_GLOBAL, BEAN_SCOPE_APPLICATION, ! BEAN_SCOPE_SESSION, BEAN_SCOPE_PAGE ! }; ! private Variable target; ! private String targetName; ! private String _className; ! private int scope; ! private boolean isStaticClass; ! private Object initArgObj; ! private Object[] initArgs; ! private Block onNewBlock; ! private Log _log; ! private List _impliedPackages; ! private List _allowedPackages; ! private Class _class; ! private BeanConf beanConf; ! private Broker _broker; ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LValueArg(BEAN_TARGET), ! new AssignmentArg(), ! new QuotedStringArg(BEAN_CLASS_NAME), ! new OptionalGroup(3), ! new KeywordArg(BEAN_SCOPE, "scope"), ! new AssignmentArg(), ! new SingleOptionChoice(5), ! new OptionalGroup(1), ! new KeywordArg(BEAN_SCOPE_GLOBAL, "global"), ! new OptionalGroup(1), ! new KeywordArg(BEAN_SCOPE_APPLICATION, "application"), ! new OptionalGroup(1), ! new KeywordArg(BEAN_SCOPE_SESSION, "session"), ! new OptionalGroup(1), ! new KeywordArg(BEAN_SCOPE_PAGE, "page"), ! new OptionalGroup(1), ! new KeywordArg(BEAN_TYPE_STATIC, "static"), ! new OptionalGroup(2), ! new KeywordArg(BEAN_INITARGS, "initArgs"), ! new RValueArg(BEAN_INITARGS_VAL), ! new OptionalGroup(2), ! new KeywordArg(BEAN_ON_NEW, "onNew"), ! new BlockArg(BEAN_ON_NEW_BLOCK) ! }; ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor("bean", null, myArgs, null); ! public static DirectiveDescriptor getDescriptor () ! { ! return myDescr; ! } ! public BeanDirective () ! { ! } ! public Object build (DirectiveBuilder builder, BuildContext bc) ! throws BuildException ! { ! _broker = bc.getBroker(); ! _log = _broker.getLog("directive"); ! // BeanConf object is created by the init method when this directive ! // is registered by the DirectiveProvider ! beanConf = (BeanConf) _broker.getBrokerLocal("BeanDirective.Conf"); ! if (beanConf == null) ! { ! throw new BuildException( ! "Error building the #bean directive. The directive has not been properly initialized!"); ! } ! try ! { ! target = (Variable) builder.getArg(BEAN_TARGET, bc); ! } ! catch (ClassCastException e) ! { ! throw new NotVariableBuildException(myDescr.name, e); ! } ! targetName = target.getName(); ! _className = (String) builder.getArg(BEAN_CLASS_NAME, bc); ! _class = classForName(_className); ! // check if bean is declared as static ! // this implies global scope and no constructor invocation ! isStaticClass = (builder.getArg(BEAN_TYPE_STATIC) != null); ! if (isStaticClass) ! scope = BEAN_SCOPE_GLOBAL; ! else ! { ! scope = getScope(builder, bc); ! // initArgs is only valid for non-static beans ! initArgObj = builder.getArg(BEAN_INITARGS_VAL); ! if (initArgObj instanceof Builder) ! initArgObj = ((Builder) initArgObj).build(bc); ! } ! onNewBlock = (Block) builder.getArg(BEAN_ON_NEW_BLOCK, bc); ! _log.debug("BeanDirective, target=" + target ! + ", className=" + _className + ", scope=" + scope ! + ", isStaticClass=" + isStaticClass + ", initArgs=" + initArgObj); ! return this; ! } ! public void write (FastWriter out, Context context) ! throws PropertyException, IOException ! { ! Map globalBeans = BeanConf.globalBeans; ! Map appBeans = beanConf.appBeans; ! boolean isNew = false; ! try ! { ! while (initArgObj instanceof Macro && initArgObj != UNDEF) ! initArgObj = ((Macro) initArgObj).evaluate(context); ! // store init args in array ! if (initArgObj == null || initArgObj.getClass().isArray()) ! { ! initArgs = (Object[]) initArgObj; ! } ! else ! { ! initArgs = new Object[]{initArgObj}; ! } ! Object o = null; ! Class c = null; ! switch (scope) ! { ! case BEAN_SCOPE_GLOBAL: ! synchronized (globalBeans) ! { ! o = globalBeans.get(targetName); ! if (o == null) ! { ! if (isStaticClass) ! { ! c = context.getBroker().classForName(_className); ! o = new org.webmacro.engine.StaticClassWrapper(c); ! } ! else ! { ! //c = Class.forName(_className); ! //o = c.newInstance(); ! o = instantiate(_className, initArgs); ! } ! isNew = true; ! globalBeans.put(targetName, o); ! } ! } ! break; ! case BEAN_SCOPE_APPLICATION: ! synchronized (appBeans) ! { ! o = appBeans.get(targetName); ! if (o == null) ! { ! o = instantiate(_className, initArgs); ! isNew = true; ! appBeans.put(targetName, o); ! } ! } ! break; ! case BEAN_SCOPE_SESSION: ! javax.servlet.http.HttpSession session = ! (javax.servlet.http.HttpSession) context.getProperty("Session"); ! //if (context instanceof WebContext){ ! if (session != null) ! { ! synchronized (session) ! { ! o = session.getAttribute(targetName); ! if (o == null) ! { ! o = instantiate(_className, initArgs); ! isNew = true; ! session.setAttribute(targetName, o); ! } ! } ! } ! else ! { ! PropertyException e = new PropertyException( ! "#bean usage error: session scope is only valid with servlets!"); ! _broker.getEvaluationExceptionHandler().evaluate( ! target, context, e); ! } ! break; ! default: ! // make "page" the default scope ! //case BEAN_SCOPE_PAGE: ! // NOTE: page beans always overwrite anything in the context ! // with the same name ! o = instantiate(_className, initArgs); ! isNew = true; ! if (o != null) ! { ! Class[] paramTypes = {Context.class}; ! try ! { ! java.lang.reflect.Method m = o.getClass().getMethod("init", paramTypes); ! if (m != null) ! { ! Object[] args = {context}; ! m.invoke(o, args); ! } ! } ! catch (Exception e) ! { // ignore ! } ! } ! break; ! } ! _log.debug("BeanDirective: Class " + _className + " loaded."); ! target.setValue(context, o); ! } ! catch (PropertyException e) ! { ! this._broker.getEvaluationExceptionHandler().evaluate(target, context, e); ! } ! catch (Exception e) ! { ! String errorText = "BeanDirective: Unable to load bean " + target + " of type " + _className; ! writeWarning(errorText, context, out); ! } ! if (isNew && onNewBlock != null) ! onNewBlock.write(out, context); ! } ! public void accept (TemplateVisitor v) ! { ! v.beginDirective(myDescr.name); ! v.visitDirectiveArg("BeanTarget", target); ! v.visitDirectiveArg("BeanClass", _className); ! v.visitDirectiveArg("BeanScope", new Integer(scope)); ! v.visitDirectiveArg("BeanIsStatic", new Boolean(isStaticClass)); ! v.visitDirectiveArg("BeanInitArgs", initArgs); ! v.endDirective(); ! } ! private Object instantiate (String className, Object[] args) ! throws Exception ! { ! Class c = classForName(className); ! return instantiate(c, args); ! } ! ! private Object instantiate (Class c, Object[] args) ! throws Exception ! { ! // @@@ FIXME(BG): either use lastException or don't record it ! Object o = null; ! if (args == null) ! { ! o = c.newInstance(); ! } ! else ! { ! Exception lastException = null; ! java.lang.reflect.Constructor[] cons = c.getConstructors(); ! for (int i = 0; i < cons.length; i++) ! { ! if (cons[i].getParameterTypes().length == args.length) ! { ! // try to instantiate using this constructor ! try ! { ! o = cons[i].newInstance(args); ! break; // if successful, we're done! ! } ! catch (Exception e) ! { ! lastException = e; ! } ! } } ! if (o == null) ! { ! throw new InstantiationException( ! "Unable to construct object of type " + c.getName() ! + " using the supplied arguments: " ! + java.util.Arrays.asList(args).toString()); ! } ! } ! return o; ! } ! private static int getScope (DirectiveBuilder builder, BuildContext bc) throws org.webmacro.engine.BuildException ! { ! int scope = -1; ! for (int i = 0; i < BEAN_SCOPES.length; i++) ! { ! scope = BEAN_SCOPES[i]; ! if (builder.getArg(scope) != null) break; ! } ! return scope; ! } ! public static void init (Broker b) ! { ! // get configuration parameters ! synchronized (b) ! { ! BeanConf bCfg = new BeanConf(b); ! b.setBrokerLocal("BeanDirective.Conf", bCfg); ! Log log = b.getLog("directive"); ! log.debug("BeanDirective initialization - impliedPackages: " + bCfg.impliedPackages); ! log.debug("BeanDirective initialization - allowedPackages: " + bCfg.allowedPackages); ! } ! } ! private Class classForName (String className) throws BuildException ! { ! Class c = null; ! Exception except = null; ! try ! { ! c = _broker.classForName(className); ! } ! catch (Exception cnfe) ! { ! except = cnfe; ! // try with implied packages prepended ! for (int i = 0; i < beanConf.impliedPackages.size(); i++) ! { ! String s = (String) beanConf.impliedPackages.get(i); ! try ! { ! c = _broker.classForName(s + "." + className); ! break; ! } ! catch (Exception cnfe2) ! { ! except = cnfe2; ! } } ! if (c == null) ! { ! throw new BuildException("Unable to load class " + className, except); } ! } ! if (!beanConf.allowedPackages.isEmpty()) ! { ! // check if class is in a permitted package ! String pkg = c.getPackage().getName(); ! if (!beanConf.allowedPackages.contains(pkg)) ! { ! throw new BuildException( ! "You are not permitted to load classes from this package (" + pkg ! + "). Check the \"BeanDirective.AllowedPackages\" parameter in the WebMacro.properties file."); ! } ! } ! return c; ! } } ! class BeanConf ! { ! static Map globalBeans = new HashMap(20); ! Map appBeans = new HashMap(20); ! List impliedPackages; ! List allowedPackages; ! public BeanConf (Broker b) ! { ! String s = b.getSetting("BeanDirective.ImpliedPackages"); ! impliedPackages = Arrays.asList(org.webmacro.servlet.TextTool.split(s, ",")); ! s = b.getSetting("BeanDirective.AllowedPackages"); ! allowedPackages = Arrays.asList(org.webmacro.servlet.TextTool.split(s, ",")); ! } ! public Map getGlobalBeans () ! { ! return globalBeans; ! } ! public Map getAppBeans () ! { ! return appBeans; ! } ! public List getImpliedPackages () ! { ! return impliedPackages; ! } ! public List getAllowedPackages () ! { ! return allowedPackages; ! } } Index: CommentDirective.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/directive/CommentDirective.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** CommentDirective.java 11 Jun 2002 17:43:20 -0000 1.6 --- CommentDirective.java 12 Jun 2003 00:47:44 -0000 1.7 *************** *** 23,28 **** package org.webmacro.directive; - import java.io.*; - import org.webmacro.Context; import org.webmacro.FastWriter; --- 23,26 ---- *************** *** 32,64 **** import org.webmacro.engine.BuildException; ! public class CommentDirective extends Directive { ! private static final int COMMENT_BLOCK = 1; ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LiteralBlockArg(COMMENT_BLOCK) ! }; ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor("comment", null, myArgs, null); ! public static DirectiveDescriptor getDescriptor() { ! return myDescr; ! } ! public Object build(DirectiveBuilder builder, ! BuildContext bc) ! throws BuildException { ! return null; ! } ! public void write(FastWriter out, Context context) ! throws PropertyException, IOException { ! } ! public void accept(TemplateVisitor v) { ! v.beginDirective(myDescr.name); ! v.endDirective(); ! } } --- 30,69 ---- import org.webmacro.engine.BuildException; ! import java.io.IOException; ! public class CommentDirective extends Directive ! { ! private static final int COMMENT_BLOCK = 1; ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LiteralBlockArg(COMMENT_BLOCK) ! }; ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor("comment", null, myArgs, null); ! public static DirectiveDescriptor getDescriptor () ! { ! return myDescr; ! } ! public Object build (DirectiveBuilder builder, ! BuildContext bc) ! throws BuildException ! { ! return null; ! } ! public void write (FastWriter out, Context context) ! throws PropertyException, IOException ! { ! } ! ! public void accept (TemplateVisitor v) ! { ! v.beginDirective(myDescr.name); ! v.endDirective(); ! } } Index: CountDirective.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/directive/CountDirective.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** CountDirective.java 11 Nov 2002 19:22:36 -0000 1.4 --- CountDirective.java 12 Jun 2003 00:47:44 -0000 1.5 *************** *** 22,28 **** package org.webmacro.directive; ! import org.webmacro.directive.*; ! import org.webmacro.engine.*; ! import org.webmacro.*; import java.io.IOException; --- 22,33 ---- package org.webmacro.directive; ! import org.webmacro.Context; ! import org.webmacro.FastWriter; ! import org.webmacro.Macro; ! import org.webmacro.PropertyException; ! import org.webmacro.engine.Block; ! import org.webmacro.engine.BuildContext; ! import org.webmacro.engine.BuildException; ! import org.webmacro.engine.Variable; import java.io.IOException; *************** *** 34,38 **** * @since 1.1b1 */ ! public class CountDirective extends org.webmacro.directive.Directive { private static final int COUNT_ITERATOR = 1; --- 39,44 ---- * @since 1.1b1 */ ! public class CountDirective extends org.webmacro.directive.Directive ! { private static final int COUNT_ITERATOR = 1; *************** *** 59,63 **** private static final DirectiveDescriptor _desc = new DirectiveDescriptor("count", null, _args, null); ! public static DirectiveDescriptor getDescriptor() { return _desc; } --- 65,70 ---- private static final DirectiveDescriptor _desc = new DirectiveDescriptor("count", null, _args, null); ! public static DirectiveDescriptor getDescriptor () ! { return _desc; } *************** *** 71,78 **** private int _start, _end, _step = 1; ! public Object build(DirectiveBuilder builder, BuildContext bc) throws BuildException { ! try { _iterator = (Variable) builder.getArg(COUNT_ITERATOR, bc); ! } catch (ClassCastException e) { throw new Directive.NotVariableBuildException(_desc.name, e); } --- 78,89 ---- private int _start, _end, _step = 1; ! public Object build (DirectiveBuilder builder, BuildContext bc) throws BuildException ! { ! try ! { _iterator = (Variable) builder.getArg(COUNT_ITERATOR, bc); ! } ! catch (ClassCastException e) ! { throw new Directive.NotVariableBuildException(_desc.name, e); } *************** *** 83,109 **** // attempt to go ahead and force the start, end, and step values into primitive ints ! if (_objStart != null) { ! if (_objStart instanceof Number) { _start = ((Number) _objStart).intValue(); _objStart = null; ! } else if (_objStart instanceof String) { _start = Integer.parseInt((String) _objStart); _objStart = null; } } ! if (_objEnd != null) { ! if (_objEnd instanceof Number) { _end = ((Number) _objEnd).intValue(); _objEnd = null; ! } else if (_objEnd instanceof String) { _end = Integer.parseInt((String) _objEnd); _objEnd = null; } } ! if (_objStep != null) { ! if (_objStep instanceof Number) { _step = ((Number) _objStep).intValue(); _objStep = null; ! } else if (_objStep instanceof String) { _step = Integer.parseInt((String) _objStep); _objStep = null; --- 94,132 ---- // attempt to go ahead and force the start, end, and step values into primitive ints ! if (_objStart != null) ! { ! if (_objStart instanceof Number) ! { _start = ((Number) _objStart).intValue(); _objStart = null; ! } ! else if (_objStart instanceof String) ! { _start = Integer.parseInt((String) _objStart); _objStart = null; } } ! if (_objEnd != null) ! { ! if (_objEnd instanceof Number) ! { _end = ((Number) _objEnd).intValue(); _objEnd = null; ! } ! else if (_objEnd instanceof String) ! { _end = Integer.parseInt((String) _objEnd); _objEnd = null; } } ! if (_objStep != null) ! { ! if (_objStep instanceof Number) ! { _step = ((Number) _objStep).intValue(); _objStep = null; ! } ! else if (_objStep instanceof String) ! { _step = Integer.parseInt((String) _objStep); _objStep = null; *************** *** 114,129 **** } ! public void write(FastWriter out, Context context) throws PropertyException, IOException { ! int start=_start, end=_end, step = _step; Object tmp; // if necessary, do run-time evaluation of our // start, end, and step objects. ! if ( (tmp = _objStart) != null) { while (tmp instanceof Macro) tmp = ((Macro) tmp).evaluate(context); if (tmp != null) start = Integer.parseInt(tmp.toString()); ! else { writeWarning("#count: Starting value cannot be null. Not counting", context, out); return; --- 137,155 ---- } ! public void write (FastWriter out, Context context) throws PropertyException, IOException ! { ! int start = _start, end = _end, step = _step; Object tmp; // if necessary, do run-time evaluation of our // start, end, and step objects. ! if ((tmp = _objStart) != null) ! { while (tmp instanceof Macro) tmp = ((Macro) tmp).evaluate(context); if (tmp != null) start = Integer.parseInt(tmp.toString()); ! else ! { writeWarning("#count: Starting value cannot be null. Not counting", context, out); return; *************** *** 131,140 **** } ! if ( (tmp = _objEnd) != null) { while (tmp instanceof Macro) tmp = ((Macro) tmp).evaluate(context); if (tmp != null) end = Integer.parseInt(tmp.toString()); ! else { writeWarning("#count: Ending value cannot be null. Not counting", context, out); return; --- 157,168 ---- } ! if ((tmp = _objEnd) != null) ! { while (tmp instanceof Macro) tmp = ((Macro) tmp).evaluate(context); if (tmp != null) end = Integer.parseInt(tmp.toString()); ! else ! { writeWarning("#count: Ending value cannot be null. Not counting", context, out); return; *************** *** 142,151 **** } ! if ( (tmp = _objStep) != null) { while (tmp instanceof Macro) tmp = ((Macro) tmp).evaluate(context); if (tmp != null) step = Integer.parseInt(tmp.toString()); ! else { writeWarning("#count: Starting value cannot be null. Not counting", context, out); return; --- 170,181 ---- } ! if ((tmp = _objStep) != null) ! { while (tmp instanceof Macro) tmp = ((Macro) tmp).evaluate(context); if (tmp != null) step = Integer.parseInt(tmp.toString()); ! else ! { writeWarning("#count: Starting value cannot be null. Not counting", context, out); return; *************** *** 153,167 **** } ! if (step > 0) { ! for (; start<=end; start+=step) { _iterator.setValue(context, new Integer(start)); _body.write(out, context); } ! } else if (step < 0) { ! for (; start>=end; start+=step) { _iterator.setValue(context, new Integer(start)); _body.write(out, context); } ! } else { writeWarning("#count: step cannot be 0. Not counting", context, out); } --- 183,204 ---- } ! if (step > 0) ! { ! for (; start <= end; start += step) ! { _iterator.setValue(context, new Integer(start)); _body.write(out, context); } ! } ! else if (step < 0) ! { ! for (; start >= end; start += step) ! { _iterator.setValue(context, new Integer(start)); _body.write(out, context); } ! } ! else ! { writeWarning("#count: step cannot be 0. Not counting", context, out); } Index: DefaultDirective.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/directive/DefaultDirective.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** DefaultDirective.java 11 Nov 2002 04:26:12 -0000 1.4 --- DefaultDirective.java 12 Jun 2003 00:47:44 -0000 1.5 *************** *** 23,28 **** package org.webmacro.directive; - import java.io.*; - import org.webmacro.*; import org.webmacro.engine.BuildContext; --- 23,26 ---- *************** *** 30,105 **** import org.webmacro.engine.Variable; ! public class DefaultDirective extends Directive { ! private static final int DEFAULT_TARGET = 1; ! private static final int DEFAULT_TO = 2; ! private static final int DEFAULT_RESULT = 3; ! private Variable target; ! private Object result; ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! new LValueArg(DEFAULT_TARGET), ! new OptionalGro... [truncated message content] |
Update of /cvsroot/webmacro/webmacro/src/org/webmacro In directory sc8-pr-cvs1:/tmp/cvs-serv6675/src/org/webmacro Modified Files: Broker.java Context.java ContextException.java ContextTool.java FastWriter.java Filter.java FilterTool.java Flags.java InitException.java InvalidContextException.java InvalidTypeException.java Log.java Macro.java NotFoundException.java PropertyException.java Provider.java ResourceException.java RethrowableException.java RethrowableRuntimeException.java Template.java TemplateException.java TemplateVisitor.java UnsettableException.java Visitable.java WM.java WMConstants.java WebMacro.java WebMacroException.java WebMacroRuntimeException.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: Broker.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Broker.java,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** Broker.java 3 Apr 2003 18:11:19 -0000 1.34 --- Broker.java 12 Jun 2003 00:47:43 -0000 1.35 *************** *** 20,23 **** --- 20,29 ---- package org.webmacro; + import org.webmacro.engine.*; + import org.webmacro.profile.Profile; + import org.webmacro.profile.ProfileCategory; + import org.webmacro.profile.ProfileSystem; + import org.webmacro.util.*; + import java.io.*; [...1690 lines suppressed...] ! String line; ! while ((line = in.readLine()) != null) ! { ! int space = line.indexOf(' '); ! String type = line.substring(0, space); ! String name = line.substring(space + 1); ! System.out.println("broker.get(\"" + type + "\", \"" ! + name + "\"):"); ! Object o = broker.get(type, name); ! System.out.println("RESULT:"); ! System.out.println(o.toString()); ! } ! } ! catch (Exception e) ! { ! e.printStackTrace(); ! } ! } } Index: Context.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Context.java,v retrieving revision 1.60 retrieving revision 1.61 diff -C2 -d -r1.60 -r1.61 *** Context.java 21 May 2003 23:01:46 -0000 1.60 --- Context.java 12 Jun 2003 00:47:43 -0000 1.61 *************** *** 24,32 **** package org.webmacro; import java.util.*; - import java.lang.reflect.*; - import org.webmacro.util.*; - import org.webmacro.profile.*; - import org.webmacro.engine.*; /** --- 24,36 ---- [...1588 lines suppressed...] ! public final void put (Object o, char c) ! { ! put(o, new Character(c)); ! } ! ! public final void put (Object o, float f) ! { ! put(o, new Float(f)); ! } ! ! public final void put (Object o, double d) ! { ! put(o, new Double(d)); ! } ! ! public final void put (Object o, boolean b) ! { ! put(o, new Boolean(b)); ! } } Index: ContextException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/ContextException.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ContextException.java 11 Jun 2002 17:43:20 -0000 1.5 --- ContextException.java 12 Jun 2003 00:47:44 -0000 1.6 *************** *** 29,45 **** * was some problem with the way the Context was used. */ ! public class ContextException extends WebMacroException { ! public ContextException() { ! super(); ! } ! public ContextException(String reason) { ! super(reason); ! } ! public ContextException(String reason, Throwable e) { ! super(reason, e); ! } } --- 29,49 ---- * was some problem with the way the Context was used. */ ! public class ContextException extends WebMacroException ! { ! public ContextException () ! { ! super(); ! } ! public ContextException (String reason) ! { ! super(reason); ! } ! public ContextException (String reason, Throwable e) ! { ! super(reason, e); ! } } Index: ContextTool.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/ContextTool.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** ContextTool.java 11 Jun 2002 17:43:20 -0000 1.7 --- ContextTool.java 12 Jun 2003 00:47:44 -0000 1.8 *************** *** 28,48 **** * with the generation of views. */ ! public interface ContextTool { ! /** ! * A new tool object will be instantiated per-request by calling ! * this method. A ContextTool is effectively a factory used to ! * create objects for use in templates. Some tools may simply return ! * themselves from this method; others may instantiate new objects ! * to hold the per-request state. ! */ ! public Object init(Context c) throws PropertyException; ! /** ! * At the end of processing this method will be called to ! * return the object generated by init(), in case it needs ! * to be recycled or otherwise cleaned up. ! */ ! public void destroy(Object o); } --- 28,49 ---- * with the generation of views. */ ! public interface ContextTool ! { ! /** ! * A new tool object will be instantiated per-request by calling ! * this method. A ContextTool is effectively a factory used to ! * create objects for use in templates. Some tools may simply return ! * themselves from this method; others may instantiate new objects ! * to hold the per-request state. ! */ ! public Object init (Context c) throws PropertyException; ! /** ! * At the end of processing this method will be called to ! * return the object generated by init(), in case it needs ! * to be recycled or otherwise cleaned up. ! */ ! public void destroy (Object o); } Index: FastWriter.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/FastWriter.java,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** FastWriter.java 17 Dec 2002 06:45:29 -0000 1.28 --- FastWriter.java 12 Jun 2003 00:47:44 -0000 1.29 *************** *** 24,30 **** package org.webmacro; - import java.io.*; - import java.util.*; - import org.webmacro.util.ByteBufferOutputStream; import org.webmacro.util.Encoder; --- 24,27 ---- *************** *** 32,35 **** [...1073 lines suppressed...] ! { ! obj = _pool.remove(0); ! _size--; ! } ! } ! return obj; ! } ! public void put (Object fw) ! { ! if (_size < _maxSize) ! { // not rqrd to be t.s. perfect ! synchronized (_pool) ! { ! _pool.add(fw); ! _size++; ! } ! } ! } } Index: Filter.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Filter.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Filter.java 11 Jun 2002 17:43:20 -0000 1.5 --- Filter.java 12 Jun 2003 00:47:44 -0000 1.6 *************** *** 35,63 **** * then it must determine how $Customer.Name is to be handled. */ ! public interface Filter { ! /** ! * Return the Filter which should be used to handle a ! * sub-property. Three options are available here: return a ! * null to indicate no filtering, return self to indicate ! * the same filtering, or return a different Filter to ! * indicate different handling for the sub-property. ! * @param name the name of the sub-property to be filtered ! * @return the Filter to be used for the sub-property, or null ! */ ! public Filter getFilter(String name); ! /** ! * Instantiate a new filter. There are several options for the ! * return value of this method: return null to drop the Macro ! * from the input stream entirely; return the Macro itself to ! * avoid filtering this particular case, or return some new ! * Macro to replace the supplied Macro. The expectation is that ! * the returned Macro will execute the original and apply some ! * post-processing to it. ! * @param source the Macro which this filter will post-process ! * @return the Macro wrapper to be executed in place of source ! */ ! public Macro getMacro(Macro source); } --- 35,64 ---- * then it must determine how $Customer.Name is to be handled. */ ! public interface Filter ! { ! /** ! * Return the Filter which should be used to handle a ! * sub-property. Three options are available here: return a ! * null to indicate no filtering, return self to indicate ! * the same filtering, or return a different Filter to ! * indicate different handling for the sub-property. ! * @param name the name of the sub-property to be filtered ! * @return the Filter to be used for the sub-property, or null ! */ ! public Filter getFilter (String name); ! /** ! * Instantiate a new filter. There are several options for the ! * return value of this method: return null to drop the Macro ! * from the input stream entirely; return the Macro itself to ! * avoid filtering this particular case, or return some new ! * Macro to replace the supplied Macro. The expectation is that ! * the returned Macro will execute the original and apply some ! * post-processing to it. ! * @param source the Macro which this filter will post-process ! * @return the Macro wrapper to be executed in place of source ! */ ! public Macro getMacro (Macro source); } Index: FilterTool.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/FilterTool.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FilterTool.java 11 Jun 2002 17:43:20 -0000 1.3 --- FilterTool.java 12 Jun 2003 00:47:44 -0000 1.4 *************** *** 35,63 **** * then it must determine how $Customer.Name is to be handled. */ ! public interface FilterTool { ! /** ! * Return the FilterTool which should be used to handle a ! * sub-property. Three options are available here: return a ! * null to indicate no filtering, return self to indicate ! * the same filtering, or return a different FilterTool to ! * indicate different handling for the sub-property. ! * @param name the name of the sub-property to be filtered ! * @return the FilterTool to be used for the sub-property, or null ! */ ! public FilterTool getFilterTool(String name); ! /** ! * Instantiate a new filter. There are several options for the ! * return value of this method: return null to drop the Macro ! * from the input stream entirely; return the Macro itself to ! * avoid filtering this particular case, or return some new ! * Macro to replace the supplied Macro. The expectation is that ! * the returned Macro will execute the original and apply some ! * post-processing to it. ! * @param source the Macro which this filter will post-process ! * @return the Macro wrapper to be executed in place of source ! */ ! public Macro getFilter(Macro source); } --- 35,64 ---- * then it must determine how $Customer.Name is to be handled. */ ! public interface FilterTool ! { ! /** ! * Return the FilterTool which should be used to handle a ! * sub-property. Three options are available here: return a ! * null to indicate no filtering, return self to indicate ! * the same filtering, or return a different FilterTool to ! * indicate different handling for the sub-property. ! * @param name the name of the sub-property to be filtered ! * @return the FilterTool to be used for the sub-property, or null ! */ ! public FilterTool getFilterTool (String name); ! /** ! * Instantiate a new filter. There are several options for the ! * return value of this method: return null to drop the Macro ! * from the input stream entirely; return the Macro itself to ! * avoid filtering this particular case, or return some new ! * Macro to replace the supplied Macro. The expectation is that ! * the returned Macro will execute the original and apply some ! * post-processing to it. ! * @param source the Macro which this filter will post-process ! * @return the Macro wrapper to be executed in place of source ! */ ! public Macro getFilter (Macro source); } Index: Flags.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Flags.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Flags.java 11 Jun 2002 17:43:20 -0000 1.3 --- Flags.java 12 Jun 2003 00:47:44 -0000 1.4 *************** *** 39,59 **** * sources with these constants set to "true" first. */ ! public final class Flags { ! /** ! * Nobody is allowed to create one ! */ ! private Flags() { ! } ! /** ! * Use debug statements in performance critical code? ! */ ! public static final boolean DEBUG = false; ! /** ! * Use in profiling statements in performance critical code? ! */ ! public static final boolean PROFILE = true; } --- 39,61 ---- * sources with these constants set to "true" first. */ ! public final class Flags ! { ! /** ! * Nobody is allowed to create one ! */ ! private Flags () ! { ! } ! /** ! * Use debug statements in performance critical code? ! */ ! public static final boolean DEBUG = false; ! /** ! * Use in profiling statements in performance critical code? ! */ ! public static final boolean PROFILE = true; } Index: InitException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/InitException.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** InitException.java 11 Jun 2002 17:43:20 -0000 1.5 --- InitException.java 12 Jun 2003 00:47:44 -0000 1.6 *************** *** 28,39 **** * able to initialize itself. */ ! public class InitException extends WebMacroException { ! public InitException(String reason) { ! super(reason); ! } ! public InitException(String reason, Throwable e) { ! super(reason, e); ! } } --- 28,42 ---- * able to initialize itself. */ ! public class InitException extends WebMacroException ! { ! public InitException (String reason) ! { ! super(reason); ! } ! public InitException (String reason, Throwable e) ! { ! super(reason, e); ! } } Index: InvalidContextException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/InvalidContextException.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** InvalidContextException.java 11 Jun 2002 17:43:20 -0000 1.7 --- InvalidContextException.java 12 Jun 2003 00:47:44 -0000 1.8 *************** *** 28,36 **** * the macro required in order to write or evaluate itself. */ ! public class InvalidContextException extends PropertyException { ! public InvalidContextException(String reason) { ! super(reason); ! } } --- 28,38 ---- * the macro required in order to write or evaluate itself. */ ! public class InvalidContextException extends PropertyException ! { ! public InvalidContextException (String reason) ! { ! super(reason); ! } } Index: InvalidTypeException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/InvalidTypeException.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** InvalidTypeException.java 11 Jun 2002 17:43:20 -0000 1.3 --- InvalidTypeException.java 12 Jun 2003 00:47:44 -0000 1.4 *************** *** 28,35 **** * or otherwise invalid. */ ! public class InvalidTypeException extends WebMacroException { ! public InvalidTypeException(String reason) { ! super(reason); ! } } --- 28,37 ---- * or otherwise invalid. */ ! public class InvalidTypeException extends WebMacroException ! { ! public InvalidTypeException (String reason) ! { ! super(reason); ! } } Index: Log.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Log.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** Log.java 10 Nov 2002 20:35:08 -0000 1.7 --- Log.java 12 Jun 2003 00:47:44 -0000 1.8 *************** *** 31,103 **** * you must ask the Logmanager or a log instance. */ ! public interface Log { ! /** ! * Debug messages are incidental programmer notes which should ! * not be enabled in a production system. They are useful only ! * during development. ! */ ! public void debug(String msg, Throwable e); ! /** ! * A shortform for debug(msg,null) ! */ ! public void debug(String msg); ! /** ! * Info is fairly unimportant information about routine processing ! * within the system. They may be interesting on a production ! * system, but also can typically be ignored. ! */ ! public void info(String msg); ! /** ! * Notices are important information about routine processing ! * within the system. For example, startup and shutdown messages. ! * They are likely interesting to people running a production ! * system since they provide timestamps for important events. ! */ ! public void notice(String msg); ! /** ! * Warnings are messages outlining unexpected non-routine events ! * within the system. They may indicate larger problems, but in ! * and of themselves refer to problems the system is capable of ! * handling on its own. On a correctly functioning production ! * system you would expect to see only a few warnings. ! */ ! public void warning(String msg, Throwable e); ! /** ! * A shortform for debug(msg,null) ! */ ! public void warning(String msg); ! /** ! * A shortform for debug(msg,null) ! */ ! public void error(String msg); ! /** ! * An error is a major failure within the system. Typically it is ! * something which cannot easily be handled by the system. On a ! * correctly functioning production system you would not expect ! * to see any error messages. ! */ ! public void error(String msg, Throwable e); ! /** ! * Ask the log system if it wants these kinds of log messages. ! * This is because the overhead of creating log messages is high, ! * even if we're not going to log them, because it usually involves ! * several string concatenations. */ ! public boolean loggingDebug(); ! public boolean loggingInfo(); ! public boolean loggingNotice(); ! public boolean loggingWarning(); } --- 31,104 ---- * you must ask the Logmanager or a log instance. */ ! public interface Log ! { ! /** ! * Debug messages are incidental programmer notes which should ! * not be enabled in a production system. They are useful only ! * during development. ! */ ! public void debug (String msg, Throwable e); ! /** ! * A shortform for debug(msg,null) ! */ ! public void debug (String msg); ! /** ! * Info is fairly unimportant information about routine processing ! * within the system. They may be interesting on a production ! * system, but also can typically be ignored. ! */ ! public void info (String msg); ! /** ! * Notices are important information about routine processing ! * within the system. For example, startup and shutdown messages. ! * They are likely interesting to people running a production ! * system since they provide timestamps for important events. ! */ ! public void notice (String msg); ! /** ! * Warnings are messages outlining unexpected non-routine events ! * within the system. They may indicate larger problems, but in ! * and of themselves refer to problems the system is capable of ! * handling on its own. On a correctly functioning production ! * system you would expect to see only a few warnings. ! */ ! public void warning (String msg, Throwable e); ! /** ! * A shortform for debug(msg,null) ! */ ! public void warning (String msg); ! /** ! * A shortform for debug(msg,null) ! */ ! public void error (String msg); ! /** ! * An error is a major failure within the system. Typically it is ! * something which cannot easily be handled by the system. On a ! * correctly functioning production system you would not expect ! * to see any error messages. ! */ ! public void error (String msg, Throwable e); ! /** ! * Ask the log system if it wants these kinds of log messages. ! * This is because the overhead of creating log messages is high, ! * even if we're not going to log them, because it usually involves ! * several string concatenations. */ ! public boolean loggingDebug (); ! public boolean loggingInfo (); ! public boolean loggingNotice (); ! public boolean loggingWarning (); } Index: Macro.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Macro.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** Macro.java 11 Jun 2002 17:43:20 -0000 1.7 --- Macro.java 12 Jun 2003 00:47:44 -0000 1.8 *************** *** 24,28 **** package org.webmacro; ! import java.io.*; /** --- 24,28 ---- package org.webmacro; ! import java.io.IOException; /** *************** *** 30,52 **** * have this as their supertype. */ ! public interface Macro { ! /** ! * Interpret the directive and write it out, using the values in ! * the supplied context as appropriate. ! * <p> ! * @exception PropertyException if required data was missing from context ! * @exception IOException if we could not successfully write to out ! */ ! public void write(FastWriter out, Context context) ! throws PropertyException, IOException; ! /** ! * same as out but returns a String ! * <p> ! * @exception PropertyException if required data was missing from context ! */ ! public Object evaluate(Context context) ! throws PropertyException; } --- 30,53 ---- * have this as their supertype. */ ! public interface Macro ! { ! /** ! * Interpret the directive and write it out, using the values in ! * the supplied context as appropriate. ! * <p> ! * @exception PropertyException if required data was missing from context ! * @exception IOException if we could not successfully write to out ! */ ! public void write (FastWriter out, Context context) ! throws PropertyException, IOException; ! /** ! * same as out but returns a String ! * <p> ! * @exception PropertyException if required data was missing from context ! */ ! public Object evaluate (Context context) ! throws PropertyException; } Index: NotFoundException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/NotFoundException.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** NotFoundException.java 11 Jun 2002 17:43:20 -0000 1.5 --- NotFoundException.java 12 Jun 2003 00:47:44 -0000 1.6 *************** *** 27,38 **** * You asked for something that is not currently available. */ ! public class NotFoundException extends ResourceException { ! public NotFoundException(String reason, Exception e) { ! super(reason, e); ! } ! public NotFoundException(String reason) { ! super(reason); ! } } --- 27,41 ---- * You asked for something that is not currently available. */ ! public class NotFoundException extends ResourceException ! { ! public NotFoundException (String reason, Exception e) ! { ! super(reason, e); ! } ! public NotFoundException (String reason) ! { ! super(reason); ! } } Index: PropertyException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/PropertyException.java,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** PropertyException.java 20 Dec 2002 02:25:24 -0000 1.16 --- PropertyException.java 12 Jun 2003 00:47:44 -0000 1.17 *************** *** 39,68 **** * @version 27-07-2002 */ ! public class PropertyException extends ContextException { private String _message = null; ! public PropertyException( String reason ) { ! super( reason ); ! } ! public PropertyException( String reason, Throwable e ) { ! super( reason, e ); ! } ! public PropertyException( String reason, Throwable e, String contextLocation ) { ! super( reason, e ); ! setContextLocation( contextLocation ); ! } ! public void setMessage (String message) { _message = message; } ! public String getMessage() { ! if (_message == null) { return super.getMessage(); ! } else { String msg = _message; ! if ( getContextLocation() != null && msg != null ) { msg += " at " + getContextLocation(); } --- 39,78 ---- * @version 27-07-2002 */ ! public class PropertyException extends ContextException ! { private String _message = null; ! public PropertyException (String reason) ! { ! super(reason); ! } ! public PropertyException (String reason, Throwable e) ! { ! super(reason, e); ! } ! public PropertyException (String reason, Throwable e, String contextLocation) ! { ! super(reason, e); ! setContextLocation(contextLocation); ! } ! public void setMessage (String message) ! { _message = message; } ! public String getMessage () ! { ! if (_message == null) ! { return super.getMessage(); ! } ! else ! { String msg = _message; ! if (getContextLocation() != null && msg != null) ! { msg += " at " + getContextLocation(); } *************** *** 73,290 **** ! /** ! * NoSuchVariableException indicates that a variable did not exist ! * in the context against which it was being evaluated. ! */ ! public static class NoSuchVariableException extends PropertyException { ! public String variableName; ! public NoSuchVariableException( String variableName ) { ! super( "No such variable: $" + variableName ); ! this.variableName = variableName; ! } ! } ! /** ! * NullStringException indicates that a variable exists but its ! * .toString() method returns null ! */ ! public static class NullToStringException extends PropertyException { ! public String variableName; ! public NullToStringException( String variableName ) { ! super( ".toString() returns null: $" + variableName ); ! this.variableName = variableName; ! } ! } ! /** ! * NullValueException indicates that a variable or property ! * exists, but evaluated to null in the context against which it ! * was being evaluated. ! */ ! public static class NullValueException extends PropertyException { ! public String variableName; ! public NullValueException( String variableName ) { ! super( "Value is null: $" + variableName ); ! this.variableName = variableName; ! } ! } ! /** ! * NoSuchMethodException indicates that the variable did not have ! * the requested method. ! */ ! public static class NoSuchMethodException extends PropertyException { ! public String methodName, className, variableName; ! public NoSuchMethodException( String methodName, ! String variableName, ! String className ) { ! super( "No public method " + methodName + " on variable $" ! + variableName + " of class " + className ); ! this.variableName = variableName; ! this.className = className; ! this.methodName = methodName; ! } ! } ! /** ! * NoSuchMethodWithArgumentsException indicates that the variable did not have ! * the a method with the request name and argument list ! */ ! public static class NoSuchMethodWithArgumentsException extends PropertyException { ! public String methodName; ! public String className; ! public String arguments; ! public NoSuchMethodWithArgumentsException( String methodName, ! String className, ! String arguments ) { ! super( "No public method " + methodName + "(" + arguments + ")" ! + " in class " + className ); ! this.className = className; ! this.methodName = methodName; ! this.arguments = arguments; ! } ! } ! /** ! * NoSuchPropertyException indicates that the variable did not have ! * the requested property. ! */ ! public static class NoSuchPropertyException extends PropertyException { ! String _propertyName; ! String _className; ! String _variableName; ! public NoSuchPropertyException( String propertyName, ! String variableName, ! String className ) { ! super( "No public property " + propertyName + " on variable $" ! + variableName + " of class " + className ); ! this._variableName = variableName; ! this._className = className; ! this._propertyName = propertyName; ! } ! } ! /** ! * VoidValueException indicates that someone tried to use the return ! * value of a void method ! */ ! public static class VoidValueException extends PropertyException { ! String _variableName; ! public VoidValueException() { ! super( "Attempt to use void value" ); ! } ! public VoidValueException( String variableName ) { ! super( "Variable $" + variableName + " has a void value " ); ! this._variableName = variableName; ! } ! } ! /** ! * Exception thrown when a Variable isn't of the specified class type. ! */ ! public static class InvalidTypeException extends PropertyException { ! public InvalidTypeException( String variableName, Class clazz ) { ! super( "$" + variableName + " is not a " + clazz.getName() ); ! } ! } ! /** ! * RestrictedPropertyException indicates that the requested property may ! * not be invoked from a template due to security constraints ! */ ! public static class RestrictedPropertyException extends PropertyException { ! String _propertyName; ! String _className; ! String _variableName; ! public RestrictedPropertyException( String propertyName, ! String variableName, ! String className ) { ! super( "The property " + propertyName + " on variable $" ! + variableName + " of class " + className + " may not be accessed from a template." ); ! this._variableName = variableName; ! this._className = className; ! this._propertyName = propertyName; ! } ! } ! /** ! * RestrictedMethodException indicates that the requested method may ! * not be invoked from a template due to security constraints ! */ ! public static class RestrictedMethodException extends PropertyException { ! String _propertyName; ! String _className; ! String _variableName; ! public RestrictedMethodException( String propertyName, ! String variableName, ! String className ) { ! super( "The method " + propertyName + " on variable $" ! + variableName + " of class " + className + " may not be accessed from a template." ); ! this._variableName = variableName; ! this._className = className; ! this._propertyName = propertyName; ! } ! } ! /** ! * UndefinedVariableException indicates that the variable did not have ! * the requested method. ! */ ! public static class UndefinedVariableException extends PropertyException { ! private String _msg = "Attempted to dereference an undefined variable."; ! public UndefinedVariableException() { ! super( null ); ! } ! /** ! * Overloaded to return the <code>reason</code> specified during construction ! * <b>plus</b> the context location, if any. ! */ ! public String getMessage() { ! String msg = _msg; ! String loc = getContextLocation(); ! if ( loc != null ) { ! msg += " at " + loc; ! } ! return msg; ! } ! public void setMessage( String msg ) { ! _msg = msg; ! } ! } } --- 83,326 ---- ! /** ! * NoSuchVariableException indicates that a variable did not exist ! * in the context against which it was being evaluated. ! */ ! public static class NoSuchVariableException extends PropertyException ! { ! public String variableName; ! public NoSuchVariableException (String variableName) ! { ! super("No such variable: $" + variableName); ! this.variableName = variableName; ! } ! } ! /** ! * NullStringException indicates that a variable exists but its ! * .toString() method returns null ! */ ! public static class NullToStringException extends PropertyException ! { ! public String variableName; ! public NullToStringException (String variableName) ! { ! super(".toString() returns null: $" + variableName); ! this.variableName = variableName; ! } ! } ! /** ! * NullValueException indicates that a variable or property ! * exists, but evaluated to null in the context against which it ! * was being evaluated. ! */ ! public static class NullValueException extends PropertyException ! { ! public String variableName; ! public NullValueException (String variableName) ! { ! super("Value is null: $" + variableName); ! this.variableName = variableName; ! } ! } ! /** ! * NoSuchMethodException indicates that the variable did not have ! * the requested method. ! */ ! public static class NoSuchMethodException extends PropertyException ! { ! public String methodName, className, variableName; ! public NoSuchMethodException (String methodName, ! String variableName, ! String className) ! { ! super("No public method " + methodName + " on variable $" ! + variableName + " of class " + className); ! this.variableName = variableName; ! this.className = className; ! this.methodName = methodName; ! } ! } ! /** ! * NoSuchMethodWithArgumentsException indicates that the variable did not have ! * the a method with the request name and argument list ! */ ! public static class NoSuchMethodWithArgumentsException extends PropertyException ! { ! public String methodName; ! public String className; ! public String arguments; ! public NoSuchMethodWithArgumentsException (String methodName, ! String className, ! String arguments) ! { ! super("No public method " + methodName + "(" + arguments + ")" ! + " in class " + className); ! this.className = className; ! this.methodName = methodName; ! this.arguments = arguments; ! } ! } ! /** ! * NoSuchPropertyException indicates that the variable did not have ! * the requested property. ! */ ! public static class NoSuchPropertyException extends PropertyException ! { ! String _propertyName; ! String _className; ! String _variableName; ! public NoSuchPropertyException (String propertyName, ! String variableName, ! String className) ! { ! super("No public property " + propertyName + " on variable $" ! + variableName + " of class " + className); ! this._variableName = variableName; ! this._className = className; ! this._propertyName = propertyName; ! } ! } ! /** ! * VoidValueException indicates that someone tried to use the return ! * value of a void method ! */ ! public static class VoidValueException extends PropertyException ! { ! String _variableName; ! public VoidValueException () ! { ! super("Attempt to use void value"); ! } ! public VoidValueException (String variableName) ! { ! super("Variable $" + variableName + " has a void value "); ! this._variableName = variableName; ! } ! } ! /** ! * Exception thrown when a Variable isn't of the specified class type. ! */ ! public static class InvalidTypeException extends PropertyException ! { ! public InvalidTypeException (String variableName, Class clazz) ! { ! super("$" + variableName + " is not a " + clazz.getName()); ! } ! } ! /** ! * RestrictedPropertyException indicates that the requested property may ! * not be invoked from a template due to security constraints ! */ ! public static class RestrictedPropertyException extends PropertyException ! { ! String _propertyName; ! String _className; ! String _variableName; ! public RestrictedPropertyException (String propertyName, ! String variableName, ! String className) ! { ! super("The property " + propertyName + " on variable $" ! + variableName + " of class " + className + " may not be accessed from a template."); ! this._variableName = variableName; ! this._className = className; ! this._propertyName = propertyName; ! } ! } ! /** ! * RestrictedMethodException indicates that the requested method may ! * not be invoked from a template due to security constraints ! */ ! public static class RestrictedMethodException extends PropertyException ! { ! String _propertyName; ! String _className; ! String _variableName; ! public RestrictedMethodException (String propertyName, ! String variableName, ! String className) ! { ! super("The method " + propertyName + " on variable $" ! + variableName + " of class " + className + " may not be accessed from a template."); ! this._variableName = variableName; ! this._className = className; ! this._propertyName = propertyName; ! } ! } ! /** ! * UndefinedVariableException indicates that the variable did not have ! * the requested method. ! */ ! public static class UndefinedVariableException extends PropertyException ! { ! private String _msg = "Attempted to dereference an undefined variable."; ! public UndefinedVariableException () ! { ! super(null); ! } ! /** ! * Overloaded to return the <code>reason</code> specified during construction ! * <b>plus</b> the context location, if any. ! */ ! public String getMessage () ! { ! String msg = _msg; ! String loc = getContextLocation(); ! if (loc != null) ! { ! msg += " at " + loc; ! } ! return msg; ! } ! public void setMessage (String msg) ! { ! _msg = msg; ! } ! } } Index: Provider.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Provider.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Provider.java 11 Jun 2002 17:43:20 -0000 1.5 --- Provider.java 12 Jun 2003 00:47:44 -0000 1.6 *************** *** 35,64 **** * WebMacro's behavior. */ ! public interface Provider { ! /** ! * Return an array representing the types this provider serves up ! */ ! public String getType(); ! /** ! * Initialize this provider based on the specified config. ! */ ! public void init(Broker b, Settings config) throws InitException; ! /** ! * Clear any cache this provider may be maintaining ! */ ! public void flush(); ! /** ! * Close down this provider, freeing any allocated resources. ! */ ! public void destroy(); ! /** ! * Get the object associated with the specified query ! */ ! public Object get(String query) throws ResourceException; } --- 35,65 ---- * WebMacro's behavior. */ ! public interface Provider ! { ! /** ! * Return an array representing the types this provider serves up ! */ ! public String getType (); ! /** ! * Initialize this provider based on the specified config. ! */ ! public void init (Broker b, Settings config) throws InitException; ! /** ! * Clear any cache this provider may be maintaining ! */ ! public void flush (); ! /** ! * Close down this provider, freeing any allocated resources. ! */ ! public void destroy (); ! /** ! * Get the object associated with the specified query ! */ ! public Object get (String query) throws ResourceException; } Index: ResourceException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/ResourceException.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ResourceException.java 11 Jun 2002 17:43:20 -0000 1.3 --- ResourceException.java 12 Jun 2003 00:47:44 -0000 1.4 *************** *** 28,40 **** * @since 0.96 */ ! public class ResourceException extends WebMacroException { ! public ResourceException(String reason, Exception e) { ! super(reason, e); ! } ! public ResourceException(String reason) { ! super(reason); ! } } --- 28,43 ---- * @since 0.96 */ ! public class ResourceException extends WebMacroException ! { ! public ResourceException (String reason, Exception e) ! { ! super(reason, e); ! } ! public ResourceException (String reason) ! { ! super(reason); ! } } Index: RethrowableException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/RethrowableException.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RethrowableException.java 11 Jun 2002 17:43:20 -0000 1.6 --- RethrowableException.java 12 Jun 2003 00:47:44 -0000 1.7 *************** *** 43,120 **** * @since 0.96 */ ! public class RethrowableException extends Exception { ! private Throwable cause; ! private final static String RETHROW_MESSAGE = "-- secondary stack trace --"; ! public RethrowableException() { ! super(); ! } ! public RethrowableException(String s) { ! super(s); ! } ! public RethrowableException(String s, Throwable e) { ! super(s + System.getProperty("line.separator") + e); ! cause = e; ! } ! public void printStackTrace() { ! super.printStackTrace(); ! if (cause != null) { ! System.err.println(RETHROW_MESSAGE); ! cause.printStackTrace(); ! } ! } ! public void printStackTrace(java.io.PrintStream ps) { ! super.printStackTrace(ps); ! if (cause != null) { ! ps.println(RETHROW_MESSAGE); ! cause.printStackTrace(ps); ! } ! } ! public void printStackTrace(java.io.PrintWriter pw) { ! super.printStackTrace(pw); ! if (cause != null) { ! pw.println(RETHROW_MESSAGE); ! cause.printStackTrace(pw); ! } ! } ! /** ! * allow access to underlying exception ! * @deprecated you should use <code>getCause</code> instead ! */ ! public Throwable getCaught() { ! return getCause(); ! } ! /** ! * Return the underlying exception provided at construction time ! * or null if none was provided. ! * @return underlying cause ! * @since 1.1 ! */ ! public Throwable getCause() { ! return cause; ! } ! /** ! * Return the original exception cause. This will recursively ! * extract the cause if cause is a subclass of ! * <code>RethrowableException</code>. ! * @return underlying root cause ! * @since 1.1 ! */ ! public Throwable getRootCause() { ! Throwable t = cause; ! while (t != null && t instanceof RethrowableException) { ! t = ((RethrowableException) t).cause; ! } ! return t; ! } } --- 43,134 ---- * @since 0.96 */ ! public class RethrowableException extends Exception ! { ! private Throwable cause; ! private final static String RETHROW_MESSAGE = "-- secondary stack trace --"; ! public RethrowableException () ! { ! super(); ! } ! public RethrowableException (String s) ! { ! super(s); ! } ! public RethrowableException (String s, Throwable e) ! { ! super(s + System.getProperty("line.separator") + e); ! cause = e; ! } ! public void printStackTrace () ! { ! super.printStackTrace(); ! if (cause != null) ! { ! System.err.println(RETHROW_MESSAGE); ! cause.printStackTrace(); ! } ! } ! public void printStackTrace (java.io.PrintStream ps) ! { ! super.printStackTrace(ps); ! if (cause != null) ! { ! ps.println(RETHROW_MESSAGE); ! cause.printStackTrace(ps); ! } ! } ! public void printStackTrace (java.io.PrintWriter pw) ! { ! super.printStackTrace(pw); ! if (cause != null) ! { ! pw.println(RETHROW_MESSAGE); ! cause.printStackTrace(pw); ! } ! } ! /** ! * allow access to underlying exception ! * @deprecated you should use <code>getCause</code> instead ! */ ! public Throwable getCaught () ! { ! return getCause(); ! } ! /** ! * Return the underlying exception provided at construction time ! * or null if none was provided. ! * @return underlying cause ! * @since 1.1 ! */ ! public Throwable getCause () ! { ! return cause; ! } ! /** ! * Return the original exception cause. This will recursively ! * extract the cause if cause is a subclass of ! * <code>RethrowableException</code>. ! * @return underlying root cause ! * @since 1.1 ! */ ! public Throwable getRootCause () ! { ! Throwable t = cause; ! while (t != null && t instanceof RethrowableException) ! { ! t = ((RethrowableException) t).cause; ! } ! return t; ! } } Index: RethrowableRuntimeException.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/RethrowableRuntimeException.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RethrowableRuntimeException.java 11 Jun 2002 17:43:20 -0000 1.3 --- RethrowableRuntimeException.java 12 Jun 2003 00:47:44 -0000 1.4 *************** *** 42,122 **** * @author Brian Goetz (Quiotix Corp) * @since 0.96 */ ! public class RethrowableRuntimeException extends RuntimeException { ! private Throwable cause; ! private final static String RETHROW_MESSAGE = "-- secondary stack trace --"; ! public RethrowableRuntimeException() { ! super(); ! } ! public RethrowableRuntimeException(String s) { ! super(s); ! } ! public RethrowableRuntimeException(String s, Throwable e) { ! super(s + System.getProperty("line.separator") + e); ! cause = e; ! while (cause instanceof RethrowableRuntimeException) { ! cause = ((RethrowableRuntimeException) cause).cause; ! } ! } ! public void printStackTrace() { ! super.printStackTrace(); ! if (cause != null) { ! System.err.println(RETHROW_MESSAGE); ! cause.printStackTrace(); ! } ! } ! public void printStackTrace(java.io.PrintStream ps) { ! super.printStackTrace(ps); ! if (cause != null) { ! ps.println(RETHROW_MESSAGE); ! cause.printStackTrace(ps); ! } ! } ! public void printStackTrace(java.io.PrintWriter pw) { ! super.printStackTrace(pw); ! if (cause != null) { ! pw.println(RETHROW_MESSAGE); ! cause.printStackTrace(pw); ! } ! } ! /** ! * allow access to underlying exception ! * @deprecated you should use <code>getCause</code> instead ! */ ! public Throwable getCaught() { ! return getCause(); ! } ! /** ! * Return the underlying exception provided at construction time ! * or null if none was provided. ! * @return underlying cause ! * @since 1.1 ! */ ! public Throwable getCause() { ! return cause; ! } ! /** ! * Return the original exception cause. This will recursively ! * extract the cause if cause is a subclass of ! * <code>RethrowableException</code>. ! * @return underlying root cause ! * @since 1.1 ! */ ! public Throwable getRootCause() { ! Throwable t = cause; ! while (t != null && t instanceof RethrowableRuntimeException) { ! t = ((RethrowableRuntimeException) t).cause; ! } ! return t; ! } } --- 42,137 ---- * @author Brian Goetz (Quiotix Corp) * @since 0.96 */ ! public class RethrowableRuntimeException extends RuntimeException ! { ! private Throwable cause; ! private final static String RETHROW_MESSAGE = "-- secondary stack trace --"; ! public RethrowableRuntimeException () ! { ! super(); ! } ! public RethrowableRuntimeException (String s) ! { ! super(s); ! } ! public RethrowableRuntimeException (String s, Throwable e) ! { ! super(s + System.getProperty("line.separator") + e); ! cause = e; ! while (cause instanceof RethrowableRuntimeException) ! { ! cause = ((RethrowableRuntimeException) cause).cause; ! } ! } ! public void printStackTrace () ! { ! super.printStackTrace(); ! if (cause != null) ! { ! System.err.println(RETHROW_MESSAGE); ! cause.printStackTrace(); ! } ! } ! public void printStackTrace (java.io.PrintStream ps) ! { ! super.printStackTrace(ps); ! if (cause != null) ! { ! ps.println(RETHROW_MESSAGE); ! cause.printStackTrace(ps); ! } ! } ! public void printStackTrace (java.io.PrintWriter pw) ! { ! super.printStackTrace(pw); ! if (cause != null) ! { ! pw.println(RETHROW_MESSAGE); ! cause.printStackTrace(pw); ! } ! } ! /** ! * allow access to underlying exception ! * @deprecated you should use <code>getCause</code> instead ! */ ! public Throwable getCaught () ! { ! return getCause(); ! } ! /** ! * Return the underlying exception provided at construction time ! * or null if none was provided. ! * @return underlying cause ! * @since 1.1 ! */ ! public Throwable getCause () ! { ! return cause; ! } ! /** ! * Return the original exception cause. This will recursively ! * extract the cause if cause is a subclass of ! * <code>RethrowableException</code>. ! * @return underlying root cause ! * @since 1.1 ! */ ! public Throwable getRootCause () ! { ! Throwable t = cause; ! while (t != null && t instanceof RethrowableRuntimeException) ! { ! t = ((RethrowableRuntimeException) t).cause; ! } ! return t; ! } } Index: Template.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Template.java,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** Template.java 11 Jun 2002 17:43:20 -0000 1.13 --- Template.java 12 Jun 2003 00:47:44 -0000 1.14 *************** *** 24,94 **** package org.webmacro; ! import java.io.*; ! import java.util.*; ! public interface Template extends Macro, Visitable { ! /** ! * Force the template to parse now. Normally the template will not parse ! * the supplied file until the data is actually needed. However if you ! * want to parse all of your templates at the start of the application ! * to avoid incurring this call during an interactive session, you can ! * call the parse() function at an appropriate time. Once a template has ! * been parsed, subsequent calls to this method do not have an effect. If ! * you want to reparse the template, because you know, it has been changed, you ! * have to create a new Template object and leave this one to the garbage collector. ! * <p> ! * @exception TemplateException if the sytax was invalid and we could not recover ! * @exception IOException if we could not successfullly read the parseTool ! */ ! public void parse() throws IOException, TemplateException; ! /** ! * A template may contain parameters, set by the #param directive. ! * These are statically evaluated during the parse phase of the ! * template and shared between all users of the template. They ! * are present so that the template can provide some meta information ! * to its user as to what kind of data it expects to find in the Context, ! * or other information about its use. ! * <p> ! * If the template has not already been parsed, it will be parsed. Thus ! * this method may throw ParseException or IOException if there is some ! * failure in accessing or parsing the template. ! * @exception IOException if an error occurred reading the template ! * @exception TemplateException if an error occurred parsing the template ! */ ! public Object getParam(String name) throws IOException, TemplateException; ! /** ! * This method can be used to get a list of all the parameters ! * that have been set in the template. getParam(Object) can be used ! * to look up any particular parameter. ! */ ! /** ! * set a parameter. Occasinally it's necessary to provide parameters ! * externally. Although these might be considered of a different nature to ! * those set by #param, they can be stored as such. ! * ! * One example might be the output character encoding which is needed ! * when the template is played. ! */ ! public void setParam(String key, Object value); ! public Map getParameters(); ! public String getName(); ! public void setName(String name); ! /** ! * Get a Map containing all #macros defined for this template. ! * The returned Map can be <code>null</code> if this Template ! * does not contain Macros, or if this Template has not been ! * parsed yet. ! * @return ! */ ! public Map getMacros(); } --- 24,95 ---- package org.webmacro; ! import java.io.IOException; ! import java.util.Map; ! public interface Template extends Macro, Visitable ! { ! /** ! * Force the template to parse now. Normally the template will not parse ! * the supplied file until the data is actually needed. However if you ! * want to parse all of your templates at the start of the application ! * to avoid incurring this call during an interactive session, you can ! * call the parse() function at an appropriate time. Once a template has ! * been parsed, subsequent calls to this method do not have an effect. If ! * you want to reparse the template, because you know, it has been changed, you ! * have to create a new Template object and leave this one to the garbage collector. ! * <p> ! * @exception TemplateException if the sytax was invalid and we could not recover ! * @exception IOException if we could not successfullly read the parseTool ! */ ! public void parse () throws IOException, TemplateException; ! /** ! * A template may contain parameters, set by the #param directive. ! * These are statically evaluated during the parse phase of the ! * template and shared between all users of the template. They ! * are present so that the template can provide some meta information ! * to its user as to what kind of data it expects to find in the Context, ! * or other information about its use. ! * <p> ! * If the template has not already been parsed, it will be parsed. Thus ! * this method may throw ParseException or IOException if there is some ! * failure in accessing or parsing the template. ! * @exception IOException if an error occurred reading the template ! * @exception TemplateException if an error occurred parsing the template ! */ ! public Object getParam (String name) throws IOException, TemplateException; ! /** ! * This method can be used to get a list of all the parameters ! * that have been set in the template. getParam(Object) can be used ! * to look up any particular parameter. ! */ ! /** ! * set a parameter. Occasinally it's necessary to provide parameters ! * externally. Although these might be considered of a different nature to ! * those set by #param, they can be stored as such. ! * ! * One example might be the output character encoding which is needed ! * when the template is played. ! */ ! public void setParam (String key, Object value); ! public Map getParameters (); ! public String getName (); ! public void setName (String name); ! /** ! * Get a Map containing all #macros defined for this template. ! * The returned Map can be <code>null</code> if this Template ! * does not contain Macros, or if this Template has not been ! * parsed yet. ! * @return ! */ ! public Map getMacros (); } Index: TemplateException.java =============================================... [truncated message content] |
From: <dr...@us...> - 2003-06-12 00:48:16
|
Update of /cvsroot/webmacro/webmacro/src/org/opendoors/util In directory sc8-pr-cvs1:/tmp/cvs-serv6675/src/org/opendoors/util Modified Files: PostponeObservable.java Timer.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: PostponeObservable.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/util/PostponeObservable.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** PostponeObservable.java 11 Jun 2002 17:43:20 -0000 1.4 --- PostponeObservable.java 12 Jun 2003 00:47:43 -0000 1.5 *************** *** 15,19 **** import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; ! import java.util.*; /** --- 15,20 ---- import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; ! import java.util.Observable; ! import java.util.Observer; /** *************** *** 48,165 **** * @see java.util.Observer */ ! public class PostponeObservable extends Observable implements PropertyChangeListener { ! //-------public members----- ! /** ! * On property change, postpone event notification this number of millis. ! */ ! protected int postponeInterval = 120000; //2 minutes ! /** ! * While waiting to fire a notification, ! * reset the interval if another change comes in. ! */ ! protected boolean resetClockOnUpdate = true; ! //-------private and protected members----- ! private long timeToNotify = System.currentTimeMillis(); ! private Timer tick = null; ! //-------constructor(s)----- ! /** ! * Constructs a default observable. ! */ ! public PostponeObservable() { ! init(); ! } ! /** ! * Constructs a default observable with the following settings. ! * @param The interval to wait in millis between notifications. ! * @param Resets the clock so that changes can be aggregated ! * over a period of time ! */ ! public PostponeObservable(int postponeInterval, boolean resetClockOnUpdate) { ! this.postponeInterval = postponeInterval; ! this.resetClockOnUpdate = resetClockOnUpdate; ! init(); ! } ! /** Initializes the instance. */ ! protected void init() { ! tick = new Timer("PropertyObservable", postponeInterval, false); ! tick.addObserver(new TimerObserver()); ! } ! //-------public initializers/destroyers----- ! /** Sets the observable period. */ ! public void setPostponePeriod(int postponeInterval) { ! this.postponeInterval = postponeInterval; ! tick.setPeriod(postponeInterval); ! } ! /** Enables postponeability if true. */ ! public void enablePostponeability(boolean enable) { ! this.resetClockOnUpdate = enable; ! } ! //-------public event handlers----- ! /** ! * Using the property event model ! * propagate a change event to the observable. ! * @param evt The property change event which can be null. ! */ ! public void propertyChange(PropertyChangeEvent evt) { ! setChanged(); ! } ! /** ! * Call back from the timer when ! * the observation period has expired. ! */ ! public void timerAction() { ! if (hasChanged() && (timeToNotify < System.currentTimeMillis())) { ! notifyObservers(); ! } ! } ! /** ! * Signals that the observable has changed. ! * <p> ! * Observers will be ! * notified when ! * <pre> ! * current time > (time of last change + postponeInterval) ! * </pre> ! * provided postponeability is enabled. ! */ ! public void setChanged() { ! super.setChanged(); ! if (resetClockOnUpdate) { ! timeToNotify = (System.currentTimeMillis() + postponeInterval); ! } ! } ! /** Destoys this instance and the associated timer. */ ! public void destroy() { ! tick.stop(); ! tick = null; ! } ! /** ! * Class which listens to updates in the observable tick and calls ! * the timer notifiction method. ! */ ! class TimerObserver implements Observer { ! public void update(Observable o, Object arg) { ! timerAction(); ! } ! } --- 49,180 ---- * @see java.util.Observer */ ! public class PostponeObservable extends Observable implements PropertyChangeListener ! { ! //-------public members----- ! /** ! * On property change, postpone event notification this number of millis. ! */ ! protected int postponeInterval = 120000; //2 minutes ! /** ! * While waiting to fire a notification, ! * reset the interval if another change comes in. ! */ ! protected boolean resetClockOnUpdate = true; ! //-------private and protected members----- ! private long timeToNotify = System.currentTimeMillis(); ! private Timer tick = null; ! //-------constructor(s)----- ! /** ! * Constructs a default observable. ! */ ! public PostponeObservable () ! { ! init(); ! } ! /** ! * Constructs a default observable with the following settings. ! * @param The interval to wait in millis between notifications. ! * @param Resets the clock so that changes can be aggregated ! * over a period of time ! */ ! public PostponeObservable (int postponeInterval, boolean resetClockOnUpdate) ! { ! this.postponeInterval = postponeInterval; ! this.resetClockOnUpdate = resetClockOnUpdate; ! init(); ! } ! /** Initializes the instance. */ ! protected void init () ! { ! tick = new Timer("PropertyObservable", postponeInterval, false); ! tick.addObserver(new TimerObserver()); ! } ! //-------public initializers/destroyers----- ! /** Sets the observable period. */ ! public void setPostponePeriod (int postponeInterval) ! { ! this.postponeInterval = postponeInterval; ! tick.setPeriod(postponeInterval); ! } ! /** Enables postponeability if true. */ ! public void enablePostponeability (boolean enable) ! { ! this.resetClockOnUpdate = enable; ! } ! //-------public event handlers----- ! /** ! * Using the property event model ! * propagate a change event to the observable. ! * @param evt The property change event which can be null. ! */ ! public void propertyChange (PropertyChangeEvent evt) ! { ! setChanged(); ! } ! /** ! * Call back from the timer when ! * the observation period has expired. ! */ ! public void timerAction () ! { ! if (hasChanged() && (timeToNotify < System.currentTimeMillis())) ! { ! notifyObservers(); ! } ! } ! /** ! * Signals that the observable has changed. ! * <p> ! * Observers will be ! * notified when ! * <pre> ! * current time > (time of last change + postponeInterval) ! * </pre> ! * provided postponeability is enabled. ! */ ! public void setChanged () ! { ! super.setChanged(); ! if (resetClockOnUpdate) ! { ! timeToNotify = (System.currentTimeMillis() + postponeInterval); ! } ! } ! /** Destoys this instance and the associated timer. */ ! public void destroy () ! { ! tick.stop(); ! tick = null; ! } ! /** ! * Class which listens to updates in the observable tick and calls ! * the timer notifiction method. ! */ ! class TimerObserver implements Observer ! { ! public void update (Observable o, Object arg) ! { ! timerAction(); ! } ! } Index: Timer.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/util/Timer.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** Timer.java 11 Jun 2002 17:43:20 -0000 1.4 --- Timer.java 12 Jun 2003 00:47:43 -0000 1.5 *************** *** 13,18 **** package org.opendoors.util; ! import java.io.*; ! import java.util.*; /** --- 13,18 ---- package org.opendoors.util; ! import java.io.Serializable; ! import java.util.Observable; /** *************** *** 30,161 **** * observable such as an observable which fires every 24 hours. */ ! public class Timer extends Observable implements Runnable, Serializable { ! /** The timer thread. */ ! private transient Thread timerThread; ! /** Signal to stop the thread. */ ! private transient boolean stopThread = false; ! /** The name. */ ! private String name; ! /** The interval for firing. */ ! private int period; // in milliseconds ! /** Is a one shot timer. */ ! private boolean oneShot; ! /** ! * Public constructor to create a timer event source using factory defaults ! * which are 1 second timer, recurring. ! */ ! public Timer() { ! this("PerSecondTimer", 1000, false); ! } ! /** ! * Construct a timer with the certain properties set. ! * @param The name of the timer. ! * @param The period in milliseconds. ! * @param True if this is a oneShot instance ! */ ! public Timer(String name, int period, boolean oneShot) { ! super(); ! // Set properties ! this.name = name; ! this.period = period; ! this.oneShot = oneShot; ! // Create the clock thread ! timerThread = new Thread(this, name); ! timerThread.setDaemon(true); ! timerThread.start(); ! } ! /** ! * Stop the timer ! */ ! public void stop() { ! stopThread = true; ! } ! // Accessor methods ! /** ! * Gets the name of the timer. ! * @return The timer name. ! */ ! public String getName() { ! return name; ! } ! /** ! * Sets the name of the timer. ! * @param The textual name. ! */ ! public void setName(String n) { ! name = n; ! } ! /** ! * Gets the period between timer events. ! * @return The interval in milliseconds ! */ ! public int getPeriod() { ! return period; ! } ! /** ! * Sets the period in milliseconds. ! * @param The interval. ! */ ! public void setPeriod(int p) { ! period = p; ! if (timerThread != null) ! timerThread.interrupt(); ! } ! /** ! * Interrogates if this is a one-shot operation. ! * @return True, if a one-shot operation. ! */ ! public boolean isOneShot() { ! return oneShot; ! } ! /** ! * Set this object to be one-shot or not. ! * @param True, if one-shot operation desired ! */ ! public void setOneShot(boolean os) { ! oneShot = os; ! } ! /** ! * Run the timer. ! */ ! public void run() { ! while (timerThread != null) { ! // Sleep for the period ! try { ! timerThread.sleep(period); ! } ! catch (InterruptedException e) { ! // Restart the loop ! continue; ! } ! // Fire an action event ! setChanged(); ! notifyObservers(); ! if (oneShot || stopThread) ! break; ! } ! // clean up: ! timerThread = null; ! } } --- 30,175 ---- * observable such as an observable which fires every 24 hours. */ ! public class Timer extends Observable implements Runnable, Serializable ! { ! /** The timer thread. */ ! private transient Thread timerThread; ! /** Signal to stop the thread. */ ! private transient boolean stopThread = false; ! /** The name. */ ! private String name; ! /** The interval for firing. */ ! private int period; // in milliseconds ! /** Is a one shot timer. */ ! private boolean oneShot; ! /** ! * Public constructor to create a timer event source using factory defaults ! * which are 1 second timer, recurring. ! */ ! public Timer () ! { ! this("PerSecondTimer", 1000, false); ! } ! /** ! * Construct a timer with the certain properties set. ! * @param The name of the timer. ! * @param The period in milliseconds. ! * @param True if this is a oneShot instance ! */ ! public Timer (String name, int period, boolean oneShot) ! { ! super(); ! // Set properties ! this.name = name; ! this.period = period; ! this.oneShot = oneShot; ! // Create the clock thread ! timerThread = new Thread(this, name); ! timerThread.setDaemon(true); ! timerThread.start(); ! } ! /** ! * Stop the timer ! */ ! public void stop () ! { ! stopThread = true; ! } ! // Accessor methods ! /** ! * Gets the name of the timer. ! * @return The timer name. ! */ ! public String getName () ! { ! return name; ! } ! /** ! * Sets the name of the timer. ! * @param The textual name. ! */ ! public void setName (String n) ! { ! name = n; ! } ! /** ! * Gets the period between timer events. ! * @return The interval in milliseconds ! */ ! public int getPeriod () ! { ! return period; ! } ! /** ! * Sets the period in milliseconds. ! * @param The interval. ! */ ! public void setPeriod (int p) ! { ! period = p; ! if (timerThread != null) ! timerThread.interrupt(); ! } ! /** ! * Interrogates if this is a one-shot operation. ! * @return True, if a one-shot operation. ! */ ! public boolean isOneShot () ! { ! return oneShot; ! } ! /** ! * Set this object to be one-shot or not. ! * @param True, if one-shot operation desired ! */ ! public void setOneShot (boolean os) ! { ! oneShot = os; ! } ! /** ! * Run the timer. ! */ ! public void run () ! { ! while (timerThread != null) ! { ! // Sleep for the period ! try ! { ! timerThread.sleep(period); ! } ! catch (InterruptedException e) ! { ! // Restart the loop ! continue; ! } ! // Fire an action event ! setChanged(); ! notifyObservers(); ! if (oneShot || stopThread) ! break; ! } ! // clean up: ! timerThread = null; ! } } |
Update of /cvsroot/webmacro/webmacro/src/org/opendoors/cache/immutable In directory sc8-pr-cvs1:/tmp/cvs-serv6675/src/org/opendoors/cache/immutable Modified Files: CacheFactory.java CacheImpl.java ChangeControl.java Depopulate.java Populate.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: CacheFactory.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/cache/immutable/CacheFactory.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** CacheFactory.java 11 Jun 2002 17:43:20 -0000 1.4 --- CacheFactory.java 12 Jun 2003 00:47:43 -0000 1.5 *************** *** 13,20 **** package org.opendoors.cache.immutable; - import java.util.*; - import org.opendoors.cache.UpdateableCache; /** * CacheFactory provides static and instance-specific --- 13,21 ---- package org.opendoors.cache.immutable; import org.opendoors.cache.UpdateableCache; + import java.util.Map; + import java.util.Properties; + /** * CacheFactory provides static and instance-specific *************** *** 32,144 **** * @see org.opendoors.cache */ ! public class CacheFactory { ! /** The optional subclass controlling the cache. */ ! Class changeControlSubClass; ! /** ! * The factory provided refresh rate for the cache. ! * <p> ! * If the cache is out of date and idle this ! * amount of time in millis, it will be updated. ! */ ! int refreshRate = 1000; ! /** ! * Creates an instance of a cache factory with ! * text property options to control the ! * behavior the factory. ! * <p> ! * Use these options to customize, in other words, ! * the kind of caches the instance this factory ! * produces. The properties names, values and defaults: ! * <pre> ! * ChangeControl=Subclass.impl.of.ChangeControl ! * default: org.opendoors.cache.imple.ChangeControl ! * usage: certain cache implementors will subclass ChangeControl ! * to provide more granular control over the regeneration ! * of the immutable image of the cache. ! * ! * RefreshRate=NumberOfMilliseconds ! * default: 2500 milliseconds ! * usage: the amount of time between updates provided ! * the cache is idle at least this amount of time. ! * </pre> ! * @param properties If null, the above defaults will be used, ! * else the elements of the properties will be employed. ! */ ! public CacheFactory(Properties properties) { ! this(properties, null); ! } ! /** ! * This constructor allows you to ! * present factory defaults different than ! * those provided by VFC. ! */ ! public CacheFactory(Properties properties, Properties defaults) { ! String prop = getValue(properties, defaults, "ChangeControl"); ! if (prop != null) { ! try { ! changeControlSubClass = Class.forName(prop); ! } ! catch (Exception e) { ! e.printStackTrace(System.out); ! } ! } ! prop = getValue(properties, defaults, "RefreshRate"); ! if (prop != null) { ! refreshRate = Integer.parseInt(prop); ! } ! } ! /** ! * Initializes a cache and returns it according to the factory ! * properties. ! */ ! public UpdateableCache initialize(Map preload) { ! return new CacheImpl(preload, changeControlSubClass, refreshRate); ! } ! /** ! * A factory static method to provide an ! * empty updateable cache. ! */ ! public static UpdateableCache create() { ! CacheFactory f = new CacheFactory(null, null); ! return f.initialize(null); ! } ! /** ! * A factory static method to provide an ! * updateable cache preloaded ! */ ! public static UpdateableCache create(Map map) { ! CacheFactory f = new CacheFactory(null, null); ! return f.initialize(map); ! } ! /** A static factory method to destroy a cache. */ ! public static void destroyCache(UpdateableCache cache) { ! ((CacheImpl) cache).destroy(); ! } ! /** Destroys the instance of the cache created by the factory. */ ! public void destroy(UpdateableCache cache) { ! ((CacheImpl) cache).destroy(); ! } ! /** Get property values for the constructor. */ ! private String getValue(Properties values, Properties defaults, ! String name) { ! String value = null; ! if (values != null) ! value = values.getProperty(name); ! if (value == null && defaults != null) ! value = defaults.getProperty(name); ! return value; ! } } --- 33,158 ---- * @see org.opendoors.cache */ ! public class CacheFactory ! { ! /** The optional subclass controlling the cache. */ ! Class changeControlSubClass; ! /** ! * The factory provided refresh rate for the cache. ! * <p> ! * If the cache is out of date and idle this ! * amount of time in millis, it will be updated. ! */ ! int refreshRate = 1000; ! /** ! * Creates an instance of a cache factory with ! * text property options to control the ! * behavior the factory. ! * <p> ! * Use these options to customize, in other words, ! * the kind of caches the instance this factory ! * produces. The properties names, values and defaults: ! * <pre> ! * ChangeControl=Subclass.impl.of.ChangeControl ! * default: org.opendoors.cache.imple.ChangeControl ! * usage: certain cache implementors will subclass ChangeControl ! * to provide more granular control over the regeneration ! * of the immutable image of the cache. ! * ! * RefreshRate=NumberOfMilliseconds ! * default: 2500 milliseconds ! * usage: the amount of time between updates provided ! * the cache is idle at least this amount of time. ! * </pre> ! * @param properties If null, the above defaults will be used, ! * else the elements of the properties will be employed. ! */ ! public CacheFactory (Properties properties) ! { ! this(properties, null); ! } ! /** ! * This constructor allows you to ! * present factory defaults different than ! * those provided by VFC. ! */ ! public CacheFactory (Properties properties, Properties defaults) ! { ! String prop = getValue(properties, defaults, "ChangeControl"); ! if (prop != null) ! { ! try ! { ! changeControlSubClass = Class.forName(prop); ! } ! catch (Exception e) ! { ! e.printStackTrace(System.out); ! } ! } ! prop = getValue(properties, defaults, "RefreshRate"); ! if (prop != null) ! { ! refreshRate = Integer.parseInt(prop); ! } ! } ! /** ! * Initializes a cache and returns it according to the factory ! * properties. ! */ ! public UpdateableCache initialize (Map preload) ! { ! return new CacheImpl(preload, changeControlSubClass, refreshRate); ! } ! /** ! * A factory static method to provide an ! * empty updateable cache. ! */ ! public static UpdateableCache create () ! { ! CacheFactory f = new CacheFactory(null, null); ! return f.initialize(null); ! } ! /** ! * A factory static method to provide an ! * updateable cache preloaded ! */ ! public static UpdateableCache create (Map map) ! { ! CacheFactory f = new CacheFactory(null, null); ! return f.initialize(map); ! } ! /** A static factory method to destroy a cache. */ ! public static void destroyCache (UpdateableCache cache) ! { ! ((CacheImpl) cache).destroy(); ! } ! /** Destroys the instance of the cache created by the factory. */ ! public void destroy (UpdateableCache cache) ! { ! ((CacheImpl) cache).destroy(); ! } ! /** Get property values for the constructor. */ ! private String getValue (Properties values, Properties defaults, ! String name) ! { ! String value = null; ! if (values != null) ! value = values.getProperty(name); ! if (value == null && defaults != null) ! value = defaults.getProperty(name); ! return value; ! } } Index: CacheImpl.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/cache/immutable/CacheImpl.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** CacheImpl.java 11 Jun 2002 17:43:20 -0000 1.6 --- CacheImpl.java 12 Jun 2003 00:47:43 -0000 1.7 *************** *** 13,20 **** package org.opendoors.cache.immutable; - import java.util.*; - import org.opendoors.cache.UpdateableCache; /** * Implements the updateable cache interface according --- 13,21 ---- package org.opendoors.cache.immutable; import org.opendoors.cache.UpdateableCache; + import java.util.HashMap; + import java.util.Map; + /** * Implements the updateable cache interface according *************** *** 22,124 **** * cache strategy of VFC. */ ! public class CacheImpl implements UpdateableCache { ! /** ! * The immutable cache with a volatile reference ! * so that its reference is cached in local memory. ! */ ! volatile HashMap immutable; ! /** The mutable cache used for updates. */ ! volatile HashMap mutable; ! /** The change control agent. */ ! ChangeControl changeControl; ! /** The change control mutex. */ ! Object changeControlMutex; ! /** The array containing the metrics. */ ! private long[] metrics = {0, 0, 0, 0}; ! /** The total number of accesses to the cache. */ ! public final static int AccessCount = 0; ! /** The total number of access hits to the immutable cache */ ! public final static int ImmutableHitCount = 1; ! /** The total number of access hits to the mutable cache. */ ! public final static int MutableHitCount = 2; ! /** The total number of access faults returning null. */ ! public final static int AccessFaultCount = 3; ! /** ! * Constructs and preloads the cache ! * and if there is a subclass of ChangeControl ! * it is to be used instead of the default ! * base class. ! * @param preload A map to place into the cache and it ! * may be null. ! * @param changeControlClass The class which implements change ! * control and this may be null in which case VFC provides ! * the change control mechanics. ! * @param refreshRate the period of time between generational ! * updates provided the cache is idle during the refresh period. ! */ ! CacheImpl(Map preload, Class changeControlClass, int refreshRate) { ! int load = 500; ! if (preload != null) load = preload.size() * 2; ! immutable = new HashMap(load, (float) 0.5); ! mutable = new HashMap(load, (float) 0.5); ! if (preload != null) { ! immutable.putAll(preload); ! mutable.putAll(preload); ! } ! if (changeControlClass == null) { ! changeControl = new ChangeControl(); ! } ! else { ! try { ! changeControl = (ChangeControl) changeControlClass.newInstance(); ! } ! catch (Exception e) { ! e.printStackTrace(System.err); changeControl = new ChangeControl(); ! } ! } ! changeControlMutex = changeControl.setCacheImpl(this, refreshRate); ! } ! // the interface implementations ! /** ! * Gets a value from the immutable cache. ! * <p> ! * Note: this implementation will also ! * search the mutable cache if the element ! * is not found in the mutable cache. ! * @param argument The key to the element in the cache. ! */ ! public Object get(Object argument) { ! HashMap h; ! synchronized (immutable) { ! h = immutable; ! } ! Object o = h.get(argument); ! if (o == null) { ! synchronized (changeControlMutex) { ! o = mutable.get(argument); ! } ! } ! return o; ! } ! /** ! * Uncomment out this method and comment the above ! * get to enable performance metrics on the public ! * variables. ! */ /* public Object get(Object argument) { --- 23,136 ---- * cache strategy of VFC. */ ! public class CacheImpl implements UpdateableCache ! { ! /** ! * The immutable cache with a volatile reference ! * so that its reference is cached in local memory. ! */ ! volatile HashMap immutable; ! /** The mutable cache used for updates. */ ! volatile HashMap mutable; ! /** The change control agent. */ ! ChangeControl changeControl; ! /** The change control mutex. */ ! Object changeControlMutex; ! /** The array containing the metrics. */ ! private long[] metrics = {0, 0, 0, 0}; ! /** The total number of accesses to the cache. */ ! public final static int AccessCount = 0; ! /** The total number of access hits to the immutable cache */ ! public final static int ImmutableHitCount = 1; ! /** The total number of access hits to the mutable cache. */ ! public final static int MutableHitCount = 2; ! /** The total number of access faults returning null. */ ! public final static int AccessFaultCount = 3; ! /** ! * Constructs and preloads the cache ! * and if there is a subclass of ChangeControl ! * it is to be used instead of the default ! * base class. ! * @param preload A map to place into the cache and it ! * may be null. ! * @param changeControlClass The class which implements change ! * control and this may be null in which case VFC provides ! * the change control mechanics. ! * @param refreshRate the period of time between generational ! * updates provided the cache is idle during the refresh period. ! */ ! CacheImpl (Map preload, Class changeControlClass, int refreshRate) ! { ! int load = 500; ! if (preload != null) load = preload.size() * 2; ! immutable = new HashMap(load, (float) 0.5); ! mutable = new HashMap(load, (float) 0.5); ! if (preload != null) ! { ! immutable.putAll(preload); ! mutable.putAll(preload); ! } ! if (changeControlClass == null) ! { changeControl = new ChangeControl(); ! } ! else ! { ! try ! { ! changeControl = (ChangeControl) changeControlClass.newInstance(); ! } ! catch (Exception e) ! { ! e.printStackTrace(System.err); ! changeControl = new ChangeControl(); ! } ! } ! changeControlMutex = changeControl.setCacheImpl(this, refreshRate); ! } ! // the interface implementations ! /** ! * Gets a value from the immutable cache. ! * <p> ! * Note: this implementation will also ! * search the mutable cache if the element ! * is not found in the mutable cache. ! * @param argument The key to the element in the cache. ! */ ! public Object get (Object argument) ! { ! HashMap h; ! synchronized (immutable) ! { ! h = immutable; ! } ! Object o = h.get(argument); ! if (o == null) ! { ! synchronized (changeControlMutex) ! { ! o = mutable.get(argument); ! } ! } ! return o; ! } ! /** ! * Uncomment out this method and comment the above ! * get to enable performance metrics on the public ! * variables. ! */ /* public Object get(Object argument) { *************** *** 139,220 **** */ ! /** ! * Returns the metrics in the following order: ! * <pre> ! * [0] The total number of gets, accesses. ! * [1] The number of accesses which resulted in a hit to the immutable cache. ! * [2] The number of accesses which resulted in a hit to the mutable cache. ! * [3] The number of accesses which resulted in a fault and a need to ! * regenerate the cache entry. ! * </pre> ! */ ! public long[] getMetrics() { ! return metrics; ! } ! /** Returns the elements in the cache as an array using the current image. */ ! public Object[] values() { ! Object[] values = null; ! synchronized (changeControlMutex) { ! values = mutable.values().toArray(); ! } ! return values; ! } ! /** Returns the keys of the cache as an array. */ ! public Object[] keys() { ! Object[] keys = null; ! synchronized (changeControlMutex) { ! keys = mutable.keySet().toArray(); ! } ! return keys; ! } ! /** ! * Invalidates an object in the cache by removing ! * it from the mutable cache. On the next ! * regeneration, this element will no longer be in the ! * cache. ! * @param argument The key to the element in the cache. ! */ ! public void invalidate(Object argument) { ! changeControl.invalidate(argument); ! } ! /** ! * Invalidates the entire cache. ! */ ! public void invalidateAll() { ! changeControl.invalidateAll(); ! } ! /** ! * Puts an object into the cache by ! * enqueueing it on the immutable cache using ! * the change control delegate. ! * @param argument The key to the element in the cache. ! * @param value The element to place into the cache. ! */ ! public void put(Object argument, Object value) { ! changeControl.put(argument, value); ! } ! // management methods ! /** Allows for the cache to be explicitly updated. */ ! public void update() { ! changeControl.update(null, null); ! } ! /** Destroys this instance allowing for speedy GC action. */ ! void destroy() { ! changeControl.destroy(); ! immutable = null; ! mutable = null; ! changeControl = null; ! changeControlMutex = null; ! } --- 151,242 ---- */ ! /** ! * Returns the metrics in the following order: ! * <pre> ! * [0] The total number of gets, accesses. ! * [1] The number of accesses which resulted in a hit to the immutable cache. ! * [2] The number of accesses which resulted in a hit to the mutable cache. ! * [3] The number of accesses which resulted in a fault and a need to ! * regenerate the cache entry. ! * </pre> ! */ ! public long[] getMetrics () ! { ! return metrics; ! } ! /** Returns the elements in the cache as an array using the current image. */ ! public Object[] values () ! { ! Object[] values = null; ! synchronized (changeControlMutex) ! { ! values = mutable.values().toArray(); ! } ! return values; ! } ! /** Returns the keys of the cache as an array. */ ! public Object[] keys () ! { ! Object[] keys = null; ! synchronized (changeControlMutex) ! { ! keys = mutable.keySet().toArray(); ! } ! return keys; ! } ! /** ! * Invalidates an object in the cache by removing ! * it from the mutable cache. On the next ! * regeneration, this element will no longer be in the ! * cache. ! * @param argument The key to the element in the cache. ! */ ! public void invalidate (Object argument) ! { ! changeControl.invalidate(argument); ! } ! /** ! * Invalidates the entire cache. ! */ ! public void invalidateAll () ! { ! changeControl.invalidateAll(); ! } ! /** ! * Puts an object into the cache by ! * enqueueing it on the immutable cache using ! * the change control delegate. ! * @param argument The key to the element in the cache. ! * @param value The element to place into the cache. ! */ ! public void put (Object argument, Object value) ! { ! changeControl.put(argument, value); ! } ! // management methods ! /** Allows for the cache to be explicitly updated. */ ! public void update () ! { ! changeControl.update(null, null); ! } ! /** Destroys this instance allowing for speedy GC action. */ ! void destroy () ! { ! changeControl.destroy(); ! immutable = null; ! mutable = null; ! changeControl = null; ! changeControlMutex = null; ! } Index: ChangeControl.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/cache/immutable/ChangeControl.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ChangeControl.java 11 Jun 2002 17:43:20 -0000 1.4 --- ChangeControl.java 12 Jun 2003 00:47:43 -0000 1.5 *************** *** 13,20 **** package org.opendoors.cache.immutable; - import java.util.*; - import org.opendoors.util.PostponeObservable; /** * Default behavior for managing --- 13,22 ---- package org.opendoors.cache.immutable; import org.opendoors.util.PostponeObservable; + import java.util.HashMap; + import java.util.Observable; + import java.util.Observer; + /** * Default behavior for managing *************** *** 46,150 **** * @see org.opendoors.cache.UpdateableCache */ ! public class ChangeControl implements Observer { ! /** The actual cache under management. */ ! protected CacheImpl cache; ! /** ! * The thread delegate for managing changes. ! * By default, 5 seconds of inactivity must occur ! * before pending updates are propagated ! * and the immutable cache is upgraded. ! */ ! protected PostponeObservable observable; ! /** The synch mutex. */ ! protected Object actionMutex = new Object(); ! /** ! * The default constructor ! * which does nothing. ! */ ! public ChangeControl() { ! } ! /** ! * Sets up the cache for change control: the cache, the refresh ! * rate and returns the mutex. ! * @param cache The cache to manage. ! * @param refreshRate How often in millis to refresh the cache. ! * @return The mutex synchronizing updates. ! */ ! protected Object setCacheImpl(CacheImpl cache, int refreshRate) { ! this.cache = cache; ! observable = new PostponeObservable(refreshRate, true); ! observable.addObserver(this); ! return actionMutex; ! } ! /** ! * Schedules a removal of an element from the cache. ! */ ! void invalidate(Object argument) { ! synchronized (actionMutex) { ! cache.mutable.remove(argument); ! observable.propertyChange(null); ! } ! } ! /** ! * Schedules a removal of everything. ! */ ! void invalidateAll() { ! synchronized (actionMutex) { ! cache.mutable.clear(); ! observable.setChanged(); ! } ! } ! /** ! * Schedules a put to the queue. ! */ ! void put(Object argument, Object value) { ! synchronized (actionMutex) { ! cache.mutable.put(argument, value); ! observable.setChanged(); ! } ! } ! /** ! * Call back for changes pending to ! * be implemented. ! * <p> ! * Cache has been idle for at least n seconds. ! * <p> ! * This routine implements the generational update ! * such that the immutable becomes identical now ! * to the most current image in the mutable instance. ! */ ! public void update(Observable o, Object arg) { ! synchronized (actionMutex) { ! HashMap tmp = new HashMap(cache.mutable.size() * 2, (float) 0.5); ! tmp.putAll(cache.mutable); ! cache.immutable = tmp; ! //System.out.println("Cache Updated. Mutable Size=" + cache.mutable.size()); ! //System.out.println("Cache Updated. Size=" + cache.immutable.size()); ! } ! } ! /** ! * Destroys this instance making it inoperable. ! */ ! void destroy() { ! synchronized (actionMutex) { ! cache.mutable.clear(); ! cache.immutable.clear(); ! cache = null; ! } ! observable.destroy(); ! observable = null; ! actionMutex = null; ! } --- 48,165 ---- * @see org.opendoors.cache.UpdateableCache */ ! public class ChangeControl implements Observer ! { ! /** The actual cache under management. */ ! protected CacheImpl cache; ! /** ! * The thread delegate for managing changes. ! * By default, 5 seconds of inactivity must occur ! * before pending updates are propagated ! * and the immutable cache is upgraded. ! */ ! protected PostponeObservable observable; ! /** The synch mutex. */ ! protected Object actionMutex = new Object(); ! /** ! * The default constructor ! * which does nothing. ! */ ! public ChangeControl () ! { ! } ! /** ! * Sets up the cache for change control: the cache, the refresh ! * rate and returns the mutex. ! * @param cache The cache to manage. ! * @param refreshRate How often in millis to refresh the cache. ! * @return The mutex synchronizing updates. ! */ ! protected Object setCacheImpl (CacheImpl cache, int refreshRate) ! { ! this.cache = cache; ! observable = new PostponeObservable(refreshRate, true); ! observable.addObserver(this); ! return actionMutex; ! } ! /** ! * Schedules a removal of an element from the cache. ! */ ! void invalidate (Object argument) ! { ! synchronized (actionMutex) ! { ! cache.mutable.remove(argument); ! observable.propertyChange(null); ! } ! } ! /** ! * Schedules a removal of everything. ! */ ! void invalidateAll () ! { ! synchronized (actionMutex) ! { ! cache.mutable.clear(); ! observable.setChanged(); ! } ! } ! /** ! * Schedules a put to the queue. ! */ ! void put (Object argument, Object value) ! { ! synchronized (actionMutex) ! { ! cache.mutable.put(argument, value); ! observable.setChanged(); ! } ! } ! /** ! * Call back for changes pending to ! * be implemented. ! * <p> ! * Cache has been idle for at least n seconds. ! * <p> ! * This routine implements the generational update ! * such that the immutable becomes identical now ! * to the most current image in the mutable instance. ! */ ! public void update (Observable o, Object arg) ! { ! synchronized (actionMutex) ! { ! HashMap tmp = new HashMap(cache.mutable.size() * 2, (float) 0.5); ! tmp.putAll(cache.mutable); ! cache.immutable = tmp; ! //System.out.println("Cache Updated. Mutable Size=" + cache.mutable.size()); ! //System.out.println("Cache Updated. Size=" + cache.immutable.size()); ! } ! } ! /** ! * Destroys this instance making it inoperable. ! */ ! void destroy () ! { ! synchronized (actionMutex) ! { ! cache.mutable.clear(); ! cache.immutable.clear(); ! cache = null; ! } ! observable.destroy(); ! observable = null; ! actionMutex = null; ! } Index: Depopulate.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/cache/immutable/Depopulate.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** Depopulate.java 11 Jun 2002 17:43:20 -0000 1.4 --- Depopulate.java 12 Jun 2003 00:47:43 -0000 1.5 *************** *** 21,42 **** * @see Populate */ ! public class Depopulate implements Runnable { ! private Cache cache; ! int n, m; ! /** Construct the depopulator with test parameters. */ ! public Depopulate(Cache cache, int n, int m) { ! this.cache = cache; ! this.n = n; ! this.m = m; ! } ! /** Depopulates the cache according to the instance parameters. */ ! public void run() { ! for (int value = n; value < m; value++) { ! Integer i = new Integer(value); ! cache.invalidate(i); ! } ! } } --- 21,46 ---- * @see Populate */ ! public class Depopulate implements Runnable ! { ! private Cache cache; ! int n, m; ! /** Construct the depopulator with test parameters. */ ! public Depopulate (Cache cache, int n, int m) ! { ! this.cache = cache; ! this.n = n; ! this.m = m; ! } ! /** Depopulates the cache according to the instance parameters. */ ! public void run () ! { ! for (int value = n; value < m; value++) ! { ! Integer i = new Integer(value); ! cache.invalidate(i); ! } ! } } Index: Populate.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/cache/immutable/Populate.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Populate.java 11 Jun 2002 17:43:20 -0000 1.3 --- Populate.java 12 Jun 2003 00:47:43 -0000 1.4 *************** *** 21,45 **** * @see Depopulate */ ! public class Populate implements Runnable { ! private Cache cache; ! int n, m; ! public long tet; ! /** Construct the populator with test parameters. */ ! public Populate(Cache cache, int n, int m) { ! this.cache = cache; ! this.n = n; ! this.m = m; ! } ! /** Populates the cache according to the instance parameters. */ ! public void run() { ! tet = System.currentTimeMillis(); ! for (int value = n; value < m; value++) { ! Integer i = new Integer(value); ! cache.put(i, i); ! } ! tet = System.currentTimeMillis() - tet; ! } } --- 21,49 ---- * @see Depopulate */ ! public class Populate implements Runnable ! { ! private Cache cache; ! int n, m; ! public long tet; ! /** Construct the populator with test parameters. */ ! public Populate (Cache cache, int n, int m) ! { ! this.cache = cache; ! this.n = n; ! this.m = m; ! } ! /** Populates the cache according to the instance parameters. */ ! public void run () ! { ! tet = System.currentTimeMillis(); ! for (int value = n; value < m; value++) ! { ! Integer i = new Integer(value); ! cache.put(i, i); ! } ! tet = System.currentTimeMillis() - tet; ! } } |
From: <dr...@us...> - 2003-06-12 00:48:16
|
Update of /cvsroot/webmacro/webmacro/src/org/opendoors/cache In directory sc8-pr-cvs1:/tmp/cvs-serv6675/src/org/opendoors/cache Modified Files: Cache.java UpdateableCache.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: Cache.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/cache/Cache.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Cache.java 11 Jun 2002 17:43:20 -0000 1.3 --- Cache.java 12 Jun 2003 00:47:42 -0000 1.4 *************** *** 25,72 **** * @author Lane Sharman */ ! public interface Cache { ! /** ! * Invalidate an object in the cache according ! * to the update strategy. ! */ ! public void invalidate(Object key); ! /** ! * Invalidates all the objects in the cache in one shot. ! * <p> ! * The action is performed according to the update strategy ! * of the implementation. ! */ ! public void invalidateAll(); ! /** ! * Put an object in the cache possibly ! * updating and replacing an existing value. ! * <p> ! * Note: some implementations elect to defer ! * this operation so the element may not ! * be immediately present. ! */ ! public void put(Object key, Object value); ! /** ! * Gets a value from the cache. ! * <p> ! * Returning null reports that the element ! * cannot be found or regenerate with the key ! * provided. ! */ ! public Object get(Object key); ! /** ! * Returns all the values in the cache. ! */ ! public Object[] values(); ! /** ! * Returns all the keys in the cache. ! */ ! public Object[] keys(); } --- 25,73 ---- * @author Lane Sharman */ ! public interface Cache ! { ! /** ! * Invalidate an object in the cache according ! * to the update strategy. ! */ ! public void invalidate (Object key); ! /** ! * Invalidates all the objects in the cache in one shot. ! * <p> ! * The action is performed according to the update strategy ! * of the implementation. ! */ ! public void invalidateAll (); ! /** ! * Put an object in the cache possibly ! * updating and replacing an existing value. ! * <p> ! * Note: some implementations elect to defer ! * this operation so the element may not ! * be immediately present. ! */ ! public void put (Object key, Object value); ! /** ! * Gets a value from the cache. ! * <p> ! * Returning null reports that the element ! * cannot be found or regenerate with the key ! * provided. ! */ ! public Object get (Object key); ! /** ! * Returns all the values in the cache. ! */ ! public Object[] values (); ! /** ! * Returns all the keys in the cache. ! */ ! public Object[] keys (); } Index: UpdateableCache.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/opendoors/cache/UpdateableCache.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** UpdateableCache.java 11 Jun 2002 17:43:20 -0000 1.3 --- UpdateableCache.java 12 Jun 2003 00:47:43 -0000 1.4 *************** *** 20,32 **** * recent mutations to the cache. */ ! public interface UpdateableCache extends Cache { ! /** ! * Updates the cache. ! * <p> ! * Upon completion, the cache is up to date ! * w/respect to all pending updates. ! */ ! public void update(); } --- 20,33 ---- * recent mutations to the cache. */ ! public interface UpdateableCache extends Cache ! { ! /** ! * Updates the cache. ! * <p> ! * Upon completion, the cache is up to date ! * w/respect to all pending updates. ! */ ! public void update (); } |
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/util In directory sc8-pr-cvs1:/tmp/cvs-serv6675/src/org/webmacro/util Modified Files: AbstractLogFile.java AbstractScalableMap.java ArrayIterator.java Atomizer.java Bag.java Base64.java ByteBufferOutputStream.java CastUtil.java Clock.java ComponentMap.java DictionaryTool.java Encoder.java EncoderProvider.java EncodingCache.java EnumIterator.java Eval.java HTMLEscaper.java IntMap.java IntStack.java InvalidArgumentException.java LogFile.java LogSource.java LogSystem.java LogTarget.java LogTargetFactory.java Named.java NativeAsciiReader.java Pool.java PrimitiveArrayIterator.java PropertyMethod.java QueueWriter.java ScalableIdentityMap.java ScalableMap.java ScalablePool.java SelectList.java Settings.java SharedObject.java SharedReference.java SimpleHashMap.java SimpleIdentityMap.java SimpleMap.java SimpleMapFactory.java SimpleStack.java SparseArrayIterator.java SparseProperties.java StringArray.java SubSettings.java ThreadScheduler.java TimeLoop.java UPool.java WMEval.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: AbstractLogFile.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/AbstractLogFile.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** AbstractLogFile.java 11 Jun 2002 17:43:23 -0000 1.3 --- AbstractLogFile.java 12 Jun 2003 00:47:48 -0000 1.4 *************** *** 32,131 **** */ ! abstract public class AbstractLogFile implements LogTarget { ! protected Map _levels = new HashMap(); ! protected boolean _trace = false; ! protected int _defaultLevel = LogSystem.NOTICE; ! protected String _defaultFormatString = "{0,time}\t{1}\t{2}\t{3}"; ! protected String _formatString = _defaultFormatString; ! protected MessageFormat _mf; ! protected List _observers = new LinkedList(); ! protected String _name; ! /** ! * Create a new LogFile instance reading properties from the ! * supplied Settings object: <pre> ! * LogTraceExceptions: true|false|yes|no|on|off ! * LogLevel: ! */ ! public AbstractLogFile(Settings s) { ! _trace = s.getBooleanSetting("LogTraceExceptions"); ! String slevel = s.getSetting("LogLevel", "NOTICE"); ! _defaultLevel = LogSystem.getLevel(slevel); ! String format = s.getSetting("LogFormat"); ! if (format != null) ! _formatString = format; ! _mf = new MessageFormat(_formatString); ! Settings levels = new SubSettings(s, "LogLevel"); ! String[] keys = levels.getKeys(); ! for (int i = 0; i < keys.length; i++) ! _levels.put(keys[i], new Integer(LogSystem.getLevel( ! levels.getSetting(keys[i])))); ! } ! public AbstractLogFile() { ! _mf = new MessageFormat(_formatString); ! } ! public String toString() { ! return "LogFile(name=" + _name + ", level=" + _defaultLevel + ", trace=" + _trace + ")"; ! } ! /** ! * Set the log level for this Logfile. The default is LogSystem.NOTICE ! */ ! public void setLogLevel(int level) { ! _defaultLevel = level; ! Iterator i = _observers.iterator(); ! while (i.hasNext()) { ! LogSystem ls = (LogSystem) i.next(); ! ls.update(this, null); ! } ! } ! /** ! * Set the log level for a specific category name. ! */ ! public void setLogLevel(String name, int level) { ! _levels.put(name, new Integer(level)); ! Iterator i = _observers.iterator(); ! while (i.hasNext()) { ! LogSystem ls = (LogSystem) i.next(); ! ls.update(this, name); ! } ! } ! /** ! * Set whether this LogFile traces exceptions. The ! * default is false. ! */ ! public void setTraceExceptions(boolean trace) { ! _trace = trace; ! } ! public boolean subscribe(String category, String name, int level) { ! Integer ilevel = (Integer) _levels.get(name); ! boolean sub; ! if (ilevel != null) { ! sub = (ilevel.intValue() <= level); ! } ! else { ! sub = (_defaultLevel <= level); ! } ! return sub; ! } ! public void addObserver(LogSystem ls) { ! _observers.add(ls); ! } ! public void removeObserver(LogSystem ls) { ! _observers.remove(ls); ! } } --- 32,145 ---- */ ! abstract public class AbstractLogFile implements LogTarget ! { ! protected Map _levels = new HashMap(); ! protected boolean _trace = false; ! protected int _defaultLevel = LogSystem.NOTICE; ! protected String _defaultFormatString = "{0,time}\t{1}\t{2}\t{3}"; ! protected String _formatString = _defaultFormatString; ! protected MessageFormat _mf; ! protected List _observers = new LinkedList(); ! protected String _name; ! /** ! * Create a new LogFile instance reading properties from the ! * supplied Settings object: <pre> ! * LogTraceExceptions: true|false|yes|no|on|off ! * LogLevel: ! */ ! public AbstractLogFile (Settings s) ! { ! _trace = s.getBooleanSetting("LogTraceExceptions"); ! String slevel = s.getSetting("LogLevel", "NOTICE"); ! _defaultLevel = LogSystem.getLevel(slevel); ! String format = s.getSetting("LogFormat"); ! if (format != null) ! _formatString = format; ! _mf = new MessageFormat(_formatString); ! Settings levels = new SubSettings(s, "LogLevel"); ! String[] keys = levels.getKeys(); ! for (int i = 0; i < keys.length; i++) ! _levels.put(keys[i], new Integer(LogSystem.getLevel( ! levels.getSetting(keys[i])))); ! } ! public AbstractLogFile () ! { ! _mf = new MessageFormat(_formatString); ! } ! public String toString () ! { ! return "LogFile(name=" + _name + ", level=" + _defaultLevel + ", trace=" + _trace + ")"; ! } ! /** ! * Set the log level for this Logfile. The default is LogSystem.NOTICE ! */ ! public void setLogLevel (int level) ! { ! _defaultLevel = level; ! Iterator i = _observers.iterator(); ! while (i.hasNext()) ! { ! LogSystem ls = (LogSystem) i.next(); ! ls.update(this, null); ! } ! } ! /** ! * Set the log level for a specific category name. ! */ ! public void setLogLevel (String name, int level) ! { ! _levels.put(name, new Integer(level)); ! Iterator i = _observers.iterator(); ! while (i.hasNext()) ! { ! LogSystem ls = (LogSystem) i.next(); ! ls.update(this, name); ! } ! } ! /** ! * Set whether this LogFile traces exceptions. The ! * default is false. ! */ ! public void setTraceExceptions (boolean trace) ! { ! _trace = trace; ! } ! public boolean subscribe (String category, String name, int level) ! { ! Integer ilevel = (Integer) _levels.get(name); ! boolean sub; ! if (ilevel != null) ! { ! sub = (ilevel.intValue() <= level); ! } ! else ! { ! sub = (_defaultLevel <= level); ! } ! return sub; ! } ! public void addObserver (LogSystem ls) ! { ! _observers.add(ls); ! } ! public void removeObserver (LogSystem ls) ! { ! _observers.remove(ls); ! } } Index: AbstractScalableMap.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/AbstractScalableMap.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** AbstractScalableMap.java 11 Jun 2002 17:43:23 -0000 1.2 --- AbstractScalableMap.java 12 Jun 2003 00:47:48 -0000 1.3 *************** *** 33,87 **** * as real maps. */ ! public class AbstractScalableMap implements SimpleMap { ! public static final int DEFAULT_FACTOR = 5; ! private final int factor; ! private final SimpleMap[] _maps; ! private int pos = 0; ! /** ! * Create a new scalable map, that uses ! * factor SimpleMaps. SimpleMap object are ! * created by mapFactory. ! * @param factor number of SimpleMaps to create ! * @param mapFactory object to create SimpleMap objects ! **/ ! public AbstractScalableMap(int factor, SimpleMapFactory mapFactory) { ! super(); ! this.factor = factor; ! _maps = new SimpleMap[factor]; ! for (int i = 0; i < factor; i++) { ! _maps[i] = mapFactory.createSimpleMap(); ! } ! } ! public AbstractScalableMap(SimpleMapFactory mapFactory) { ! this(DEFAULT_FACTOR, mapFactory); ! } ! public void put(final Object key, final Object value) { ! for (int i = 0; i < factor; i++) { ! _maps[i].put(key, value); ! } ! } ! public Object get(final Object key) { ! pos = (pos + 1) % factor; ! return _maps[pos].get(key); ! } ! public Object remove(final Object key) { ! Object o = null; ! for (int i = 0; i < _maps.length; i++) { ! o = _maps[i].remove(key); ! } ! return o; ! } ! public void clear() { ! for (int i = 0; i < _maps.length; i++) { ! _maps[i].clear(); ! } ! } } --- 33,98 ---- * as real maps. */ ! public class AbstractScalableMap implements SimpleMap ! { ! public static final int DEFAULT_FACTOR = 5; ! private final int factor; ! private final SimpleMap[] _maps; ! private int pos = 0; ! /** ! * Create a new scalable map, that uses ! * factor SimpleMaps. SimpleMap object are ! * created by mapFactory. ! * @param factor number of SimpleMaps to create ! * @param mapFactory object to create SimpleMap objects ! **/ ! public AbstractScalableMap (int factor, SimpleMapFactory mapFactory) ! { ! super(); ! this.factor = factor; ! _maps = new SimpleMap[factor]; ! for (int i = 0; i < factor; i++) ! { ! _maps[i] = mapFactory.createSimpleMap(); ! } ! } ! public AbstractScalableMap (SimpleMapFactory mapFactory) ! { ! this(DEFAULT_FACTOR, mapFactory); ! } ! public void put (final Object key, final Object value) ! { ! for (int i = 0; i < factor; i++) ! { ! _maps[i].put(key, value); ! } ! } ! public Object get (final Object key) ! { ! pos = (pos + 1) % factor; ! return _maps[pos].get(key); ! } ! public Object remove (final Object key) ! { ! Object o = null; ! for (int i = 0; i < _maps.length; i++) ! { ! o = _maps[i].remove(key); ! } ! return o; ! } ! public void clear () ! { ! for (int i = 0; i < _maps.length; i++) ! { ! _maps[i].clear(); ! } ! } } Index: ArrayIterator.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/ArrayIterator.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ArrayIterator.java 11 Jun 2002 17:43:23 -0000 1.6 --- ArrayIterator.java 12 Jun 2003 00:47:48 -0000 1.7 *************** *** 24,28 **** package org.webmacro.util; ! import java.util.*; --- 24,29 ---- package org.webmacro.util; ! import java.util.Iterator; ! import java.util.NoSuchElementException; *************** *** 30,88 **** * This provides an iterator interface to an array */ ! final public class ArrayIterator implements Iterator { ! final Object[] a; ! int pos; ! /** ! * Construct an iterator given an enumeration ! */ ! public ArrayIterator(Object[] array) { ! this.a = array; ! pos = 0; ! } ! /** ! * Return true if we have not yet reached the end of the enumeration ! */ ! final public boolean hasNext() { ! return (pos < a.length); ! } ! /** ! * Advance the iterator and return the next value. Return null if we ! * reach the end of the enumeration. ! */ ! final public Object next() throws NoSuchElementException { ! if (pos < a.length) { ! return a[pos++]; ! } ! else { ! throw new NoSuchElementException("Advanced beyond end of array"); ! } ! } ! /** ! * Unsupported ! */ ! final public void remove() throws UnsupportedOperationException { ! throw new UnsupportedOperationException(); ! } ! /** ! * Test harness ! */ ! static public void main(String arg[]) { ! try { ! Iterator i = new ArrayIterator(arg); ! while (i.hasNext()) { ! System.out.println("item: " + i.next()); ! } ! } ! catch (Exception e) { ! e.printStackTrace(); ! } ! } } --- 31,100 ---- * This provides an iterator interface to an array */ ! final public class ArrayIterator implements Iterator ! { ! final Object[] a; ! int pos; ! /** ! * Construct an iterator given an enumeration ! */ ! public ArrayIterator (Object[] array) ! { ! this.a = array; ! pos = 0; ! } ! /** ! * Return true if we have not yet reached the end of the enumeration ! */ ! final public boolean hasNext () ! { ! return (pos < a.length); ! } ! /** ! * Advance the iterator and return the next value. Return null if we ! * reach the end of the enumeration. ! */ ! final public Object next () throws NoSuchElementException ! { ! if (pos < a.length) ! { ! return a[pos++]; ! } ! else ! { ! throw new NoSuchElementException("Advanced beyond end of array"); ! } ! } ! /** ! * Unsupported ! */ ! final public void remove () throws UnsupportedOperationException ! { ! throw new UnsupportedOperationException(); ! } ! /** ! * Test harness ! */ ! static public void main (String arg[]) ! { ! try ! { ! Iterator i = new ArrayIterator(arg); ! while (i.hasNext()) ! { ! System.out.println("item: " + i.next()); ! } ! } ! catch (Exception e) ! { ! e.printStackTrace(); ! } ! } } Index: Atomizer.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/Atomizer.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** Atomizer.java 11 Jun 2002 17:43:23 -0000 1.7 --- Atomizer.java 12 Jun 2003 00:47:48 -0000 1.8 *************** *** 24,28 **** package org.webmacro.util; ! import java.util.*; /** --- 24,29 ---- package org.webmacro.util; ! import java.util.HashMap; ! import java.util.Iterator; /** *************** *** 30,204 **** * that atomic number back into the original object. */ ! final public class Atomizer implements Cloneable { ! private HashMap _atoms; ! private Object[] _values; ! private Pool _freeAtoms = new ScalablePool(); ! private int _max = 0; ! /** ! * Create an atomizer with space for 100 atoms ! */ ! public Atomizer() { ! this(100); ! } ! /** ! * Create an atomizer with space for the specified number ! * of atoms. ! */ ! public Atomizer(int size) { ! _atoms = new HashMap((int) (size / .75 + 1)); ! _values = new Object[size]; ! } ! /** ! * Clone this Atomizer ! */ ! public Object clone() { ! try { ! Atomizer c = (Atomizer) super.clone(); ! c._atoms = (HashMap) _atoms.clone(); ! c._values = (Object[]) _values.clone(); ! c._freeAtoms = new ScalablePool(); ! return c; ! } ! catch (CloneNotSupportedException e) { ! // never gonna happen ! return null; ! } ! } ! /** ! * Get the atomic number for o. If o does not have an atomic ! * number return -1. ! */ ! public int lookup(Object o) { ! Integer atom = (Integer) _atoms.get(o); ! return (atom != null) ? atom.intValue() : -1; ! } ! /** ! * Put an object in the atomizer, return its atomic number. ! * You will need this atomic number later to access the object. ! * If the object is already in the atomizer you will get back ! * the same atomic number as last time. ! */ ! public int atomize(Object o) { ! Integer atom = (Integer) _atoms.get(o); ! int i; ! if (atom == null) { ! atom = (Integer) _freeAtoms.get(); ! if (atom == null) { ! atom = new Integer(_max++); ! } ! i = atom.intValue(); ! if (_max == _values.length) { ! int newM = _max * 2 + 1; ! Object[] newV = new Object[newM]; ! System.arraycopy(_values, 0, newV, 0, _max); ! _values = newV; ! } ! _values[i] = o; ! _atoms.put(o, atom); ! } ! else { ! i = atom.intValue(); ! } ! return i; ! } ! /** ! * Get the Object matching this atom ! */ ! public Object get(int atom) { ! try { ! return _values[atom]; ! } ! catch (ArrayIndexOutOfBoundsException e) { ! return null; ! } ! } ! /** ! * Remove an entry by atomic number, returning its former value. ! */ ! public Object remove(int atom) { ! try { ! Object o = _values[atom]; ! remove(o); ! return o; ! } ! catch (ArrayIndexOutOfBoundsException e) { ! return null; ! } ! } ! /** ! * Remove an entry by value ! */ ! public void remove(Object o) { ! if (o == null) { ! return; ! } ! Integer atom = (Integer) _atoms.remove(o); ! if (atom == null) { ! return; ! } ! _values[atom.intValue()] = null; ! _freeAtoms.put(atom); ! } ! /** ! * Get an iterator capable of walking through all the values ! * in the atomizer. ! */ ! public Iterator iterator() { ! return new Iter(_values); ! } ! /** ! * Test based on command line args ! */ ! public static void main(String arg[]) { ! Atomizer a = new Atomizer(3); ! int atoms[] = new int[arg.length]; ! for (int i = 0; i < arg.length; i++) { ! atoms[i] = a.atomize(arg[i]); ! System.out.println("Atomized " + arg[i] + " to " + atoms[i]); ! } ! for (int i = 0; i < atoms.length; i++) { ! System.out.println("Atom " + atoms[i] + " is " + a.get(atoms[i])); ! } ! Iterator iter = a.iterator(); ! while (iter.hasNext()) { ! Object o = iter.next(); ! System.out.println("RM: Object " + o + " was atom " + a.atomize(o)); ! iter.remove(); ! } ! atoms = new int[arg.length]; ! for (int i = 0; i < arg.length; i++) { ! atoms[i] = a.atomize(arg[i]); ! System.out.println("Atomized " + arg[i] + " to " + atoms[i]); ! } ! } ! class Iter extends SparseArrayIterator { ! Iter(Object values[]) { ! super(values); ! } ! public void remove() throws IllegalStateException { ! if (_last < 0) { ! throw new IllegalStateException("Remove called before next()"); ! } ! Atomizer.this.remove(this._values[this._last]); ! } ! } } --- 31,236 ---- * that atomic number back into the original object. */ ! final public class Atomizer implements Cloneable ! { ! private HashMap _atoms; ! private Object[] _values; ! private Pool _freeAtoms = new ScalablePool(); ! private int _max = 0; ! /** ! * Create an atomizer with space for 100 atoms ! */ ! public Atomizer () ! { ! this(100); ! } ! /** ! * Create an atomizer with space for the specified number ! * of atoms. ! */ ! public Atomizer (int size) ! { ! _atoms = new HashMap((int) (size / .75 + 1)); ! _values = new Object[size]; ! } ! /** ! * Clone this Atomizer ! */ ! public Object clone () ! { ! try ! { ! Atomizer c = (Atomizer) super.clone(); ! c._atoms = (HashMap) _atoms.clone(); ! c._values = (Object[]) _values.clone(); ! c._freeAtoms = new ScalablePool(); ! return c; ! } ! catch (CloneNotSupportedException e) ! { ! // never gonna happen ! return null; ! } ! } ! /** ! * Get the atomic number for o. If o does not have an atomic ! * number return -1. ! */ ! public int lookup (Object o) ! { ! Integer atom = (Integer) _atoms.get(o); ! return (atom != null) ? atom.intValue() : -1; ! } ! /** ! * Put an object in the atomizer, return its atomic number. ! * You will need this atomic number later to access the object. ! * If the object is already in the atomizer you will get back ! * the same atomic number as last time. ! */ ! public int atomize (Object o) ! { ! Integer atom = (Integer) _atoms.get(o); ! int i; ! if (atom == null) ! { ! atom = (Integer) _freeAtoms.get(); ! if (atom == null) ! { ! atom = new Integer(_max++); ! } ! i = atom.intValue(); ! if (_max == _values.length) ! { ! int newM = _max * 2 + 1; ! Object[] newV = new Object[newM]; ! System.arraycopy(_values, 0, newV, 0, _max); ! _values = newV; ! } ! _values[i] = o; ! _atoms.put(o, atom); ! } ! else ! { ! i = atom.intValue(); ! } ! return i; ! } ! /** ! * Get the Object matching this atom ! */ ! public Object get (int atom) ! { ! try ! { ! return _values[atom]; ! } ! catch (ArrayIndexOutOfBoundsException e) ! { ! return null; ! } ! } ! /** ! * Remove an entry by atomic number, returning its former value. ! */ ! public Object remove (int atom) ! { ! try ! { ! Object o = _values[atom]; ! remove(o); ! return o; ! } ! catch (ArrayIndexOutOfBoundsException e) ! { ! return null; ! } ! } ! /** ! * Remove an entry by value ! */ ! public void remove (Object o) ! { ! if (o == null) ! { ! return; ! } ! Integer atom = (Integer) _atoms.remove(o); ! if (atom == null) ! { ! return; ! } ! _values[atom.intValue()] = null; ! _freeAtoms.put(atom); ! } ! /** ! * Get an iterator capable of walking through all the values ! * in the atomizer. ! */ ! public Iterator iterator () ! { ! return new Iter(_values); ! } ! /** ! * Test based on command line args ! */ ! public static void main (String arg[]) ! { ! Atomizer a = new Atomizer(3); ! int atoms[] = new int[arg.length]; ! for (int i = 0; i < arg.length; i++) ! { ! atoms[i] = a.atomize(arg[i]); ! System.out.println("Atomized " + arg[i] + " to " + atoms[i]); ! } ! for (int i = 0; i < atoms.length; i++) ! { ! System.out.println("Atom " + atoms[i] + " is " + a.get(atoms[i])); ! } ! Iterator iter = a.iterator(); ! while (iter.hasNext()) ! { ! Object o = iter.next(); ! System.out.println("RM: Object " + o + " was atom " + a.atomize(o)); ! iter.remove(); ! } ! atoms = new int[arg.length]; ! for (int i = 0; i < arg.length; i++) ! { ! atoms[i] = a.atomize(arg[i]); ! System.out.println("Atomized " + arg[i] + " to " + atoms[i]); ! } ! } ! class Iter extends SparseArrayIterator ! { ! Iter (Object values[]) ! { ! super(values); ! } ! public void remove () throws IllegalStateException ! { ! if (_last < 0) ! { ! throw new IllegalStateException("Remove called before next()"); ! } ! Atomizer.this.remove(this._values[this._last]); ! } ! } } Index: Bag.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/Bag.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Bag.java 11 Jun 2002 17:43:23 -0000 1.5 --- Bag.java 12 Jun 2003 00:47:48 -0000 1.6 *************** *** 31,50 **** * a dictionary, but similar in nature. */ ! public interface Bag { ! /** ! * Add an item to the bag ! */ ! public void put(String itemName, Object item) throws UnsettableException; ! /** ! * Get an item from the bag ! */ ! public Object get(String itemName); ! /** ! * Remove an item from the bag ! */ ! public void remove(String itemName) throws UnsettableException; --- 31,51 ---- * a dictionary, but similar in nature. */ ! public interface Bag ! { ! /** ! * Add an item to the bag ! */ ! public void put (String itemName, Object item) throws UnsettableException; ! /** ! * Get an item from the bag ! */ ! public Object get (String itemName); ! /** ! * Remove an item from the bag ! */ ! public void remove (String itemName) throws UnsettableException; Index: Base64.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/Base64.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** Base64.java 12 Jun 2002 17:17:28 -0000 1.4 --- Base64.java 12 Jun 2003 00:47:48 -0000 1.5 *************** *** 24,289 **** package org.webmacro.util; ! final public class Base64 { ! ! private static final byte UPPER_FOUR = (byte) (16 + 32 + 64 + 128); ! private static final byte LOWER_FOUR = (byte) (1 + 2 + 4 + 8); ! private static final byte UPPER_SIX = (byte) (4 + 8 + 16 + 32 + 64 + 128); ! private static final byte LOWER_TWO = (byte) (1 + 2); ! private static final byte UPPER_TWO = (byte) (64 + 128); ! private static final byte LOWER_SIX = (byte) (1 + 2 + 4 + 8 + 16 + 32); ! ! /** ! * Get the plain text version of a base64 encoded string ! */ - final public static String decode(String encoded) { - return decode(encoded.getBytes()); - } ! /** ! * Get the base64 encoded version of a plain text String ! */ ! final public static String encode(String plainText) { ! return encode(plainText.getBytes()); ! } ! /** ! * Ge tthe plain text version of a base64 encoded byte array ! */ ! final public static String decode(byte[] encoded) { ! byte[] plain = new byte[(int) (encoded.length * 0.75) + 2]; ! byte code, ptext; ! int ppos = 0; ! int epos = 0; ! boolean cutShort = false; ! while (epos < encoded.length) { ! /* ! * base64 decoding: turn 4*6 bits into 3*8 bits via the pattern: ! * xx111111 xx112222 xx222233 xx333333 (xx: high bits unused) ! */ ! code = sixBits(encoded[epos]); ! // 1st byte: lower six bits from 1st char ! ptext = (byte) (code << 2); - // 1st byte: plus upper two (of six) bits from 2nd char - epos++; - try { code = sixBits(encoded[epos]); - } - catch (Exception e) { - code = 0; // too few chars, assume missing pad - cutShort = true; - } - ptext |= (code & UPPER_FOUR) >>> 4; - plain[ppos++] = ptext; - if (cutShort) { - break; // loop - } ! // 2nd byte: lower four bytes from 2nd char ! ptext = (byte) ((code & LOWER_FOUR) << 4); - // 2nd byte: plus upper four (of six) bits from 3rd char - epos++; - try { - code = sixBits(encoded[epos]); - } - catch (Exception e) { - code = 0; // too few chars, assume missing pad - } - ptext |= (code & UPPER_SIX) >>> 2; - plain[ppos++] = ptext; - if (cutShort) { - break; // loop - } ! // 3rd byte: lower two bits of 3rd char ! ptext = (byte) ((code & LOWER_TWO) << 6); ! // 3rd byte: lower six bits of fourth char ! epos++; ! try { ! code = sixBits(encoded[epos]); ! } ! catch (Exception e) { ! code = 0; // too few chars, assume missing pad ! } ! ptext |= code; ! plain[ppos++] = ptext; ! // advance loop ! epos++; ! } ! return new String(plain); ! } - /** - * Get the base64 encoded version of a plain text byte array - */ - final static public String encode(byte[] plain) { ! /* ! * base64 encoding: turn 3*8 bits into 4*6 bits via the pattern: ! * 111111 112222 222233 333333 (xx: high bits unused) ! * UPPER6 LOWER2 LOWER4 LOWER6 ! * UPPER4 UPPER2 ! **/ ! StringBuffer encoded = new StringBuffer((int) (plain.length * 1.34) + 1); ! byte ptext; ! byte sixbits; ! int ppos = 0; ! boolean cutShort = false; ! while (ppos < plain.length) { ! // first char: upper 6 bytes ! ptext = plain[ppos]; ! sixbits = (byte) ((ptext & UPPER_SIX) >>> 2); ! encoded.append(base64(sixbits)); ! // second char: lower 2, upper 4 ! sixbits = (byte) ((ptext & LOWER_TWO) << 4); ! ppos++; ! try { ptext = plain[ppos]; ! } ! catch (ArrayIndexOutOfBoundsException e) { ! ptext = 0; ! cutShort = true; ! } ! sixbits |= (byte) ((ptext & UPPER_FOUR) >>> 4); ! encoded.append(base64(sixbits)); ! if (cutShort) { ! encoded.append("=="); ! return encoded.toString(); ! } ! // third char: lower four, upper 2 ! sixbits = (byte) ((ptext & LOWER_FOUR) << 2); ! ppos++; ! try { ! ptext = plain[ppos]; ! } ! catch (ArrayIndexOutOfBoundsException e) { ! ptext = 0; ! cutShort = true; ! } ! sixbits |= (byte) ((ptext & UPPER_TWO) >>> 6); ! encoded.append(base64(sixbits)); ! if (cutShort) { ! encoded.append("="); ! return encoded.toString(); ! } ! // fourth char: lower six ! sixbits = (byte) (ptext & LOWER_SIX); ! encoded.append(base64(sixbits)); ! // increment loop ! ppos++; ! } ! return encoded.toString(); ! } ! /** ! * Translate a character in the base64 alphabet into a byte with ! * the corresponding bits set (ie: a number from 0 to 64). ! * @return the base64 value, or 0 for the special '=' pad character ! * @param base64 the character to be translated ! * @exception NumberFormatException if base64 is not a base64 character ! */ ! private static byte sixBits(byte base64) ! throws NumberFormatException { - if ((base64 >= 'A') && (base64 <= 'Z')) { - return (byte) (base64 - 'A'); - } ! if ((base64 >= 'a') && (base64 <= 'z')) { ! return (byte) (base64 - 'a' + 26); ! } ! if ((base64 >= '0') && (base64 <= '9')) { ! return (byte) (base64 - '0' + 52); ! } ! if (base64 == '+') { ! return 62; ! } ! if (base64 == '/') { ! return 63; ! } ! if (base64 == '=') { ! return 0; // pad means zeroed bits FIXME: i am not sure, really? ! } ! throw new NumberFormatException("Not a base64 character: " + base64); ! } ! /** ! * Turn a six-bit value into a base64 digit ! */ ! static private char base64(byte sixBits) { ! if (sixBits <= 25) { // less/equal base64 'Z' ! return (char) ('A' + sixBits); ! } ! if (sixBits <= 51) { // less/equal base64 'z' ! return (char) ('a' + sixBits - 26); // count from base64 'a' ! } ! if (sixBits <= 61) { // less/equal base64 '9' ! return (char) ('0' + sixBits - 52); // count from base64 '0' ! } ! if (sixBits == 62) { ! return '+'; ! } ! if (sixBits == 63) { ! return '/'; ! } ! throw new NumberFormatException("Not a base64 digit: " + sixBits); ! } ! /** ! * Test harness ! */ ! public static void main(String arg[]) { - boolean encode; ! if (arg.length < 2) { ! System.out.println("Usage: Base64 encode|decode string"); ! return; ! } ! if (arg[0].equals("encode")) { ! encode = true; ! } ! else if (arg[0].equals("decode")) { ! encode = false; ! } ! else { ! System.out.println("Unrecognized argument: " + arg[0]); ! return; ! } ! System.out.println(encode ? encode(arg[1]) : decode(arg[1])); ! } } --- 24,328 ---- package org.webmacro.util; ! final public class Base64 ! { ! private static final byte UPPER_FOUR = (byte) (16 + 32 + 64 + 128); ! private static final byte LOWER_FOUR = (byte) (1 + 2 + 4 + 8); ! private static final byte UPPER_SIX = (byte) (4 + 8 + 16 + 32 + 64 + 128); ! private static final byte LOWER_TWO = (byte) (1 + 2); ! private static final byte UPPER_TWO = (byte) (64 + 128); ! private static final byte LOWER_SIX = (byte) (1 + 2 + 4 + 8 + 16 + 32); ! /** ! * Get the plain text version of a base64 encoded string ! */ ! final public static String decode (String encoded) ! { ! return decode(encoded.getBytes()); ! } ! /** ! * Get the base64 encoded version of a plain text String ! */ ! final public static String encode (String plainText) ! { ! return encode(plainText.getBytes()); ! } ! /** ! * Ge tthe plain text version of a base64 encoded byte array ! */ ! final public static String decode (byte[] encoded) ! { ! byte[] plain = new byte[(int) (encoded.length * 0.75) + 2]; ! byte code, ptext; ! int ppos = 0; ! int epos = 0; ! boolean cutShort = false; ! while (epos < encoded.length) ! { ! /* ! * base64 decoding: turn 4*6 bits into 3*8 bits via the pattern: ! * xx111111 xx112222 xx222233 xx333333 (xx: high bits unused) ! */ code = sixBits(encoded[epos]); + // 1st byte: lower six bits from 1st char + ptext = (byte) (code << 2); ! // 1st byte: plus upper two (of six) bits from 2nd char ! epos++; ! try ! { ! code = sixBits(encoded[epos]); ! } ! catch (Exception e) ! { ! code = 0; // too few chars, assume missing pad ! cutShort = true; ! } ! ptext |= (code & UPPER_FOUR) >>> 4; ! plain[ppos++] = ptext; ! if (cutShort) ! { ! break; // loop ! } ! // 2nd byte: lower four bytes from 2nd char ! ptext = (byte) ((code & LOWER_FOUR) << 4); ! // 2nd byte: plus upper four (of six) bits from 3rd char ! epos++; ! try ! { ! code = sixBits(encoded[epos]); ! } ! catch (Exception e) ! { ! code = 0; // too few chars, assume missing pad ! } ! ptext |= (code & UPPER_SIX) >>> 2; ! plain[ppos++] = ptext; ! if (cutShort) ! { ! break; // loop ! } + // 3rd byte: lower two bits of 3rd char + ptext = (byte) ((code & LOWER_TWO) << 6); ! // 3rd byte: lower six bits of fourth char ! epos++; ! try ! { ! code = sixBits(encoded[epos]); ! } ! catch (Exception e) ! { ! code = 0; // too few chars, assume missing pad ! } ! ptext |= code; ! plain[ppos++] = ptext; ! // advance loop ! epos++; ! } ! return new String(plain); ! } ! /** ! * Get the base64 encoded version of a plain text byte array ! */ ! final static public String encode (byte[] plain) ! { ! /* ! * base64 encoding: turn 3*8 bits into 4*6 bits via the pattern: ! * 111111 112222 222233 333333 (xx: high bits unused) ! * UPPER6 LOWER2 LOWER4 LOWER6 ! * UPPER4 UPPER2 ! **/ ! StringBuffer encoded = new StringBuffer((int) (plain.length * 1.34) + 1); ! byte ptext; ! byte sixbits; ! int ppos = 0; ! boolean cutShort = false; ! while (ppos < plain.length) ! { ! // first char: upper 6 bytes ptext = plain[ppos]; ! sixbits = (byte) ((ptext & UPPER_SIX) >>> 2); ! encoded.append(base64(sixbits)); ! // second char: lower 2, upper 4 ! sixbits = (byte) ((ptext & LOWER_TWO) << 4); ! ppos++; ! try ! { ! ptext = plain[ppos]; ! } ! catch (ArrayIndexOutOfBoundsException e) ! { ! ptext = 0; ! cutShort = true; ! } ! sixbits |= (byte) ((ptext & UPPER_FOUR) >>> 4); ! encoded.append(base64(sixbits)); ! if (cutShort) ! { ! encoded.append("=="); ! return encoded.toString(); ! } ! // third char: lower four, upper 2 ! sixbits = (byte) ((ptext & LOWER_FOUR) << 2); ! ppos++; ! try ! { ! ptext = plain[ppos]; ! } ! catch (ArrayIndexOutOfBoundsException e) ! { ! ptext = 0; ! cutShort = true; ! } ! sixbits |= (byte) ((ptext & UPPER_TWO) >>> 6); ! encoded.append(base64(sixbits)); ! if (cutShort) ! { ! encoded.append("="); ! return encoded.toString(); ! } + // fourth char: lower six + sixbits = (byte) (ptext & LOWER_SIX); + encoded.append(base64(sixbits)); ! // increment loop ! ppos++; ! } ! return encoded.toString(); ! } ! /** ! * Translate a character in the base64 alphabet into a byte with ! * the corresponding bits set (ie: a number from 0 to 64). ! * @return the base64 value, or 0 for the special '=' pad character ! * @param base64 the character to be translated ! * @exception NumberFormatException if base64 is not a base64 character ! */ ! private static byte sixBits (byte base64) ! throws NumberFormatException ! { ! if ((base64 >= 'A') && (base64 <= 'Z')) ! { ! return (byte) (base64 - 'A'); ! } ! if ((base64 >= 'a') && (base64 <= 'z')) ! { ! return (byte) (base64 - 'a' + 26); ! } ! if ((base64 >= '0') && (base64 <= '9')) ! { ! return (byte) (base64 - '0' + 52); ! } ! if (base64 == '+') ! { ! return 62; ! } ! if (base64 == '/') ! { ! return 63; ! } ! if (base64 == '=') ! { ! return 0; // pad means zeroed bits FIXME: i am not sure, really? ! } ! throw new NumberFormatException("Not a base64 character: " + base64); ! } ! /** ! * Turn a six-bit value into a base64 digit ! */ ! static private char base64 (byte sixBits) ! { ! if (sixBits <= 25) ! { // less/equal base64 'Z' ! return (char) ('A' + sixBits); ! } ! if (sixBits <= 51) ! { // less/equal base64 'z' ! return (char) ('a' + sixBits - 26); // count from base64 'a' ! } ! if (sixBits <= 61) ! { // less/equal base64 '9' ! return (char) ('0' + sixBits - 52); // count from base64 '0' ! } ! if (sixBits == 62) ! { ! return '+'; ! } + if (sixBits == 63) + { + return '/'; + } ! throw new NumberFormatException("Not a base64 digit: " + sixBits); ! } ! /** ! * Test harness ! */ ! public static void main (String arg[]) ! { ! boolean encode; ! if (arg.length < 2) ! { ! System.out.println("Usage: Base64 encode|decode string"); ! return; ! } ! if (arg[0].equals("encode")) ! { ! encode = true; ! } ! else if (arg[0].equals("decode")) ! { ! encode = false; ! } ! else ! { ! System.out.println("Unrecognized argument: " + arg[0]); ! return; ! } ! ! System.out.println(encode ? encode(arg[1]) : decode(arg[1])); ! ! } } Index: ByteBufferOutputStream.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/ByteBufferOutputStream.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ByteBufferOutputStream.java 11 Jun 2002 17:43:23 -0000 1.6 --- ByteBufferOutputStream.java 12 Jun 2003 00:47:48 -0000 1.7 *************** *** 24,192 **** package org.webmacro.util; ! import java.io.*; ! final public class ByteBufferOutputStream extends OutputStream { ! private byte[] _buf; ! private int _pos; ! private final int _initialSize; ! /** ! * Create a new ByteBuffer with the specified capacity ! */ ! public ByteBufferOutputStream(int size) { ! _buf = new byte[size]; ! _pos = 0; ! _initialSize = size; ! } ! /** ! * Clear the contents of the byte buffer. Also shrinks the byte buffer ! * to the size specified during construction of this ByteBufferOutputStream ! */ ! public void reset() { ! _pos = 0; ! _buf = new byte[_initialSize]; ! } ! public void write(int i) { ! write((byte) i); ! } ! /** ! * Copy an array of bytes on to the end of the buffer ! */ ! public void write(byte[] b) { ! int len = b.length; ! ensureCapacity(len); ! System.arraycopy(b, 0, _buf, _pos, len); ! _pos += len; ! } ! /** ! * Copy an array of bytes on to the end of the buffer ! */ ! public void write(byte[] b, int offset, int len) { ! ensureCapacity(len); ! System.arraycopy(b, 0, _buf, _pos, len); ! _pos += len; ! } ! /** ! * Append a single byte ! */ ! public void write(byte b) { ! ensureCapacity(1); ! _buf[_pos] = b; ! _pos++; ! } ! /** ! * Make sure the buffer contains space for len more bytes. ! */ ! public final void ensureCapacity(int len) { ! if (_buf.length < _pos + len) { ! int blen = _buf.length; ! while (blen < _pos + len) { ! blen *= 2; ! } ! byte[] tmp = new byte[blen]; ! System.arraycopy(_buf, 0, tmp, 0, _pos); ! _buf = tmp; ! } ! } ! /** ! * How many bytes currently in the buffer ! */ ! public int size() { ! return _pos; ! } ! /** ! * Get the bytes in the buffer. Note that you are getting the ! * live buffer. You also need to call size() to find out how ! * many of these bytes are significant. If you just want a ! * byte array call getBytes() instead--that will allocate a ! * new one for you. ! */ ! public byte[] getBuffer() { ! return _buf; ! } ! /** ! * Allocate a new byte[] and fill it with the contents of the ! * current byte buffer. If you want the live byte buffer instead ! * of this newly allocated copy call getBuffer() instead. ! */ ! public byte[] getBytes() { ! byte[] ret = new byte[_pos]; ! System.arraycopy(_buf, 0, ret, 0, _pos); ! return ret; ! } ! /** ! * Convert the bytes to a String using the default encoding ! */ ! public String toString() { ! return new String(_buf, 0, _pos); ! } ! /** ! * Convert the bytes to a String using the specified encodign ! */ ! public String toString(String encoding) throws UnsupportedEncodingException { ! return new String(_buf, 0, _pos, encoding); ! } ! /** ! * Write the bytes to the specified output stream ! */ ! public void writeTo(OutputStream out) throws IOException { ! out.write(_buf, 0, _pos); ! } ! public static void main(String arg[]) { ! try { ! ByteBufferOutputStream bb = new ByteBufferOutputStream(5); ! bb.write((byte) 'T'); ! bb.write((byte) 'h'); ! bb.write((byte) 'i'); ! bb.write((byte) 's'); ! bb.write((byte) ' '); ! bb.write((byte) 'i'); ! bb.write((byte) 's'); ! bb.write((byte) ' '); ! bb.write((byte) 'a'); ! bb.write((byte) ' '); ! bb.write((byte) 't'); ! bb.write((byte) 'e'); ! bb.write((byte) 's'); ! bb.write((byte) 't'); ! bb.write((byte) '\n'); ! bb.write("This is the second line of the byte buffer".getBytes()); ! bb.write((byte) '\n'); ! bb.write("This is the third line\n".getBytes()); ! bb.write("This is the fourth line\n".getBytes()); ! bb.write((byte) 'E'); ! bb.write((byte) 'N'); ! bb.write((byte) 'D'); ! bb.write((byte) '.'); ! bb.write((byte) '\n'); ! System.out.println("Byte buffer as a string: [" + bb + "]"); ! System.out.print("Byte buffer written to a stream: ["); ! bb.writeTo(System.out); ! System.out.print("]"); ! System.out.println("DONE"); ! } ! catch (Exception e) { ! e.printStackTrace(); ! } ! } } --- 24,213 ---- package org.webmacro.util; ! import java.io.IOException; ! import java.io.OutputStream; ! import java.io.UnsupportedEncodingException; ! final public class ByteBufferOutputStream extends OutputStream ! { ! private byte[] _buf; ! private int _pos; ! private final int _initialSize; ! /** ! * Create a new ByteBuffer with the specified capacity ! */ ! public ByteBufferOutputStream (int size) ! { ! _buf = new byte[size]; ! _pos = 0; ! _initialSize = size; ! } ! /** ! * Clear the contents of the byte buffer. Also shrinks the byte buffer ! * to the size specified during construction of this ByteBufferOutputStream ! */ ! public void reset () ! { ! _pos = 0; ! _buf = new byte[_initialSize]; ! } ! public void write (int i) ! { ! write((byte) i); ! } ! /** ! * Copy an array of bytes on to the end of the buffer ! */ ! public void write (byte[] b) ! { ! int len = b.length; ! ensureCapacity(len); ! System.arraycopy(b, 0, _buf, _pos, len); ! _pos += len; ! } ! /** ! * Copy an array of bytes on to the end of the buffer ! */ ! public void write (byte[] b, int offset, int len) ! { ! ensureCapacity(len); ! System.arraycopy(b, 0, _buf, _pos, len); ! _pos += len; ! } ! /** ! * Append a single byte ! */ ! public void write (byte b) ! { ! ensureCapacity(1); ! _buf[_pos] = b; ! _pos++; ! } ! /** ! * Make sure the buffer contains space for len more bytes. ! */ ! public final void ensureCapacity (int len) ! { ! if (_buf.length < _pos + len) ! { ! int blen = _buf.length; ! while (blen < _pos + len) ! { ! blen *= 2; ! } ! byte[] tmp = new byte[blen]; ! System.arraycopy(_buf, 0, tmp, 0, _pos); ! _buf = tmp; ! } ! } ! /** ! * How many bytes currently in the buffer ! */ ! public int size () ! { ! return _pos; ! } ! /** ! * Get the bytes in the buffer. Note that you are getting the ! * live buffer. You also need to call size() to find out how ! * many of these bytes are significant. If you just want a ! * byte array call getBytes() instead--that will allocate a ! * new one for you. ! */ ! public byte[] getBuffer () ! { ! return _buf; ! } ! /** ! * Allocate a new byte[] and fill it with the contents of the ! * current byte buffer. If you want the live byte buffer instead ! * of this newly allocated copy call getBuffer() instead. ! */ ! public byte[] getBytes () ! { ! byte[] ret = new byte[_pos]; ! System.arraycopy(_buf, 0, ret, 0, _pos); ! return ret; ! } ! /** ! * Convert the bytes to a String using the default encoding ! */ ! public String toString () ! { ! return new String(_buf, 0, _pos); ! } ! /** ! * Convert the bytes to a String using the specified encodign ! */ ! public String toString (String encoding) throws UnsupportedEncodingException ! { ! return new String(_buf, 0, _pos, encoding); ! } ! /** ! * Write the bytes to the specified output stream ! */ ! public void writeTo (OutputStream out) throws IOException ! { ! out.write(_buf, 0, _pos); ! } ! public static void main (String arg[]) ! { ! try ! { ! ByteBufferOutputStream bb = new ByteBufferOutputStream(5); ! bb.write((byte) 'T'); ! bb.write((byte) 'h'); ! bb.write((byte) 'i'); ! bb.write((byte) 's'); ! bb.write((byte) ' '); ! bb.write((byte) 'i'); ! bb.write((byte) 's'); ! bb.write((byte) ' '); ! bb.write((byte) 'a'); ! bb.write((byte) ' '); ! bb.write((byte) 't'); ! bb.write((byte) 'e'); ! bb.write((byte) 's'); ! bb.write((byte) 't'); ! bb.write((byte) '\n'); ! bb.write("This is the second line of the byte buffer".getBytes()); ! bb.write((byte) '\n'); ! bb.write("This is the third line\n".getBytes()); ! bb.write("This is the fourth line\n".getBytes()); ! bb.write((byte) 'E'); ! bb.write((byte) 'N'); ! bb.write((byte) 'D'); ! bb.write((byte) '.'); ! bb.write((byte) '\n'); ! System.out.println("Byte buffer as a string: [" + bb + "]"); ! System.out.print("Byte buffer written to a stream: ["); ! bb.writeTo(System.out); ! System.out.print("]"); ! System.out.println("DONE"); ! } ! catch (Exception e) ! { ! e.printStackTrace(); ! } ! } } Index: CastUtil.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/CastUtil.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** CastUtil.java 13 May 2003 05:33:29 -0000 1.8 --- CastUtil.java 12 Jun 2003 00:47:48 -0000 1.9 *************** *** 27,227 **** * @since 0.96 */ ! public class CastUtil extends java.lang.Object { ! static private CastUtil _singleton = new CastUtil(); ! /** private constructor for singleton */ ! private CastUtil() { ! } ! static public CastUtil getInstance() { ! return _singleton; ! } ! public static Boolean toBoolean(java.lang.Object o) { ! if (o == null) return Boolean.FALSE; ! return Boolean.valueOf(o.toString()); ! } ! public static Character toChar(Object o) throws org.webmacro.PropertyException { ! Character c = null; ! if (o == null || o == "") return null; ! if (o instanceof Character) return (Character) o; ! if (o instanceof Number) { ! try { ! c = new Character((char) ((Number) o).intValue()); ! } ! catch (Exception e) { ! throw new IllegalArgumentException("Not a valid char: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); ! } ! } ! else if (o instanceof String) { ! String s = (String) o; ! if (s.startsWith("\\u") && s.length() == 6) { ! // unicode char ! int i = Integer.parseInt(s.substring(2), 16); ! c = new Character((char) i); ! } ! else { // use the first character of the string ! char ch = s.charAt(0); ! c = new Character(ch); ! } ! } ! else { // throw exception ! throw new org.webmacro.PropertyException( ! "$Type.toChar() is unable to convert the supplied value to a Character. The argument" ! + " must be a number or a String. The supplied argument was " ! + o + " of type " + o.getClass().getName()); ! } ! return c; ! } ! public static Byte toByte(java.lang.Object o) { ! if (o instanceof Byte) return (Byte) o; ! Byte v = null; ! try { ! int i = Integer.parseInt(o.toString()); ! v = new Byte((byte) i); ! } ! catch (Exception e) { ! throw new IllegalArgumentException("Not a valid byte: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); ! } ! return v; ! } ! public static Short toShort(java.lang.Object o) { ! if (o instanceof Short) return (Short) o; ! Short v = null; ! try { ! int i = Integer.parseInt(o.toString()); ! v = new Short((short) i); ! } ! catch (Exception e) { ! throw new IllegalArgumentException("Not a valid short: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); ! } ! return v; ! } ! public static Integer toInt(java.lang.Object o) { ! Integer i = null; ! if (o instanceof Integer) return (Integer) o; ! try { ! i = new Integer(o.toString()); ! } ! catch (Exception e) { ! throw new IllegalArgumentException("Not a valid int: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); ! } ! return i; ! } ! public static Long toLong(java.lang.Object o) { ! Long l = null; ! if (o instanceof Long) return (Long) o; ! try { ! l = new Long(o.toString()); ! } ! catch (Exception e) { ! throw new IllegalArgumentException("Not a valid long: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); ! } ! return l; ! } ! public static Float toFloat(java.lang.Object o) { ! Float f = null; ! if (o instanceof Float) return (Float) o; ! try { ! f = new Float(o.toString()); ! } ! catch (Exception e) { ! throw new IllegalArgumentException("Not a valid float: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); ! } ! return f; ! } ! public static Double toDouble(java.lang.Object o) { ! Double d = null; ! if (o instanceof Double) return (Double) o; ! try { ! d = new Double(o.toString()); ! } ! catch (Exception e) { ! throw new IllegalArgumentException("Not a valid double: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); ! } ! return d; ! } ! static public void main(String[] args) { ! CastUtil cu = CastUtil.getInstance(); ! println("77" ! + test(BOOLEAN, "77") ! + test(CHAR, "77") ! + test(BYTE, "77") ! + test(SHORT, "77") ! + test(INTEGER, "77") ! + test(LONG, "77") ! + test(FLOAT, "77") ! + test(DOUBLE, "77") ! + "."); ! println("true: " + test(BOOLEAN, "true") + "."); ! println("FalSE: " + test(BOOLEAN, "FalSE") + "."); ! println("null: " + test(BOOLEAN, null) + "."); ! } ! static private void println(String s) { ! System.out.println(s); ! } ! static private void print(Object o) { ! System.out.print(o); ! } ! final static public int BOOLEAN = 1; ! final static public int CHAR = 2; ! final static public int BYTE = 3; ! final static public int SHORT = 4; ! final static public int INTEGER = 5; ! final static public int LONG = 6; ! final static public int FLOAT = 7; ! final static public int DOUBLE = 8; ! static private String test(int type, Object val) { ! String s = null; ! try { ! Object o = null; ! switch (type) { ! case BOOLEAN: ! o = toBoolean(val); ! break; ! case CHAR: ! o = toChar(val); ! break; ! case BYTE: ! o = toByte(val); ! break; ! case SHORT: ! o = toShort(val); ! break; ! case INTEGER: ! o = toInt(val); ! break; ! case LONG: ! o = toLong(val); ! break; ! case FLOAT: ! o = toFloat(val); ! break; ! case DOUBLE: ! o = toDouble(val); ! break; ! default: ! throw new IllegalArgumentException("Unknown type: " + type); ! } ! s = ", " + o + " (" + o.getClass().getName() + ")"; ! } ! catch (Exception e) { ! e.printStackTrace(); ! } ! return s; ! } } --- 27,264 ---- * @since 0.96 */ ! public class CastUtil extends java.lang.Object ! { ! static private CastUtil _singleton =... [truncated message content] |
Update of /cvsroot/webmacro/webmacro/test/unit/org/webmacro/template In directory sc8-pr-cvs1:/tmp/cvs-serv6675/test/unit/org/webmacro/template Modified Files: AbstractVariableTestCase.java EncodingTestCase.java PerformanceOperations.java PrivateValue.java PublicValue.java TemplateTestCase.java TestAbuse.java TestAlternate.java TestArithmetic.java TestBlocks.java TestCountDirective.java TestCrankyEEH.java TestDefaultEEH.java TestDirectiveParser.java TestFunction.java TestGetSet.java TestISO88591Encoding.java TestIf.java TestLineNumbers.java TestList.java TestMacro.java TestNastySebastianTemplate.java TestParseInclude.java TestPerformanceAreas.java TestQuote.java TestSetblock.java TestShortCircuit.java TestSyntheticTemplate.java TestUndefined.java TestWhitespace.java TestWindows1251Encoding.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: AbstractVariableTestCase.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/template/AbstractVariableTestCase.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** AbstractVariableTestCase.java 23 Mar 2003 02:00:37 -0000 1.5 --- AbstractVariableTestCase.java 12 Jun 2003 00:47:49 -0000 1.6 *************** *** 1,10 **** package org.webmacro.template; - import java.io.*; - import org.webmacro.*; - import org.webmacro.engine.StringTemplate; - - import junit.framework.*; /** abstract variable test case for ROGUE variables/properties --- 1,5 ---- *************** *** 12,150 **** It is expected that atleast 3 subclasses will exist: TestDefaultEEH, TestCrankyEEH, TestComplacentEEH ! */ ! public abstract class AbstractVariableTestCase extends TemplateTestCase { ! public static class ObjectWithNullMethod { ! public Object getNull () { ! return null; ! } } - public AbstractVariableTestCase (String name) { - super (name); - } ! public void testGoodVariable () throws Exception { ! assertTrue(false); ! } - public void testGoodMethod () throws Exception { - assertTrue(false); - } ! public void testGoodProperty () throws Exception { ! assertTrue(false); ! } - public void testNoSuchVariable () throws Exception { - assertTrue(false); - } ! public void testNoSuchMethod () throws Exception { ! assertTrue(false); ! } - public void testNoSuchProperty () throws Exception { - assertTrue(false); - } ! public void testVoidMethod () throws Exception { ! assertTrue(false); ! } - public void testNullMethod () throws Exception { - assertTrue(false); - } ! public void testThrowsMethod() throws Exception { ! assertTrue(false); ! } - /** A variable in the context who's .toString() method returns null */ - public void testNullVariable () throws Exception { - assertTrue(false); - } - public void testEvalGoodVariable () throws Exception { - assertTrue(false); - } ! public void testEvalGoodMethod () throws Exception { ! assertTrue(false); ! } - public void testEvalGoodProperty () throws Exception { - assertTrue(false); - } ! public void testEvalNoSuchVariable () throws Exception { ! assertTrue(false); ! } - public void testEvalNoSuchMethod () throws Exception { - assertTrue(false); - } - - public void testNoSuchMethodWithArguments () throws Exception { - assertTrue(false); - } ! public void testEvalNoSuchMethodWithArguments () throws Exception { ! assertTrue(false); ! } - public void testEvalNoSuchProperty () throws Exception { - assertTrue(false); - } ! public void testEvalVoidMethod () throws Exception { ! assertTrue(false); ! } - public void testEvalNullMethod () throws Exception { - assertTrue(false); - } ! public void testEvalThrowsMethod() throws Exception { ! assertTrue(false); ! } - public void testEvalNullVariable () throws Exception { - assertTrue(false); - } ! /** ! * This is the old "... --possibly null?" error message. ! * It has always thrown a PropertyExcpetion, and probably still should. ! */ ! public void testEvaluationOfNullReturnValue() throws Exception { ! assertTrue(false); ! } ! /** Below are a few objects that should be used to ! do the actual testing */ - public static class TestObject { ! public String property = "Property"; ! ! public String toString () { return "TestObject"; } ! public String getString () { return "String"; } ! public void voidMethod () { ; } - public Object nullMethod () { return null; } ! public void throwException() throws Exception { ! throw new Exception ("GoodTestObject.throwException() was called"); ! } ! } ! public static class NullTestObject extends TestObject { ! public String toString () { return null; } ! } } --- 7,218 ---- It is expected that atleast 3 subclasses will exist: TestDefaultEEH, TestCrankyEEH, TestComplacentEEH ! */ ! public abstract class AbstractVariableTestCase extends TemplateTestCase ! { ! public static class ObjectWithNullMethod ! { ! public Object getNull () ! { ! return null; ! } } ! public AbstractVariableTestCase (String name) ! { ! super(name); ! } ! public void testGoodVariable () throws Exception ! { ! assertTrue(false); ! } ! public void testGoodMethod () throws Exception ! { ! assertTrue(false); ! } ! public void testGoodProperty () throws Exception ! { ! assertTrue(false); ! } ! public void testNoSuchVariable () throws Exception ! { ! assertTrue(false); ! } + public void testNoSuchMethod () throws Exception + { + assertTrue(false); + } ! public void testNoSuchProperty () throws Exception ! { ! assertTrue(false); ! } ! public void testVoidMethod () throws Exception ! { ! assertTrue(false); ! } ! public void testNullMethod () throws Exception ! { ! assertTrue(false); ! } ! public void testThrowsMethod () throws Exception ! { ! assertTrue(false); ! } ! /** A variable in the context who's .toString() method returns null */ ! public void testNullVariable () throws Exception ! { ! assertTrue(false); ! } ! public void testEvalGoodVariable () throws Exception ! { ! assertTrue(false); ! } ! public void testEvalGoodMethod () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalGoodProperty () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalNoSuchVariable () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalNoSuchMethod () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testNoSuchMethodWithArguments () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalNoSuchMethodWithArguments () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalNoSuchProperty () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalVoidMethod () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalNullMethod () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalThrowsMethod () throws Exception ! { ! assertTrue(false); ! } ! ! ! public void testEvalNullVariable () throws Exception ! { ! assertTrue(false); ! } ! ! ! /** ! * This is the old "... --possibly null?" error message. ! * It has always thrown a PropertyExcpetion, and probably still should. */ + public void testEvaluationOfNullReturnValue () throws Exception + { + assertTrue(false); + } ! /** Below are a few objects that should be used to ! do the actual testing ! */ ! public static class TestObject ! { ! public String property = "Property"; ! public String toString () ! { ! return "TestObject"; ! } ! ! public String getString () ! { ! return "String"; ! } ! ! ! public void voidMethod () ! { ! ; ! } ! ! ! public Object nullMethod () ! { ! return null; ! } ! ! ! public void throwException () throws Exception ! { ! throw new Exception("GoodTestObject.throwException() was called"); ! } ! } ! ! public static class NullTestObject extends TestObject ! { ! public String toString () ! { ! return null; ! } ! } } Index: EncodingTestCase.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/template/EncodingTestCase.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EncodingTestCase.java 23 Mar 2003 02:00:37 -0000 1.3 --- EncodingTestCase.java 12 Jun 2003 00:47:49 -0000 1.4 *************** *** 1,9 **** package org.webmacro.template; ! import java.io.*; ! import org.webmacro.*; ! import junit.framework.*; /** --- 1,8 ---- package org.webmacro.template; ! import junit.framework.TestCase; import org.webmacro.*; ! import java.io.*; /** *************** *** 22,26 **** * @author Sebastian Kanthak */ ! public abstract class EncodingTestCase extends TestCase { public static final String TEMPLATE_FILENAME = "org.webmacro.template.TestEncoding.wm"; public static final String TEMPLATE_FILENAME_UTF8 = "org.webmacro.templateTestEncoding-utf8.wm"; --- 21,26 ---- * @author Sebastian Kanthak */ ! public abstract class EncodingTestCase extends TestCase ! { public static final String TEMPLATE_FILENAME = "org.webmacro.template.TestEncoding.wm"; public static final String TEMPLATE_FILENAME_UTF8 = "org.webmacro.templateTestEncoding-utf8.wm"; *************** *** 32,41 **** protected String expected; protected String encoding; ! ! public EncodingTestCase(String name) { super(name); } ! protected void setUp() throws Exception { this.template = getTemplate(); this.expected = getExpected(); --- 32,45 ---- protected String expected; protected String encoding; ! ! ! public EncodingTestCase (String name) ! { super(name); } ! ! protected void setUp () throws Exception ! { this.template = getTemplate(); this.expected = getExpected(); *************** *** 45,66 **** } ! protected void tearDown() throws Exception { deleteFiles(); } /** * Return the template source to test with */ ! protected abstract String getTemplate(); /** * Return the encoding to test with */ ! protected abstract String getEncoding(); /** * Return the expected result */ ! protected abstract String getExpected(); /** --- 49,76 ---- } ! ! protected void tearDown () throws Exception ! { deleteFiles(); } + /** * Return the template source to test with */ ! protected abstract String getTemplate (); ! /** * Return the encoding to test with */ ! protected abstract String getEncoding (); ! /** * Return the expected result */ ! protected abstract String getExpected (); ! /** *************** *** 68,84 **** * in your template */ ! protected abstract void stuffContext(Context context); ! ! protected void createWebMacro() throws Exception { File f = new File("WebMacro.properties-".concat(encoding)); PrintWriter w = new PrintWriter(new FileWriter(f)); w.println("TemplateEncoding: ".concat(encoding)); w.close(); ! f = new File("WebMacro.properties-UTF8"); w = new PrintWriter(new FileWriter(f)); w.println("TemplateEncoding: UTF8"); w.close(); ! if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) System.getProperties().setProperty("org.webmacro.LogLevel", "ERROR"); --- 78,96 ---- * in your template */ ! protected abstract void stuffContext (Context context); ! ! ! protected void createWebMacro () throws Exception ! { File f = new File("WebMacro.properties-".concat(encoding)); PrintWriter w = new PrintWriter(new FileWriter(f)); w.println("TemplateEncoding: ".concat(encoding)); w.close(); ! f = new File("WebMacro.properties-UTF8"); w = new PrintWriter(new FileWriter(f)); w.println("TemplateEncoding: UTF8"); w.close(); ! if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) System.getProperties().setProperty("org.webmacro.LogLevel", "ERROR"); *************** *** 88,105 **** } ! protected void createFiles() throws IOException { File f = new File(TEMPLATE_FILENAME); ! Writer writer = new OutputStreamWriter(new FileOutputStream(f),encoding); writer.write(template); writer.close(); ! f = new File(TEMPLATE_FILENAME_UTF8); ! writer = new OutputStreamWriter(new FileOutputStream(f),"UTF8"); writer.write(template); writer.close(); ! } ! protected void deleteFile(String filename) throws IOException { File f = new File(filename); if (f.exists()) --- 100,121 ---- } ! ! protected void createFiles () throws IOException ! { File f = new File(TEMPLATE_FILENAME); ! Writer writer = new OutputStreamWriter(new FileOutputStream(f), encoding); writer.write(template); writer.close(); ! f = new File(TEMPLATE_FILENAME_UTF8); ! writer = new OutputStreamWriter(new FileOutputStream(f), "UTF8"); writer.write(template); writer.close(); ! } ! ! protected void deleteFile (String filename) throws IOException ! { File f = new File(filename); if (f.exists()) *************** *** 107,111 **** } ! protected void deleteFiles() throws IOException { deleteFile(TEMPLATE_FILENAME); deleteFile(TEMPLATE_FILENAME_UTF8); --- 123,129 ---- } ! ! protected void deleteFiles () throws IOException ! { deleteFile(TEMPLATE_FILENAME); deleteFile(TEMPLATE_FILENAME_UTF8); *************** *** 113,118 **** deleteFile("WebMacro.properties-UTF8"); } ! ! private Context getContext(WebMacro wm) { Context context = wm.getContext(); stuffContext(context); --- 131,138 ---- deleteFile("WebMacro.properties-UTF8"); } ! ! ! private Context getContext (WebMacro wm) ! { Context context = wm.getContext(); stuffContext(context); *************** *** 120,174 **** } ! public void testInputEncoding() throws Exception { ! assertEquals("Input Encoding is not "+encoding, ! wm.getConfig("TemplateEncoding"),encoding); Template t = wm.getTemplate(TEMPLATE_FILENAME); String evaluated = t.evaluate(getContext(wm)).toString(); ! assertEquals("Template evaluated to \""+evaluated+"\" instead of \""+expected+"\"", ! evaluated,expected); } ! public void testOutputEncoding() throws Exception { ! assertEquals("InputEncoding is not "+encoding, ! wm.getConfig("TemplateEncoding"),encoding); Template t = wm.getTemplate(TEMPLATE_FILENAME); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ! FastWriter fw = wm.getFastWriter(bos,encoding); ! t.write(fw,getContext(wm)); fw.flush(); fw.close(); ! assertByteArrayEquals(bos.toByteArray(),expected.getBytes(encoding)); } ! public void testUTF8OutputEncoding() throws Exception { ! assertEquals("InputEncoding is not "+encoding, ! wm.getConfig("TemplateEncoding"),encoding); Template t = wm.getTemplate(TEMPLATE_FILENAME); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ! FastWriter fw = wm.getFastWriter(bos,"UTF8"); ! t.write(fw,getContext(wm)); fw.flush(); fw.close(); ! assertByteArrayEquals(bos.toByteArray(),expected.getBytes("UTF8")); } ! public void testUTF8InputEncoding() throws Exception { assertEquals("InputEncoding is not UFT8", ! wmUTF8.getConfig("TemplateEncoding"),"UTF8"); Template t = wmUTF8.getTemplate(TEMPLATE_FILENAME_UTF8); String evaluated = t.evaluate(getContext(wmUTF8)).toString(); ! assertEquals("Template evaluated to \""+evaluated+"\" instead of \""+expected+"\"", ! expected,evaluated); } ! protected void assertByteArrayEquals(byte[] a,byte[] b) throws Exception { if (a == b) return; assertTrue("One byte array is null", ! ((a != null) && (b != null))); assertTrue("Size of binary output differs", ! a.length == b.length); ! for (int i=0; i < a.length; i++) { assertTrue("Binary output differs", ! a[i] == b[i]); } } --- 140,205 ---- } ! ! public void testInputEncoding () throws Exception ! { ! assertEquals("Input Encoding is not " + encoding, ! wm.getConfig("TemplateEncoding"), encoding); Template t = wm.getTemplate(TEMPLATE_FILENAME); String evaluated = t.evaluate(getContext(wm)).toString(); ! assertEquals("Template evaluated to \"" + evaluated + "\" instead of \"" + expected + "\"", ! evaluated, expected); } ! ! public void testOutputEncoding () throws Exception ! { ! assertEquals("InputEncoding is not " + encoding, ! wm.getConfig("TemplateEncoding"), encoding); Template t = wm.getTemplate(TEMPLATE_FILENAME); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ! FastWriter fw = wm.getFastWriter(bos, encoding); ! t.write(fw, getContext(wm)); fw.flush(); fw.close(); ! assertByteArrayEquals(bos.toByteArray(), expected.getBytes(encoding)); } ! ! public void testUTF8OutputEncoding () throws Exception ! { ! assertEquals("InputEncoding is not " + encoding, ! wm.getConfig("TemplateEncoding"), encoding); Template t = wm.getTemplate(TEMPLATE_FILENAME); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ! FastWriter fw = wm.getFastWriter(bos, "UTF8"); ! t.write(fw, getContext(wm)); fw.flush(); fw.close(); ! assertByteArrayEquals(bos.toByteArray(), expected.getBytes("UTF8")); } ! ! public void testUTF8InputEncoding () throws Exception ! { assertEquals("InputEncoding is not UFT8", ! wmUTF8.getConfig("TemplateEncoding"), "UTF8"); Template t = wmUTF8.getTemplate(TEMPLATE_FILENAME_UTF8); String evaluated = t.evaluate(getContext(wmUTF8)).toString(); ! assertEquals("Template evaluated to \"" + evaluated + "\" instead of \"" + expected + "\"", ! expected, evaluated); } ! ! protected void assertByteArrayEquals (byte[] a, byte[] b) throws Exception ! { if (a == b) return; assertTrue("One byte array is null", ! ((a != null) && (b != null))); assertTrue("Size of binary output differs", ! a.length == b.length); ! for (int i = 0; i < a.length; i++) ! { assertTrue("Binary output differs", ! a[i] == b[i]); } } Index: PerformanceOperations.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/template/PerformanceOperations.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PerformanceOperations.java 12 Oct 2001 21:31:48 -0000 1.1 --- PerformanceOperations.java 12 Jun 2003 00:47:49 -0000 1.2 *************** *** 1,7 **** package org.webmacro.template; ! import java.io.*; ! import java.util.*; ! import org.webmacro.*; /** --- 1,10 ---- package org.webmacro.template; ! import org.webmacro.Context; ! import org.webmacro.WM; ! import org.webmacro.WebMacro; ! ! import java.util.ArrayList; ! import java.util.List; /** *************** *** 20,116 **** * required. */ ! public class PerformanceOperations implements Runnable { ! ! // the classes which are to be run: ! Runnable[] testCases = { ! new PublicVersusPrivate() ! }; ! ! // The WebMacro instance which can be shared for each test case. ! private WebMacro wm; ! ! // the public variables available for introspection ! /** The iteration count used in the test. Defaults to 100K.*/ ! public int iterationCount = 100000; ! ! /** The total elapsed time for public access. */ ! public long tetPublicAccess; ! ! /** The total elapsed time for private access. */ ! public long tetPrivateAccess; ! ! public PerformanceOperations() {} ! ! public PerformanceOperations(int iterationCount) { ! this.iterationCount = iterationCount; ! } ! public void run() { ! try { ! wm = new WM(); ! } ! catch (Exception e) { ! throw new IllegalStateException(e.toString()); } ! for (int index = 0; index < testCases.length; index++) ! testCases[index].run(); ! } ! ! /** ! * The private versus public test case. ! */ ! class PublicVersusPrivate implements Runnable { ! static final String publicTemplate = ! "org/webmacro/template/Public.wm"; ! static final String privateTemplate = ! "org/webmacro/template/Private.wm"; ! ! ! private Context setupPublic() { ! // the public values: ! PublicValue pub = new PublicValue(); ! pub.object = this; ! // the lists for iteration: ! List pubList = new ArrayList(iterationCount); ! // populate: ! for (int index = 0; index < iterationCount; index++){ ! pubList.add(pub); ! } ! Context context = wm.getContext(); ! context.put("PublicList", pubList); ! return context; } ! ! private Context setupPrivate() { ! // the public values: ! PrivateValue priv = new PrivateValue(); ! priv.setObject(this); ! // the lists for iteration: ! List privList = new ArrayList(iterationCount); ! // populate: ! for (int index = 0; index < iterationCount; index++){ ! privList.add(priv); ! } ! Context context = wm.getContext(); ! context.put("PrivateList", privList); ! return context; } ! ! public void run(){ ! try { ! Context c = setupPublic(); ! long start = System.currentTimeMillis(); ! wm.writeTemplate(publicTemplate, System.out, c); ! tetPublicAccess = System.currentTimeMillis() - start; ! ! c = setupPrivate(); ! start = System.currentTimeMillis(); ! wm.writeTemplate(privateTemplate, System.out, c); ! tetPrivateAccess = System.currentTimeMillis() - start; ! } ! catch (Exception e) { ! throw new IllegalStateException(e.toString()); ! } } - } } --- 23,140 ---- * required. */ ! public class PerformanceOperations implements Runnable ! { ! ! // the classes which are to be run: ! Runnable[] testCases = { ! new PublicVersusPrivate() ! }; ! ! // The WebMacro instance which can be shared for each test case. ! private WebMacro wm; ! // the public variables available for introspection ! /** The iteration count used in the test. Defaults to 100K.*/ ! public int iterationCount = 100000; ! ! /** The total elapsed time for public access. */ ! public long tetPublicAccess; ! ! /** The total elapsed time for private access. */ ! public long tetPrivateAccess; ! ! ! public PerformanceOperations () ! { } ! ! ! public PerformanceOperations (int iterationCount) ! { ! this.iterationCount = iterationCount; } ! ! ! public void run () ! { ! try ! { ! wm = new WM(); ! } ! catch (Exception e) ! { ! throw new IllegalStateException(e.toString()); ! } ! for (int index = 0; index < testCases.length; index++) ! testCases[index].run(); } ! ! ! /** ! * The private versus public test case. ! */ ! class PublicVersusPrivate implements Runnable ! { ! static final String publicTemplate = ! "org/webmacro/template/Public.wm"; ! static final String privateTemplate = ! "org/webmacro/template/Private.wm"; ! ! ! private Context setupPublic () ! { ! // the public values: ! PublicValue pub = new PublicValue(); ! pub.object = this; ! // the lists for iteration: ! List pubList = new ArrayList(iterationCount); ! // populate: ! for (int index = 0; index < iterationCount; index++) ! { ! pubList.add(pub); ! } ! Context context = wm.getContext(); ! context.put("PublicList", pubList); ! return context; ! } ! ! ! private Context setupPrivate () ! { ! // the public values: ! PrivateValue priv = new PrivateValue(); ! priv.setObject(this); ! // the lists for iteration: ! List privList = new ArrayList(iterationCount); ! // populate: ! for (int index = 0; index < iterationCount; index++) ! { ! privList.add(priv); ! } ! Context context = wm.getContext(); ! context.put("PrivateList", privList); ! return context; ! } ! ! ! public void run () ! { ! try ! { ! Context c = setupPublic(); ! long start = System.currentTimeMillis(); ! wm.writeTemplate(publicTemplate, System.out, c); ! tetPublicAccess = System.currentTimeMillis() - start; ! ! c = setupPrivate(); ! start = System.currentTimeMillis(); ! wm.writeTemplate(privateTemplate, System.out, c); ! tetPrivateAccess = System.currentTimeMillis() - start; ! } ! catch (Exception e) ! { ! throw new IllegalStateException(e.toString()); ! } ! } } } Index: PrivateValue.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/template/PrivateValue.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PrivateValue.java 12 Oct 2001 21:31:48 -0000 1.1 --- PrivateValue.java 12 Jun 2003 00:47:49 -0000 1.2 *************** *** 1,9 **** package org.webmacro.template; ! public class PrivateValue { private long value; private Object object; ! public long getValue() { return value; } ! public void setValue(long value) { this.value = value; } ! public Object getObject() { return object; } ! public void setObject(Object object) { this.object = object; } } --- 1,31 ---- package org.webmacro.template; ! ! public class PrivateValue ! { private long value; private Object object; ! ! ! public long getValue () ! { ! return value; ! } ! ! ! public void setValue (long value) ! { ! this.value = value; ! } ! ! ! public Object getObject () ! { ! return object; ! } ! ! ! public void setObject (Object object) ! { ! this.object = object; ! } } Index: PublicValue.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/template/PublicValue.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PublicValue.java 12 Oct 2001 21:31:48 -0000 1.1 --- PublicValue.java 12 Jun 2003 00:47:49 -0000 1.2 *************** *** 1,4 **** package org.webmacro.template; ! public class PublicValue { public long value; public Object object; --- 1,6 ---- package org.webmacro.template; ! ! public class PublicValue ! { public long value; public Object object; Index: TemplateTestCase.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/template/TemplateTestCase.java,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** TemplateTestCase.java 23 Mar 2003 02:00:38 -0000 1.14 --- TemplateTestCase.java 12 Jun 2003 00:47:49 -0000 1.15 *************** *** 1,305 **** package org.webmacro.template; ! import java.io.*; ! import java.util.*; ! import org.webmacro.*; import org.webmacro.engine.StringTemplate; ! import junit.framework.*; - import org.apache.regexp.RE; ! public abstract class TemplateTestCase extends TestCase { ! /** our WebMacro instance */ ! protected WebMacro _wm; - /** context to use for each template */ - protected Context _context; ! public TemplateTestCase(String name) { ! super(name); ! } - protected void setUp() throws Exception { - init(); - } ! /** ! * create a default-configured instance of WebMacro. Subclasses may ! * override if WM needs to be created/configured differently. ! */ ! protected WebMacro createWebMacro () throws Exception ! { ! return new WM (); ! } ! /** ! * initialize this TemplateTester by creating a WebMacro instance ! * and a default Context. ! */ ! public void init () throws Exception ! { ! if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) ! System.getProperties().setProperty("org.webmacro.LogLevel", "NONE"); ! _wm = createWebMacro (); ! _context = _wm.getContext (); - // let subclasses stuff the context with custom data - stuffContext (_context); - } ! /** ! * stuff the provided context with custom variables and objects<p> ! * ! * @throws Exception if something goes wrong while stuffing context ! */ ! protected abstract void stuffContext (Context context) throws Exception; ! /** ! * Utility method to convert a template file to a string for use in ! * the test suite. ! * Note: if the file is not found as an absolute arg, then the ! * broker is called to use its get resource method. */ ! public String templateFileToString(String fileReference) throws Exception { ! InputStream in = null; ! try { ! in = new FileInputStream(fileReference); ! } ! catch (FileNotFoundException e) { ! in = _wm.getBroker().getResourceAsStream(fileReference); ! if (in == null) throw new Exception(fileReference + " not found"); ! } ! byte[] value = new byte[in.available()]; ! in.read(value); ! in.close(); ! String string = new String(value); ! return string; ! } - /* - * Evaluates a template and returns its value. */ - public String executeTemplate(Template template) throws Exception { - return template.evaluate(_context).toString(); - } ! /** ! * Executes a file template. ! */ ! public String executeFileTemplate(String fileReference) throws Exception { ! return executeStringTemplate(templateFileToString(fileReference)); ! } - /** Execute a string as a template against the current context, - * and return the result. */ - public String executeStringTemplate(String templateText) throws Exception { - Template template = new StringTemplate(_wm.getBroker(), templateText); - template.parse(); - FastWriter fw = FastWriter.getInstance(_wm.getBroker(), null, "UTF8"); - template.write (fw, _context); - String output = fw.toString(); - fw.close(); - return output; - } - - public void store(String fileName, String value) throws Exception { - Writer out = new FileWriter(fileName); - out.write(value); - out.close(); - } ! public void assertEvalutionEquals (String eval, Object result) throws Exception { String template = "#set $assertEvalutionEquals = " + eval; executeStringTemplate(template); if (result == null) ! assertTrue (_context.get("assertEvalutionEquals") == null); else ! assertTrue (result==null ? "null" : result.toString(), result.equals(_context.get("assertEvalutionEquals"))); } - /** - * asserts that the specified template file (loaded via classpath) evaluates - * to the given result text when evaluated against the current context - */ - public void assertTemplateEquals (String templateName, String resultText) throws Exception { - String result = null; ! try { ! result = executeStringTemplate (templateFileToString(templateName)); ! } catch (Exception e) { ! System.err.println ("Execution of /" + templateName + "/ threw " + e.getClass() ! + ", expecting /" + resultText + "/"); ! } ! if (result == null || !result.equals(resultText)) { ! System.err.println ("/" + templateName + "/ does not " ! + "evaluate to /" + resultText + "/ " ! + "result=/" + result + "/"); ! assertTrue (false); ! } ! } ! /** Asserts that the given template text evalutes to the given result text ! * when evaluated against the current context */ - public void assertStringTemplateEquals(String templateText, - String resultText) { - String result = null; ! try { ! result = executeStringTemplate(templateText); ! } ! catch (Exception e) { ! System.err.println("Execution of /" + templateText + "/" ! + " threw " + e.getClass() ! + "(" + e.getMessage() + ")" ! + ", expecting /" ! + resultText + "/"); ! e.printStackTrace(); ! assertTrue(false); ! } ! if (result == null) ! return; ! if (!result.equals(resultText)) { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + result + "/, expecting /" ! + resultText + "/"); ! assertTrue(false); } - } - /** Asserts that the given template text throws the given exception - * when evaluated against the current context, and the message text - * matches the specified RE */ ! public void assertStringTemplateThrows(String templateText, ! Class exceptionClass, ! String messageMatchText) ! throws Exception { ! String result = null; ! Exception caught = null; ! try { ! result = executeStringTemplate(templateText); ! } ! catch (Exception e) { ! caught = e; ! } ! if (caught == null) { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + result + "/, expecting throw " ! + exceptionClass); ! assertTrue(false); ! } ! else if (!exceptionClass.isAssignableFrom(caught.getClass())) { ! System.err.println("Execution of /" + templateText + "/" ! + " threw " + caught.getClass() + ", expecting " ! + exceptionClass); ! assertTrue(false); } ! else if (messageMatchText != null) { ! RE re = new RE(messageMatchText); ! if (!re.match(caught.getMessage())) { ! System.err.println("Exception " + caught.getMessage() ! + " does not match /" ! + messageMatchText + "/"); ! assertTrue(false); ! } } - } - /** Asserts that the given template text throws the given exception - * when evaluated against the current context */ - public void assertStringTemplateThrows(String templateText, - Class exceptionClass) - throws Exception { - assertStringTemplateThrows(templateText, exceptionClass, null); - } ! /** Asserts that the given template text matches the given regular ! * expression when evaluated against the current context */ ! public void assertStringTemplateMatches(String templateText, ! String resultPattern) ! throws Exception { ! String result = null; ! try { ! result = executeStringTemplate(templateText); ! } ! catch (Exception e) { ! System.err.println("Execution of /" + templateText + "/" ! + " threw " + e.getClass() + "/, expecting match /" ! + resultPattern + "/"); ! e.printStackTrace(System.err); ! assertTrue(false); ! } ! if (result == null) ! return; ! RE re = new RE(resultPattern); ! if (!re.match(result)) { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + result + "/, expecting match /" ! + resultPattern + "/"); ! assertTrue(false); } - } ! public void assertStringTemplateThrowsWithCaught(String templateText, ! Class exceptionClass) { ! String result = null; ! Throwable caught = null; ! try { ! result = executeStringTemplate(templateText); ! } ! catch (Exception e) { ! caught = e; ! if (!(caught instanceof PropertyException)) { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + caught.getClass() ! + "/, expecting throw PropertyException"); ! assertTrue(false); ! } else { ! caught = ((PropertyException)e).getCaught(); ! } ! } ! if (caught == null) { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + result + "/, expecting throw " ! + "PropertyException with caught exception " ! + exceptionClass); ! assertTrue(false); } ! else if (!exceptionClass.isAssignableFrom(caught.getClass())) { ! System.err.println("Execution of /" + templateText + "/" ! + " threw " + caught.getClass() + ", expecting throw " ! + "PropertyException with caught exception " ! + exceptionClass); ! assertTrue(false); } - } - /** Asserts that the specified expression is considered true or false - * depending on the value of 'yesno' */ - public void assertExpr(String expr, boolean yesno) { - assertStringTemplateEquals("#if (" + expr +") {Yes} #else {No}", - yesno? "Yes" : "No"); - } ! /** Asserts that the specified expression evaluates to the desired ! * boolean result */ ! public void assertBooleanExpr(String expr, boolean result) { ! assertStringTemplateEquals("#set $result=(" + expr + ") $result", ! result? "true" : "false"); ! } } --- 1,358 ---- package org.webmacro.template; ! import junit.framework.TestCase; ! import org.apache.regexp.RE; import org.webmacro.*; import org.webmacro.engine.StringTemplate; ! import java.io.*; + public abstract class TemplateTestCase extends TestCase + { ! /** our WebMacro instance */ ! protected WebMacro _wm; ! /** context to use for each template */ ! protected Context _context; ! public TemplateTestCase (String name) ! { ! super(name); ! } ! protected void setUp () throws Exception ! { ! init(); ! } ! /** ! * create a default-configured instance of WebMacro. Subclasses may ! * override if WM needs to be created/configured differently. ! */ ! protected WebMacro createWebMacro () throws Exception ! { ! return new WM(); ! } ! /** ! * initialize this TemplateTester by creating a WebMacro instance ! * and a default Context. ! */ ! public void init () throws Exception ! { ! if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) ! System.getProperties().setProperty("org.webmacro.LogLevel", "NONE"); ! _wm = createWebMacro(); ! _context = _wm.getContext(); ! // let subclasses stuff the context with custom data ! stuffContext(_context); ! } + /** + * stuff the provided context with custom variables and objects<p> + * + * @throws Exception if something goes wrong while stuffing context + */ + protected abstract void stuffContext (Context context) throws Exception; ! /** ! * Utility method to convert a template file to a string for use in ! * the test suite. ! * Note: if the file is not found as an absolute arg, then the ! * broker is called to use its get resource method. */ ! public String templateFileToString (String fileReference) throws Exception ! { ! InputStream in = null; ! try ! { ! in = new FileInputStream(fileReference); ! } ! catch (FileNotFoundException e) ! { ! in = _wm.getBroker().getResourceAsStream(fileReference); ! if (in == null) throw new Exception(fileReference + " not found"); ! } ! byte[] value = new byte[in.available()]; ! in.read(value); ! in.close(); ! String string = new String(value); ! return string; ! } + /* + * Evaluates a template and returns its value. */ + public String executeTemplate (Template template) throws Exception + { + return template.evaluate(_context).toString(); + } ! ! /** ! * Executes a file template. ! */ ! public String executeFileTemplate (String fileReference) throws Exception ! { ! return executeStringTemplate(templateFileToString(fileReference)); ! } ! ! ! /** Execute a string as a template against the current context, ! * and return the result. */ ! public String executeStringTemplate (String templateText) throws Exception ! { ! Template template = new StringTemplate(_wm.getBroker(), templateText); ! template.parse(); ! FastWriter fw = FastWriter.getInstance(_wm.getBroker(), null, "UTF8"); ! template.write(fw, _context); ! String output = fw.toString(); ! fw.close(); ! return output; ! } ! ! ! public void store (String fileName, String value) throws Exception ! { ! Writer out = new FileWriter(fileName); ! out.write(value); ! out.close(); ! } ! ! ! public void assertEvalutionEquals (String eval, Object result) throws Exception ! { String template = "#set $assertEvalutionEquals = " + eval; executeStringTemplate(template); if (result == null) ! assertTrue(_context.get("assertEvalutionEquals") == null); else ! assertTrue(result == null ? "null" : result.toString(), result.equals(_context.get("assertEvalutionEquals"))); } ! /** ! * asserts that the specified template file (loaded via classpath) evaluates ! * to the given result text when evaluated against the current context ! */ ! public void assertTemplateEquals (String templateName, String resultText) throws Exception ! { ! String result = null; ! try ! { ! result = executeStringTemplate(templateFileToString(templateName)); ! } ! catch (Exception e) ! { ! System.err.println("Execution of /" + templateName + "/ threw " + e.getClass() ! + ", expecting /" + resultText + "/"); ! } ! if (result == null || !result.equals(resultText)) ! { ! System.err.println("/" + templateName + "/ does not " ! + "evaluate to /" + resultText + "/ " ! + "result=/" + result + "/"); ! assertTrue(false); ! } ! } ! /** Asserts that the given template text evalutes to the given result text ! * when evaluated against the current context */ ! public void assertStringTemplateEquals (String templateText, ! String resultText) ! { ! String result = null; ! ! try ! { ! result = executeStringTemplate(templateText); ! } ! catch (Exception e) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " threw " + e.getClass() ! + "(" + e.getMessage() + ")" ! + ", expecting /" ! + resultText + "/"); ! e.printStackTrace(); ! assertTrue(false); ! } ! if (result == null) ! return; ! ! if (!result.equals(resultText)) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + result + "/, expecting /" ! + resultText + "/"); ! assertTrue(false); ! } } ! /** Asserts that the given template text throws the given exception ! * when evaluated against the current context, and the message text ! * matches the specified RE */ ! public void assertStringTemplateThrows (String templateText, ! Class exceptionClass, ! String messageMatchText) ! throws Exception ! { ! String result = null; ! Exception caught = null; ! ! try ! { ! result = executeStringTemplate(templateText); ! } ! catch (Exception e) ! { ! caught = e; ! } ! if (caught == null) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + result + "/, expecting throw " ! + exceptionClass); ! assertTrue(false); ! } ! else if (!exceptionClass.isAssignableFrom(caught.getClass())) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " threw " + caught.getClass() + ", expecting " ! + exceptionClass); ! assertTrue(false); ! } ! else if (messageMatchText != null) ! { ! RE re = new RE(messageMatchText); ! if (!re.match(caught.getMessage())) ! { ! System.err.println("Exception " + caught.getMessage() ! + " does not match /" ! + messageMatchText + "/"); ! assertTrue(false); ! } ! } } ! ! ! /** Asserts that the given template text throws the given exception ! * when evaluated against the current context */ ! public void assertStringTemplateThrows (String templateText, ! Class exceptionClass) ! throws Exception ! { ! assertStringTemplateThrows(templateText, exceptionClass, null); } ! /** Asserts that the given template text matches the given regular ! * expression when evaluated against the current context */ ! public void assertStringTemplateMatches (String templateText, ! String resultPattern) ! throws Exception ! { ! String result = null; ! try ! { ! result = executeStringTemplate(templateText); ! } ! catch (Exception e) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " threw " + e.getClass() + "/, expecting match /" ! + resultPattern + "/"); ! e.printStackTrace(System.err); ! assertTrue(false); ! } ! if (result == null) ! return; ! RE re = new RE(resultPattern); ! if (!re.match(result)) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + result + "/, expecting match /" ! + resultPattern + "/"); ! assertTrue(false); ! } } ! public void assertStringTemplateThrowsWithCaught (String templateText, ! Class exceptionClass) ! { ! String result = null; ! Throwable caught = null; ! try ! { ! result = executeStringTemplate(templateText); ! } ! catch (Exception e) ! { ! caught = e; ! if (!(caught instanceof PropertyException)) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + caught.getClass() ! + "/, expecting throw PropertyException"); ! assertTrue(false); ! } ! else ! { ! caught = ((PropertyException) e).getCaught(); ! } ! } ! if (caught == null) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " yielded /" + result + "/, expecting throw " ! + "PropertyException with caught exception " ! + exceptionClass); ! assertTrue(false); ! } ! else if (!exceptionClass.isAssignableFrom(caught.getClass())) ! { ! System.err.println("Execution of /" + templateText + "/" ! + " threw " + caught.getClass() + ", expecting throw " ! + "PropertyException with caught exception " ! + exceptionClass); ! assertTrue(false); ! } } ! ! ! /** Asserts that the specified expression is considered true or false ! * depending on the value of 'yesno' */ ! public void assertExpr (String expr, boolean yesno) ! { ! assertStringTemplateEquals("#if (" + expr + ") {Yes} #else {No}", ! yesno ? "Yes" : "No"); } ! /** Asserts that the specified expression evaluates to the desired ! * boolean result */ ! public void assertBooleanExpr (String expr, boolean result) ! { ! assertStringTemplateEquals("#set $result=(" + expr + ") $result", ! result ? "true" : "false"); ! } } Index: TestAbuse.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/template/TestAbuse.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** TestAbuse.java 23 Mar 2003 02:00:38 -0000 1.8 --- TestAbuse.java 12 Jun 2003 00:47:49 -0000 1.9 *************** *** 1,13 **** package org.webmacro.template; ! import java.io.*; ! import org.webmacro.*; ! import org.webmacro.engine.StringTemplate; import org.webmacro.engine.DefaultEvaluationExceptionHandler; - import junit.framework.*; - - import org.apache.regexp.RE; - /** --- 1,7 ---- package org.webmacro.template; ! import org.webmacro.Context; import org.webmacro.engine.DefaultEvaluationExceptionHandler; /** *************** *** 16,139 **** * correctly. */ ! public class TestAbuse extends TemplateTestCase { ! public TestAbuse (String name) { ! super (name); ! } - public void stuffContext (Context context) throws Exception { - context.setEvaluationExceptionHandler ( - new DefaultEvaluationExceptionHandler ()); - context.put ("User", "Eric"); - } ! /** We'll start easy */ ! public void testEOLComment () throws Exception { ! assertStringTemplateEquals ("## a comment", ""); ! } - /** this is easy too */ - public void testBlockComment () throws Exception { - assertStringTemplateEquals ("#comment { this is a comment }", ""); - } ! /** test a variable reference like: Welcome to the site, $User. */ ! public void testTrailingDot () throws Exception { ! assertStringTemplateEquals ("Hello, $User.", ! "Hello, Eric."); ! } - /** EOL comments at end of directive blocks. */ - public void testEOLCommentWithDirective () throws Exception { - String tmpl = "#if (true) { ## this is a comment\n" - + "pass\n" - + "} else { ## this is another comment\n" - + "fail\n" - + "}"; ! assertStringTemplateMatches (tmpl, ".*pass.*"); ! } ! /** WMScript that would fail if it weren't commented out */ ! public void testBlockCommentWithBadWMScript () throws Exception { ! String tmpl = "#comment { #if ($true) }"; ! assertStringTemplateMatches (tmpl, ""); ! } ! ! /** split an #if across multiple lines. ! currently produces a big parse error ! */ ! public void testMultiLineIf () throws Exception { ! System.err.println ("NEED TO REVISIT: TestAbuse.testMultiLineIf()"); ! assertTrue (true); // String tmpl = "#if (true\n&& true && true\n) {pass} #else {fail}"; // assertStringTemplateEquals (tmpl, "pass"); ! } - /** - * The error message this produces is: - * Attempt to dereference null value $Object - * but $Object <b>isn't</b> null. Only its - * toString() method returns null. The message - * implies that $Object is null. - * - * Can this be detected and say something like: - * $Object's toString() method returned null. - * - * Probably requires another Exception type for EEH - * and friends. - */ - public void testToStringIsNull () throws Exception { - Object obj = new Object () { - public String toString () { return null; } - }; ! _context.put ("Object", obj); ! assertStringTemplateMatches("$Object", ! "<!--.*returns null.*-->"); ! } ! /** the infamous "but I want to put Javascript in an #if block!!" - Currently fails when using { and }, but passes with - #begin and #end. Any reason why? - */ - public void testBlockDirectiveWithJavascript () throws Exception { - String jscript = "<script>\n" - + " if (true) {\n" - + " alert (\"Hello, World\");\n" - + " } else {\n" - + " alert (\"Goodbye, World\");\n" - + " }\n" - + "</script>"; - String jscriptnl = "<script>\n" - + " if (true) {\n" - + " alert (\"Hello, World\");\n" - + " } else {\n" - + " alert (\"Goodbye, World\");\n" - + " }\n" - + "</script>\n"; ! // check it with #begin and #end ! String tmpl = "#if (true) #begin" ! + jscript ! + "#end"; ! assertStringTemplateEquals (tmpl, jscript); ! } ! public void testSemi() throws Exception { ! String assn = "#set $foo=\"blah\" "; ! assertStringTemplateEquals(assn + "$(foo);", "blah;"); ! assertStringTemplateEquals(assn + "$(foo)", "blah"); ! assertStringTemplateEquals(assn + "$foo", "blah"); ! assertStringTemplateEquals(assn + "$foo;", "blah"); ! assertStringTemplateEquals(assn + "$foo.substring(1)", "lah"); ! assertStringTemplateEquals(assn + "$foo.substring(1);", "lah;"); ! } ! public void testNastyEndreTemplate() throws Exception { String tmpl = templateFileToString("org/webmacro/template/nasty_endre.wm"); assertStringTemplateThrows(tmpl, org.webmacro.engine.BuildException.class); --- 10,161 ---- * correctly. */ ! public class TestAbuse extends TemplateTestCase ! { ! public TestAbuse (String name) ! { ! super(name); ! } ! public void stuffContext (Context context) throws Exception ! { ! context.setEvaluationExceptionHandler( ! new DefaultEvaluationExceptionHandler()); ! context.put("User", "Eric"); ! } ! /** We'll start easy */ ! public void testEOLComment () throws Exception ! { ! assertStringTemplateEquals("## a comment", ""); ! } ! /** this is easy too */ ! public void testBlockComment () throws Exception ! { ! assertStringTemplateEquals("#comment { this is a comment }", ""); ! } ! ! /** test a variable reference like: Welcome to the site, $User. */ ! public void testTrailingDot () throws Exception ! { ! assertStringTemplateEquals("Hello, $User.", ! "Hello, Eric."); ! } ! ! ! /** EOL comments at end of directive blocks. */ ! public void testEOLCommentWithDirective () throws Exception ! { ! String tmpl = "#if (true) { ## this is a comment\n" ! + "pass\n" ! + "} else { ## this is another comment\n" ! + "fail\n" ! + "}"; ! ! assertStringTemplateMatches(tmpl, ".*pass.*"); ! } ! ! ! /** WMScript that would fail if it weren't commented out */ ! public void testBlockCommentWithBadWMScript () throws Exception ! { ! String tmpl = "#comment { #if ($true) }"; ! assertStringTemplateMatches(tmpl, ""); ! } ! ! ! /** split an #if across multiple lines. ! currently produces a big parse error ! */ ! public void testMultiLineIf () throws Exception ! { ! System.err.println("NEED TO REVISIT: TestAbuse.testMultiLineIf()"); ! assertTrue(true); // String tmpl = "#if (true\n&& true && true\n) {pass} #else {fail}"; // assertStringTemplateEquals (tmpl, "pass"); ! } ! /** ! * The error message this produces is: ! * Attempt to dereference null value $Obje... [truncated message content] |
From: <dr...@us...> - 2003-06-12 00:47:56
|
Update of /cvsroot/webmacro/webmacro/test/perf In directory sc8-pr-cvs1:/tmp/cvs-serv6675/test/perf Modified Files: SpinTest.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: SpinTest.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/perf/SpinTest.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** SpinTest.java 4 May 2001 00:39:28 -0000 1.2 --- SpinTest.java 12 Jun 2003 00:47:49 -0000 1.3 *************** *** 1,43 **** - import java.io.*; ! import org.webmacro.*; public class SpinTest { ! public static void main(String[] args) throws Exception { ! long initStart, loopStart, loopEnd; ! String template = args[0]; ! int count = Integer.parseInt(args[1]); ! initStart = System.currentTimeMillis(); ! WM wm = new WM(); ! loopStart = System.currentTimeMillis(); ! for (int i=0; i<count; i++) { ! Context c = wm.getContext(); ! c.put("One", "1"); ! c.put("Two", "2"); ! c.put("Three", "3"); ! Template t = wm.getTemplate(template); ! FastWriter fw = new FastWriter(wm.getBroker(), new FileOutputStream("/dev/null"), "US-ASCII"); ! t.write(fw, c); ! fw.close(); ! } ! loopEnd = System.currentTimeMillis(); ! System.out.println("Total time: " ! + ((double) (loopEnd-initStart)/1000) ! + "s, loop time " ! + ((double) (loopEnd-loopStart)/1000) ! + "s, template time " ! + ((double) (loopEnd-loopStart)/count) + "ms"); ! } } --- 1,49 ---- ! import org.webmacro.Context; ! import org.webmacro.FastWriter; ! import org.webmacro.Template; ! import org.webmacro.WM; ! ! import java.io.FileOutputStream; public class SpinTest { ! public static void main (String[] args) throws Exception ! { ! long initStart, loopStart, loopEnd; ! String template = args[0]; ! int count = Integer.parseInt(args[1]); ! initStart = System.currentTimeMillis(); ! WM wm = new WM(); ! loopStart = System.currentTimeMillis(); ! for (int i = 0; i < count; i++) ! { ! Context c = wm.getContext(); ! c.put("One", "1"); ! c.put("Two", "2"); ! c.put("Three", "3"); ! Template t = wm.getTemplate(template); ! FastWriter fw = new FastWriter(wm.getBroker(), new FileOutputStream("/dev/null"), "US-ASCII"); ! t.write(fw, c); ! fw.close(); ! } ! loopEnd = System.currentTimeMillis(); ! System.out.println("Total time: " ! + ((double) (loopEnd - initStart) / 1000) ! + "s, loop time " ! + ((double) (loopEnd - loopStart) / 1000) ! + "s, template time " ! + ((double) (loopEnd - loopStart) / count) + "ms"); ! } } |
From: <dr...@us...> - 2003-06-12 00:47:56
|
Update of /cvsroot/webmacro/webmacro/test/unit/org/webmacro/engine In directory sc8-pr-cvs1:/tmp/cvs-serv6675/test/unit/org/webmacro/engine Modified Files: TestStaticClasses.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: TestStaticClasses.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/engine/TestStaticClasses.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TestStaticClasses.java 10 Nov 2002 21:45:46 -0000 1.1 --- TestStaticClasses.java 12 Jun 2003 00:47:49 -0000 1.2 *************** *** 9,21 **** package org.webmacro.engine; - import junit.framework.TestCase; - import org.webmacro.template.TemplateTestCase; import org.webmacro.Context; ! public class TestStaticClasses extends TemplateTestCase { ! public static class Simple { ! public static String foo (String arg, String arg2) { ! if (arg == null) return "arg is null"; else --- 9,23 ---- package org.webmacro.engine; import org.webmacro.Context; + import org.webmacro.template.TemplateTestCase; ! public class TestStaticClasses extends TemplateTestCase ! { ! public static class Simple ! { ! public static String foo (String arg, String arg2) ! { ! if (arg == null) return "arg is null"; else *************** *** 24,41 **** } ! public TestStaticClasses(String s) { super(s); } ! protected void stuffContext(Context context) throws Exception { ! _context.put ("SimpleInstance", new Simple()); ! _context.put ("SimpleClass", Simple.class); } ! public void testStaticClassWithNullAsFirstArg_1 () throws Exception { assertEvalutionEquals("$SimpleClass.foo(null, null)", "arg is null"); assertEvalutionEquals("$SimpleInstance.foo(null, null)", "arg is null"); } ! public void testStaticClassWithNullAsFirstArg_2 () throws Exception { executeStringTemplate("$SimpleClass.foo(null, null)"); executeStringTemplate("$SimpleInstance.foo(null, null)"); --- 26,52 ---- } ! ! public TestStaticClasses (String s) ! { super(s); } ! ! protected void stuffContext (Context context) throws Exception ! { ! _context.put("SimpleInstance", new Simple()); ! _context.put("SimpleClass", Simple.class); } ! ! public void testStaticClassWithNullAsFirstArg_1 () throws Exception ! { assertEvalutionEquals("$SimpleClass.foo(null, null)", "arg is null"); assertEvalutionEquals("$SimpleInstance.foo(null, null)", "arg is null"); } ! ! ! public void testStaticClassWithNullAsFirstArg_2 () throws Exception ! { executeStringTemplate("$SimpleClass.foo(null, null)"); executeStringTemplate("$SimpleInstance.foo(null, null)"); |
From: <dr...@us...> - 2003-06-12 00:47:56
|
Update of /cvsroot/webmacro/webmacro/test/unit/org/webmacro/parser In directory sc8-pr-cvs1:/tmp/cvs-serv6675/test/unit/org/webmacro/parser Modified Files: TestBackupCharStream.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: TestBackupCharStream.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/parser/TestBackupCharStream.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** TestBackupCharStream.java 1 Dec 2001 07:09:34 -0000 1.5 --- TestBackupCharStream.java 12 Jun 2003 00:47:49 -0000 1.6 *************** *** 1,168 **** package org.webmacro.parser; import java.io.*; - import junit.framework.*; - import org.webmacro.*; ! public class TestBackupCharStream extends TestCase { ! String loc = "org/webmacro/parser/"; ! String[] testFiles = new String[] { ! loc+"test1.wm", loc+"test2.wm", loc+"test3.wm", loc+"test4.wm", ! loc+"test5.wm", loc+"test6.wm", loc+"test7.wm", ! loc+"nasty_sebastian.wm" ! }; - public TestBackupCharStream (String name) { - super (name); - } - - private char[] readFile(String name) throws IOException { - Reader in; - CharArrayWriter out; - char[] buf = new char[512]; ! try { ! in = new FileReader(name); } ! catch (IOException e) { ! in = new InputStreamReader(ClassLoader.getSystemResourceAsStream(name)); } ! out = new CharArrayWriter(); ! while (in.ready()) { ! int n = in.read(buf, 0, 512); ! if (n > 0) ! out.write(buf, 0, n); } - char[] result = out.toCharArray(); - out.close(); - in.close(); - return result; - } ! private void failAt(String file, int pos, char c1, char c2) { ! fail("Characters do not match at position " + pos ! + " of " + file + " (" + c1 + "/" + c2 + ")"); ! } ! ! private void assertBcsEqual(char[] chars, String file) { ! BackupCharStream in = new BackupCharStream(new CharArrayReader(chars)); ! for (int i=0; i<chars.length; i++) { ! char c; ! try { ! c = in.readChar(); ! } ! catch (IOException e) { ! fail("Premature end-of-file reading stream with BCS"); ! break; ! } ! if (c != chars[i]) ! failAt(file, i, c, chars[i]); } ! try { ! char c = in.readChar(); ! fail("Expecting BCS to return EOF; found /" + c + "/"); } ! catch (IOException e) { } - } - private void assertBcsEqual(char[] chars, String file, - int readChars, int backupChars) - throws Exception { - BackupCharStream in = new BackupCharStream(new CharArrayReader(chars)); - int counter = 0; - char c; ! for (int i=0; i<chars.length; i++) { ! try { ! c = (counter == 0) ? in.BeginToken() : in.readChar(); ! } ! catch (IOException e) { ! fail("Premature end-of-file reading stream with BCS"); ! break; ! } ! if (c != chars[i]) ! failAt(file, i, c, chars[i]); ! ++counter; ! if (counter == readChars) { ! counter = 0; ! int jMax = Math.min(backupChars, i); ! in.backup(jMax); ! for (int j=0; j<jMax; j++) { ! c = in.readChar(); ! if (c != chars[i+1-jMax+j]) ! failAt(file, i+1-jMax+j, c, chars[i+1-jMax+j]); ! } ! } } ! try { ! c = in.readChar(); ! fail("Expecting BCS to return EOF; found /" + c + "/"); } ! catch (IOException e) { } - in.backup(1); - c = in.readChar(); - if (c != chars[chars.length-1]) - failAt(file, chars.length-1, c, chars[chars.length-1]); - } - - public void testBasic() throws Exception { - for (int i=0; i<testFiles.length; i++) - assertBcsEqual(readFile(testFiles[i]), testFiles[i]); - } ! public void test_1_1() throws Exception { ! for (int i=0; i<testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 1, 1); ! } - public void test_1_2() throws Exception { - for (int i=0; i<testFiles.length; i++) - assertBcsEqual(readFile(testFiles[i]), testFiles[i], 1, 2); - } ! public void test_1_4() throws Exception { ! for (int i=0; i<testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 1, 4); ! } - public void test_2_1() throws Exception { - for (int i=0; i<testFiles.length; i++) - assertBcsEqual(readFile(testFiles[i]), testFiles[i], 2, 1); - } ! public void test_3_2() throws Exception { ! for (int i=0; i<testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 3, 2); ! } - public void test_5_4() throws Exception { - for (int i=0; i<testFiles.length; i++) - assertBcsEqual(readFile(testFiles[i]), testFiles[i], 5, 4); - } ! public void test_10_9() throws Exception { ! for (int i=0; i<testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 10, 9); ! } - public void test_10_2() throws Exception { - for (int i=0; i<testFiles.length; i++) - assertBcsEqual(readFile(testFiles[i]), testFiles[i], 10, 2); - } ! public void test_1000_500() throws Exception { ! for (int i=0; i<testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 1000, 500); ! } ! public void test_4000_2000() throws Exception { ! for (int i=0; i<testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 4000, 2000); ! } } --- 1,216 ---- package org.webmacro.parser; + import junit.framework.TestCase; + import java.io.*; ! public class TestBackupCharStream extends TestCase ! { ! String loc = "org/webmacro/parser/"; ! String[] testFiles = new String[]{ ! loc + "test1.wm", loc + "test2.wm", loc + "test3.wm", loc + "test4.wm", ! loc + "test5.wm", loc + "test6.wm", loc + "test7.wm", ! loc + "nasty_sebastian.wm" ! }; ! public TestBackupCharStream (String name) ! { ! super(name); } ! ! ! private char[] readFile (String name) throws IOException ! { ! Reader in; ! CharArrayWriter out; ! char[] buf = new char[512]; ! ! try ! { ! in = new FileReader(name); ! } ! catch (IOException e) ! { ! in = new InputStreamReader(ClassLoader.getSystemResourceAsStream(name)); ! } ! out = new CharArrayWriter(); ! while (in.ready()) ! { ! int n = in.read(buf, 0, 512); ! if (n > 0) ! out.write(buf, 0, n); ! } ! char[] result = out.toCharArray(); ! out.close(); ! in.close(); ! return result; } ! ! ! private void failAt (String file, int pos, char c1, char c2) ! { ! fail("Characters do not match at position " + pos ! + " of " + file + " (" + c1 + "/" + c2 + ")"); } ! ! private void assertBcsEqual (char[] chars, String file) ! { ! BackupCharStream in = new BackupCharStream(new CharArrayReader(chars)); ! for (int i = 0; i < chars.length; i++) ! { ! char c; ! try ! { ! c = in.readChar(); ! } ! catch (IOException e) ! { ! fail("Premature end-of-file reading stream with BCS"); ! break; ! } ! if (c != chars[i]) ! failAt(file, i, c, chars[i]); ! } ! try ! { ! char c = in.readChar(); ! fail("Expecting BCS to return EOF; found /" + c + "/"); ! } ! catch (IOException e) ! { ! } } ! ! ! private void assertBcsEqual (char[] chars, String file, ! int readChars, int backupChars) ! throws Exception ! { ! BackupCharStream in = new BackupCharStream(new CharArrayReader(chars)); ! int counter = 0; ! char c; ! ! for (int i = 0; i < chars.length; i++) ! { ! try ! { ! c = (counter == 0) ? in.BeginToken() : in.readChar(); ! } ! catch (IOException e) ! { ! fail("Premature end-of-file reading stream with BCS"); ! break; ! } ! if (c != chars[i]) ! failAt(file, i, c, chars[i]); ! ! ++counter; ! if (counter == readChars) ! { ! counter = 0; ! int jMax = Math.min(backupChars, i); ! in.backup(jMax); ! for (int j = 0; j < jMax; j++) ! { ! c = in.readChar(); ! if (c != chars[i + 1 - jMax + j]) ! failAt(file, i + 1 - jMax + j, c, chars[i + 1 - jMax + j]); ! } ! } ! } ! try ! { ! c = in.readChar(); ! fail("Expecting BCS to return EOF; found /" + c + "/"); ! } ! catch (IOException e) ! { ! } ! ! in.backup(1); ! c = in.readChar(); ! if (c != chars[chars.length - 1]) ! failAt(file, chars.length - 1, c, chars[chars.length - 1]); } ! ! ! public void testBasic () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i]); } ! public void test_1_1 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 1, 1); ! } ! ! public void test_1_2 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 1, 2); } ! ! ! public void test_1_4 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 1, 4); } ! ! ! public void test_2_1 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 2, 1); } ! public void test_3_2 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 3, 2); ! } ! public void test_5_4 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 5, 4); ! } ! public void test_10_9 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 10, 9); ! } ! public void test_10_2 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 10, 2); ! } ! public void test_1000_500 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 1000, 500); ! } ! ! public void test_4000_2000 () throws Exception ! { ! for (int i = 0; i < testFiles.length; i++) ! assertBcsEqual(readFile(testFiles[i]), testFiles[i], 4000, 2000); ! } } |
From: <dr...@us...> - 2003-06-12 00:47:55
|
Update of /cvsroot/webmacro/webmacro/test/unit/org/webmacro/util In directory sc8-pr-cvs1:/tmp/cvs-serv6675/test/unit/org/webmacro/util Modified Files: TestMathTool.java TestSettings.java TestTextTool.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: TestMathTool.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/util/TestMathTool.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** TestMathTool.java 23 Mar 2003 02:00:42 -0000 1.2 --- TestMathTool.java 12 Jun 2003 00:47:50 -0000 1.3 *************** *** 12,24 **** import org.webmacro.servlet.MathTool; ! public class TestMathTool extends TestCase { ! public TestMathTool(String s) { super(s); } ! public void testRandom () { ! for (int x=0; x<1000000; x++) { int rnd = MathTool.random(3, 5); ! assertTrue (""+rnd, rnd >= 3 && rnd <=5); } } --- 12,29 ---- import org.webmacro.servlet.MathTool; ! public class TestMathTool extends TestCase ! { ! public TestMathTool (String s) ! { super(s); } ! ! public void testRandom () ! { ! for (int x = 0; x < 1000000; x++) ! { int rnd = MathTool.random(3, 5); ! assertTrue("" + rnd, rnd >= 3 && rnd <= 5); } } Index: TestSettings.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/util/TestSettings.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** TestSettings.java 23 Mar 2003 02:00:42 -0000 1.3 --- TestSettings.java 12 Jun 2003 00:47:50 -0000 1.4 *************** *** 1,74 **** package org.webmacro.util; ! import java.io.*; ! import org.webmacro.*; ! import org.webmacro.util.*; - import junit.framework.*; ! public class TestSettings extends TestCase { ! public TestSettings(String name) { ! super(name); ! } - protected void setUp() { - } - - public void testSimple() throws Exception { - Settings s = new Settings(); ! s.load("org/webmacro/util/settings1.properties"); // String k[] = s.getKeys(); // for (int i=0; i<k.length; i++) // System.out.println("/" + k[i] + "/" + s.getSetting(k[i]) + "/"); ! assertTrue(s.getIntegerSetting("one") == 1); ! assertTrue(s.getIntegerSetting("two") == 2); ! assertTrue(s.getIntegerSetting("three") == 3); ! assertTrue(s.getIntegerSetting("four") == 4); ! assertTrue(s.getIntegerSetting("notthere", 0) == 0); ! assertTrue(s.getSetting("a").equals("a")); ! assertTrue(s.getSetting("b").equals("b")); ! assertTrue(s.getSetting("c").equals("c")); ! assertTrue(s.getSetting("d").equals("d")); ! assertTrue(s.getSetting("e").equals("e")); ! assertTrue(s.getSetting("f").equals("f")); ! assertTrue(s.getSetting("a.b.c").equals("abc")); ! assertTrue(s.getSetting("a.*.c").equals("astarc")); ! assertTrue(s.getSetting("quoted").equals("quoted")); ! assertTrue(s.getSetting("quoted2").equals("quoted2")); ! assertTrue(s.getSetting("quoted3").equals(" quoted3 ")); ! assertTrue(s.getSetting("with.spaces").equals("with spaces")); ! assertTrue(s.getSetting("nothing").equals("")); ! assertTrue(s.getSetting("alsonothing").equals("")); ! } - public void testOcclude() throws Exception { - Settings s = new Settings(); ! s.load("org/webmacro/util/settings1.properties"); ! s.load("org/webmacro/util/settings2.properties"); ! assertTrue(s.getSetting("a").equals("aa")); ! assertTrue(s.getSetting("bb").equals("bb")); ! } ! public void testSubsettings() throws Exception { ! Settings s = new Settings(); ! s.load("org/webmacro/util/settings1.properties"); ! Settings ss = new SubSettings(s, "sub"); ! Settings sss = new SubSettings(ss, "sub"); ! Settings sssStar = new SubSettings(ss, "*"); ! Settings ssss = new SubSettings(s, "sub.sub"); ! assertTrue(s.getSetting("sub.sub.a").equals("a")); ! assertTrue(ss.getSetting("sub.a").equals("a")); ! assertTrue(ss.getSetting("a").equals("not a")); ! assertTrue(sss.getSetting("a").equals("a")); ! assertTrue(ssss.getSetting("a").equals("a")); ! assertTrue(sssStar.getSetting("a").equals("default")); ! } } --- 1,79 ---- package org.webmacro.util; ! import junit.framework.TestCase; ! public class TestSettings extends TestCase ! { ! public TestSettings (String name) ! { ! super(name); ! } ! protected void setUp () ! { ! } ! public void testSimple () throws Exception ! { ! Settings s = new Settings(); ! ! s.load("org/webmacro/util/settings1.properties"); // String k[] = s.getKeys(); // for (int i=0; i<k.length; i++) // System.out.println("/" + k[i] + "/" + s.getSetting(k[i]) + "/"); ! assertTrue(s.getIntegerSetting("one") == 1); ! assertTrue(s.getIntegerSetting("two") == 2); ! assertTrue(s.getIntegerSetting("three") == 3); ! assertTrue(s.getIntegerSetting("four") == 4); ! assertTrue(s.getIntegerSetting("notthere", 0) == 0); ! assertTrue(s.getSetting("a").equals("a")); ! assertTrue(s.getSetting("b").equals("b")); ! assertTrue(s.getSetting("c").equals("c")); ! assertTrue(s.getSetting("d").equals("d")); ! assertTrue(s.getSetting("e").equals("e")); ! assertTrue(s.getSetting("f").equals("f")); ! assertTrue(s.getSetting("a.b.c").equals("abc")); ! assertTrue(s.getSetting("a.*.c").equals("astarc")); ! assertTrue(s.getSetting("quoted").equals("quoted")); ! assertTrue(s.getSetting("quoted2").equals("quoted2")); ! assertTrue(s.getSetting("quoted3").equals(" quoted3 ")); ! assertTrue(s.getSetting("with.spaces").equals("with spaces")); ! assertTrue(s.getSetting("nothing").equals("")); ! assertTrue(s.getSetting("alsonothing").equals("")); ! } ! public void testOcclude () throws Exception ! { ! Settings s = new Settings(); ! s.load("org/webmacro/util/settings1.properties"); ! s.load("org/webmacro/util/settings2.properties"); ! assertTrue(s.getSetting("a").equals("aa")); ! assertTrue(s.getSetting("bb").equals("bb")); ! } ! ! public void testSubsettings () throws Exception ! { ! Settings s = new Settings(); ! s.load("org/webmacro/util/settings1.properties"); ! Settings ss = new SubSettings(s, "sub"); ! Settings sss = new SubSettings(ss, "sub"); ! Settings sssStar = new SubSettings(ss, "*"); ! Settings ssss = new SubSettings(s, "sub.sub"); ! ! assertTrue(s.getSetting("sub.sub.a").equals("a")); ! assertTrue(ss.getSetting("sub.a").equals("a")); ! assertTrue(ss.getSetting("a").equals("not a")); ! assertTrue(sss.getSetting("a").equals("a")); ! assertTrue(ssss.getSetting("a").equals("a")); ! assertTrue(sssStar.getSetting("a").equals("default")); ! } } Index: TestTextTool.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/util/TestTextTool.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TestTextTool.java 10 Nov 2002 21:11:28 -0000 1.1 --- TestTextTool.java 12 Jun 2003 00:47:50 -0000 1.2 *************** *** 12,29 **** import org.webmacro.servlet.TextTool; ! public class TestTextTool extends TestCase { ! public TestTextTool(String s) { super(s); } ! public void testRTrim() { String toTrim = "This is a test "; String expected = "This is a test"; ! assertEquals (expected, TextTool.rtrim(toTrim)); } ! public void testLTrim() { String toTrim = " This is a test "; String expected = "This is a test "; ! assertEquals (expected, TextTool.ltrim(toTrim)); } } --- 12,36 ---- import org.webmacro.servlet.TextTool; ! public class TestTextTool extends TestCase ! { ! public TestTextTool (String s) ! { super(s); } ! ! public void testRTrim () ! { String toTrim = "This is a test "; String expected = "This is a test"; ! assertEquals(expected, TextTool.rtrim(toTrim)); } ! ! ! public void testLTrim () ! { String toTrim = " This is a test "; String expected = "This is a test "; ! assertEquals(expected, TextTool.ltrim(toTrim)); } } |
Update of /cvsroot/webmacro/webmacro/test/unit/org/webmacro In directory sc8-pr-cvs1:/tmp/cvs-serv6675/test/unit/org/webmacro Modified Files: FooDirective.java TestBroker.java TestContext.java TestFastWriter.java TestMultipleInstances.java TestStaticIdentityCM.java TestVersion.java Log Message: If this doesn't drive our SF "activity" stats through the roof, I don't know what will. Mass re-formatting of all code, following (to the best of my interpertation) the Sun (w/ jakarta tweaks) coding style guidelines defined here: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html and here: http://jakarta.apache.org/turbine/common/code-standards.html I did this reformatting with IDEA 3.0.5, and I am going to commit the style configuration for IDEA (if I can find it). Index: FooDirective.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/FooDirective.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FooDirective.java 5 Jan 2002 22:19:33 -0000 1.3 --- FooDirective.java 12 Jun 2003 00:47:49 -0000 1.4 *************** *** 23,62 **** package org.webmacro; - import java.io.*; - import org.webmacro.*; import org.webmacro.directive.Directive; - import org.webmacro.directive.DirectiveDescriptor; import org.webmacro.directive.DirectiveBuilder; ! import org.webmacro.engine.*; ! public class FooDirective extends Directive { ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[] { ! }; ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor("foo", null, myArgs, null); ! public static DirectiveDescriptor getDescriptor() { ! return myDescr; ! } - public Object build(DirectiveBuilder builder, - BuildContext bc) - throws BuildException { - return this; - } ! public void write(FastWriter out, Context context) ! throws PropertyException, IOException { ! out.write ("foo"); ! } ! public void accept(TemplateVisitor v) { ! v.beginDirective(myDescr.name); ! v.endDirective(); ! } } --- 23,72 ---- package org.webmacro; import org.webmacro.directive.Directive; import org.webmacro.directive.DirectiveBuilder; ! import org.webmacro.directive.DirectiveDescriptor; ! import org.webmacro.engine.BuildContext; ! import org.webmacro.engine.BuildException; ! import java.io.IOException; ! public class FooDirective extends Directive ! { ! private static final ArgDescriptor[] ! myArgs = new ArgDescriptor[]{ ! }; ! private static final DirectiveDescriptor ! myDescr = new DirectiveDescriptor("foo", null, myArgs, null); ! public static DirectiveDescriptor getDescriptor () ! { ! return myDescr; ! } ! ! public Object build (DirectiveBuilder builder, ! BuildContext bc) ! throws BuildException ! { ! return this; ! } ! ! ! public void write (FastWriter out, Context context) ! throws PropertyException, IOException ! { ! out.write("foo"); ! } ! ! ! public void accept (TemplateVisitor v) ! { ! v.beginDirective(myDescr.name); ! v.endDirective(); ! } } Index: TestBroker.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/TestBroker.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** TestBroker.java 23 Mar 2003 02:00:34 -0000 1.3 --- TestBroker.java 12 Jun 2003 00:47:49 -0000 1.4 *************** *** 1,62 **** package org.webmacro; ! import java.io.*; ! import org.webmacro.*; ! import org.webmacro.util.*; ! import junit.framework.*; - /* Test various features of a default-configured Broker */ - public class TestBroker extends TestCase { - private WebMacro _wm; - private Broker _broker; ! public TestBroker(String name) { ! super(name); ! } - protected void setUp() { - try { - if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) - System.getProperties().setProperty("org.webmacro.LogLevel", "ERROR"); - _wm = new WM (); - } catch (Exception e) { - System.err.println ("Could not initialize WebMacro!"); - } - _broker = _wm.getBroker (); - } - - public void testBrokerLocal () throws Exception { - _broker.setBrokerLocal ("MyName", "Mud"); ! assertTrue (_broker.getBrokerLocal ("MyName") ! .toString().equals ("Mud")); ! } - public void testGetSettings() throws Exception { - Settings s = _broker.getSettings(); - assertTrue (s != null); - assertTrue (_broker.getSetting("ErrorTemplate") - .equals ("error.wm")); - } ! public void testGetProvider() throws Exception { ! Provider p = _broker.getProvider ("template"); ! assertTrue (p != null); ! } ! public void testGetLog() throws Exception { ! Log l = _broker.getLog ("template"); ! assertTrue (l != null); - l = _broker.getLog ("NewLog"); - assertTrue (l != null); - } ! public void testGetResource() throws Exception { ! java.net.URL url = _broker.getResource ("WebMacro.defaults"); ! assertTrue (url != null); ! } } --- 1,77 ---- package org.webmacro; ! import junit.framework.TestCase; ! import org.webmacro.util.Settings; ! /* Test various features of a default-configured Broker */ ! public class TestBroker extends TestCase ! { ! private WebMacro _wm; ! private Broker _broker; ! public TestBroker (String name) ! { ! super(name); ! } ! protected void setUp () ! { ! try ! { ! if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) ! System.getProperties().setProperty("org.webmacro.LogLevel", "ERROR"); ! _wm = new WM(); ! } ! catch (Exception e) ! { ! System.err.println("Could not initialize WebMacro!"); ! } ! _broker = _wm.getBroker(); ! } ! public void testBrokerLocal () throws Exception ! { ! _broker.setBrokerLocal("MyName", "Mud"); ! assertTrue(_broker.getBrokerLocal("MyName") ! .toString().equals("Mud")); ! } ! public void testGetSettings () throws Exception ! { ! Settings s = _broker.getSettings(); ! assertTrue(s != null); ! assertTrue(_broker.getSetting("ErrorTemplate") ! .equals("error.wm")); ! } ! ! ! public void testGetProvider () throws Exception ! { ! Provider p = _broker.getProvider("template"); ! assertTrue(p != null); ! } ! ! ! public void testGetLog () throws Exception ! { ! Log l = _broker.getLog("template"); ! assertTrue(l != null); ! ! l = _broker.getLog("NewLog"); ! assertTrue(l != null); ! } ! ! ! public void testGetResource () throws Exception ! { ! java.net.URL url = _broker.getResource("WebMacro.defaults"); ! assertTrue(url != null); ! } } Index: TestContext.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/TestContext.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** TestContext.java 23 Mar 2003 02:00:34 -0000 1.2 --- TestContext.java 12 Jun 2003 00:47:49 -0000 1.3 *************** *** 1,21 **** package org.webmacro; - import java.io.*; - - import org.webmacro.engine.StringTemplate; import org.webmacro.engine.DefaultEvaluationExceptionHandler; import org.webmacro.template.TemplateTestCase; ! import junit.framework.*; ! ! import org.apache.regexp.RE; ! ! public class TestContext extends TemplateTestCase { ! public TestContext(String name) { super(name); } ! public void stuffContext(Context context) throws Exception { context.setEvaluationExceptionHandler( new DefaultEvaluationExceptionHandler()); --- 1,18 ---- package org.webmacro; import org.webmacro.engine.DefaultEvaluationExceptionHandler; import org.webmacro.template.TemplateTestCase; ! public class TestContext extends TemplateTestCase ! { ! public TestContext (String name) ! { super(name); } ! ! public void stuffContext (Context context) throws Exception ! { context.setEvaluationExceptionHandler( new DefaultEvaluationExceptionHandler()); *************** *** 23,88 **** ! ! ! public void testPutGet_NULL() throws Exception { ! _context.put ("Foo", null); Object o = _context.get("Foo"); ! assertTrue (_context.get("Foo") == null); } - public void testPutGet_int() throws Exception { - _context.put ("Foo", 123); - Integer i = (Integer) _context.get ("Foo"); - assertTrue (i.intValue() == 123); - } ! public void testPutGet_boolean() throws Exception { ! _context.put ("Foo", true); ! Boolean b = (Boolean) _context.get ("Foo"); ! assertTrue (b.booleanValue() == true); } ! public void testPutGet_byte() throws Exception { ! _context.put ("Foo", (byte)123); ! Byte b = (Byte) _context.get ("Foo"); ! assertTrue (b.byteValue() == (byte) 123); } - public void testPutGet_char() throws Exception { - _context.put ("Foo", (char)123); - Character c = (Character) _context.get ("Foo"); - assertTrue (c.charValue() == (char)123); - } ! public void testPutGet_Class() throws Exception { ! _context.put ("Foo", this.getClass()); ! Object o = _context.get ("Foo"); ! assertTrue (o instanceof org.webmacro.engine.StaticClassWrapper); } - public void testPutGet_double() throws Exception { - _context.put ("Foo", 123.4D); - Double d= (Double) _context.get ("Foo"); - assertTrue (d.doubleValue() == 123.4D); - } ! public void testPutGet_long() throws Exception { ! _context.put ("Foo", 123L); ! Long l = (Long) _context.get ("Foo"); ! assertTrue (l.longValue() == 123L); } ! public void testPutGet_short() throws Exception { ! _context.put ("Foo", (short) 123); ! Short s = (Short) _context.get ("Foo"); ! assertTrue (s.shortValue() == (short) 123); } --- 20,93 ---- ! public void testPutGet_NULL () throws Exception ! { ! _context.put("Foo", null); Object o = _context.get("Foo"); ! assertTrue(_context.get("Foo") == null); } ! public void testPutGet_int () throws Exception ! { ! _context.put("Foo", 123); ! Integer i = (Integer) _context.get("Foo"); ! assertTrue(i.intValue() == 123); } ! public void testPutGet_boolean () throws Exception ! { ! _context.put("Foo", true); ! Boolean b = (Boolean) _context.get("Foo"); ! assertTrue(b.booleanValue() == true); } ! public void testPutGet_byte () throws Exception ! { ! _context.put("Foo", (byte) 123); ! Byte b = (Byte) _context.get("Foo"); ! assertTrue(b.byteValue() == (byte) 123); } ! public void testPutGet_char () throws Exception ! { ! _context.put("Foo", (char) 123); ! Character c = (Character) _context.get("Foo"); ! assertTrue(c.charValue() == (char) 123); } ! ! public void testPutGet_Class () throws Exception ! { ! _context.put("Foo", this.getClass()); ! Object o = _context.get("Foo"); ! assertTrue(o instanceof org.webmacro.engine.StaticClassWrapper); } + public void testPutGet_double () throws Exception + { + _context.put("Foo", 123.4D); + Double d = (Double) _context.get("Foo"); + assertTrue(d.doubleValue() == 123.4D); + } + public void testPutGet_long () throws Exception + { + _context.put("Foo", 123L); + Long l = (Long) _context.get("Foo"); + assertTrue(l.longValue() == 123L); + } + public void testPutGet_short () throws Exception + { + _context.put("Foo", (short) 123); + Short s = (Short) _context.get("Foo"); + assertTrue(s.shortValue() == (short) 123); + } Index: TestFastWriter.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/TestFastWriter.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** TestFastWriter.java 23 Mar 2003 02:00:35 -0000 1.2 --- TestFastWriter.java 12 Jun 2003 00:47:49 -0000 1.3 *************** *** 11,22 **** import junit.framework.TestCase; ! public class TestFastWriter extends TestCase { private WebMacro wm; ! public TestFastWriter(String name) { super(name); } ! protected void setUp() throws Exception { java.lang.System.setProperty("org.webmacro.LogLevel", "NONE"); wm = new WM(); --- 11,28 ---- import junit.framework.TestCase; ! public class TestFastWriter extends TestCase ! { private WebMacro wm; ! ! ! public TestFastWriter (String name) ! { super(name); } ! ! protected void setUp () throws Exception ! { java.lang.System.setProperty("org.webmacro.LogLevel", "NONE"); wm = new WM(); *************** *** 24,35 **** ! public void testFastWriter() throws Exception { doIt(4 * 1024); doIt(10 * 1024); doIt(100 * 1024); ! doIt(1000* 1024); doIt(4000 * 1024); } ! private void doIt(int size) throws Exception { String data = makeData(size); --- 30,45 ---- ! public void testFastWriter () throws Exception ! { doIt(4 * 1024); doIt(10 * 1024); doIt(100 * 1024); ! doIt(1000 * 1024); doIt(4000 * 1024); } ! ! ! private void doIt (int size) throws Exception ! { String data = makeData(size); *************** *** 41,53 **** long end = System.currentTimeMillis(); ! System.err.println (size + " bytes in " + ((end-start)/1000D) + " seconds."); ! assertTrue (after.equals(data)); } ! private String makeData (int size) { StringBuffer sb = new StringBuffer(size); ! for (int x=0; x<size; x++) sb.append('x'); --- 51,64 ---- long end = System.currentTimeMillis(); ! System.err.println(size + " bytes in " + ((end - start) / 1000D) + " seconds."); ! assertTrue(after.equals(data)); } ! private String makeData (int size) ! { StringBuffer sb = new StringBuffer(size); ! for (int x = 0; x < size; x++) sb.append('x'); Index: TestMultipleInstances.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/TestMultipleInstances.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** TestMultipleInstances.java 27 Mar 2003 00:35:31 -0000 1.5 --- TestMultipleInstances.java 12 Jun 2003 00:47:49 -0000 1.6 *************** *** 1,35 **** package org.webmacro; - import java.util.*; - import junit.framework.TestCase; import org.webmacro.engine.StringTemplate; /** * Ensure that multiple instances of WM can co-exist in the same JVM. */ ! public class TestMultipleInstances extends TestCase { private WebMacro _instanceOne; private WebMacro _instanceTwo; ! public TestMultipleInstances(String name) { super(name); } ! protected void setUp() throws Exception { // we don't want to see any WebMacro output from this test if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) System.getProperties().setProperty("org.webmacro.LogLevel", "NONE"); ! try { _instanceOne = new WM(); ! } catch (Exception e) { System.err.println("Could not initialize Default WebMacro Instance"); throw e; } ! try { _instanceTwo = new WM("org/webmacro/TestMulti_1.properties"); ! } catch (Exception e) { System.err.println("Could not initialize another WebMacro Instance using org/webmacro/TestMulti_1.properties!"); throw e; --- 1,46 ---- package org.webmacro; import junit.framework.TestCase; import org.webmacro.engine.StringTemplate; + import java.util.Properties; + /** * Ensure that multiple instances of WM can co-exist in the same JVM. */ ! public class TestMultipleInstances extends TestCase ! { private WebMacro _instanceOne; private WebMacro _instanceTwo; ! ! public TestMultipleInstances (String name) ! { super(name); } ! ! protected void setUp () throws Exception ! { // we don't want to see any WebMacro output from this test if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) System.getProperties().setProperty("org.webmacro.LogLevel", "NONE"); ! try ! { _instanceOne = new WM(); ! } ! catch (Exception e) ! { System.err.println("Could not initialize Default WebMacro Instance"); throw e; } ! try ! { _instanceTwo = new WM("org/webmacro/TestMulti_1.properties"); ! } ! catch (Exception e) ! { System.err.println("Could not initialize another WebMacro Instance using org/webmacro/TestMulti_1.properties!"); throw e; *************** *** 37,41 **** } ! public void testFooDirective() throws Exception { String template = " #foo "; String output = null; --- 48,54 ---- } ! ! public void testFooDirective () throws Exception ! { String template = " #foo "; String output = null; *************** *** 44,58 **** // against the default configured WM isntance, this *should* throw // an exception ! System.err.println ("----------- instance 1 -----------------"); ! try { if (_instanceOne != null) executeStringTemplate(_instanceOne, _instanceOne.getContext(), template); ! } catch (Exception e) { assertTrue(e.toString().indexOf("No such directive #foo") > -1); } // against the other WM instance, this should return the string "foo" ! System.err.println (); ! System.err.println ("----------- instance 2 -----------------"); output = executeStringTemplate(_instanceTwo, _instanceTwo.getContext(), template); assertTrue(output.equals("foo")); --- 57,74 ---- // against the default configured WM isntance, this *should* throw // an exception ! System.err.println("----------- instance 1 -----------------"); ! try ! { if (_instanceOne != null) executeStringTemplate(_instanceOne, _instanceOne.getContext(), template); ! } ! catch (Exception e) ! { assertTrue(e.toString().indexOf("No such directive #foo") > -1); } // against the other WM instance, this should return the string "foo" ! System.err.println(); ! System.err.println("----------- instance 2 -----------------"); output = executeStringTemplate(_instanceTwo, _instanceTwo.getContext(), template); assertTrue(output.equals("foo")); *************** *** 60,64 **** ! public void testDefaultConstructor() throws InitException { WM wm1 = new WM(); WM wm2 = new WM(); --- 76,81 ---- ! public void testDefaultConstructor () throws InitException ! { WM wm1 = new WM(); WM wm2 = new WM(); *************** *** 92,98 **** } /** Execute a string as a template against the current context, * and return the result. */ ! public String executeStringTemplate(WebMacro wm, Context context, String templateText) throws Exception { Broker b = wm.getBroker(); Template template = new StringTemplate(b, templateText); --- 109,117 ---- } + /** Execute a string as a template against the current context, * and return the result. */ ! public String executeStringTemplate (WebMacro wm, Context context, String templateText) throws Exception ! { Broker b = wm.getBroker(); Template template = new StringTemplate(b, templateText); Index: TestStaticIdentityCM.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/TestStaticIdentityCM.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** TestStaticIdentityCM.java 23 Mar 2003 02:00:36 -0000 1.2 --- TestStaticIdentityCM.java 12 Jun 2003 00:47:49 -0000 1.3 *************** *** 1,7 **** package org.webmacro; ! import org.webmacro.resource.*; ! ! import junit.framework.*; import java.util.Random; --- 1,7 ---- package org.webmacro; ! import junit.framework.TestCase; ! import org.webmacro.resource.CacheManager; ! import org.webmacro.resource.StaticIdentityCacheManager; import java.util.Random; *************** *** 12,16 **** * @author Sebastian Kanthak */ ! public class TestStaticIdentityCM extends TestCase { public static final int THREADS = 10; public static final int LOOPS = 10000; --- 12,17 ---- * @author Sebastian Kanthak */ ! public class TestStaticIdentityCM extends TestCase ! { public static final int THREADS = 10; public static final int LOOPS = 10000; *************** *** 19,75 **** private WebMacro wm; private CacheManager cm; ! ! public TestStaticIdentityCM(String name) { super(name); } ! protected void setUp() throws InitException { if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) System.getProperties().setProperty("org.webmacro.LogLevel", "ERROR"); wm = new WM(); cm = new StaticIdentityCacheManager(); ! cm.init(wm.getBroker(),wm.getBroker().getSettings(),"foo"); } /** * Tests integrity of cache under high load */ ! public void testCacheIntegrity() throws InterruptedException { TestThread[] threads = new TestThread[THREADS]; ! for (int i=0; i < THREADS; i++) { ! threads[i] = new TestThread(cm,i); } ! for (int i=0; i < THREADS; i++) { threads[i].start(); } ! for (int i=0; i < THREADS; i++) { threads[i].join(); } ! for (int i=0; i < THREADS; i++) { ! assertTrue("Test integrity check failed in thread "+i, ! threads[i].correct); } } /** * Assures, that cm uses "==" to test * for equality */ ! public void testCacheIdentityBehaviour() { String key1 = new String("foo"); String key2 = new String("foo"); assertTrue("test preconditions not met: keys should be different", ! key1 != key2 && key1.equals(key2)); Object cached1 = new Object(); Object cached2 = new Object(); ! cm.put(key1,cached1); ! cm.put(key2,cached2); assertTrue("cm returned wrong object", ! cm.get(key1) == cached1); assertTrue("cm returned wrong object", ! cm.get(key2) == cached2); } ! static class TestThread extends Thread { private CacheManager cm; private int id; --- 20,90 ---- private WebMacro wm; private CacheManager cm; ! ! ! public TestStaticIdentityCM (String name) ! { super(name); } ! ! protected void setUp () throws InitException ! { if (System.getProperties().getProperty("org.webmacro.LogLevel") == null) System.getProperties().setProperty("org.webmacro.LogLevel", "ERROR"); wm = new WM(); cm = new StaticIdentityCacheManager(); ! cm.init(wm.getBroker(), wm.getBroker().getSettings(), "foo"); } + /** * Tests integrity of cache under high load */ ! public void testCacheIntegrity () throws InterruptedException ! { TestThread[] threads = new TestThread[THREADS]; ! for (int i = 0; i < THREADS; i++) ! { ! threads[i] = new TestThread(cm, i); } ! for (int i = 0; i < THREADS; i++) ! { threads[i].start(); } ! for (int i = 0; i < THREADS; i++) ! { threads[i].join(); } ! for (int i = 0; i < THREADS; i++) ! { ! assertTrue("Test integrity check failed in thread " + i, ! threads[i].correct); } } + /** * Assures, that cm uses "==" to test * for equality */ ! public void testCacheIdentityBehaviour () ! { String key1 = new String("foo"); String key2 = new String("foo"); assertTrue("test preconditions not met: keys should be different", ! key1 != key2 && key1.equals(key2)); Object cached1 = new Object(); Object cached2 = new Object(); ! cm.put(key1, cached1); ! cm.put(key2, cached2); assertTrue("cm returned wrong object", ! cm.get(key1) == cached1); assertTrue("cm returned wrong object", ! cm.get(key2) == cached2); } ! ! static class TestThread extends Thread ! { private CacheManager cm; private int id; *************** *** 77,84 **** private Object[] sources = new Object[10]; private Object[] cached = new Object[10]; ! boolean correct = true; // until proved otherwise ! ! public TestThread(CacheManager cm,int id) { super(); this.cm = cm; --- 92,101 ---- private Object[] sources = new Object[10]; private Object[] cached = new Object[10]; ! boolean correct = true; // until proved otherwise ! ! ! public TestThread (CacheManager cm, int id) ! { super(); this.cm = cm; *************** *** 86,104 **** } ! public void run() { int count = 0; int loops = 0; ! for (int i=0; i < LOOPS; i++) { ! if (count++ == 0) fillCache(); ! if (count == 100) { count = 0; } int index = random.nextInt(sources.length); ! try { Object test = cm.get(sources[index]); if (test != cached[index]) correct = false; ! } catch (Exception e) { correct = false; } --- 103,128 ---- } ! ! public void run () ! { int count = 0; int loops = 0; ! for (int i = 0; i < LOOPS; i++) ! { ! if (count++ == 0) fillCache(); ! if (count == 100) ! { count = 0; } int index = random.nextInt(sources.length); ! try ! { Object test = cm.get(sources[index]); if (test != cached[index]) correct = false; ! } ! catch (Exception e) ! { correct = false; } *************** *** 106,114 **** } ! private void fillCache() { ! for (int i=0; i < sources.length; i++) { sources[i] = new byte[1000]; // dummy cache key cached[i] = new Object(); // dummy cache load ! cm.put(sources[i],cached[i]); } } --- 130,141 ---- } ! ! private void fillCache () ! { ! for (int i = 0; i < sources.length; i++) ! { sources[i] = new byte[1000]; // dummy cache key cached[i] = new Object(); // dummy cache load ! cm.put(sources[i], cached[i]); } } Index: TestVersion.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/test/unit/org/webmacro/TestVersion.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** TestVersion.java 23 Mar 2003 02:00:36 -0000 1.4 --- TestVersion.java 12 Jun 2003 00:47:49 -0000 1.5 *************** *** 1,33 **** package org.webmacro; ! import java.io.*; ! import org.webmacro.*; ! import org.webmacro.util.*; ! import junit.framework.*; ! /* Make sure our ANT filter to set the Version of WebMacro actually worked. */ ! public class TestVersion extends TestCase { - public TestVersion(String name) { - super(name); - } ! protected void setUp() { ! // no need to do any setup work ! } - - /** - * ensure the build-time version has been inserted into WebMacro.java - * by making sure the version does NOT equal the tag @VERSION@ - */ - public void testVersion () throws Exception { - assertTrue (!WebMacro.VERSION.equals("@VERSION@")); - } ! public void testBuildDate() throws Exception { ! assertTrue (!WebMacro.BUILD_DATE.equals("@BUILD_DATE@")); ! } } --- 1,36 ---- package org.webmacro; ! import junit.framework.TestCase; ! /* Make sure our ANT filter to set the Version of WebMacro actually worked. */ ! public class TestVersion extends TestCase ! { ! public TestVersion (String name) ! { ! super(name); ! } ! protected void setUp () ! { ! // no need to do any setup work ! } ! /** ! * ensure the build-time version has been inserted into WebMacro.java ! * by making sure the version does NOT equal the tag @VERSION@ ! */ ! public void testVersion () throws Exception ! { ! assertTrue(!WebMacro.VERSION.equals("@VERSION@")); ! } ! ! ! public void testBuildDate () throws Exception ! { ! assertTrue(!WebMacro.BUILD_DATE.equals("@BUILD_DATE@")); ! } } |
From: <dr...@us...> - 2003-06-12 00:17:52
|
Update of /cvsroot/webmacro/webmacro In directory sc8-pr-cvs1:/tmp/cvs-serv29146 Modified Files: build.xml Log Message: - change "...Expecting #end" error message to (per Keats): Unclosed block beginning at line XX. Check for invalid directive options or missing a #end - add a <javacc> target to ant, so you can re-gen the parser with this: ant javacc You could previously have done it with "ant precompile", but I could never remember that. :) Index: build.xml =================================================================== RCS file: /cvsroot/webmacro/webmacro/build.xml,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** build.xml 27 Mar 2003 00:35:30 -0000 1.33 --- build.xml 12 Jun 2003 00:17:48 -0000 1.34 *************** *** 103,110 **** </target> ! <target name="precompile" depends="prepare" if="javacc.present"> ! <javacc target="src/org/webmacro/parser/WMParser_impl.jj" ! javacchome="${javacc.home}" /> </target> --- 103,111 ---- </target> + <target name='javacc' depends='prepare' if='javacc.present'> + <javacc target="src/org/webmacro/parser/WMParser_impl.jj" javacchome="${javacc.home}" /> + </target> ! <target name="precompile" depends="javacc" if="javacc.present"> </target> |
From: <dr...@us...> - 2003-06-12 00:17:52
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/parser In directory sc8-pr-cvs1:/tmp/cvs-serv29146/src/org/webmacro/parser Modified Files: WMParser_impl.java WMParser_impl.jj Log Message: - change "...Expecting #end" error message to (per Keats): Unclosed block beginning at line XX. Check for invalid directive options or missing a #end - add a <javacc> target to ant, so you can re-gen the parser with this: ant javacc You could previously have done it with "ant precompile", but I could never remember that. :) Index: WMParser_impl.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/parser/WMParser_impl.java,v retrieving revision 1.49 retrieving revision 1.50 diff -C2 -d -r1.49 -r1.50 *** WMParser_impl.java 21 May 2003 23:04:55 -0000 1.49 --- WMParser_impl.java 12 Jun 2003 00:17:49 -0000 1.50 *************** *** 2199,2203 **** case 0: jj_consume_token(0); ! {if (true) throw new ParseException("Encountered EOF, expecting #end at " + token.beginLine + "." + token.beginColumn);} break; case RBRACE: --- 2199,2203 ---- case 0: jj_consume_token(0); ! {if (true) throw new ParseException("Unclosed block beginning at line " + token.beginLine + ". Check for invalid directive options or missing a #end");} break; case RBRACE: Index: WMParser_impl.jj =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/parser/WMParser_impl.jj,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** WMParser_impl.jj 21 May 2003 23:04:55 -0000 1.47 --- WMParser_impl.jj 12 Jun 2003 00:17:49 -0000 1.48 *************** *** 1175,1179 **** | ( [ <BEGIN> EatWsNlOrSpace(block) ] ( WMContentNoDirective(block) ! | (<EOF>) { throw new ParseException("Encountered EOF, expecting #end at " + token.beginLine + "." + token.beginColumn); } | (t=<LBRACE> | t=<RBRACE>) { block.addElement(t.image); } | LOOKAHEAD(<POUND>, { lookahead_not_breaking_subd() }) --- 1175,1179 ---- | ( [ <BEGIN> EatWsNlOrSpace(block) ] ( WMContentNoDirective(block) ! | (<EOF>) { throw new ParseException("Unclosed block beginning at line " + token.beginLine + ". Check for invalid directive options or missing a #end"); } | (t=<LBRACE> | t=<RBRACE>) { block.addElement(t.image); } | LOOKAHEAD(<POUND>, { lookahead_not_breaking_subd() }) |
From: <wan...@us...> - 2003-06-04 12:25:24
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/servlet In directory sc8-pr-cvs1:/tmp/cvs-serv8771 Modified Files: ServletBroker.java Log Message: Fixed linebreaks Index: ServletBroker.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/servlet/ServletBroker.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** ServletBroker.java 4 Jun 2003 12:14:54 -0000 1.7 --- ServletBroker.java 4 Jun 2003 12:25:20 -0000 1.8 *************** *** 1,138 **** ! /* ! * Copyright (C) 1998-2000 Semiotek Inc. All Rights Reserved. ! * ! * Redistribution and use in source and binary forms, with or without ! * modification, are permitted under the terms of either of the following ! * Open Source licenses: ! * ! * The GNU General Public License, version 2, or any later version, as ! * published by the Free Software Foundation ! * (http://www.fsf.org/copyleft/gpl.html); ! * ! * or ! * ! * The Semiotek Public License (http://webmacro.org/LICENSE.) ! * ! * This software is provided "as is", with NO WARRANTY, not even the ! * implied warranties of fitness to purpose, or merchantability. You ! * assume all risks and liabilities associated with its use. ! * ! * See www.webmacro.org for more information on the WebMacro project. ! */ ! ! ! /** ! * Base class for servlet brokers. ! * @see Servlet20Broker ! * @see Servlet22Broker ! * @see Broker ! * @author Brian Goetz ! * @since 0.96 ! */ ! package org.webmacro.servlet; ! ! import java.util.*; ! import javax.servlet.*; ! ! import org.webmacro.Broker; ! import org.webmacro.InitException; ! import org.webmacro.util.Settings; ! ! abstract public class ServletBroker extends Broker { ! ! protected ServletContext _servletContext; ! ! /** ! * Tracks ServletContexts we have been instantiated for, to prevent ! * duplicate log targets where multiple ServletBroker instances are ! * created. We use WeakHashMap instead of Set because it does the ! * key polled removal for us. ! */ ! private static Map servletContextsWithLogTargets = new WeakHashMap(); ! ! protected ServletBroker(ServletContext sc) throws InitException { ! super((Broker) null, sc.toString()); ! _servletContext = sc; ! } ! ! public void initLog(Settings config) { ! String logFile = config.getSetting("LogFile"); ! if ((logFile == null || logFile.equals("")) ! && _config.getBooleanSetting("LogUsingServletLog")) ! addLogTarget(); ! else ! initLog(); ! } ! ! private void addLogTarget() ! { ! synchronized (servletContextsWithLogTargets) ! { ! if (!servletContextsWithLogTargets.containsKey(_servletContext)) ! { ! _ls.addTarget( new ServletLog( _servletContext, _config )); ! servletContextsWithLogTargets.put( _servletContext, Boolean.TRUE); ! } ! } ! } ! ! public static Broker getBroker(Servlet s, Properties additionalProperties) throws InitException { ! int minorVersion, majorVersion; ! ! ServletContext sc = s.getServletConfig().getServletContext(); ! try { ! majorVersion = sc.getMajorVersion(); ! minorVersion = sc.getMinorVersion(); ! } ! catch (NoSuchMethodError e) { ! majorVersion = 2; ! minorVersion = 0; ! } ! ! Broker b; ! if (majorVersion > 2 ! || (majorVersion == 2 && minorVersion >= 2)) ! b = Servlet22Broker.getBroker(s, additionalProperties); ! else ! b = Servlet20Broker.getBroker(s, additionalProperties); ! b.startClient(); ! return b; ! } ! ! public static Broker getBroker(Servlet s) throws InitException { ! return getBroker(s, null); ! } ! ! public ServletContext getServletContext() { ! return _servletContext; ! } ! ! protected static final class PropertiesPair { ! private final Object obj; ! private final Properties p; ! ! public PropertiesPair(Object s, Properties p) { ! this.obj = s; ! this.p = p; ! } ! ! public boolean equals(Object o) { ! if (this == o) return true; ! if (!(o instanceof PropertiesPair)) return false; ! ! final PropertiesPair servletPropertiesPair = (PropertiesPair) o; ! ! if (!p.equals(servletPropertiesPair.p)) return false; ! if (!obj.equals(servletPropertiesPair.obj)) return false; ! ! return true; ! } ! ! public int hashCode() { ! int result; ! result = obj.hashCode(); ! result = 29 * result + p.hashCode(); ! return result; ! } ! } ! } --- 1,138 ---- ! /* ! * Copyright (C) 1998-2000 Semiotek Inc. All Rights Reserved. ! * ! * Redistribution and use in source and binary forms, with or without ! * modification, are permitted under the terms of either of the following ! * Open Source licenses: ! * ! * The GNU General Public License, version 2, or any later version, as ! * published by the Free Software Foundation ! * (http://www.fsf.org/copyleft/gpl.html); ! * ! * or ! * ! * The Semiotek Public License (http://webmacro.org/LICENSE.) ! * ! * This software is provided "as is", with NO WARRANTY, not even the ! * implied warranties of fitness to purpose, or merchantability. You ! * assume all risks and liabilities associated with its use. ! * ! * See www.webmacro.org for more information on the WebMacro project. ! */ ! ! ! /** ! * Base class for servlet brokers. ! * @see Servlet20Broker ! * @see Servlet22Broker ! * @see Broker ! * @author Brian Goetz ! * @since 0.96 ! */ ! package org.webmacro.servlet; ! ! import java.util.*; ! import javax.servlet.*; ! ! import org.webmacro.Broker; ! import org.webmacro.InitException; ! import org.webmacro.util.Settings; ! ! abstract public class ServletBroker extends Broker { ! ! protected ServletContext _servletContext; ! ! /** ! * Tracks ServletContexts we have been instantiated for, to prevent ! * duplicate log targets where multiple ServletBroker instances are ! * created. We use WeakHashMap instead of Set because it does the ! * key polled removal for us. ! */ ! private static Map servletContextsWithLogTargets = new WeakHashMap(); ! ! protected ServletBroker(ServletContext sc) throws InitException { ! super((Broker) null, sc.toString()); ! _servletContext = sc; ! } ! ! public void initLog(Settings config) { ! String logFile = config.getSetting("LogFile"); ! if ((logFile == null || logFile.equals("")) ! && _config.getBooleanSetting("LogUsingServletLog")) ! addLogTarget(); ! else ! initLog(); ! } ! ! private void addLogTarget() ! { ! synchronized (servletContextsWithLogTargets) ! { ! if (!servletContextsWithLogTargets.containsKey(_servletContext)) ! { ! _ls.addTarget( new ServletLog( _servletContext, _config )); ! servletContextsWithLogTargets.put( _servletContext, Boolean.TRUE); ! } ! } ! } ! ! public static Broker getBroker(Servlet s, Properties additionalProperties) throws InitException { ! int minorVersion, majorVersion; ! ! ServletContext sc = s.getServletConfig().getServletContext(); ! try { ! majorVersion = sc.getMajorVersion(); ! minorVersion = sc.getMinorVersion(); ! } ! catch (NoSuchMethodError e) { ! majorVersion = 2; ! minorVersion = 0; ! } ! ! Broker b; ! if (majorVersion > 2 ! || (majorVersion == 2 && minorVersion >= 2)) ! b = Servlet22Broker.getBroker(s, additionalProperties); ! else ! b = Servlet20Broker.getBroker(s, additionalProperties); ! b.startClient(); ! return b; ! } ! ! public static Broker getBroker(Servlet s) throws InitException { ! return getBroker(s, null); ! } ! ! public ServletContext getServletContext() { ! return _servletContext; ! } ! ! protected static final class PropertiesPair { ! private final Object obj; ! private final Properties p; ! ! public PropertiesPair(Object s, Properties p) { ! this.obj = s; ! this.p = p; ! } ! ! public boolean equals(Object o) { ! if (this == o) return true; ! if (!(o instanceof PropertiesPair)) return false; ! ! final PropertiesPair servletPropertiesPair = (PropertiesPair) o; ! ! if (!p.equals(servletPropertiesPair.p)) return false; ! if (!obj.equals(servletPropertiesPair.obj)) return false; ! ! return true; ! } ! ! public int hashCode() { ! int result; ! result = obj.hashCode(); ! result = 29 * result + p.hashCode(); ! return result; ! } ! } ! } |
From: <wan...@us...> - 2003-06-04 12:14:58
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/servlet In directory sc8-pr-cvs1:/tmp/cvs-serv3501 Modified Files: ServletBroker.java Log Message: Fixed duplicate logging when more than one ServletBroker instance using the same ServletContext Index: ServletBroker.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/servlet/ServletBroker.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ServletBroker.java 27 Mar 2003 00:35:30 -0000 1.6 --- ServletBroker.java 4 Jun 2003 12:14:54 -0000 1.7 *************** *** 1,118 **** ! /* ! * Copyright (C) 1998-2000 Semiotek Inc. All Rights Reserved. ! * ! * Redistribution and use in source and binary forms, with or without ! * modification, are permitted under the terms of either of the following ! * Open Source licenses: ! * ! * The GNU General Public License, version 2, or any later version, as ! * published by the Free Software Foundation ! * (http://www.fsf.org/copyleft/gpl.html); ! * ! * or ! * ! * The Semiotek Public License (http://webmacro.org/LICENSE.) ! * ! * This software is provided "as is", with NO WARRANTY, not even the ! * implied warranties of fitness to purpose, or merchantability. You ! * assume all risks and liabilities associated with its use. ! * ! * See www.webmacro.org for more information on the WebMacro project. ! */ ! ! ! /** ! * Base class for servlet brokers. ! * @see Servlet20Broker ! * @see Servlet22Broker ! * @see Broker ! * @author Brian Goetz ! * @since 0.96 ! */ ! package org.webmacro.servlet; ! ! import java.util.*; ! import javax.servlet.*; ! ! import org.webmacro.Broker; ! import org.webmacro.InitException; ! import org.webmacro.util.Settings; ! ! abstract public class ServletBroker extends Broker { ! ! protected ServletContext _servletContext; ! ! protected ServletBroker(ServletContext sc) throws InitException { ! super((Broker) null, sc.toString()); ! _servletContext = sc; ! } ! ! public void initLog(Settings config) { ! String logFile = config.getSetting("LogFile"); ! if ((logFile == null || logFile.equals("")) ! && _config.getBooleanSetting("LogUsingServletLog")) ! _ls.addTarget(new ServletLog(_servletContext, _config)); ! else ! initLog(); ! } ! ! public static Broker getBroker(Servlet s, Properties additionalProperties) throws InitException { ! int minorVersion, majorVersion; ! ! ServletContext sc = s.getServletConfig().getServletContext(); ! try { ! majorVersion = sc.getMajorVersion(); ! minorVersion = sc.getMinorVersion(); ! } ! catch (NoSuchMethodError e) { ! majorVersion = 2; ! minorVersion = 0; ! } ! ! Broker b; ! if (majorVersion > 2 ! || (majorVersion == 2 && minorVersion >= 2)) ! b = Servlet22Broker.getBroker(s, additionalProperties); ! else ! b = Servlet20Broker.getBroker(s, additionalProperties); ! b.startClient(); ! return b; ! } ! ! public static Broker getBroker(Servlet s) throws InitException { ! return getBroker(s, null); ! } ! ! public ServletContext getServletContext() { ! return _servletContext; ! } ! ! protected static final class PropertiesPair { ! private final Object obj; ! private final Properties p; ! ! public PropertiesPair(Object s, Properties p) { ! this.obj = s; ! this.p = p; ! } ! ! public boolean equals(Object o) { ! if (this == o) return true; ! if (!(o instanceof PropertiesPair)) return false; ! ! final PropertiesPair servletPropertiesPair = (PropertiesPair) o; ! ! if (!p.equals(servletPropertiesPair.p)) return false; ! if (!obj.equals(servletPropertiesPair.obj)) return false; ! ! return true; ! } ! ! public int hashCode() { ! int result; ! result = obj.hashCode(); ! result = 29 * result + p.hashCode(); ! return result; ! } ! } ! } --- 1,138 ---- ! /* ! * Copyright (C) 1998-2000 Semiotek Inc. All Rights Reserved. ! * ! * Redistribution and use in source and binary forms, with or without ! * modification, are permitted under the terms of either of the following ! * Open Source licenses: ! * ! * The GNU General Public License, version 2, or any later version, as ! * published by the Free Software Foundation ! * (http://www.fsf.org/copyleft/gpl.html); ! * ! * or ! * ! * The Semiotek Public License (http://webmacro.org/LICENSE.) ! * ! * This software is provided "as is", with NO WARRANTY, not even the ! * implied warranties of fitness to purpose, or merchantability. You ! * assume all risks and liabilities associated with its use. ! * ! * See www.webmacro.org for more information on the WebMacro project. ! */ ! ! ! /** ! * Base class for servlet brokers. ! * @see Servlet20Broker ! * @see Servlet22Broker ! * @see Broker ! * @author Brian Goetz ! * @since 0.96 ! */ ! package org.webmacro.servlet; ! ! import java.util.*; ! import javax.servlet.*; ! ! import org.webmacro.Broker; ! import org.webmacro.InitException; ! import org.webmacro.util.Settings; ! ! abstract public class ServletBroker extends Broker { ! ! protected ServletContext _servletContext; ! ! /** ! * Tracks ServletContexts we have been instantiated for, to prevent ! * duplicate log targets where multiple ServletBroker instances are ! * created. We use WeakHashMap instead of Set because it does the ! * key polled removal for us. ! */ ! private static Map servletContextsWithLogTargets = new WeakHashMap(); ! ! protected ServletBroker(ServletContext sc) throws InitException { ! super((Broker) null, sc.toString()); ! _servletContext = sc; ! } ! ! public void initLog(Settings config) { ! String logFile = config.getSetting("LogFile"); ! if ((logFile == null || logFile.equals("")) ! && _config.getBooleanSetting("LogUsingServletLog")) ! addLogTarget(); ! else ! initLog(); ! } ! ! private void addLogTarget() ! { ! synchronized (servletContextsWithLogTargets) ! { ! if (!servletContextsWithLogTargets.containsKey(_servletContext)) ! { ! _ls.addTarget( new ServletLog( _servletContext, _config )); ! servletContextsWithLogTargets.put( _servletContext, Boolean.TRUE); ! } ! } ! } ! ! public static Broker getBroker(Servlet s, Properties additionalProperties) throws InitException { ! int minorVersion, majorVersion; ! ! ServletContext sc = s.getServletConfig().getServletContext(); ! try { ! majorVersion = sc.getMajorVersion(); ! minorVersion = sc.getMinorVersion(); ! } ! catch (NoSuchMethodError e) { ! majorVersion = 2; ! minorVersion = 0; ! } ! ! Broker b; ! if (majorVersion > 2 ! || (majorVersion == 2 && minorVersion >= 2)) ! b = Servlet22Broker.getBroker(s, additionalProperties); ! else ! b = Servlet20Broker.getBroker(s, additionalProperties); ! b.startClient(); ! return b; ! } ! ! public static Broker getBroker(Servlet s) throws InitException { ! return getBroker(s, null); ! } ! ! public ServletContext getServletContext() { ! return _servletContext; ! } ! ! protected static final class PropertiesPair { ! private final Object obj; ! private final Properties p; ! ! public PropertiesPair(Object s, Properties p) { ! this.obj = s; ! this.p = p; ! } ! ! public boolean equals(Object o) { ! if (this == o) return true; ! if (!(o instanceof PropertiesPair)) return false; ! ! final PropertiesPair servletPropertiesPair = (PropertiesPair) o; ! ! if (!p.equals(servletPropertiesPair.p)) return false; ! if (!obj.equals(servletPropertiesPair.obj)) return false; ! ! return true; ! } ! ! public int hashCode() { ! int result; ! result = obj.hashCode(); ! result = 29 * result + p.hashCode(); ! return result; ! } ! } ! } |
From: <ke...@us...> - 2003-06-03 05:22:40
|
Update of /cvsroot/webmacro/webmacro In directory sc8-pr-cvs1:/tmp/cvs-serv16856 Modified Files: WebMacro.defaults Log Message: added $eval() function declaration Index: WebMacro.defaults =================================================================== RCS file: /cvsroot/webmacro/webmacro/WebMacro.defaults,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** WebMacro.defaults 23 Mar 2003 02:00:31 -0000 1.37 --- WebMacro.defaults 3 Jun 2003 05:22:37 -0000 1.38 *************** *** 442,443 **** --- 442,444 ---- Functions.split=org.webmacro.servlet.TextTool.split Functions.join=org.webmacro.servlet.TextTool.join + Functions.eval=org.webmacro.util.Eval.eval |
From: <ke...@us...> - 2003-06-03 05:21:54
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/util In directory sc8-pr-cvs1:/tmp/cvs-serv16403/org/webmacro/util Added Files: Eval.java Log Message: Provides a WMScript function, $eval(), that does nothing but provide a holder that allows an expression to be evaluated and expanded into the template. --- NEW FILE: Eval.java --- package org.webmacro.util; /* * Eval.java - static class with one method eval which just returns its * argument. This is a workaround for a WebMacro syntax issue, where an * expression isn't recognized properly outside of a directive or method call. * The eval() function can be configured in the WebMacro.properties file, e.g.: * functions.eval=org.webmacro.util.Eval.eval * * Created on May 6, 2003, 12:51 AM */ /** * * @author Keats */ public class Eval { /** Private constructor for a static class */ private Eval() { } static public Object eval(Object o){ return o; } } |
From: <dr...@us...> - 2003-05-21 23:04:58
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/parser In directory sc8-pr-cvs1:/tmp/cvs-serv22015/src/org/webmacro/parser Modified Files: WMParser_impl.java WMParser_impl.jj Log Message: rollback "multi-line arguments" changes to the parser, except for maps. I plan on making this work, but I also want to keep something useable in CVS Index: WMParser_impl.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/parser/WMParser_impl.java,v retrieving revision 1.48 retrieving revision 1.49 diff -C2 -d -r1.48 -r1.49 *** WMParser_impl.java 14 May 2003 05:01:19 -0000 1.48 --- WMParser_impl.java 21 May 2003 23:04:55 -0000 1.49 *************** *** 712,743 **** switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case WS: ! case NEWLINE: ! label_2: ! while (true) { ! switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { ! case WS: ! jj_consume_token(WS); ! break; ! case NEWLINE: [...4267 lines suppressed...] } --- 3233,3237 ---- jj_ntk = -1; jj_gen = 0; ! for (int i = 0; i < 120; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } *************** *** 4468,4472 **** jj_kind = -1; } ! for (int i = 0; i < 156; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { --- 3348,3352 ---- jj_kind = -1; } ! for (int i = 0; i < 120; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { Index: WMParser_impl.jj =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/parser/WMParser_impl.jj,v retrieving revision 1.46 retrieving revision 1.47 diff -C2 -d -r1.46 -r1.47 *** WMParser_impl.jj 14 May 2003 05:01:20 -0000 1.46 --- WMParser_impl.jj 21 May 2003 23:04:55 -0000 1.47 *************** *** 716,720 **** } { ! <LPAREN> [(<WS>|<NEWLINE>)+] e=Expression() [(<WS>|<NEWLINE>)+] <RPAREN> { return e; } } --- 716,720 ---- } { ! <LPAREN> [<WS>] e=Expression() [<WS>] <RPAREN> { return e; } } *************** *** 854,860 **** } { ! [ [(<WS>|<NEWLINE>)+] e=Expression() [(<WS>|<NEWLINE>)+] { list.addElement(e); } ( ! <COMMA> [(<WS>|<NEWLINE>)+] e=Expression() [(<WS>|<NEWLINE>)+] { list.addElement(e); } ) * ] --- 854,860 ---- } { ! [ [<WS>] e=Expression() [<WS>] { list.addElement(e); } ( ! <COMMA> [<WS>] e=Expression() [<WS>] { list.addElement(e); } ) * ] *************** *** 876,882 **** { [ <LPAREN> ! [ [(<WS>|<NEWLINE>)+] <DOLLAR> name=<WORD> [(<WS>|<NEWLINE>)+] { list.add(name.image); } ( ! <COMMA> [(<WS>|<NEWLINE>)+] <DOLLAR> name=<WORD> [(<WS>|<NEWLINE>)+] { list.add(name.image); } ) * ] --- 876,882 ---- { [ <LPAREN> ! [ [<WS>] <DOLLAR> name=<WORD> [<WS>] { list.add(name.image); } ( ! <COMMA> [<WS>] <DOLLAR> name=<WORD> [<WS>] { list.add(name.image); } ) * ] *************** *** 902,906 **** ( e=VariableReference() ! | <LPAREN> [(<WS>|<NEWLINE>)+] e=Expression() [(<WS>|<NEWLINE>)+] <RPAREN> | e=QuotedString() | e=BracketList() --- 902,906 ---- ( e=VariableReference() ! | <LPAREN> [<WS>] e=Expression() [<WS>] <RPAREN> | e=QuotedString() | e=BracketList() *************** *** 982,986 **** { e1=AExpression() ! [ LOOKAHEAD(4) [(<WS>|<NEWLINE>)+] op=RelOp() [(<WS>|<NEWLINE>)+] e2=AExpression() ] { if (op == null) --- 982,986 ---- { e1=AExpression() ! [ LOOKAHEAD(2) [<WS>] op=RelOp() [<WS>] e2=AExpression() ] { if (op == null) *************** *** 1006,1010 **** e=CExpression() ( ! LOOKAHEAD(4) [(<WS>|<NEWLINE>)+] <OP_AND> [(<WS>|<NEWLINE>)+] e2=CExpression() { e = new Expression.AndBuilder(e, e2); --- 1006,1010 ---- e=CExpression() ( ! LOOKAHEAD(2) [<WS>] <OP_AND> [<WS>] e2=CExpression() { e = new Expression.AndBuilder(e, e2); *************** *** 1020,1024 **** e=AndExpression() ( ! LOOKAHEAD(4) [(<WS>|<NEWLINE>)+] <OP_OR> [(<WS>|<NEWLINE>)+] e2=AndExpression() { e = new Expression.OrBuilder(e, e2); --- 1020,1024 ---- e=AndExpression() ( ! LOOKAHEAD(2) [<WS>] <OP_OR> [<WS>] e2=AndExpression() { e = new Expression.OrBuilder(e, e2); |
From: <dr...@us...> - 2003-05-21 23:01:49
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/engine In directory sc8-pr-cvs1:/tmp/cvs-serv19720/src/org/webmacro/engine Modified Files: BuildContext.java Log Message: BuildContext.java was loading ContextTools that it just doesn't need. Overloaded Context's constructor to provide an argument for "should load tools", default is "true", but BuildContext specifies "false". Maybe should do this via a method?: protected boolean shouldLoadTools(); Index: BuildContext.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/engine/BuildContext.java,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** BuildContext.java 27 Mar 2003 05:16:32 -0000 1.24 --- BuildContext.java 21 May 2003 23:01:46 -0000 1.25 *************** *** 46,50 **** public BuildContext(Broker b) { ! super(b); } --- 46,50 ---- public BuildContext(Broker b) { ! super(b, false); } |
From: <dr...@us...> - 2003-05-21 23:01:49
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro In directory sc8-pr-cvs1:/tmp/cvs-serv19720/src/org/webmacro Modified Files: Context.java Log Message: BuildContext.java was loading ContextTools that it just doesn't need. Overloaded Context's constructor to provide an argument for "should load tools", default is "true", but BuildContext specifies "false". Maybe should do this via a method?: protected boolean shouldLoadTools(); Index: Context.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/Context.java,v retrieving revision 1.59 retrieving revision 1.60 diff -C2 -d -r1.59 -r1.60 *** Context.java 20 Dec 2002 02:25:23 -0000 1.59 --- Context.java 21 May 2003 23:01:46 -0000 1.60 *************** *** 84,87 **** --- 84,91 ---- */ public Context(Broker broker) { + this (broker, true); + } + + protected Context(Broker broker, boolean loadTools) { _prof = broker.newProfile(); if (_prof != null) { startTiming("Context life"); } *************** *** 89,93 **** _broker = broker; _log = broker.getLog("context", "property and evaluation errors"); ! loadTools("ContextTools"); if (_prof != null) { stopTiming(); } } --- 93,98 ---- _broker = broker; _log = broker.getLog("context", "property and evaluation errors"); ! if (loadTools) ! loadTools("ContextTools"); if (_prof != null) { stopTiming(); } } |
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/parser In directory sc8-pr-cvs1:/tmp/cvs-serv27032/src/org/webmacro/parser Modified Files: WMParser_impl.java WMParser_impl.jj WMParser_implConstants.java WMParser_implTokenManager.java Log Message: - multi-line value support for maps and lists - multi-line support for anything that takes an argument list: $functions(), #macros(), and $Variable.methodCall() - multi-line support for #if statements Index: WMParser_impl.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/parser/WMParser_impl.java,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** WMParser_impl.java 13 May 2003 05:29:17 -0000 1.47 --- WMParser_impl.java 14 May 2003 05:01:19 -0000 1.48 *************** *** 712,719 **** switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case WS: ! jj_consume_token(WS); break; default: ! jj_la1[26] = jj_gen; ; } --- 712,743 ---- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { [...4192 lines suppressed...] } --- 4353,4357 ---- jj_ntk = -1; jj_gen = 0; ! for (int i = 0; i < 156; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } *************** *** 3155,3159 **** jj_kind = -1; } ! for (int i = 0; i < 104; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { --- 4468,4472 ---- jj_kind = -1; } ! for (int i = 0; i < 156; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { Index: WMParser_impl.jj =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/parser/WMParser_impl.jj,v retrieving revision 1.45 retrieving revision 1.46 diff -C2 -d -r1.45 -r1.46 *** WMParser_impl.jj 13 May 2003 05:29:18 -0000 1.45 --- WMParser_impl.jj 14 May 2003 05:01:20 -0000 1.46 *************** *** 284,288 **** | <LBRACKET: "["> | <RBRACKET: "]"> ! | <ASSOC: "=>"> | <DOT: "."> | <OP_LT: "<"> --- 284,288 ---- | <LBRACKET: "["> | <RBRACKET: "]"> ! | <COLON: ":"> | <DOT: "."> | <OP_LT: "<"> *************** *** 716,720 **** } { ! <LPAREN> [ <WS> ] e=Expression() [ <WS> ] <RPAREN> { return e; } } --- 716,720 ---- } { ! <LPAREN> [(<WS>|<NEWLINE>)+] e=Expression() [(<WS>|<NEWLINE>)+] <RPAREN> { return e; } } *************** *** 826,829 **** --- 826,831 ---- } + + MapBuilder MapArgList() : { MapBuilder map = new MapBuilder(); *************** *** 831,837 **** } { ! [ [<WS>] key=Expression() [<WS>] <ASSOC> [<WS>] value=Expression() [<WS>] { map.put(key, value); } ( ! <COMMA> [<WS>] key=Expression() [<WS>] <ASSOC> [<WS>] value=Expression() [<WS>] { map.put(key, value); } ) * ] --- 833,839 ---- } { ! [ [(<WS>|<NEWLINE>)+] key=Expression() [(<WS>|<NEWLINE>)+] <COLON> [(<WS>|<NEWLINE>)+] value=Expression() [(<WS>|<NEWLINE>)+] { map.put(key, value); } ( ! <COMMA> [(<WS>|<NEWLINE>)+] key=Expression() [(<WS>|<NEWLINE>)+] <COLON> [(<WS>|<NEWLINE>)+] value=Expression() [(<WS>|<NEWLINE>)+] { map.put(key, value); } ) * ] *************** *** 852,858 **** } { ! [ [<WS>] e=Expression() [<WS>] { list.addElement(e); } ( ! <COMMA> [ <WS> ] e=Expression() [<WS>] { list.addElement(e); } ) * ] --- 854,860 ---- } { ! [ [(<WS>|<NEWLINE>)+] e=Expression() [(<WS>|<NEWLINE>)+] { list.addElement(e); } ( ! <COMMA> [(<WS>|<NEWLINE>)+] e=Expression() [(<WS>|<NEWLINE>)+] { list.addElement(e); } ) * ] *************** *** 874,880 **** { [ <LPAREN> ! [ [<WS>] <DOLLAR> name=<WORD> [<WS>] { list.add(name.image); } ( ! <COMMA> [ <WS> ] <DOLLAR> name=<WORD> [<WS>] { list.add(name.image); } ) * ] --- 876,882 ---- { [ <LPAREN> ! [ [(<WS>|<NEWLINE>)+] <DOLLAR> name=<WORD> [(<WS>|<NEWLINE>)+] { list.add(name.image); } ( ! <COMMA> [(<WS>|<NEWLINE>)+] <DOLLAR> name=<WORD> [(<WS>|<NEWLINE>)+] { list.add(name.image); } ) * ] *************** *** 900,904 **** ( e=VariableReference() ! | <LPAREN> [<WS>] e=Expression() [<WS>] <RPAREN> | e=QuotedString() | e=BracketList() --- 902,906 ---- ( e=VariableReference() ! | <LPAREN> [(<WS>|<NEWLINE>)+] e=Expression() [(<WS>|<NEWLINE>)+] <RPAREN> | e=QuotedString() | e=BracketList() *************** *** 980,984 **** { e1=AExpression() ! [ LOOKAHEAD(2) [<WS>] op=RelOp() [<WS>] e2=AExpression() ] { if (op == null) --- 982,986 ---- { e1=AExpression() ! [ LOOKAHEAD(4) [(<WS>|<NEWLINE>)+] op=RelOp() [(<WS>|<NEWLINE>)+] e2=AExpression() ] { if (op == null) *************** *** 1004,1008 **** e=CExpression() ( ! LOOKAHEAD(2) [<WS>] <OP_AND> [<WS>] e2=CExpression() { e = new Expression.AndBuilder(e, e2); --- 1006,1010 ---- e=CExpression() ( ! LOOKAHEAD(4) [(<WS>|<NEWLINE>)+] <OP_AND> [(<WS>|<NEWLINE>)+] e2=CExpression() { e = new Expression.AndBuilder(e, e2); *************** *** 1018,1022 **** e=AndExpression() ( ! LOOKAHEAD(2) [<WS>] <OP_OR> [<WS>] e2=AndExpression() { e = new Expression.OrBuilder(e, e2); --- 1020,1024 ---- e=AndExpression() ( ! LOOKAHEAD(4) [(<WS>|<NEWLINE>)+] <OP_OR> [(<WS>|<NEWLINE>)+] e2=AndExpression() { e = new Expression.OrBuilder(e, e2); Index: WMParser_implConstants.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/parser/WMParser_implConstants.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** WMParser_implConstants.java 13 May 2003 05:29:18 -0000 1.11 --- WMParser_implConstants.java 14 May 2003 05:01:20 -0000 1.12 *************** *** 39,43 **** int LBRACKET = 34; int RBRACKET = 35; ! int ASSOC = 36; int DOT = 37; int OP_LT = 38; --- 39,43 ---- int LBRACKET = 34; int RBRACKET = 35; ! int COLON = 36; int DOT = 37; int OP_LT = 38; *************** *** 106,110 **** "\"[\"", "\"]\"", ! "\"=>\"", "\".\"", "\"<\"", --- 106,110 ---- "\"[\"", "\"]\"", ! "\":\"", "\".\"", "\"<\"", Index: WMParser_implTokenManager.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/parser/WMParser_implTokenManager.java,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** WMParser_implTokenManager.java 13 May 2003 05:29:18 -0000 1.25 --- WMParser_implTokenManager.java 14 May 2003 05:01:20 -0000 1.26 *************** *** 685,688 **** --- 685,690 ---- case 47: return jjStopAtPos(0, 48); + case 58: + return jjStopAtPos(0, 36); case 59: return jjStopAtPos(0, 53); *************** *** 692,696 **** case 61: jjmatchedKind = 43; ! return jjMoveStringLiteralDfa1_3(0x41000000000L); case 62: jjmatchedKind = 40; --- 694,698 ---- case 61: jjmatchedKind = 43; ! return jjMoveStringLiteralDfa1_3(0x40000000000L); case 62: jjmatchedKind = 40; *************** *** 733,740 **** return jjStopAtPos(1, 42); break; - case 62: - if ((active0 & 0x1000000000L) != 0L) - return jjStopAtPos(1, 36); - break; case 97: return jjMoveStringLiteralDfa2_3(active0, 0x10000000L); --- 735,738 ---- *************** *** 1364,1370 **** "\134", "\43", "\42", "\47", "\156\165\154\154", "\164\162\165\145", "\146\141\154\163\145", "\165\156\144\145\146\151\156\145\144", null, null, "\50", "\51", "\133", ! "\135", "\75\76", "\56", "\74", "\74\75", "\76", "\76\75", "\75\75", "\75", null, ! "\53", "\55", "\52", "\57", null, null, null, "\54", "\73", null, null, null, null, ! null, }; public static final String[] lexStateNames = { "SQS", --- 1362,1367 ---- "\134", "\43", "\42", "\47", "\156\165\154\154", "\164\162\165\145", "\146\141\154\163\145", "\165\156\144\145\146\151\156\145\144", null, null, "\50", "\51", "\133", ! "\135", "\72", "\56", "\74", "\74\75", "\76", "\76\75", "\75\75", "\75", null, "\53", ! "\55", "\52", "\57", null, null, null, "\54", "\73", null, null, null, null, null, }; public static final String[] lexStateNames = { "SQS", |
From: <dr...@us...> - 2003-05-13 05:33:32
|
Update of /cvsroot/webmacro/webmacro/src/org/webmacro/util In directory sc8-pr-cvs1:/tmp/cvs-serv9122/src/org/webmacro/util Modified Files: CastUtil.java Log Message: cleanup some error messages that have always confused me Index: CastUtil.java =================================================================== RCS file: /cvsroot/webmacro/webmacro/src/org/webmacro/util/CastUtil.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** CastUtil.java 11 Nov 2002 19:22:38 -0000 1.7 --- CastUtil.java 13 May 2003 05:33:29 -0000 1.8 *************** *** 53,57 **** } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid char: " + o); } } --- 53,57 ---- } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid char: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); } } *************** *** 85,89 **** } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid byte: " + o); } return v; --- 85,89 ---- } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid byte: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); } return v; *************** *** 98,102 **** } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid short: " + o); } return v; --- 98,102 ---- } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid short: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); } return v; *************** *** 110,114 **** } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid int: " + o); } return i; --- 110,114 ---- } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid int: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); } return i; *************** *** 122,126 **** } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid long: " + o); } return l; --- 122,126 ---- } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid long: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); } return l; *************** *** 134,138 **** } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid float: " + o); } return f; --- 134,138 ---- } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid float: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); } return f; *************** *** 146,150 **** } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid double: " + o); } return d; --- 146,150 ---- } catch (Exception e) { ! throw new IllegalArgumentException("Not a valid double: " + ((o==null) ? "null" : (o.toString() + "; type=" + o.getClass().getName())) ); } return d; |