adapdev-commits Mailing List for Adapdev.NET (Page 15)
Status: Beta
Brought to you by:
intesar66
You can subscribe to this list here.
2005 |
Jan
|
Feb
|
Mar
(26) |
Apr
(59) |
May
(37) |
Jun
(53) |
Jul
(13) |
Aug
(7) |
Sep
(5) |
Oct
(74) |
Nov
(404) |
Dec
(14) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2006 |
Jan
(10) |
Feb
(26) |
Mar
(64) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: Sean M. <int...@us...> - 2005-11-16 06:08:13
|
Update of /cvsroot/adapdev/Adapdev/lib In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25410/lib Removed Files: Genghis.dll MagicLibrary.DLL MySql.Data.dll Nini.dll TestDriven.Framework.dll log4net.dll nunit.framework.dll Log Message: --- MySql.Data.dll DELETED --- --- Genghis.dll DELETED --- --- Nini.dll DELETED --- --- MagicLibrary.DLL DELETED --- --- TestDriven.Framework.dll DELETED --- --- nunit.framework.dll DELETED --- --- log4net.dll DELETED --- |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache/Scavengers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25410/src/Adapdev.Cache/Scavengers Removed Files: AbsoluteExpirationScavenger.cs GreaterThanOrdinalScavenger.cs IScavenger.cs LIFONumberScavenger.cs SlidingExpirationScavenger.cs Log Message: --- IScavenger.cs DELETED --- --- LIFONumberScavenger.cs DELETED --- --- SlidingExpirationScavenger.cs DELETED --- --- AbsoluteExpirationScavenger.cs DELETED --- --- GreaterThanOrdinalScavenger.cs DELETED --- |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Parser/Node In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime/Parser/Node Added Files: ASTAddNode.cs ASTAndNode.cs ASTAssignment.cs ASTBlock.cs ASTComment.cs ASTDirective.cs ASTDivNode.cs ASTEQNode.cs ASTElseIfStatement.cs ASTElseStatement.cs ASTEscape.cs ASTEscapedDirective.cs ASTExpression.cs ASTFalse.cs ASTGENode.cs ASTGTNode.cs ASTIdentifier.cs ASTIfStatement.cs ASTIncludeStatement.cs ASTIntegerRange.cs ASTLENode.cs ASTLTNode.cs ASTMethod.cs ASTModNode.cs ASTMulNode.cs ASTNENode.cs ASTNotNode.cs ASTNumberLiteral.cs ASTObjectArray.cs ASTOrNode.cs ASTParameters.cs ASTReference.cs ASTSetDirective.cs ASTStringLiteral.cs ASTSubtractNode.cs ASTText.cs ASTTrue.cs ASTVariable.cs ASTWord.cs ASTprocess.cs AbstractExecutor.cs BooleanPropertyExecutor.cs GetExecutor.cs INode.cs NodeUtils.cs ParserVisitor.cs PropertyExecutor.cs SimpleNode.cs Log Message: --- NEW FILE: ASTTrue.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; public class ASTTrue : SimpleNode { //UPGRADE_NOTE: Field value was renamed. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1029"' private static Boolean value_Renamed_Field = true; public ASTTrue(int id) : base(id) { } public ASTTrue(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool evaluate(InternalContextAdapter context) { return true; } public override Object value_Renamed(InternalContextAdapter context) { return value_Renamed_Field; } } } --- NEW FILE: ASTObjectArray.cs --- namespace NVelocity.Runtime.Parser.Node { /* Generated By:JJTree: Do not edit this line. ASTObjectArray.java */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.Collections; using NVelocity.Context; public class ASTObjectArray : SimpleNode { public ASTObjectArray(int id) : base(id) { } public ASTObjectArray(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override Object value_Renamed(InternalContextAdapter context) { int size = jjtGetNumChildren(); ArrayList objectArray = new ArrayList(); for (int i = 0; i < size; i++) { objectArray.Add(jjtGetChild(i).value_Renamed(context)); } return objectArray; } } } --- NEW FILE: ASTGENode.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; public class ASTGENode : SimpleNode { public ASTGENode(int id) : base(id) { } public ASTGENode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool evaluate(InternalContextAdapter context) { /* * get the two args */ Object left = jjtGetChild(0).value_Renamed(context); Object right = jjtGetChild(1).value_Renamed(context); /* * if either is null, lets log and bail */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal() + ") of '>=' operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } /* * if not an Integer, not much we can do either */ if (!(left is Int32) || !(right is Int32)) { rsvc.error((!(left is Int32) ? "Left" : "Right") + " side of '>=' operation is not a valid type. " + " It is a " + (!(left is Int32) ? left.GetType() : right.GetType()) + ". Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } return ((Int32) left) >= ((Int32) right); } } } --- NEW FILE: ASTGTNode.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; public class ASTGTNode : SimpleNode { public ASTGTNode(int id) : base(id) { } public ASTGTNode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool evaluate(InternalContextAdapter context) { /* * get the two args */ Object left = jjtGetChild(0).value_Renamed(context); Object right = jjtGetChild(1).value_Renamed(context); /* * if either is null, lets log and bail */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal() + ") of '>' operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } /* * if not an Integer, not much we can do either */ if (!(left is Int32) || !(right is Int32)) { rsvc.error((!(left is Int32) ? "Left" : "Right") + " side of '>' operation is not a valid type. " + " It is a " + (!(left is Int32) ? left.GetType() : right.GetType()) + ". Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } return ((Int32) left) > ((Int32) right); } } } --- NEW FILE: AbstractExecutor.cs --- namespace NVelocity.Runtime.Parser.Node { using System; using System.Reflection; using NVelocity.Context; /// <summary> Abstract class that is used to execute an arbitrary /// method that is in introspected. This is the superclass /// for the GetExecutor and PropertyExecutor. /// </summary> public abstract class AbstractExecutor { protected internal RuntimeServices rsvc = null; /// <summary> Method to be executed. /// </summary> protected internal MethodInfo method = null; protected internal PropertyInfo property = null; /// <summary> Execute method against context. /// </summary> public abstract Object execute(Object o, InternalContextAdapter context); /// <summary> Tell whether the executor is alive by looking /// at the value of the method. /// </summary> public virtual bool isAlive() { return (method != null || property != null); } } } --- NEW FILE: ASTAndNode.cs --- namespace NVelocity.Runtime.Parser.Node { /* Generated By:JJTree: Do not edit this line. ASTAndNode.java */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; /// <summary> Please look at the Parser.jjt file which is /// what controls the generation of this class. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ASTAndNode.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ASTAndNode : SimpleNode { public ASTAndNode(int id) : base(id) { } public ASTAndNode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } /// <summary> Returns the value of the expression. /// Since the value of the expression is simply the boolean /// result of evaluate(), lets return that. /// </summary> public override Object value_Renamed(InternalContextAdapter context) { return evaluate(context); } /// <summary> logical and : /// null && right = false /// left && null = false /// null && null = false /// </summary> public override bool evaluate(InternalContextAdapter context) { INode left = jjtGetChild(0); INode right = jjtGetChild(1); /* * if either is null, lets log and bail */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side of '&&' operation is null." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } /* * short circuit the test. Don't eval the RHS if the LHS is false */ if (left.evaluate(context)) { if (right.evaluate(context)) { return true; } } return false; } } } --- NEW FILE: ASTEscapedDirective.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; using NVelocity.Context; /// <summary> This class is responsible for handling EscapedDirectives /// in VTL. /// /// Please look at the Parser.jjt file which is /// what controls the generation of this class. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ASTEscapedDirective.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ASTEscapedDirective : SimpleNode { public ASTEscapedDirective(int id) : base(id) { } public ASTEscapedDirective(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool render(InternalContextAdapter context, TextWriter writer) { writer.Write(FirstToken.image); return true; } } } --- NEW FILE: ASTMulNode.cs --- namespace NVelocity.Runtime.Parser.Node { /* Generated By:JJTree: Do not edit this line. ASTMulNode.java */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; /// <summary> Handles integer multiplication /// * /// Please look at the Parser.jjt file which is /// what controls the generation of this class. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ASTMulNode.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// </version> public class ASTMulNode : SimpleNode { public ASTMulNode(int id) : base(id) { } public ASTMulNode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } /// <summary> computes the product of the two args. Returns null if either arg is null /// or if either arg is not an integer /// </summary> public override Object value_Renamed(InternalContextAdapter context) { /* * get the two args */ Object left = jjtGetChild(0).value_Renamed(context); Object right = jjtGetChild(1).value_Renamed(context); /* * if either is null, lets log and bail */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal() + ") of multiplication operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return null; } /* * if not an Integer, not much we can do either */ if (!(left is Int32) || !(right is Int32)) { rsvc.error((!(left is Int32) ? "Left" : "Right") + " side of multiplication operation is not a valid type. " + "Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return null; } return ((Int32) left)*((Int32) right); } } } --- NEW FILE: NodeUtils.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.Text; using Context = Context.IContext; /// <summary> Utilities for dealing with the AST node structure. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: NodeUtils.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class NodeUtils { /// <summary> Collect all the <SPECIAL_TOKEN>s that /// are carried along with a token. Special /// tokens do not participate in parsing but /// can still trigger certain lexical actions. /// In some cases you may want to retrieve these /// special tokens, this is simply a way to /// extract them. /// </summary> public static String specialText(Token t) { String specialText = ""; if (t.specialToken == null || t.specialToken.image.StartsWith("##")) return specialText; Token tmp_t = t.specialToken; while (tmp_t.specialToken != null) { tmp_t = tmp_t.specialToken; } while (tmp_t != null) { String st = tmp_t.image; StringBuilder sb = new StringBuilder(); for (int i = 0; i < st.Length; i++) { char c = st[i]; if (c == '#' || c == '$') { sb.Append(c); } /* * more dreaded MORE hack :) * * looking for ("\\")*"$" sequences */ if (c == '\\') { bool ok = true; bool term = false; int j = i; for (ok = true; ok && j < st.Length; j++) { char cc = st[j]; if (cc == '\\') { /* * if we see a \, keep going */ continue; } else if (cc == '$') { /* * a $ ends it correctly */ term = true; ok = false; } else { /* * nah... */ ok = false; } } if (term) { String foo = st.Substring(i, (j) - (i)); sb.Append(foo); i = j; } } } specialText += sb.ToString(); tmp_t = tmp_t.next; } return specialText; } /// <summary> complete node literal /// * /// </summary> public static String tokenLiteral(Token t) { return specialText(t) + t.image; } /// <summary> Utility method to interpolate context variables /// into string literals. So that the following will /// work: /// * /// #set $name = "candy" /// $image.getURI("${name}.jpg") /// * /// And the string literal argument will /// be transformed into "candy.jpg" before /// the method is executed. /// </summary> public static String interpolate(String argStr, Context vars) { StringBuilder argBuf = new StringBuilder(); for (int cIdx = 0; cIdx < argStr.Length; ) { char ch = argStr[cIdx]; switch (ch) { case '$': StringBuilder nameBuf = new StringBuilder(); for (++cIdx; cIdx < argStr.Length; ++cIdx) { ch = argStr[cIdx]; if (ch == '_' || ch == '-' || Char.IsLetterOrDigit(ch)) nameBuf.Append(ch); else if (ch == '{' || ch == '}') continue; else break; } if (nameBuf.Length > 0) { Object value_Renamed = vars.Get(nameBuf.ToString()); if (value_Renamed == null) argBuf.Append("$").Append(nameBuf.ToString()); else { //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' argBuf.Append(value_Renamed.ToString()); } } break; default: argBuf.Append(ch); ++cIdx; break; } } return argBuf.ToString(); } } } --- NEW FILE: ASTWord.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; public class ASTWord : SimpleNode { public ASTWord(int id) : base(id) { } public ASTWord(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } } } --- NEW FILE: ASTStringLiteral.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; using NVelocity.Context; /// <summary> ASTStringLiteral support. Will interpolate! /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: ASTStringLiteral.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ASTStringLiteral : SimpleNode { /* cache the value of the interpolation switch */ private bool interpolate = true; private SimpleNode nodeTree = null; private String image = ""; private String interpolateimage = ""; public ASTStringLiteral(int id) : base(id) { } public ASTStringLiteral(Parser p, int id) : base(p, id) { } /// <summary> init : we don't have to do much. Init the tree (there /// shouldn't be one) and then see if interpolation is turned on. /// </summary> public override Object init(InternalContextAdapter context, Object data) { /* * simple habit... we prollie don't have an AST beneath us */ base.init(context, data); /* * the stringlit is set at template parse time, so we can * do this here for now. if things change and we can somehow * create stringlits at runtime, this must * move to the runtime execution path * * so, only if interpolation is turned on AND it starts * with a " AND it has a directive or reference, then we * can interpolate. Otherwise, don't bother. */ interpolate = rsvc.getBoolean(RuntimeConstants_Fields.INTERPOLATE_STRINGLITERALS, true) && FirstToken.image.StartsWith("\"") && ((FirstToken.image.IndexOf((Char) '$') != - 1) || (FirstToken.image.IndexOf((Char) '#') != - 1)); /* * get the contents of the string, minus the '/" at each end */ image = FirstToken.image.Substring(1, (FirstToken.image.Length - 1) - (1)); /* * tack a space on the end (dreaded <MORE> kludge) */ interpolateimage = image + " "; if (interpolate) { /* * now parse and init the nodeTree */ //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' TextReader br = new StringReader(interpolateimage); /* * it's possible to not have an initialization context - or we don't * want to trust the caller - so have a fallback value if so * * Also, do *not* dump the VM namespace for this template */ nodeTree = rsvc.parse(br, (context != null) ? context.CurrentTemplateName : "StringLiteral", false); /* * init with context. It won't modify anything */ nodeTree.init(context, rsvc); } return data; } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } /// <summary> renders the value of the string literal /// If the properties allow, and the string literal contains a $ or a # /// the literal is rendered against the context /// Otherwise, the stringlit is returned. /// </summary> public override Object value_Renamed(InternalContextAdapter context) { if (interpolate) { try { /* * now render against the real context */ TextWriter writer = new StringWriter(); nodeTree.render(context, writer); /* * and return the result as a String */ String ret = writer.ToString(); /* * remove the space from the end (dreaded <MORE> kludge) */ return ret.Substring(0, (ret.Length - 1) - (0)); } catch (Exception e) { /* * eh. If anything wrong, just punt * and output the literal */ rsvc.error("Error in interpolating string literal : " + e); } } /* * ok, either not allowed to interpolate, there wasn't * a ref or directive, or we failed, so * just output the literal */ return image; } } } --- NEW FILE: ASTNENode.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; public class ASTNENode : SimpleNode { public ASTNENode(int id) : base(id) { } public ASTNENode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool evaluate(InternalContextAdapter context) { Object left = jjtGetChild(0).value_Renamed(context); Object right = jjtGetChild(1).value_Renamed(context); /* * null check */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal() + ") of '!=' operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } /* * check to see if they are the same class. I don't think this is slower * as I don't think that getClass() results in object creation, and we can * extend == to handle all classes */ if (left.GetType().Equals(right.GetType())) { return !(left.Equals(right)); } else { rsvc.error("Error in evaluation of != expression." + " Both arguments must be of the same Class." + " Currently left = " + left.GetType() + ", right = " + right.GetType() + ". " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "] (ASTEQNode)"); return false; } } } } --- NEW FILE: ASTReference.cs --- namespace NVelocity.Runtime.Parser.Node { using System; using System.Collections; using System.IO; using System.Reflection; using System.Text; using NVelocity.App.Events; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime.Exception; /// <summary> /// This class is responsible for handling the references in /// VTL ($foo). /// /// Please look at the Parser.jjt file which is /// what controls the generation of this class. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:Chr...@dl...">Christoph Reck</a></author> /// <author> <a href="mailto:kjo...@tr...>Kent Johnson</a></author> /// <version> $Id: ASTReference.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ </version> public class ASTReference : SimpleNode { public virtual String RootString { get { return rootString; } } private String Root { get { Token t = FirstToken; /* * we have a special case where something like * $(\\)*!, where the user want's to see something * like $!blargh in the output, but the ! prevents it from showing. * I think that at this point, this isn't a reference. */ /* so, see if we have "\\!" */ int slashbang = t.image.IndexOf("\\!"); if (slashbang != - 1) { /* * lets do all the work here. I would argue that if this occurrs, it's * not a reference at all, so preceeding \ characters in front of the $ * are just schmoo. So we just do the escape processing trick (even | odd) * and move on. This kind of breaks the rule pattern of $ and # but '!' really * tosses a wrench into things. */ /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.Length; i = t.image.IndexOf((Char) '$'); if (i == - 1) { /* yikes! */ rsvc.error("ASTReference.getRoot() : internal error : no $ found for slashbang."); computableReference = false; nullString = t.image; return nullString; } while (i < len && t.image[i] != '\\') { i++; } /* ok, i is the first \ char */ int start = i; int count = 0; while (i < len && t.image[i++] == '\\') { count++; } /* * now construct the output string. We really don't care about leading * slashes as this is not a reference. It's quasi-schmoo */ nullString = t.image.Substring(0, (start) - (0)); // prefix up to the first nullString += t.image.Substring(start, (start + count - 1) - (start)); // get the slashes nullString += t.image.Substring(start + count); // and the rest, including the /* * this isn't a valid reference, so lets short circuit the value and set calcs */ computableReference = false; return nullString; } /* * we need to see if this reference is escaped. if so * we will clean off the leading \'s and let the * regular behavior determine if we should output this * as \$foo or $foo later on in render(). Lazyness.. */ escaped = false; if (t.image.StartsWith("\\")) { /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.Length; while (i < len && t.image[i] == '\\') { i++; } if ((i%2) != 0) escaped = true; if (i > 0) escPrefix = t.image.Substring(0, (i/2) - (0)); t.image = t.image.Substring(i); } /* * Look for preceeding stuff like '#' and '$' * and snip it off, except for the * last $ */ int loc1 = t.image.LastIndexOf((Char) '$'); /* * if we have extra stuff, loc > 0 * ex. '#$foo' so attach that to * the prefix. */ if (loc1 > 0) { morePrefix = morePrefix + t.image.Substring(0, (loc1) - (0)); t.image = t.image.Substring(loc1); } /* * Now it should be clean. Get the literal in case this reference * isn't backed by the context at runtime, and then figure out what * we are working with. */ nullString = literal(); if (t.image.StartsWith("$!")) { referenceType = QUIET_REFERENCE; /* * only if we aren't escaped do we want to null the output */ if (!escaped) nullString = ""; if (t.image.StartsWith("$!{")) { /* * ex : $!{provider.Title} */ return t.next.image; } else { /* * ex : $!provider.Title */ return t.image.Substring(2); } } else if (t.image.Equals("${")) { /* * ex : ${provider.Title} */ referenceType = FORMAL_REFERENCE; return t.next.image; } else if (t.image.StartsWith("$")) { /* * just nip off the '$' so we have * the root */ referenceType = NORMAL_REFERENCE; return t.image.Substring(1); } else { /* * this is a 'RUNT', which can happen in certain circumstances where * the parser is fooled into believeing that an IDENTIFIER is a real * reference. Another 'dreaded' MORE hack :). */ referenceType = RUNT; return t.image; } } } public virtual String Literal { set { /* * do only once */ if (this.literal_Renamed_Field == null) this.literal_Renamed_Field = value; } } /* Reference types */ private const int NORMAL_REFERENCE = 1; private const int FORMAL_REFERENCE = 2; private const int QUIET_REFERENCE = 3; private const int RUNT = 4; private int referenceType; private String nullString; private String rootString; private bool escaped = false; private bool computableReference = true; private String escPrefix = ""; private String morePrefix = ""; private String identifier = ""; //UPGRADE_NOTE: Field literal was renamed. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1029"' private String literal_Renamed_Field = null; private int numChildren = 0; public ASTReference(int id) : base(id) { } public ASTReference(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override Object init(InternalContextAdapter context, Object data) { /* * init our children */ base.init(context, data); /* * the only thing we can do in init() is getRoot() * as that is template based, not context based, * so it's thread- and context-safe */ rootString = Root; numChildren = jjtGetNumChildren(); /* * and if appropriate... */ if (numChildren > 0) { identifier = jjtGetChild(numChildren - 1).FirstToken.image; } return data; } /// <summary> Returns the 'root string', the reference key /// </summary> /// <summary> gets an Object that 'is' the value of the reference /// * /// </summary> /// <param name="o"> unused Object parameter /// </param> /// <param name="context">context used to generate value /// /// </param> public override Object execute(Object o, InternalContextAdapter context) { if (referenceType == RUNT) return null; /* * get the root object from the context */ Object result = getVariableValue(context, rootString); if (result == null) { return null; } /* * Iteratively work 'down' (it's flat...) the reference * to get the value, but check to make sure that * every result along the path is valid. For example: * * $hashtable.Customer.Name * * The $hashtable may be valid, but there is no key * 'Customer' in the hashtable so we want to stop * when we find a null value and return the null * so the error gets logged. */ try { for (int i = 0; i < numChildren; i++) { result = jjtGetChild(i).execute(result, context); if (result == null) { return null; } } return result; } catch (MethodInvocationException mie) { /* * someone tossed their cookies */ rsvc.error("Method " + mie.MethodName + " threw exception for reference $" + rootString + " in template " + context.CurrentTemplateName + " at " + " [" + this.Line + "," + this.Column + "]"); mie.ReferenceName = rootString; throw mie; } } /// <summary> gets the value of the reference and outputs it to the /// writer. /// * /// </summary> /// <param name="context"> context of data to use in getting value /// </param> /// <param name="writer"> writer to render to /// /// </param> public override bool render(InternalContextAdapter context, TextWriter writer) { if (referenceType == RUNT) { writer.Write(rootString); return true; } Object value_Renamed = execute(null, context); /* * if this reference is escaped (\$foo) then we want to do one of two things : * 1) if this is a reference in the context, then we want to print $foo * 2) if not, then \$foo (its considered shmoo, not VTL) */ if (escaped) { if (value_Renamed == null) { writer.Write(escPrefix); writer.Write("\\"); writer.Write(nullString); } else { writer.Write(escPrefix); writer.Write(nullString); } return true; } /* * the normal processing * * if we have an event cartridge, get a new value object */ EventCartridge ec = context.EventCartridge; if (ec != null) { value_Renamed = ec.referenceInsert(nullString, value_Renamed); } /* * if value is null... */ if (value_Renamed == null) { /* * write prefix twice, because it's shmoo, so the \ don't escape each other... */ writer.Write(escPrefix); writer.Write(escPrefix); writer.Write(morePrefix); writer.Write(nullString); if (referenceType != QUIET_REFERENCE && rsvc.getBoolean(RuntimeConstants_Fields.RUNTIME_LOG_REFERENCE_LOG_INVALID, true)) { rsvc.warn(new ReferenceException("reference : template = " + context.CurrentTemplat... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 05:45:34
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Resource In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime/Resource Added Files: ContentResource.cs Resource.cs ResourceCache.cs ResourceCacheImpl.cs ResourceFactory.cs ResourceManager.cs ResourceManagerImpl.cs Log Message: --- NEW FILE: ResourceFactory.cs --- namespace NVelocity.Runtime.Resource { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; /// <summary> Class responsible for instantiating <code>Resource</code> objects, /// given name and type. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ResourceFactory.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ResourceFactory { public static Resource getResource(String resourceName, int resourceType) { Resource resource = null; switch (resourceType) { case ResourceManager_Fields.RESOURCE_TEMPLATE: resource = new Template(); break; case ResourceManager_Fields.RESOURCE_CONTENT: resource = new ContentResource(); break; } return resource; } } } --- NEW FILE: ContentResource.cs --- namespace NVelocity.Runtime.Resource { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; /// <summary> This class represent a general text resource that /// may have been retrieved from any number of possible /// sources. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ContentResource.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ContentResource : Resource { /// <summary>Default empty constructor /// </summary> public ContentResource() { } /// <summary>Pull in static content and store it /// </summary> public override bool Process() { try { StringWriter sw = new StringWriter(); //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' StreamReader reader = new StreamReader(new StreamReader(resourceLoader.getResourceStream(name), System.Text.Encoding.GetEncoding(encoding)).BaseStream); char[] buf = new char[1024]; int len = 0; // -1 in java, 0 in .Net while ((len = reader.Read(buf, 0, 1024)) > 0) { sw.Write(buf, 0, len); } data = sw.ToString(); return true; } catch (Exception e) { rsvc.error("Cannot process content resource : " + e.ToString()); return false; } } } } --- NEW FILE: ResourceCacheImpl.cs --- namespace NVelocity.Runtime.Resource { using System; using System.Collections; /// <summary> Default implementation of the resource cache for the default /// ResourceManager. /// * /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:dl...@fi...">Daniel Rall</a> /// </author> /// <version> $Id: ResourceCacheImpl.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ResourceCacheImpl : ResourceCache { /// <summary> /// Cache storage, assumed to be thread-safe. /// </summary> //UPGRADE_NOTE: The initialization of 'cache' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' protected internal Hashtable cache = new Hashtable(); /// <summary> /// Runtime services, generally initialized by the /// <code>initialize()</code> method. /// </summary> protected internal RuntimeServices rsvc = null; public ResourceCacheImpl() { } public virtual void initialize(RuntimeServices rs) { rsvc = rs; rsvc.info("ResourceCache : initialized. (" + this.GetType() + ")"); } public virtual Resource get(Object key) { return (Resource) cache[key]; } public virtual Resource put(Object key, Resource value_Renamed) { Object o = cache[key]; cache[key] = value_Renamed; return (Resource) o; } public virtual Resource remove(Object key) { Object o = cache[key]; cache.Remove(key); return (Resource) o; } public virtual IEnumerator enumerateKeys() { return cache.Keys.GetEnumerator(); } } } --- NEW FILE: ResourceCache.cs --- namespace NVelocity.Runtime.Resource { using System; using System.Collections; /// <summary> Interface that defines the shape of a pluggable resource cache /// for the included ResourceManager /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ResourceCache.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public interface ResourceCache { /// <summary> initializes the ResourceCache. Will be /// called before any utilization /// * /// </summary> /// <param name="rs">RuntimeServices to use for logging, etc /// /// </param> void initialize(RuntimeServices rs); /// <summary> retrieves a Resource from the /// cache /// * /// </summary> /// <param name="resourceKey">key for Resource to be retrieved /// </param> /// <returns>Resource specified or null if not found /// /// </returns> Resource get(Object resourceKey); /// <summary> stores a Resource in the cache /// * /// </summary> /// <param name="resourceKey">key to associate with the Resource /// </param> /// <param name="resource">Resource to be stored /// </param> /// <returns>existing Resource stored under this key, or null if none /// /// </returns> Resource put(Object resourceKey, Resource resource); /// <summary> removes a Resource from the cache /// * /// </summary> /// <param name="resourceKey">resource to be removed /// </param> /// <param name="Resource">stored under key /// /// </param> Resource remove(Object resourceKey); /// <summary> returns an Iterator of Keys in the cache /// </summary> IEnumerator enumerateKeys(); } } --- NEW FILE: Resource.cs --- namespace NVelocity.Runtime.Resource { using System; using NVelocity.Runtime.Resource.Loader; /// <summary> This class represent a general text resource that /// may have been retrieved from any number of possible /// sources. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: Resource.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public abstract class Resource { private void InitBlock() { encoding = RuntimeConstants_Fields.ENCODING_DEFAULT; } public virtual RuntimeServices RuntimeServices { set { rsvc = value; } } public virtual long ModificationCheckInterval { set { this.modificationCheckInterval = value; } } public virtual String Name { get { return name; } set { this.name = value; } } public virtual String Encoding { get { return encoding; } set { this.encoding = value; } } public virtual long LastModified { get { return lastModified; } set { this.lastModified = value; } } public virtual ResourceLoader ResourceLoader { get { return resourceLoader; } set { this.resourceLoader = value; } } public virtual Object Data { get { return data; } set { this.data = value; } } protected internal RuntimeServices rsvc = null; /// <summary> The template loader that initially loaded the input /// stream for this template, and knows how to check the /// source of the input stream for modification. /// </summary> protected internal ResourceLoader resourceLoader; /// <summary> The number of milliseconds in a minute, used to calculate the /// check interval. /// </summary> protected internal const long MILLIS_PER_SECOND = 1000; /// <summary> How often the file modification time is checked (in milliseconds). /// </summary> protected internal long modificationCheckInterval = 0; /// <summary> The file modification time (in milliseconds) for the cached template. /// </summary> protected internal long lastModified = 0; /// <summary> The next time the file modification time will be checked (in /// milliseconds). /// </summary> protected internal long nextCheck = 0; /// <summary> Name of the resource /// </summary> protected internal String name; /// <summary> Character encoding of this resource /// </summary> //UPGRADE_NOTE: The initialization of 'encoding' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' protected internal String encoding; /// /// <summary> Resource might require ancillary storage of some kind /// </summary> protected internal Object data = null; /// /// <summary> Default constructor /// </summary> public Resource() { InitBlock(); } /// <summary> Perform any subsequent processing that might need /// to be done by a resource. In the case of a template /// the actual parsing of the input stream needs to be /// performed. /// </summary> public abstract bool Process(); public virtual bool IsSourceModified() { return resourceLoader.isSourceModified(this); } /// <summary> Set the modification check interval. /// </summary> /// <param name="interval">The interval (in minutes). /// /// </param> /// <summary> Is it time to check to see if the resource /// source has been updated? /// </summary> public virtual bool RequiresChecking() { /* * short circuit this if modificationCheckInterval == 0 * as this means "don't check" */ if (modificationCheckInterval <= 0) { return false; } /* * see if we need to check now */ return ((DateTime.Now.Ticks - 621355968000000000)/10000 >= nextCheck); } /// <summary> 'Touch' this template and thereby resetting /// the nextCheck field. /// </summary> public virtual void Touch() { nextCheck = (DateTime.Now.Ticks - 621355968000000000)/10000 + (MILLIS_PER_SECOND*modificationCheckInterval); } /// <summary> Set the name of this resource, for example /// test.vm. /// </summary> /// <summary> Get the name of this template. /// </summary> /// <summary> set the encoding of this resource /// for example, "ISO-8859-1" /// </summary> /// <summary> get the encoding of this resource /// for example, "ISO-8859-1" /// </summary> /// <summary> Return the lastModifed time of this /// template. /// </summary> /// <summary> Set the last modified time for this /// template. /// </summary> /// <summary> Return the template loader that pulled /// in the template stream /// </summary> /// <summary> Set the template loader for this template. Set /// when the Runtime determines where this template /// came from the list of possible sources. /// </summary> /// /// <summary> Set arbitrary data object that might be used /// by the resource. /// </summary> /// <summary> Get arbitrary data object that might be used /// by the resource. /// </summary> } } --- NEW FILE: ResourceManager.cs --- namespace NVelocity.Runtime.Resource { using System; /// <summary> Class to manage the text resource for the Velocity /// Runtime. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:pau...@kr...">Paulo Gaspar</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ResourceManager.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public struct ResourceManager_Fields { public const int RESOURCE_TEMPLATE = 1; public const int RESOURCE_CONTENT = 2; } public interface ResourceManager { //UPGRADE_NOTE: Members of interface 'ResourceManager' were extracted into structure 'ResourceManager_Fields'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1045"' /// <summary> A template resources. /// </summary> /// <summary> A static content resource. /// </summary> /// <summary> Initialize the ResourceManager. It is assumed /// that assembleSourceInitializers() has been /// called before this is run. /// </summary> void initialize(RuntimeServices rs); /// <summary> Gets the named resource. Returned class type corresponds to specified type /// (i.e. <code>Template</code> to <code>RESOURCE_TEMPLATE</code>). /// * /// </summary> /// <param name="resourceName">The name of the resource to retrieve. /// </param> /// <param name="resourceType">The type of resource (<code>RESOURCE_TEMPLATE</code>, /// <code>RESOURCE_CONTENT</code>, etc.). /// </param> /// <param name="encoding"> The character encoding to use. /// </param> /// <returns>Resource with the template parsed and ready. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// /// </returns> Resource getResource(String resourceName, int resourceType, String encoding); /// <summary> Determines is a template exists, and returns name of the loader that /// provides it. This is a slightly less hokey way to support /// the Velocity.templateExists() utility method, which was broken /// when per-template encoding was introduced. We can revisit this. /// * /// </summary> /// <param name="resourceName">Name of template or content resource /// </param> /// <returns>class name of loader than can provide it /// /// </returns> String getLoaderNameForResource(String resourceName); } } --- NEW FILE: ResourceManagerImpl.cs --- namespace NVelocity.Runtime.Resource { using System; using System.Collections; using System.IO; using Commons.Collections; using NVelocity.Exception; using NVelocity.Runtime.Resource.Loader; /// <summary> Class to manage the text resource for the Velocity /// Runtime. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:pau...@kr...">Paulo Gaspar</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ResourceManagerImpl.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ResourceManagerImpl : ResourceManager { public ResourceManagerImpl() { InitBlock(); } private void InitBlock() { resourceLoaders = new ArrayList(); sourceInitializerList = new ArrayList(); sourceInitializerMap = new Hashtable(); } /// <summary> A template resources. /// </summary> public const int RESOURCE_TEMPLATE = 1; /// <summary> A static content resource. /// </summary> public const int RESOURCE_CONTENT = 2; /// <summary> token used to identify the loader internally /// </summary> private const String RESOURCE_LOADER_IDENTIFIER = "_RESOURCE_LOADER_IDENTIFIER_"; /// <summary> Object implementing ResourceCache to /// be our resource manager's Resource cache. /// </summary> protected internal ResourceCache globalCache = null; /// <summary> The List of templateLoaders that the Runtime will /// use to locate the InputStream source of a template. /// </summary> //UPGRADE_NOTE: The initialization of 'resourceLoaders' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' protected internal ArrayList resourceLoaders; /// <summary> This is a list of the template input stream source /// initializers, basically properties for a particular /// template stream source. The order in this list /// reflects numbering of the properties i.e. /// * /// <loader-id>.resource.loader.<property> = <value> /// </summary> //UPGRADE_NOTE: The initialization of 'sourceInitializerList' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private ArrayList sourceInitializerList; /// <summary> This is a map of public name of the template /// stream source to it's initializer. This is so /// that clients of velocity can set properties of /// a template source stream with its public name. /// So for example, a client could set the /// File.resource.path property and this would /// change the resource.path property for the /// file template stream source. /// </summary> //UPGRADE_NOTE: The initialization of 'sourceInitializerMap' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Hashtable sourceInitializerMap; /// <summary> Each loader needs a configuration object for /// its initialization, this flags keeps track of whether /// or not the configuration objects have been created /// for the resource loaders. /// </summary> private bool resourceLoaderInitializersActive = false; /// <summary> /// switch to turn off log notice when a resource is found for /// the first time. /// </summary> private bool logWhenFound = true; protected internal RuntimeServices rsvc = null; /// <summary> Initialize the ResourceManager. It is assumed /// that assembleSourceInitializers() has been /// called before this is run. /// </summary> public virtual void initialize(RuntimeServices rs) { rsvc = rs; rsvc.info("Default ResourceManager initializing. (" + this.GetType() + ")"); ResourceLoader resourceLoader; assembleResourceLoaderInitializers(); for (int i = 0; i < sourceInitializerList.Count; i++) { ExtendedProperties configuration = (ExtendedProperties) sourceInitializerList[i]; String loaderClass = configuration.GetString("class"); if (loaderClass == null) { rsvc.error("Unable to find '" + configuration.GetString(RESOURCE_LOADER_IDENTIFIER) + ".resource.loader.class' specification in configuation." + " This is a critical value. Please adjust configuration."); continue; } resourceLoader = ResourceLoaderFactory.getLoader(rsvc, loaderClass); resourceLoader.commonInit(rsvc, configuration); resourceLoader.init(configuration); resourceLoaders.Add(resourceLoader); } /* * now see if this is overridden by configuration */ logWhenFound = rsvc.getBoolean(RuntimeConstants_Fields.RESOURCE_MANAGER_LOGWHENFOUND, true); /* * now, is a global cache specified? */ String claz = rsvc.getString(RuntimeConstants_Fields.RESOURCE_MANAGER_CACHE_CLASS); Object o = null; if (claz != null && claz.Length > 0) { try { Type type = Type.GetType(claz); o = Activator.CreateInstance(type); } catch (Exception cnfe) { String err = "The specified class for ResourceCache (" + claz + ") does not exist (or is not accessible to the current classlaoder)."; rsvc.error(err); o = null; } if (!(o is ResourceCache)) { String err = "The specified class for ResourceCache (" + claz + ") does not implement NVelocity.Runtime.Resource.ResourceCache." + " Using default ResourceCache implementation."; rsvc.error(err); o = null; } } /* * if we didn't get through that, just use the default. */ if (o == null) { o = new ResourceCacheImpl(); } globalCache = (ResourceCache) o; globalCache.initialize(rsvc); rsvc.info("Default ResourceManager initialization complete."); } /// <summary> This will produce a List of Hashtables, each /// hashtable contains the intialization info for /// a particular resource loader. This Hastable /// will be passed in when initializing the /// the template loader. /// </summary> private void assembleResourceLoaderInitializers() { if (resourceLoaderInitializersActive) { return; } ArrayList resourceLoaderNames = rsvc.Configuration.GetVector(RuntimeConstants_Fields.RESOURCE_LOADER); for (int i = 0; i < resourceLoaderNames.Count; i++) { /* * The loader id might look something like the following: * * file.resource.loader * * The loader id is the prefix used for all properties * pertaining to a particular loader. */ String loaderID = resourceLoaderNames[i] + "." + RuntimeConstants_Fields.RESOURCE_LOADER; ExtendedProperties loaderConfiguration = rsvc.Configuration.Subset(loaderID); /* * we can't really count on ExtendedProperties to give us an empty set */ if (loaderConfiguration == null) { rsvc.warn("ResourceManager : No configuration information for resource loader named '" + resourceLoaderNames[i] + "'. Skipping."); continue; } /* * add the loader name token to the initializer if we need it * for reference later. We can't count on the user to fill * in the 'name' field */ loaderConfiguration.SetProperty(RESOURCE_LOADER_IDENTIFIER, resourceLoaderNames[i]); /* * Add resources to the list of resource loader * initializers. */ sourceInitializerList.Add(loaderConfiguration); } resourceLoaderInitializersActive = true; } /// <summary> Gets the named resource. Returned class type corresponds to specified type /// (i.e. <code>Template</code> to <code>RESOURCE_TEMPLATE</code>). /// * /// </summary> /// <param name="resourceName">The name of the resource to retrieve. /// </param> /// <param name="resourceType">The type of resource (<code>RESOURCE_TEMPLATE</code>, /// <code>RESOURCE_CONTENT</code>, etc.). /// </param> /// <param name="encoding"> The character encoding to use. /// </param> /// <returns>Resource with the template parsed and ready. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// /// </returns> public virtual Resource getResource(String resourceName, int resourceType, String encoding) { /* * Check to see if the resource was placed in the cache. * If it was placed in the cache then we will use * the cached version of the resource. If not we * will load it. */ Resource resource = globalCache.get(resourceName); if (resource != null) { /* * refresh the resource */ try { refreshResource(resource, encoding); } catch (ResourceNotFoundException rnfe) { /* * something exceptional happened to that resource * this could be on purpose, * so clear the cache and try again */ globalCache.remove(resourceName); return getResource(resourceName, resourceType, encoding); } catch (ParseErrorException pee) { rsvc.error("ResourceManager.getResource() exception: " + pee); throw pee; } catch (Exception eee) { rsvc.error("ResourceManager.getResource() exception: " + eee); throw eee; } } else { try { /* * it's not in the cache, so load it. */ resource = loadResource(resourceName, resourceType, encoding); if (resource.ResourceLoader.isCachingOn()) { globalCache.put(resourceName, resource); } } catch (ResourceNotFoundException rnfe2) { rsvc.error("ResourceManager : unable to find resource '" + resourceName + "' in any resource loader."); throw rnfe2; } catch (ParseErrorException pee) { rsvc.error("ResourceManager.getResource() parse exception: " + pee); throw pee; } catch (Exception ee) { rsvc.error("ResourceManager.getResource() exception new: " + ee); throw ee; } } return resource; } /// <summary> /// Loads a resource from the current set of resource loaders /// </summary> /// <param name="resourceName">The name of the resource to retrieve.</param> /// <param name="resourceType">The type of resource (<code>RESOURCE_TEMPLATE</code>, /// <code>RESOURCE_CONTENT</code>, etc.). /// </param> /// <param name="encoding"> The character encoding to use.</param> /// <returns>Resource with the template parsed and ready. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// </returns> protected internal virtual Resource loadResource(String resourceName, int resourceType, String encoding) { Resource resource = ResourceFactory.getResource(resourceName, resourceType); resource.RuntimeServices = rsvc; resource.Name = resourceName; resource.Encoding = encoding; /* * Now we have to try to find the appropriate * loader for this resource. We have to cycle through * the list of available resource loaders and see * which one gives us a stream that we can use to * make a resource with. */ long howOldItWas = 0; // Initialize to avoid warnings ResourceLoader resourceLoader = null; for (int i = 0; i < resourceLoaders.Count; i++) { resourceLoader = (ResourceLoader) resourceLoaders[i]; resource.ResourceLoader = resourceLoader; /* * catch the ResourceNotFound exception * as that is ok in our new multi-loader environment */ try { if (resource.Process()) { /* * FIXME (gmj) * moved in here - technically still * a problem - but the resource needs to be * processed before the loader can figure * it out due to to the new * multi-path support - will revisit and fix */ if (logWhenFound) { rsvc.info("ResourceManager : found " + resourceName + " with loader " + resourceLoader.ClassName); } howOldItWas = resourceLoader.getLastModified(resource); break; } } catch (ResourceNotFoundException rnfe) { /* * that's ok - it's possible to fail in * multi-loader environment */ } } /* * Return null if we can't find a resource. */ if (resource.Data == null) { throw new ResourceNotFoundException("Unable to find resource '" + resourceName + "'"); } /* * some final cleanup */ resource.LastModified = howOldItWas; resource.ModificationCheckInterval = resourceLoader.ModificationCheckInterval; resource.Touch(); return resource; } /// <summary> Takes an existing resource, and 'refreshes' it. This /// generally means that the source of the resource is checked /// for changes according to some cache/check algorithm /// and if the resource changed, then the resource data is /// reloaded and re-parsed. /// * /// </summary> /// <param name="resource">resource to refresh /// * /// @throws ResourceNotFoundException if template not found /// from current source for this Resource /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// /// </param> protected internal virtual void refreshResource(Resource resource, String encoding) { /* * The resource knows whether it needs to be checked * or not, and the resource's loader can check to * see if the source has been modified. If both * these conditions are true then we must reload * the input stream and parse it to make a new * AST for the resource. */ if (resource.RequiresChecking()) { /* * touch() the resource to reset the counters */ resource.Touch(); if (resource.IsSourceModified()) { /* * now check encoding info. It's possible that the newly declared * encoding is different than the encoding already in the resource * this strikes me as bad... */ if (!resource.Encoding.Equals(encoding)) { rsvc.error("Declared encoding for template '" + resource.Name + "' is different on reload. Old = '" + resource.Encoding + "' New = '" + encoding); resource.Encoding = encoding; } /* * read how old the resource is _before_ * processing (=>reading) it */ long howOldItWas = resource.ResourceLoader.getLastModified(resource); /* * read in the fresh stream and parse */ resource.Process(); /* * now set the modification info and reset * the modification check counters */ resource.LastModified = howOldItWas; } } } /// <summary> Gets the named resource. Returned class type corresponds to specified type /// (i.e. <code>Template</code> to <code>RESOURCE_TEMPLATE</code>). /// * /// </summary> /// <param name="resourceName">The name of the resource to retrieve. /// </param> /// <param name="resourceType">The type of resource (<code>RESOURCE_TEMPLATE</code>, /// <code>RESOURCE_CONTENT</code>, etc.). /// </param> /// <returns>Resource with the template parsed and ready. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// * /// </returns> /// <deprecated>Use /// {@link #getResource(String resourceName, int resourceType, /// String encoding )} /// /// </deprecated> public virtual Resource getResource(String resourceName, int resourceType) { return getResource(resourceName, resourceType, RuntimeConstants_Fields.ENCODING_DEFAULT); } /// <summary> Determines is a template exists, and returns name of the loader that /// provides it. This is a slightly less hokey way to support /// the Velocity.templateExists() utility method, which was broken /// when per-template encoding was introduced. We can revisit this. /// * /// </summary> /// <param name="resourceName">Name of template or content resource /// </param> /// <returns>class name of loader than can provide it /// /// </returns> public virtual String getLoaderNameForResource(String resourceName) { ResourceLoader resourceLoader = null; /* * loop through our loaders... */ for (int i = 0; i < resourceLoaders.Count; i++) { resourceLoader = (ResourceLoader) resourceLoaders[i]; Stream is_Renamed = null; /* * if we find one that can provide the resource, * return the name of the loaders's Class */ try { is_Renamed = resourceLoader.getResourceStream(resourceName); if (is_Renamed != null) { return resourceLoader.GetType().ToString(); } } catch (ResourceNotFoundException e) { /* * this isn't a problem. keep going */ } finally { /* * if we did find one, clean up because we were * returned an open stream */ if (is_Renamed != null) { try { is_Renamed.Close(); } catch (IOException ioe) { } } } } return null; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:34
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Parser In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime/Parser Added Files: CharStream.cs JJTParserState.cs ParseException.cs Parser.cs ParserConstants.cs ParserTokenManager.cs ParserTreeConstants.cs Token.cs TokenMgrError.cs VelocityCharStream.cs Log Message: --- NEW FILE: ParserConstants.cs --- namespace NVelocity.Runtime.Parser { using System; /* Generated By:JJTree&JavaCC: Do not edit this line. ParserConstants.java */ public class ParserConstants { public const int EOF = 0; public const int LBRACKET = 1; public const int RBRACKET = 2; public const int COMMA = 3; public const int DOUBLEDOT = 4; public const int LPAREN = 5; public const int RPAREN = 6; public const int REFMOD2_RPAREN = 7; public const int ESCAPE_DIRECTIVE = 8; public const int SET_DIRECTIVE = 9; public const int DOLLAR = 10; public const int DOLLARBANG = 11; public const int HASH = 15; public const int DOUBLE_ESCAPE = 16; public const int ESCAPE = 17; public const int TEXT = 18; public const int SINGLE_LINE_COMMENT = 19; public const int FORMAL_COMMENT = 20; public const int MULTI_LINE_COMMENT = 21; public const int WHITESPACE = 23; public const int STRING_LITERAL = 24; public const int TRUE = 25; public const int FALSE = 26; public const int NEWLINE = 27; public const int MINUS = 28; public const int PLUS = 29; public const int MULTIPLY = 30; public const int DIVIDE = 31; public const int MODULUS = 32; public const int LOGICAL_AND = 33; public const int LOGICAL_OR = 34; public const int LOGICAL_LT = 35; public const int LOGICAL_LE = 36; public const int LOGICAL_GT = 37; public const int LOGICAL_GE = 38; public const int LOGICAL_EQUALS = 39; public const int LOGICAL_NOT_EQUALS = 40; public const int LOGICAL_NOT = 41; public const int EQUALS = 42; public const int END = 43; public const int IF_DIRECTIVE = 44; public const int ELSEIF_DIRECTIVE = 45; public const int ELSE_DIRECTIVE = 46; public const int STOP_DIRECTIVE = 47; public const int DIGIT = 48; public const int NUMBER_LITERAL = 49; public const int LETTER = 50; public const int DIRECTIVE_CHAR = 51; public const int WORD = 52; public const int ALPHA_CHAR = 53; public const int ALPHANUM_CHAR = 54; public const int IDENTIFIER_CHAR = 55; public const int IDENTIFIER = 56; public const int DOT = 57; public const int LCURLY = 58; public const int RCURLY = 59; public const int REFERENCE_TERMINATOR = 60; public const int DIRECTIVE_TERMINATOR = 61; public const int DIRECTIVE = 0; public const int REFMOD2 = 1; public const int REFMODIFIER = 2; public const int DEFAULT = 3; public const int PRE_DIRECTIVE = 4; public const int REFERENCE = 5; public const int IN_MULTI_LINE_COMMENT = 6; public const int IN_FORMAL_COMMENT = 7; public const int IN_SINGLE_LINE_COMMENT = 8; public static readonly String[] tokenImage = new String[] {"<EOF>", "\"[\"", "\"]\"", "\",\"", "\"..\"", "\"(\"", "<RPAREN>", "\")\"", "<ESCAPE_DIRECTIVE>", "<SET_DIRECTIVE>", "<DOLLAR>", "<DOLLARBANG>", "\"##\"", "<token of kind 13>", "\"#*\"", "\"#\"", "\"\\\\\\\\\"", "\"\\\\\"", "<TEXT>", "<SINGLE_LINE_COMMENT>", "\"*#\"", "\"*#\"", "<token of kind 22>", "<WHITESPACE>", "<STRING_LITERAL>", "\"true\"", "\"false\"", "<NEWLINE>", "\"-\"", "\"+\"", "\"*\"", "\"/\"", "\"%\"", "\"&&\"", "\"||\"", "\"<\"", "\"<=\"", "\">\"", "\">=\"", "\"==\"", "\"!=\"", "\"!\"", "\"=\"", "<END>", "\"if\"", "\"elseif\"", "<ELSE_DIRECTIVE>", "\"stop\"", "<DIGIT>", "<NUMBER_LITERAL>", "<LETTER>", "<DIRECTIVE_CHAR>", "<WORD>", "<ALPHA_CHAR>", "<ALPHANUM_CHAR>", "<IDENTIFIER_CHAR>", "<IDENTIFIER>", "<DOT>", "\"{\"", "\"}\"", "<REFERENCE_TERMINATOR>", "<DIRECTIVE_TERMINATOR>"}; } } --- NEW FILE: ParseException.cs --- /* Generated By:JavaCC: Do not edit this line. ParseException.java Version 2.1 */ namespace NVelocity.Runtime.Parser { using System; using System.Text; /// <summary> This exception is thrown when parse errors are encountered. /// You can explicitly create objects of this exception type by /// calling the method generateParseException in the generated /// parser. /// * /// You can modify this class to customize your error reporting /// mechanisms so long as you retain the public fields. /// </summary> public class ParseException : Exception { /// <summary> The end of line string for this machine. /// </summary> protected internal String eol = Environment.NewLine; public override String Message { get { if (!specialConstructor) { return base.Message; } String expected = ""; int maxSize = 0; for (int i = 0; i < expectedTokenSequences.Length; i++) { if (maxSize < expectedTokenSequences[i].Length) { maxSize = expectedTokenSequences[i].Length; } for (int j = 0; j < expectedTokenSequences[i].Length; j++) { expected += tokenImage[expectedTokenSequences[i][j]] + " "; } if (expectedTokenSequences[i][expectedTokenSequences[i].Length - 1] != 0) { expected += "..."; } expected += eol + " "; } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += add_escapes(tok.image); tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.Length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected; return retval; } } /// <summary> This constructor is used by the method "generateParseException" /// in the generated parser. Calling this constructor generates /// a new object of this type with the fields "currentToken", /// "expectedTokenSequences", and "tokenImage" set. The boolean /// flag "specialConstructor" is also set to true to indicate that /// this constructor was used to create this object. /// This constructor calls its super class with the empty string /// to force the "toString" method of parent class "Throwable" to /// print the error message in the form: /// ParseException: <result of getMessage> /// </summary> public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal) : base("") { specialConstructor = true; currentToken = currentTokenVal; expectedTokenSequences = expectedTokenSequencesVal; tokenImage = tokenImageVal; } /// <summary> The following constructors are for use by you for whatever /// purpose you can think of. Constructing the exception in this /// manner makes the exception behave in the normal way - i.e., as /// documented in the class "Throwable". The fields "errorToken", /// "expectedTokenSequences", and "tokenImage" do not contain /// relevant information. The JavaCC generated code does not use /// these constructors. /// </summary> public ParseException() : base() { specialConstructor = false; } public ParseException(String message) : base(message) { specialConstructor = false; } /// <summary> This variable determines which constructor was used to create /// this object and thereby affects the semantics of the /// "getMessage" method (see below). /// </summary> protected internal bool specialConstructor; /// <summary> This is the last token that has been consumed successfully. If /// this object has been created due to a parse error, the token /// followng this token will (therefore) be the first error token. /// </summary> public Token currentToken; /// <summary> Each entry in this array is an array of integers. Each array /// of integers represents a sequence of tokens (by their ordinal /// values) that is expected at this point of the parse. /// </summary> public int[][] expectedTokenSequences; /// <summary> This is a reference to the "tokenImage" array of the generated /// parser within which the parse error occurred. This array is /// defined in the generated ...Constants interface. /// </summary> public String[] tokenImage; /// <summary> This method has the standard behavior when this object has been /// created using the standard constructors. Otherwise, it uses /// "currentToken" and "expectedTokenSequences" to generate a parse /// error message and returns it. If this object has been created /// due to a parse error, and you do not catch it (it gets thrown /// from the parser), then this method is called during the printing /// of the final stack trace, and hence the correct error message /// gets displayed. /// </summary> /// <summary> Used to convert raw characters to their escaped version /// when these raw version cannot be used as part of an ASCII /// string literal. /// </summary> protected internal virtual String add_escapes(String str) { StringBuilder retval = new StringBuilder(); char ch; for (int i = 0; i < str.Length; i++) { switch (str[i]) { case (char) (0): continue; case '\b': retval.Append("\\b"); continue; case '\t': retval.Append("\\t"); continue; case '\n': retval.Append("\\n"); continue; case '\f': retval.Append("\\f"); continue; case '\r': retval.Append("\\r"); continue; case '\"': retval.Append("\\\""); continue; case '\'': retval.Append("\\\'"); continue; case '\\': retval.Append("\\\\"); continue; default: if ((ch = str[i]) < 0x20 || ch > 0x7e) { String s = "0000" + Convert.ToString(ch, 16); retval.Append("\\u" + s.Substring(s.Length - 4, (s.Length) - (s.Length - 4))); } else { retval.Append(ch); } continue; } } return retval.ToString(); } } } --- NEW FILE: JJTParserState.cs --- /* Generated By:JJTree: Do not edit this line. JJTParserState.java */ namespace NVelocity.Runtime.Parser { using System; using System.Collections; using NVelocity.Runtime.Parser.Node; internal class JJTParserState { private Stack nodes; private Stack marks; private int sp; // number of nodes on stack private int mk; // current mark private bool node_created; internal JJTParserState() { nodes = new Stack(); marks = new Stack(); sp = 0; mk = 0; } /* Determines whether the current node was actually closed and pushed. This should only be called in the final user action of a node scope. */ internal virtual bool nodeCreated() { return node_created; } /* Call this to reinitialize the node stack. It is called automatically by the parser's ReInit() method. */ internal virtual void reset() { nodes.Clear(); marks.Clear(); sp = 0; mk = 0; } /* Returns the root node of the AST. It only makes sense to call this after a successful parse. */ internal virtual INode rootNode() { return (INode) (nodes.ToArray())[nodes.Count - (0 + 1)]; } /* Pushes a node on to the stack. */ internal virtual void pushNode(INode n) { Object temp_object; temp_object = n; Object generatedAux = temp_object; nodes.Push(temp_object); ++sp; } /* Returns the node on the top of the stack, and remove it from the stack. */ internal virtual INode popNode() { if (--sp < mk) { mk = ((Int32) marks.Pop()); } return (INode) nodes.Pop(); } /* Returns the node currently on the top of the stack. */ internal virtual INode peekNode() { return (INode) nodes.Peek(); } /* Returns the number of children on the stack in the current node scope. */ internal virtual int nodeArity() { return sp - mk; } internal virtual void clearNodeScope(INode n) { while (sp > mk) { popNode(); } mk = ((Int32) marks.Pop()); } internal virtual void openNodeScope(INode n) { Object temp_object; temp_object = mk; Object generatedAux = temp_object; marks.Push(temp_object); mk = sp; n.jjtOpen(); } /* A definite node is constructed from a specified number of children. That number of nodes are popped from the stack and made the children of the definite node. Then the definite node is pushed on to the stack. */ internal virtual void closeNodeScope(INode n, int num) { mk = ((Int32) marks.Pop()); while (num-- > 0) { INode c = popNode(); c.jjtSetParent(n); n.jjtAddChild(c, num); } n.jjtClose(); pushNode(n); node_created = true; } /* A conditional node is constructed if its condition is true. All the nodes that have been pushed since the node was opened are made children of the the conditional node, which is then pushed on to the stack. If the condition is false the node is not constructed and they are left on the stack. */ internal virtual void closeNodeScope(INode n, bool condition) { if (condition) { int a = nodeArity(); mk = ((Int32) marks.Pop()); while (a-- > 0) { INode c = popNode(); c.jjtSetParent(n); n.jjtAddChild(c, a); } n.jjtClose(); pushNode(n); node_created = true; } else { mk = ((Int32) marks.Pop()); node_created = false; } } } } --- NEW FILE: ParserTokenManager.cs --- namespace NVelocity.Runtime.Parser { using System; using System.Collections; using System.IO; using System.Text; /* Generated By:JJTree&JavaCC: Do not edit this line. ParserTokenManager.java */ public class ParserTokenManager : ParserConstants { private int fileDepth = 0; private int lparen = 0; private int rparen = 0; private Stack stateStack = new Stack(); public bool debugPrint = false; [...4273 lines suppressed...] matchedToken.image = "."; if (debugPrint) Console.Out.Write("DOT : switching to " + REFMODIFIER); SwitchTo(ParserConstants.REFMODIFIER); break; case 59: if (image == null) image = new StringBuilder(new String(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)))); else image.Append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); stateStackPop(); break; default: break; } } } } --- NEW FILE: Parser.cs --- /* Generated By:JJTree&JavaCC: Do not edit this line. Parser.java */ namespace NVelocity.Runtime.Parser { using System; using System.Collections; using System.IO; using NVelocity.Runtime.Directive; using NVelocity.Runtime.Parser.Node; using NVelocity.Util; /// <summary> This class is responsible for parsing a Velocity /// template. This class was generated by JavaCC using /// the JJTree extension to produce an Abstract /// Syntax Tree (AST) of the template. /// /// Please look at the Parser.jjt file which is /// what controls the generation of this class. /// </summary> [...5189 lines suppressed...] { p = p.next = new JJCalls(); break; } p = p.next; } p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; } private sealed class JJCalls { internal int gen; internal Token first; internal int arg; internal JJCalls next; } } } --- NEW FILE: TokenMgrError.cs --- /* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 2.1 */ namespace NVelocity.Runtime.Parser { using System; using System.Text; public class TokenMgrError : ApplicationException { public override String Message { get { return base.Message; } } /* * Ordinals for various reasons why an Error of this type can be thrown. */ /// <summary> Lexical error occured. /// </summary> internal const int LEXICAL_ERROR = 0; /// <summary> An attempt wass made to create a second instance of a static token manager. /// </summary> internal const int STATIC_LEXER_ERROR = 1; /// <summary> Tried to change to an invalid lexical state. /// </summary> internal const int INVALID_LEXICAL_STATE = 2; /// <summary> Detected (and bailed out of) an infinite loop in the token manager. /// </summary> internal const int LOOP_DETECTED = 3; /// <summary> Indicates the reason why the exception is thrown. It will have /// one of the above 4 values. /// </summary> internal int errorCode; /// <summary> Replaces unprintable characters by their espaced (or unicode escaped) /// equivalents in the given string /// </summary> protected internal static String addEscapes(String str) { StringBuilder retval = new StringBuilder(); char ch; for (int i = 0; i < str.Length; i++) { switch (str[i]) { case (char) (0): continue; case '\b': retval.Append("\\b"); continue; case '\t': retval.Append("\\t"); continue; case '\n': retval.Append("\\n"); continue; case '\f': retval.Append("\\f"); continue; case '\r': retval.Append("\\r"); continue; case '\"': retval.Append("\\\""); continue; case '\'': retval.Append("\\\'"); continue; case '\\': retval.Append("\\\\"); continue; default: if ((ch = str[i]) < 0x20 || ch > 0x7e) { String s = "0000" + Convert.ToString(ch, 16); retval.Append("\\u" + s.Substring(s.Length - 4, (s.Length) - (s.Length - 4))); } else { retval.Append(ch); } continue; } } return retval.ToString(); } /// <summary> Returns a detailed message for the Error when it is thrown by the /// token manager to indicate a lexical error. /// Parameters : /// EOFSeen : indicates if EOF caused the lexicl error /// curLexState : lexical state in which this error occured /// errorLine : line number when the error occured /// errorColumn : column number when the error occured /// errorAfter : prefix that was seen before this error occured /// curchar : the offending character /// Note: You can customize the lexical error message by modifying this method. /// </summary> private static String LexicalError(bool EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return ("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? "<EOF> " : ("\"" + addEscapes(curChar.ToString()) + "\"") + " (" + (int) curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /// <summary> You can also modify the body of this method to customize your error messages. /// For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not /// of end-users concern, so you can return something like : /// * /// "Internal Error : Please file a bug report .... " /// * /// from this method for such cases in the release version of your parser. /// </summary> /* * Constructors of various flavors follow. */ public TokenMgrError() { } public TokenMgrError(String message, int reason) : base(message) { errorCode = reason; } public TokenMgrError(bool EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) : this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason) { } } } --- NEW FILE: ParserTreeConstants.cs --- namespace NVelocity.Runtime.Parser { using System; /* Generated By:JJTree: Do not edit this line. ParserTreeConstants.java */ public class ParserTreeConstants { /// <summary> /// private constructor as class is meant to hold constants only. /// Class was orginally an interface in Java, but as C# does not support Fields in an interface and /// the jjtNodeName field, I converted it to a class with no constructor. /// </summary> private ParserTreeConstants() { } public const int JJTPROCESS = 0; public const int JJTVOID = 1; public const int JJTESCAPEDDIRECTIVE = 2; public const int JJTESCAPE = 3; public const int JJTCOMMENT = 4; public const int JJTNUMBERLITERAL = 5; public const int JJTSTRINGLITERAL = 6; public const int JJTIDENTIFIER = 7; public const int JJTWORD = 8; public const int JJTDIRECTIVE = 9; public const int JJTBLOCK = 10; public const int JJTOBJECTARRAY = 11; public const int JJTINTEGERRANGE = 12; public const int JJTMETHOD = 13; public const int JJTREFERENCE = 14; public const int JJTTRUE = 15; public const int JJTFALSE = 16; public const int JJTTEXT = 17; public const int JJTIFSTATEMENT = 18; public const int JJTELSESTATEMENT = 19; public const int JJTELSEIFSTATEMENT = 20; public const int JJTSETDIRECTIVE = 21; public const int JJTEXPRESSION = 22; public const int JJTASSIGNMENT = 23; public const int JJTORNODE = 24; public const int JJTANDNODE = 25; public const int JJTEQNODE = 26; public const int JJTNENODE = 27; public const int JJTLTNODE = 28; public const int JJTGTNODE = 29; public const int JJTLENODE = 30; public const int JJTGENODE = 31; public const int JJTADDNODE = 32; public const int JJTSUBTRACTNODE = 33; public const int JJTMULNODE = 34; public const int JJTDIVNODE = 35; public const int JJTMODNODE = 36; public const int JJTNOTNODE = 37; public static readonly String[] jjtNodeName = new String[] {"process", "void", "EscapedDirective", "Escape", "Comment", "NumberLiteral", "StringLiteral", "Identifier", "Word", "Directive", "Block", "ObjectArray", "IntegerRange", "Method", "Reference", "True", "False", "Text", "IfStatement", "ElseStatement", "ElseIfStatement", "SetDirective", "Expression", "Assignment", "OrNode", "AndNode", "EQNode", "NENode", "LTNode", "GTNode", "LENode", "GENode", "AddNode", "SubtractNode", "MulNode", "DivNode", "ModNode", "NotNode"}; } } --- NEW FILE: CharStream.cs --- /* Generated By:JavaCC: Do not edit this line. CharStream.java Version 2.1 */ namespace NVelocity.Runtime.Parser { using System; /// <summary> This interface describes a character stream that maintains line and /// column number positions of the characters. It also has the capability /// to backup the stream to some extent. An implementation of this /// interface is used in the TokenManager implementation generated by /// JavaCCParser. /// /// All the methods except backup can be implemented in any fashion. backup /// needs to be implemented correctly for the correct operation of the lexer. /// Rest of the methods are all used to get information like line number, /// column number and the String that constitutes a token and are not used /// by the lexer. Hence their implementation won't affect the generated lexer's /// operation. /// </summary> public interface CharStream { int Column { get; } int Line { get; } int EndColumn { get; } int EndLine { get; } int BeginColumn { get; } int BeginLine { get; } /// <summary> Returns the next character from the selected input. The method /// of selecting the input is the responsibility of the class /// implementing this interface. Can throw any java.io.IOException. /// </summary> char readChar(); /// <summary> Returns the column position of the character last read. /// </summary> /// <deprecated> /// </deprecated> /// <seealso cref=" #getEndColumn /// /// "/> /// <summary> Returns the line number of the character last read. /// </summary> /// <deprecated> /// </deprecated> /// <seealso cref=" #getEndLine /// /// "/> /// <summary> Returns the column number of the last character for current token (being /// matched after the last call to BeginTOken). /// </summary> /// <summary> Returns the line number of the last character for current token (being /// matched after the last call to BeginTOken). /// </summary> /// <summary> Returns the column number of the first character for current token (being /// matched after the last call to BeginTOken). /// </summary> /// <summary> Returns the line number of the first character for current token (being /// matched after the last call to BeginTOken). /// </summary> /// <summary> Backs up the input stream by amount steps. Lexer calls this method if it /// had already read some characters, but could not use them to match a /// (longer) token. So, they will be used again as the prefix of the next /// token and it is the implemetation's responsibility to do this right. /// </summary> void backup(int amount); /// <summary> Returns the next character that marks the beginning of the next token. /// All characters must remain in the buffer between two successive calls /// to this method to implement backup correctly. /// </summary> char BeginToken(); /// <summary> Returns a string made up of characters from the marked token beginning /// to the current buffer position. Implementations have the choice of returning /// anything that they want to. For example, for efficiency, one might decide /// to just return null, which is a valid implementation. /// </summary> String GetImage(); /// <summary> Returns an array of characters that make up the suffix of length 'len' for /// the currently matched token. This is used to build up the matched string /// for use in actions in the case of MORE. A simple and inefficient /// implementation of this is as follows : /// /// { /// String t = GetImage(); /// return t.substring(t.length() - len, t.length()).toCharArray(); /// } /// </summary> char[] GetSuffix(int len); /// <summary> The lexer calls this function to indicate that it is done with the stream /// and hence implementations can free any resources held by this class. /// Again, the body of this function can be just empty and it will not /// affect the lexer's operation. /// </summary> void Done(); } } --- NEW FILE: VelocityCharStream.cs --- namespace NVelocity.Runtime.Parser { using System; using System.IO; /// <summary> NOTE : This class was originally an ASCII_CharStream autogenerated /// by Javacc. It was then modified via changing class name with appropriate /// fixes for CTORS, and mods to readChar(). /// /// This is safe because we *always* use Reader with this class, and never a /// InputStream. This guarantees that we have a correct stream of 16-bit /// chars - all encoding transformations have been done elsewhere, so we /// believe that there is no risk in doing this. Time will tell :) /// </summary> /// <summary> An implementation of interface CharStream, where the stream is assumed to /// contain only ASCII characters (without unicode processing). /// </summary> public sealed class VelocityCharStream : CharStream { public int Column { get { return bufcolumn[bufpos]; } } public int Line { get { return bufline[bufpos]; } } public int EndColumn { get { return bufcolumn[bufpos]; } } public int EndLine { get { return bufline[bufpos]; } } public int BeginColumn { get { return bufcolumn[tokenBegin]; } } public int BeginLine { get { return bufline[tokenBegin]; } } public const bool staticFlag = false; internal int bufsize; internal int available; internal int tokenBegin; public int bufpos = - 1; private int[] bufline; private int[] bufcolumn; private int column = 0; private int line = 1; private bool prevCharIsCR = false; private bool prevCharIsLF = false; private TextReader inputStream; private char[] buffer; private int maxNextCharInd = 0; private int inBuf = 0; private void ExpandBuff(bool wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int[] newbufline = new int[bufsize + 2048]; int[] newbufcolumn = new int[bufsize + 2048]; //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' try { if (wrapAround) { Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); Array.Copy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); Array.Copy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); Array.Copy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Exception t) { throw new ApplicationException(t.Message); } bufsize += 2048; available = bufsize; tokenBegin = 0; } private void FillBuff() { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { // NOTE: java streams return -1 when done // NOTE: java throws java.io.IOException when anything goes wrong - .Net will throw // a System.ObjectDisposedException when the reader is closed try { i = inputStream.Read(buffer, maxNextCharInd, available - maxNextCharInd); } catch (Exception ex) { throw new IOException("exception reading from inputStream", ex); } if (i <= 0) { inputStream.Close(); throw new IOException(); } else maxNextCharInd += i; return; } catch (IOException e) { --bufpos; backup(0); if (tokenBegin == - 1) tokenBegin = bufpos; throw e; } } public char BeginToken() { tokenBegin = - 1; char c = readChar(); tokenBegin = bufpos; return c; } private void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r': prevCharIsCR = true; break; case '\n': prevCharIsLF = true; break; case '\t': column--; column += (8 - (column & 7)); break; default: break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } public char readChar() { if (inBuf > 0) { --inBuf; /* * was : return (char)((char)0xff & buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]); */ return buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); /* * was : char c = (char)((char)0xff & buffer[bufpos]); */ char c = buffer[bufpos]; UpdateLineColumn(c); return (c); } /// <deprecated> /// </deprecated> /// <seealso cref=" #getEndColumn /// /// "/> /// <deprecated> /// </deprecated> /// <seealso cref=" #getEndLine /// /// "/> public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } public VelocityCharStream(TextReader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } public VelocityCharStream(TextReader dstream, int startline, int startcolumn) : this(dstream, startline, startcolumn, 4096) { } public void ReInit(TextReader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.Length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = - 1; } public void ReInit(TextReader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } // TODO - I am still not sure what place regular Streams will play - so I will just stick with Text* streams // public VelocityCharStream(System.IO.Stream dstream, int startline, int startcolumn, int buffersize):this(new System.IO.TextReader(dstream), startline, startcolumn, 4096) { // } // // public VelocityCharStream(System.IO.Stream dstream, int startline, int startcolumn):this(dstream, startline, startcolumn, 4096) { // } // // public void ReInit(System.IO.Stream dstream, int startline, int startcolumn, int buffersize) { // ReInit(new System.IO.TextReader(dstream), startline, startcolumn, 4096); // } // public void ReInit(System.IO.Stream dstream, int startline, int startcolumn) { // ReInit(dstream, startline, startcolumn, 4096); // } public String GetImage() { if (bufpos >= tokenBegin) { Int32 len = (bufpos - tokenBegin + 1) > buffer.Length ? buffer.Length : (bufpos - tokenBegin + 1); //return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); return new String(buffer, tokenBegin, len); } else { return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } } public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) Array.Copy(buffer, bufpos - len + 1, ret, 0, len); else { Array.Copy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); Array.Copy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } public void Done() { buffer = null; bufline = null; bufcolumn = null; } /// <summary> Method to adjust line and column numbers for the start of a token.<BR> /// </summary> public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start%bufsize] == bufline[k = ++start%bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start%bufsize] != bufline[++start%bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } } --- NEW FILE: Token.cs --- /* Generated By:JavaCC: Do not edit this line. Token.java Version 2.1 */ namespace NVelocity.Runtime.Parser { using System; /// <summary> Describes the input token stream. /// </summary> public class Token { /// <summary> An integer that describes the kind of this token. This numbering /// system is determined by JavaCCParser, and a table of these numbers is /// stored in the file ...Constants.java. /// </summary> public int kind; /// <summary> beginLine and beginColumn describe the position of the first character /// of this token; endLine and endColumn describe the position of the /// last character of this token. /// </summary> public int beginLine, beginColumn, endLine, endColumn; /// <summary> The string image of the token. /// </summary> public String image; /// <summary> A reference to the next regular (non-special) token from the input /// stream. If this is the last token from the input stream, or if the /// token manager has not read tokens beyond this one, this field is /// set to null. This is true only if this token is also a regular /// token. Otherwise, see below for a description of the contents of /// this field. /// </summary> public Token next; /// <summary> This field is used to access special tokens that occur prior to this /// token, but after the immediately preceding regular (non-special) token. /// If there are no such special tokens, this field is set to null. /// When there are more than one such special token, this field refers /// to the last of these special tokens, which in turn refers to the next /// previous special token through its specialToken field, and so on /// until the first special token (whose specialToken field is null). /// The next fields of special tokens refer to other special tokens that /// immediately follow it (without an intervening regular token). If there /// is no such token, this field is null. /// </summary> public Token specialToken; /// <summary> Returns the image. /// </summary> public override String ToString() { return image; } /// <summary> Returns a new Token object, by default. However, if you want, you /// can create and return subclass objects based on the value of ofKind. /// Simply add the cases to the switch for all those special cases. /// For example, if you have a subclass of Token called IDToken that /// you want to create if ofKind is ID, simlpy add something like : /// * /// case MyParserConstants.ID : return new IDToken(); /// * /// to the following switch statement. Then you can cast matchedToken /// variable to the appropriate type and use it in your lexical actions. /// </summary> public static Token newToken(int ofKind) { switch (ofKind) { default: return new Token(); } } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Util/Introspection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Util/Introspection Added Files: AmbiguousException.cs ClassMap.cs IntrospectionCacheData.cs Introspector.cs IntrospectorBase.cs MethodMap.cs Twonk.cs Log Message: --- NEW FILE: MethodMap.cs --- namespace NVelocity.Util.Introspection { using System; using System.Collections; using System.Reflection; public class MethodMap { public MethodMap() { } /// <summary> Keep track of all methods with the same name. /// </summary> //UPGRADE_NOTE: The initialization of 'methodByNameMap' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' internal Hashtable methodByNameMap = new Hashtable(); /// <summary> Add a method to a list of methods by name. /// For a particular class we are keeping track /// of all the methods with the same name. /// </summary> public virtual void add(MethodInfo method) { String methodName = method.Name; IList l = (IList) methodByNameMap[methodName]; if (l == null) { l = new ArrayList(); methodByNameMap[methodName] = l; } l.Add(method); return; } /// <summary> Return a list of methods with the same name. /// </summary> /// <param name="String">key /// </param> /// <returns>List list of methods /// /// </returns> public virtual IList get(String key) { return (IList) methodByNameMap[key]; } /// <summary> <p> /// Find a method. Attempts to find the /// most appropriate method using the /// sense of 'specificity'. /// </p> /// /// <p> /// This turns out to be a relatively rare case /// where this is needed - however, functionality /// like this is needed. This may not be the /// optimum approach, but it works. /// </p> /// </summary> /// <param name="String">name of method /// </param> /// <param name="Object[]">params /// </param> /// <returns>Method /// /// </returns> public virtual MethodInfo find(String methodName, Object[] params_Renamed) { IList methodList = (IList) methodByNameMap[methodName]; if (methodList == null) { return null; } Type[] parameterTypes = null; MethodInfo method = null; int numMethods = methodList.Count; int bestDistance = - 2; MethodInfo bestMethod = null; Twonk bestTwonk = null; bool ambiguous = false; for (int i = 0; i < numMethods; i++) { method = (MethodInfo) methodList[i]; parameterTypes = GetMethodParameterTypes(method); /* * The methods we are trying to compare must * the same number of arguments. */ if (parameterTypes.Length == params_Renamed.Length) { /* * use the calling parameters as the baseline * and calculate the 'distance' from the parameters * to the method args. This will be useful when * determining specificity */ Twonk twonk = calcDistance(params_Renamed, parameterTypes); if (twonk != null) { /* * if we don't have anything yet, take it */ if (bestTwonk == null) { bestTwonk = twonk; bestMethod = method; } else { /* * now see which is more specific, this current * versus what we think of as the best candidate */ int val = twonk.moreSpecific(bestTwonk); //System.out.println("Val = " + val + " for " + method + " vs " + bestMethod ); if (val == 0) { /* * this means that the parameters 'crossed' * therefore, it's ambiguous because one is as * good as the other */ ambiguous = true; } else if (val == 1) { /* * the current method is clearly more * specific than the current best, so * we take the current we are testing * and clear the ambiguity flag */ ambiguous = false; bestTwonk = twonk; bestMethod = method; } } } } } /* * if ambiguous is true, it means we couldn't decide * so inform the caller... */ if (ambiguous) { throw new AmbiguousException(); } return bestMethod; } /// <summary> Calculates the distance, expressed as a vector of inheritance /// steps, between the calling args and the method args. /// There still is an issue re interfaces... /// </summary> private Twonk calcDistance(Object[] set, Type[] base_Renamed) { if (set.Length != base_Renamed.Length) return null; Twonk twonk = new Twonk(set.Length); int distance = 0; for (int i = 0; i < set.Length; i++) { /* * can I get from here to there? */ Type setclass = set[i].GetType(); if (!base_Renamed[i].IsAssignableFrom(set[i].GetType())) return null; /* * ok, I can. How many steps? */ Type c = setclass; while (c != null) { /* * is this a valid step? */ if (!base_Renamed[i].IsAssignableFrom(c)) { /* * it stopped being assignable - therefore we are looking at * an interface as our target, so move back one step * from the distance as the stop wasn't valid */ break; } if (base_Renamed[i].Equals(c)) { /* * we are equal, so no need to move forward */ break; } c = c.BaseType; twonk.distance++; twonk.vec[i]++; } } return twonk; } private static Type[] GetMethodParameterTypes(MethodInfo method) { ParameterInfo[] parms = method.GetParameters(); Type[] types = new Type[parms.Length]; for (Int32 i = 0; i < parms.Length; i++) { types[i] = parms[i].ParameterType; } return types; } } } --- NEW FILE: AmbiguousException.cs --- namespace NVelocity.Util.Introspection { using System; /// <summary> simple distinguishable exception, used when /// we run across ambiguous overloading /// </summary> public class AmbiguousException : Exception { } } --- NEW FILE: Introspector.cs --- namespace NVelocity.Util.Introspection { using System; using System.Reflection; using NVelocity.Runtime; /// <summary> This basic function of this class is to return a Method /// object for a particular class given the name of a method /// and the parameters to the method in the form of an Object[] /// /// The first time the Introspector sees a /// class it creates a class method map for the /// class in question. Basically the class method map /// is a Hastable where Method objects are keyed by a /// concatenation of the method name and the names of /// classes that make up the parameters. /// /// For example, a method with the following signature: /// /// public void method(String a, StringBuffer b) /// /// would be mapped by the key: /// /// "method" + "java.lang.String" + "java.lang.StringBuffer" /// /// This mapping is performed for all the methods in a class /// and stored for /// </summary> public class Introspector : IntrospectorBase { /// <summary> define a public string so that it can be looked for /// if interested /// </summary> public const String CACHEDUMP_MSG = "Introspector : detected classloader change. Dumping cache."; /// <summary> our engine runtime services /// </summary> private RuntimeServices rsvc = null; /// <summary> Recieves our RuntimeServices object /// </summary> public Introspector(RuntimeServices r) { this.rsvc = r; } /// <summary> Gets the method defined by <code>name</code> and /// <code>params</code> for the Class <code>c</code>. /// </summary> /// <param name="c">Class in which the method search is taking place /// </param> /// <param name="name">Name of the method being searched for /// </param> /// <param name="params">An array of Objects (not Classes) that describe the /// the parameters /// </param> /// <returns>The desired Method object. /// </returns> public override MethodInfo getMethod(Type c, String name, Object[] params_Renamed) { /* * just delegate to the base class */ try { return base.getMethod(c, name, params_Renamed); } catch (AmbiguousException ae) { /* * whoops. Ambiguous. Make a nice log message and return null... */ String msg = "Introspection Error : Ambiguous method invocation " + name + "( "; for (int i = 0; i < params_Renamed.Length; i++) { if (i > 0) msg = msg + ", "; msg = msg + params_Renamed[i].GetType().FullName; } msg = msg + ") for class " + c; rsvc.error(msg); } return null; } /// <summary> Gets the method defined by <code>name</code> and /// <code>params</code> for the Class <code>c</code>. /// </summary> /// <param name="c">Class in which the method search is taking place /// </param> /// <param name="name">Name of the method being searched for /// </param> /// <param name="params">An array of Objects (not Classes) that describe the /// the parameters /// </param> /// <returns>The desired Method object. /// </returns> public override PropertyInfo getProperty(Type c, String name) { /* * just delegate to the base class */ try { return base.getProperty(c, name); } catch (AmbiguousException ae) { /* * whoops. Ambiguous. Make a nice log message and return null... */ String msg = "Introspection Error : Ambiguous property invocation " + name + " "; msg = msg + " for class " + c; rsvc.error(msg); } return null; } /// <summary> Clears the classmap and classname /// caches, and logs that we did so /// </summary> protected internal override void clearCache() { base.clearCache(); rsvc.info(CACHEDUMP_MSG); } } } --- NEW FILE: Twonk.cs --- namespace NVelocity.Util.Introspection { /// <summary> little class to hold 'distance' information /// for calling params, as well as determine /// specificity /// </summary> internal class Twonk { public int distance; public int[] vec; public Twonk(int size) { vec = new int[size]; } public virtual int moreSpecific(Twonk other) { if (other.vec.Length != vec.Length) return - 1; bool low = false; bool high = false; for (int i = 0; i < vec.Length; i++) { if (vec[i] > other.vec[i]) { high = true; } else if (vec[i] < other.vec[i]) { low = true; } } /* * this is a 'crossing' - meaning that * we saw the parameter 'slopes' cross * this means ambiguity */ if (high && low) return 0; /* * we saw that all args were 'high', meaning * that the other method is more specific so * we are less */ if (high && !low) return - 1; /* * we saw that all points were lower, therefore * we are more specific */ if (!high && low) return 1; /* * the remainder, neither high or low * means we are the same. This really can't * happen, as it implies the same args, right? */ return 1; } } } --- NEW FILE: IntrospectorBase.cs --- namespace NVelocity.Util.Introspection { using System; using System.Collections; using System.Reflection; /// <summary> This basic function of this class is to return a Method /// object for a particular class given the name of a method /// and the parameters to the method in the form of an Object[] /// /// The first time the Introspector sees a /// class it creates a class method map for the /// class in question. Basically the class method map /// is a Hastable where Method objects are keyed by a /// concatenation of the method name and the names of /// classes that make up the parameters. /// /// For example, a method with the following signature: /// /// public void method(String a, StringBuffer b) /// /// would be mapped by the key: /// /// "method" + "java.lang.String" + "java.lang.StringBuffer" /// /// This mapping is performed for all the methods in a class /// and stored for /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:bo...@we...">Bob McWhirter</a> /// </author> /// <author> <a href="mailto:sze...@fr...">Attila Szegedi</a> /// </author> /// <author> <a href="mailto:pau...@kr...">Paulo Gaspar</a> /// </author> /// <version> $Id: IntrospectorBase.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// </version> public class IntrospectorBase { public IntrospectorBase() { } /// <summary> Holds the method maps for the classes we know about, keyed by /// Class object. /// </summary> protected internal Hashtable classMethodMaps = new Hashtable(); /// <summary> Holds the qualified class names for the classes /// we hold in the classMethodMaps hash /// </summary> protected internal IList cachedClassNames = new ArrayList(); /// <summary> Gets the method defined by <code>name</code> and /// <code>params</code> for the Class <code>c</code>. /// </summary> /// <param name="c">Class in which the method search is taking place /// </param> /// <param name="name">Name of the method being searched for /// </param> /// <param name="params">An array of Objects (not Classes) that describe the /// the parameters /// </param> /// <returns>The desired Method object. /// </returns> public virtual MethodInfo getMethod(Type c, String name, Object[] params_Renamed) { if (c == null) { throw new Exception("Introspector.getMethod(): Class method key was null: " + name); } ClassMap classMap = null; lock (classMethodMaps) { classMap = (ClassMap) classMethodMaps[c]; /* * if we don't have this, check to see if we have it * by name. if so, then we have a classloader change * so dump our caches. */ if (classMap == null) { if (cachedClassNames.Contains(c.FullName)) { /* * we have a map for a class with same name, but not * this class we are looking at. This implies a * classloader change, so dump */ clearCache(); } classMap = createClassMap(c); } } return classMap.findMethod(name, params_Renamed); } /// <summary> Gets the method defined by <code>name</code> and /// <code>params</code> for the Class <code>c</code>. /// </summary> /// <param name="c">Class in which the method search is taking place /// </param> /// <param name="name">Name of the method being searched for /// </param> /// <param name="params">An array of Objects (not Classes) that describe the /// the parameters /// </param> /// <returns>The desired Method object. /// </returns> public virtual PropertyInfo getProperty(Type c, String name) { if (c == null) { throw new Exception("Introspector.getMethod(): Class method key was null: " + name); } ClassMap classMap = null; lock (classMethodMaps) { classMap = (ClassMap) classMethodMaps[c]; /* * if we don't have this, check to see if we have it * by name. if so, then we have a classloader change * so dump our caches. */ if (classMap == null) { if (cachedClassNames.Contains(c.FullName)) { /* * we have a map for a class with same name, but not * this class we are looking at. This implies a * classloader change, so dump */ clearCache(); } classMap = createClassMap(c); } } return classMap.findProperty(name); } /// <summary> Creates a class map for specific class and registers it in the /// cache. Also adds the qualified name to the name->class map /// for later Classloader change detection. /// </summary> protected internal virtual ClassMap createClassMap(Type c) { ClassMap classMap = new ClassMap(c); classMethodMaps[c] = classMap; cachedClassNames.Add(c.FullName); return classMap; } /// <summary> Clears the classmap and classname /// caches /// </summary> protected internal virtual void clearCache() { /* * since we are synchronizing on this * object, we have to clear it rather than * just dump it. */ classMethodMaps.Clear(); /* * for speed, we can just make a new one * and let the old one be GC'd */ cachedClassNames = new ArrayList(); } } } --- NEW FILE: ClassMap.cs --- namespace NVelocity.Util.Introspection { using System; using System.Collections; using System.Reflection; using System.Text; /// <summary> A cache of introspection information for a specific class instance. /// Keys {@link java.lang.Method} objects by a concatenation of the /// method name and the names of classes that make up the parameters. /// </summary> public class ClassMap { internal virtual Type CachedClass { get { return clazz; } } private sealed class CacheMiss { } //UPGRADE_NOTE: Final was removed from the declaration of 'CACHE_MISS '. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1003"' private static CacheMiss CACHE_MISS = new CacheMiss(); //UPGRADE_NOTE: Final was removed from the declaration of 'OBJECT '. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1003"' private static Object OBJECT = new Object(); /// /// <summary> Class passed into the constructor used to as /// the basis for the Method map. /// </summary> private Type clazz; /// <summary> Cache of Methods, or CACHE_MISS, keyed by method /// name and actual arguments used to find it. /// </summary> private Hashtable methodCache = new Hashtable(); private Hashtable propertyCache = new Hashtable(); private MethodMap methodMap = new MethodMap(); /// <summary> Standard constructor /// </summary> public ClassMap(Type clazz) { this.clazz = clazz; populateMethodCache(); populatePropertyCache(); } public ClassMap() { } /// <returns>the class object whose methods are cached by this map. /// </returns> /// <summary> Find a Method using the methodKey /// provided. /// /// Look in the methodMap for an entry. If found, /// it'll either be a CACHE_MISS, in which case we /// simply give up, or it'll be a Method, in which /// case, we return it. /// /// If nothing is found, then we must actually go /// and introspect the method from the MethodMap. /// </summary> public virtual System.Reflection.MethodInfo findMethod(String name, Object[] params_Renamed) { String methodKey = makeMethodKey(name, params_Renamed); Object cacheEntry = methodCache[methodKey]; if (cacheEntry == CACHE_MISS) { return null; } if (cacheEntry == null) { try { cacheEntry = methodMap.find(name, params_Renamed); } catch (AmbiguousException ae) { /* * that's a miss :) */ methodCache[methodKey] = CACHE_MISS; throw ae; } if (cacheEntry == null) { methodCache[methodKey] = CACHE_MISS; } else { methodCache[methodKey] = cacheEntry; } } // Yes, this might just be null. return (System.Reflection.MethodInfo) cacheEntry; } /// <summary> Find a Method using the methodKey /// provided. /// /// Look in the methodMap for an entry. If found, /// it'll either be a CACHE_MISS, in which case we /// simply give up, or it'll be a Method, in which /// case, we return it. /// /// If nothing is found, then we must actually go /// and introspect the method from the MethodMap. /// </summary> public virtual PropertyInfo findProperty(String name) { Object cacheEntry = propertyCache[name]; if (cacheEntry == CACHE_MISS) { return null; } // Yes, this might just be null. return (PropertyInfo) cacheEntry; } /// <summary> Populate the Map of direct hits. These /// are taken from all the public methods /// that our class provides. /// </summary> private void populateMethodCache() { StringBuilder methodKey; /* * get all publicly accessible methods */ System.Reflection.MethodInfo[] methods = getAccessibleMethods(clazz); /* * map and cache them */ for (int i = 0; i < methods.Length; i++) { System.Reflection.MethodInfo method = methods[i]; /* * now get the 'public method', the method declared by a * public interface or class. (because the actual implementing * class may be a facade... */ System.Reflection.MethodInfo publicMethod = getPublicMethod(method); /* * it is entirely possible that there is no public method for * the methods of this class (i.e. in the facade, a method * that isn't on any of the interfaces or superclass * in which case, ignore it. Otherwise, map and cache */ if (publicMethod != null) { methodMap.add(publicMethod); methodCache[makeMethodKey(publicMethod)] = publicMethod; } } } private void populatePropertyCache() { StringBuilder methodKey; /* * get all publicly accessible methods */ PropertyInfo[] properties = getAccessibleProperties(clazz); /* * map and cache them */ for (int i = 0; i < properties.Length; i++) { PropertyInfo property = properties[i]; /* * now get the 'public method', the method declared by a * public interface or class. (because the actual implementing * class may be a facade... */ PropertyInfo publicProperty = getPublicProperty(property); /* * it is entirely possible that there is no public method for * the methods of this class (i.e. in the facade, a method * that isn't on any of the interfaces or superclass * in which case, ignore it. Otherwise, map and cache */ if (publicProperty != null) { //propertyMap.add(publicProperty); propertyCache[publicProperty.Name] = publicProperty; } } } /// <summary> Make a methodKey for the given method using /// the concatenation of the name and the /// types of the method parameters. /// </summary> private String makeMethodKey(System.Reflection.MethodInfo method) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Method.getParameterTypes' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' ParameterInfo[] parameterTypes = method.GetParameters(); StringBuilder methodKey = new StringBuilder(method.Name); for (int j = 0; j < parameterTypes.Length; j++) { /* * If the argument type is primitive then we want * to convert our primitive type signature to the * corresponding Object type so introspection for * methods with primitive types will work correctly. */ // TODO: I don't think that this is needed in .Net - boxing will happen and the types will still be available. // if (parameterTypes[j].GetType().IsPrimitive) { // if (parameterTypes[j].Equals(System.Type.GetType("System.Boolean"))) // methodKey.Append("java.lang.Boolean"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Byte"))) // methodKey.Append("java.lang.Byte"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Char"))) // methodKey.Append("java.lang.Character"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Double"))) // methodKey.Append("java.lang.Double"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Single"))) // methodKey.Append("java.lang.Float"); // else { // //UPGRADE_TODO: Field java.lang.Integer.TYPE was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' // if (parameterTypes[j].Equals(typeof(Int32))) // methodKey.Append("System.Int32"); // else { // //UPGRADE_TODO: Field java.lang.Long.TYPE was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' // if (parameterTypes[j].Equals(typeof(Int64))) // methodKey.Append("System.Int64"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Int16"))) // methodKey.Append("System.Int16"); // } // } // } // else { // methodKey.Append(parameterTypes[j].FullName); // } methodKey.Append(parameterTypes[j].ParameterType.FullName); } return methodKey.ToString(); } private static String makeMethodKey(String method, Object[] params_Renamed) { StringBuilder methodKey = new StringBuilder().Append(method); if (params_Renamed != null) { for (int j = 0; j < params_Renamed.Length; j++) { Object arg = params_Renamed[j]; if (arg == null) { arg = OBJECT; } methodKey.Append(arg.GetType().FullName); } } return methodKey.ToString(); } /// <summary> Retrieves public methods for a class. In case the class is not /// public, retrieves methods with same signature as its public methods /// from public superclasses and interfaces (if they exist). Basically /// upcasts every method to the nearest acccessible method. /// </summary> private static System.Reflection.MethodInfo[] getAccessibleMethods(Type clazz) { System.Reflection.MethodInfo[] methods = clazz.GetMethods(); // TODO: the rest of this method is trying to determine what is supposed to be callable - I think .Net just returns what is callable return methods; /* * Short circuit for the (hopefully) majority of cases where the * clazz is public */ //UPGRADE_TODO: Method java.lang.reflect.Modifier.isPublic was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' //UPGRADE_ISSUE: Method 'java.lang.Class.getModifiers' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassgetModifiers"' if (clazz.IsPublic) { return methods; } /* * No luck - the class is not public, so we're going the longer way. */ MethodInfo[] methodInfos = new MethodInfo[methods.Length]; for (int i = methods.Length; i-- > 0; ) { methodInfos[i] = new MethodInfo(methods[i]); } int upcastCount = getAccessibleMethods(clazz, methodInfos, 0); /* * Reallocate array in case some method had no accessible counterpart. */ if (upcastCount < methods.Length) { methods = new System.Reflection.MethodInfo[upcastCount]; } int j = 0; for (int i = 0; i < methodInfos.Length; ++i) { MethodInfo methodInfo = methodInfos[i]; if (methodInfo.upcast) { methods[j++] = methodInfo.method; } } return methods; } private static PropertyInfo[] getAccessibleProperties(Type clazz) { PropertyInfo[] properties = clazz.GetProperties(); //TODO return properties; /* * Short circuit for the (hopefully) majority of cases where the * clazz is public */ if (clazz.IsPublic) { return properties; } /* * No luck - the class is not public, so we're going the longer way. */ properties = new PropertyInfo[0]; return properties; // TODO // MethodInfo[] methodInfos = new MethodInfo[methods.Length]; // // for (int i = methods.Length; i-- > 0; ) { // methodInfos[i] = new MethodInfo(methods[i]); // } // // int upcastCount = getAccessibleMethods(clazz, methodInfos, 0); // // /* // * Reallocate array in case some method had no accessible counterpart. // */ // // if (upcastCount < methods.Length) { // methods = new System.Reflection.MethodInfo[upcastCount]; // } // // int j = 0; // for (int i = 0; i < methodInfos.Length; ++i) { // MethodInfo methodInfo = methodInfos[i]; // if (methodInfo.upcast) { // methods[j++] = methodInfo.method; // } // } // return methods; } /// <summary> /// Recursively finds a match for each method, starting with the class, and then /// searching the superclass and interfaces. /// </summary> /// <param name="clazz">Class to check</param> /// <param name="methodInfos">array of methods we are searching to match</param> /// <param name="upcastCount">current number of methods we have matched</param> /// <returns>count of matched methods</returns> private static int getAccessibleMethods(Type clazz, MethodInfo[] methodInfos, int upcastCount) { int l = methodInfos.Length; /* * if this class is public, then check each of the currently * 'non-upcasted' methods to see if we have a match */ //UPGRADE_TODO: Method java.lang.reflect.Modifier.isPublic was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' //UPGRADE_ISSUE: Method 'java.lang.Class.getModifiers' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassgetModifiers"' if (clazz.IsPublic) { for (int i = 0; i < l && upcastCount < l; ++i) { try { MethodInfo methodInfo = methodInfos[i]; if (!methodInfo.upcast) { methodInfo.tryUpcasting(clazz); upcastCount++; } } catch (MethodAccessException e) { /* * Intentionally ignored - it means * it wasn't found in the current class */ } } /* * Short circuit if all methods were upcast */ if (upcastCount == l) { return upcastCount; } } /* * Examine superclass */ Type superclazz = clazz.BaseType; if (superclazz != null) { upcastCount = getAccessibleMethods(superclazz, methodInfos, upcastCount); /* * Short circuit if all methods were upcast */ if (upcastCount == l) { return upcastCount; } } /* * Examine interfaces. Note we do it even if superclazz == null. * This is redundant as currently java.lang.Object does not implement * any interfaces, however nothing guarantees it will not in future. */ Type[] interfaces = clazz.GetInterfaces(); for (int i = interfaces.Length; i-- > 0; ) { upcastCount = getAccessibleMethods(interfaces[i], methodInfos, upcastCount); /* * Short circuit if all methods were upcast */ if (upcastCount == l) { return upcastCount; } } return upcastCount; } /// <summary> For a given method, retrieves its publicly accessible counterpart. /// This method will look for a method with same name /// and signature declared in a public superclass or implemented interface of this /// method's declaring class. This counterpart method is publicly callable. /// </summary> /// <param name="method">a method whose publicly callable counterpart is requested. /// </param> /// <returns>the publicly callable counterpart method. Note that if the parameter /// method is itself declared by a public class, this method is an identity /// function. /// </returns> public static System.Reflection.MethodInfo getPublicMethod(System.Reflection.MethodInfo method) { Type clazz = method.DeclaringType; //TODO see other todo messages in this class return method; /* * Short circuit for (hopefully the majority of) cases where the declaring * class is public. */ if (clazz.IsPublic) { return method; } return getPublicMethod(clazz, method.Name, GetMethodParameterTypes(method)); } public static PropertyInfo getPublicProperty(PropertyInfo property) { Type clazz = property.DeclaringType; // TODO: return property; /* * Short circuit for (hopefully the majority of) cases where the declaring * class is public. */ if (clazz.IsPublic) { return property; } //TODO return null; // return getPublicMethod(clazz, method.Name, GetMethodParameterTypes(method)); } /// <summary> Looks up the method with specified name and signature in the first public /// superclass or implemented interface of the class. /// </summary> /// <param name="class">the class whose method is sought /// </param> /// <param name="name">the name of the method /// </param> /// <param name="paramTypes">the classes of method parameters /// </param> private static System.Reflection.MethodInfo getPublicMethod(Type clazz, String name, Type[] paramTypes) { /* * if this class is public, then try to get it */ if (clazz.IsPublic) { try { return clazz.GetMethod(name, (Type[]) paramTypes); } catch (MethodAccessException e) { /* * If the class does not have the method, then neither its * superclass nor any of its interfaces has it so quickly return * null. */ return null; } } /* * try the superclass */ Type superclazz = clazz.BaseType; if (superclazz != null) { System.Reflection.MethodInfo superclazzMethod = getPublicMethod(superclazz, name, paramTypes); if (superclazzMethod != null) { return superclazzMethod; } } /* * and interfaces */ Type[] interfaces = clazz.GetInterfaces(); for (int i = 0; i < interfaces.Length; ++i) { System.Reflection.MethodInfo interfaceMethod = getPublicMethod(interfaces[i], name, paramTypes); if (interfaceMethod != null) { return interfaceMethod; } } return null; } /// <summary> Used for the iterative discovery process for public methods. /// </summary> private sealed class MethodInfo { internal System.Reflection.MethodInfo method; internal String name; internal Type[] parameterTypes; internal bool upcast; internal MethodInfo(System.Reflection.MethodInfo method) { this.method = null; name = method.Name; parameterTypes = GetMethodParameterTypes(method); upcast = false; } internal void tryUpcasting(Type clazz) { method = clazz.GetMethod(name, (Type[]) parameterTypes); name = null; parameterTypes = null; upcast = true; } } private static Type[] GetMethodParameterTypes(System.Reflection.MethodInfo method) { ParameterInfo[] parms = method.GetParameters(); Type[] types = new Type[parms.Length]; for (Int32 i = 0; i < parms.Length; i++) { types[i] = parms[i].ParameterType; } return types; } } } --- NEW FILE: IntrospectionCacheData.cs --- namespace NVelocity.Util.Introspection { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Holds information for node-local context data introspection /// information. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: IntrospectionCacheData.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public class IntrospectionCacheData { /// /// <summary> Object to pair with class - currently either a Method or /// AbstractExecutor. It can be used in any way the using node /// wishes. /// </summary> public Object thingy; /* * Class of context data object associated with the introspection * information */ public Type contextData; } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:34
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Util In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Util Added Files: Iterator.cs SimplePool.cs StringUtils.cs Log Message: --- NEW FILE: StringUtils.cs --- namespace NVelocity.Util { using System; using System.Collections; using System.IO; using System.Text; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> This class provides some methods for dynamically /// invoking methods in objects, and some string /// manipulation methods used by torque. The string /// methods will soon be moved into the turbine /// string utilities class. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:dl...@fi...">Daniel Rall</a> /// </author> /// <version> $Id: StringUtils.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public class StringUtils { public StringUtils() { InitBlock(); } private void InitBlock() { //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangSystemgetProperty_javalangString"' EOL = Environment.NewLine; EOL_LENGTH = EOL.Length; } /// <summary> Line separator for the OS we are operating on. /// </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'EOL '. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1003"' //UPGRADE_NOTE: The initialization of 'EOL' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private static String EOL; /// <summary> Length of the line separator. /// </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'EOL_LENGTH '. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1003"' //UPGRADE_NOTE: The initialization of 'EOL_LENGTH' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private static int EOL_LENGTH; /// <summary> Concatenates a list of objects as a String. /// * /// </summary> /// <param name="list">The list of objects to concatenate. /// </param> /// <returns> A text representation of the concatenated objects. /// /// </returns> public virtual String concat(IList list) { StringBuilder sb = new StringBuilder(); int size = list.Count; for (int i = 0; i < size; i++) { sb.Append(list[i].ToString()); } return sb.ToString(); } /// <summary> Return a package name as a relative path name /// * /// </summary> /// <param name="String">package name to convert to a directory. /// </param> /// <returns>String directory path. /// /// </returns> public static String getPackageAsPath(String pckge) { return pckge.Replace('.', Path.DirectorySeparatorChar.ToString()[0]) + Path.DirectorySeparatorChar.ToString(); } /// <summary> <p> /// Remove underscores from a string and replaces first /// letters with capitals. Other letters are changed to lower case. /// </p> /// * /// <p> /// For example <code>foo_bar</code> becomes <code>FooBar</code> /// but <code>foo_barBar</code> becomes <code>FooBarbar</code>. /// </p> /// * /// </summary> /// <param name="data">string to remove underscores from. /// </param> /// <returns>String /// </returns> /// <deprecated>Use the org.apache.commons.util.StringUtils class /// instead. Using its firstLetterCaps() method in conjunction /// with a StringTokenizer will achieve the same result. /// /// </deprecated> public static String removeUnderScores(String data) { String temp = null; StringBuilder out_Renamed = new StringBuilder(); temp = data; SupportClass.Tokenizer st = new SupportClass.Tokenizer(temp, "_"); while (st.HasMoreTokens()) { String element = (String) st.NextToken(); out_Renamed.Append(firstLetterCaps(element)); } return out_Renamed.ToString(); } /// <summary> <p> /// 'Camels Hump' replacement of underscores. /// </p> /// * /// <p> /// Remove underscores from a string but leave the capitalization of the /// other letters unchanged. /// </p> /// * /// <p> /// For example <code>foo_barBar</code> becomes <code>FooBarBar</code>. /// </p> /// * /// </summary> /// <param name="data">string to hump /// </param> /// <returns>String /// /// </returns> public static String removeAndHump(String data) { return removeAndHump(data, "_"); } /// <summary> <p> /// 'Camels Hump' replacement. /// </p> /// * /// <p> /// Remove one string from another string but leave the capitalization of the /// other letters unchanged. /// </p> /// * /// <p> /// For example, removing "_" from <code>foo_barBar</code> becomes <code>FooBarBar</code>. /// </p> /// * /// </summary> /// <param name="data">string to hump /// </param> /// <param name="replaceThis">string to be replaced /// </param> /// <returns>String /// /// </returns> public static String removeAndHump(String data, String replaceThis) { String temp = null; StringBuilder out_Renamed = new StringBuilder(); temp = data; SupportClass.Tokenizer st = new SupportClass.Tokenizer(temp, replaceThis); while (st.HasMoreTokens()) { String element = (String) st.NextToken(); out_Renamed.Append(capitalizeFirstLetter(element)); } //while return out_Renamed.ToString(); } /// <summary> <p> /// Makes the first letter caps and the rest lowercase. /// </p> /// * /// <p> /// For example <code>fooBar</code> becomes <code>Foobar</code>. /// </p> /// * /// </summary> /// <param name="data">capitalize this /// </param> /// <returns>String /// /// </returns> public static String firstLetterCaps(String data) { String firstLetter = data.Substring(0, (1) - (0)).ToUpper(); String restLetters = data.Substring(1).ToLower(); return firstLetter + restLetters; } /// <summary> <p> /// Capitalize the first letter but leave the rest as they are. /// </p> /// * /// <p> /// For example <code>fooBar</code> becomes <code>FooBar</code>. /// </p> /// * /// </summary> /// <param name="data">capitalize this /// </param> /// <returns>String /// /// </returns> public static String capitalizeFirstLetter(String data) { String firstLetter = data.Substring(0, (1) - (0)).ToUpper(); String restLetters = data.Substring(1); return firstLetter + restLetters; } /// <summary> Create a string array from a string separated by delim /// * /// </summary> /// <param name="line">the line to split /// </param> /// <param name="delim">the delimter to split by /// </param> /// <returns>a string array of the split fields /// /// </returns> public static String[] split(String line, String delim) { ArrayList list = new ArrayList(); SupportClass.Tokenizer t = new SupportClass.Tokenizer(line, delim); while (t.HasMoreTokens()) { list.Add(t.NextToken()); } return (String[]) list.ToArray(typeof (String)); } /// <summary> Chop i characters off the end of a string. /// This method assumes that any EOL characters in String s /// and the platform EOL will be the same. /// A 2 character EOL will count as 1 character. /// * /// </summary> /// <param name="string">String to chop. /// </param> /// <param name="i">Number of characters to chop. /// </param> /// <returns>String with processed answer. /// /// </returns> public static String chop(String s, int i) { return chop(s, i, EOL); } /// <summary> Chop i characters off the end of a string. /// A 2 character EOL will count as 1 character. /// * /// </summary> /// <param name="string">String to chop. /// </param> /// <param name="i">Number of characters to chop. /// </param> /// <param name="eol">A String representing the EOL (end of line). /// </param> /// <returns>String with processed answer. /// /// </returns> public static String chop(String s, int i, String eol) { if (i == 0 || s == null || eol == null) { return s; } int length = s.Length; /* * if it is a 2 char EOL and the string ends with * it, nip it off. The EOL in this case is treated like 1 character */ if (eol.Length == 2 && s.EndsWith(eol)) { length -= 2; i -= 1; } if (i > 0) { length -= i; } if (length < 0) { length = 0; } return s.Substring(0, (length) - (0)); } // public static System.Text.StringBuilder stringSubstitution(System.String argStr, System.Collections.Hashtable vars) // { // return stringSubstitution(argStr, (Map) vars); // } /// <summary> Perform a series of substitutions. The substitions /// are performed by replacing $variable in the target /// string with the value of provided by the key "variable" /// in the provided hashtable. /// * /// </summary> /// <param name="String">target string /// </param> /// <param name="Hashtable">name/value pairs used for substitution /// </param> /// <returns>String target string with replacements. /// /// </returns> public static StringBuilder stringSubstitution(String argStr, Hashtable vars) { StringBuilder argBuf = new StringBuilder(); for (int cIdx = 0; cIdx < argStr.Length; ) { char ch = argStr[cIdx]; switch (ch) { case '$': StringBuilder nameBuf = new StringBuilder(); for (++cIdx; cIdx < argStr.Length; ++cIdx) { ch = argStr[cIdx]; if (ch == '_' || Char.IsLetterOrDigit(ch)) nameBuf.Append(ch); else break; } if (nameBuf.Length > 0) { String value_Renamed = (String) vars[nameBuf.ToString()]; if (value_Renamed != null) { argBuf.Append(value_Renamed); } } break; default: argBuf.Append(ch); ++cIdx; break; } } return argBuf; } /// <summary> Read the contents of a file and place them in /// a string object. /// * /// </summary> /// <param name="String">path to file. /// </param> /// <returns>String contents of the file. /// /// </returns> public static String fileContentsToString(String file) { String contents = ""; FileInfo f = new FileInfo(file); bool tmpBool; if (File.Exists(f.FullName)) tmpBool = true; else tmpBool = Directory.Exists(f.FullName); if (tmpBool) { try { StreamReader fr = new StreamReader(f.FullName); char[] template = new char[(int) SupportClass.FileLength(f)]; fr.Read((Char[]) template, 0, template.Length); contents = new String(template); fr.Close(); } catch (Exception e) { Console.Out.WriteLine(e); SupportClass.WriteStackTrace(e, Console.Error); } } return contents; } /// <summary> Remove/collapse multiple newline characters. /// * /// </summary> /// <param name="String">string to collapse newlines in. /// </param> /// <returns>String /// /// </returns> public static String collapseNewlines(String argStr) { char last = argStr[0]; StringBuilder argBuf = new StringBuilder(); for (int cIdx = 0; cIdx < argStr.Length; cIdx++) { char ch = argStr[cIdx]; if (ch != '\n' || last != '\n') { argBuf.Append(ch); last = ch; } } return argBuf.ToString(); } /// <summary> Remove/collapse multiple spaces. /// * /// </summary> /// <param name="String">string to remove multiple spaces from. /// </param> /// <returns>String /// /// </returns> public static String collapseSpaces(String argStr) { char last = argStr[0]; StringBuilder argBuf = new StringBuilder(); for (int cIdx = 0; cIdx < argStr.Length; cIdx++) { char ch = argStr[cIdx]; if (ch != ' ' || last != ' ') { argBuf.Append(ch); last = ch; } } return argBuf.ToString(); } /// <summary> Replaces all instances of oldString with newString in line. /// Taken from the Jive forum package. /// * /// </summary> /// <param name="String">original string. /// </param> /// <param name="String">string in line to replace. /// </param> /// <param name="String">replace oldString with this. /// </param> /// <returns>String string with replacements. /// /// </returns> public static String sub(String line, String oldString, String newString) { int i = 0; if ((i = line.IndexOf(oldString, i)) >= 0) { char[] line2 = line.ToCharArray(); char[] newString2 = newString.ToCharArray(); int oLength = oldString.Length; StringBuilder buf = new StringBuilder(line2.Length); buf.Append(line2, 0, i).Append(newString2); i += oLength; int j = i; while ((i = line.IndexOf(oldString, i)) > 0) { buf.Append(line2, j, i - j).Append(newString2); i += oLength; j = i; } buf.Append(line2, j, line2.Length - j); return buf.ToString(); } return line; } /// <summary> Returns the output of printStackTrace as a String. /// * /// </summary> /// <param name="e">A Throwable. /// </param> /// <returns>A String. /// /// </returns> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' public static String stackTrace(Exception e) { String foo = null; try { // And show the Error Screen. MemoryStream ostr = new MemoryStream(); StreamWriter temp_writer; temp_writer = new StreamWriter(ostr); temp_writer.AutoFlush = true; SupportClass.WriteStackTrace(e, temp_writer); char[] tmpChar; byte[] tmpByte; tmpByte = ostr.GetBuffer(); tmpChar = new char[tmpByte.Length]; tmpByte.CopyTo(tmpChar, 0); foo = new String(tmpChar); } catch (Exception f) { // Do nothing. } return foo; } /// <summary> Return a context-relative path, beginning with a "/", that represents /// the canonical version of the specified path after ".." and "." elements /// are resolved out. If the specified path attempts to go outside the /// boundaries of the current context (i.e. too many ".." path elements /// are present), return <code>null</code> instead. /// * /// </summary> /// <param name="path">Path to be normalized /// </param> /// <returns>String normalized path /// /// </returns> public static String normalizePath(String path) { // Normalize the slashes and add leading slash if necessary String normalized = path; if (normalized.IndexOf((Char) '\\') >= 0) { normalized = normalized.Replace('\\', '/'); } if (!normalized.StartsWith("/")) { normalized = "/" + normalized; } // Resolve occurrences of "//" in the normalized path while (true) { int index = normalized.IndexOf("//"); if (index < 0) break; normalized = normalized.Substring(0, (index) - (0)) + normalized.Substring(index + 1); } // Resolve occurrences of "%20" in the normalized path while (true) { int index = normalized.IndexOf("%20"); if (index < 0) break; normalized = normalized.Substring(0, (index) - (0)) + " " + normalized.Substring(index + 3); } // Resolve occurrences of "/./" in the normalized path while (true) { int index = normalized.IndexOf("/./"); if (index < 0) break; normalized = normalized.Substring(0, (index) - (0)) + normalized.Substring(index + 2); } // Resolve occurrences of "/../" in the normalized path while (true) { int index = normalized.IndexOf("/../"); if (index < 0) break; if (index == 0) return (null); // Trying to go outside our context int index2 = normalized.LastIndexOf((Char) '/', index - 1); normalized = normalized.Substring(0, (index2) - (0)) + normalized.Substring(index + 3); } // Return the normalized path that we have completed return (normalized); } /// <summary> If state is true then return the trueString, else /// return the falseString. /// * /// </summary> /// <param name="boolean"> /// </param> /// <param name="String">trueString /// </param> /// <param name="String">falseString /// /// </param> public virtual String select(bool state, String trueString, String falseString) { if (state) { return trueString; } else { return falseString; } } /// <summary> Check to see if all the string objects passed /// in are empty. /// * /// </summary> /// <param name="list">A list of {@link java.lang.String} objects. /// </param> /// <returns> Whether all strings are empty. /// /// </returns> public virtual bool allEmpty(IList list) { int size = list.Count; for (int i = 0; i < size; i++) { if (list[i] != null && list[i].ToString().Length > 0) { return false; } } return true; } } } --- NEW FILE: SimplePool.cs --- namespace NVelocity.Util { using System; /* * $Header: /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Util/SimplePool.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ * $Revision: 1.3 $ * $Date: 2005/11/16 05:45:24 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * [Additional notices, if required by prior licensing conditions] * */ /// <summary> Simple object pool. Based on ThreadPool and few other classes /// * /// The pool will ignore overflow and return null if empty. /// * /// </summary> /// <author> Gal Shachor /// </author> /// <author> Costin /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: SimplePool.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public sealed class SimplePool { public int Max { get { return max; } } /* * Where the objects are held. */ private Object[] pool; /// <summary> max amount of objects to be managed /// set via CTOR /// </summary> private int max; /// <summary> index of previous to next /// free slot /// </summary> private int current = - 1; public SimplePool(int max) { this.max = max; pool = new Object[max]; } /// <summary> Add the object to the pool, silent nothing if the pool is full /// </summary> public void put(Object o) { int idx = - 1; lock (this) { /* * if we aren't full */ if (current < max - 1) { /* * then increment the * current index. */ idx = ++current; } if (idx >= 0) { pool[idx] = o; } } } /// <summary> Get an object from the pool, null if the pool is empty. /// </summary> public Object get() { int idx = - 1; lock (this) { /* * if we have any in the pool */ if (current >= 0) { /* * take one out, so to speak - * separate the two operations * to make it clear that you * don't want idx = --current; :) */ idx = current; current--; /* * and since current was >= 0 * to get in here, idx must be as well * so save the if() opration */ return pool[idx]; } } return null; } /// <summary>Return the size of the pool /// </summary> } } --- NEW FILE: Iterator.cs --- namespace NVelocity.Util { using System; public interface Iterator { /// <summary> Move to next element in the array. /// </summary> /// <returns>The next object in the array. /// </returns> Object next(); /// <summary> Check to see if there is another element in the array. /// </summary> /// <returns>Whether there is another element. /// </returns> bool hasNext(); } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/App Added Files: AppSupportClass.cs FieldMethodizer.cs Velocity.cs VelocityEngine.cs Log Message: --- NEW FILE: AppSupportClass.cs --- using System; public class AppSupportClass { public class TextNumberFormat { // Declaration of fields private System.Globalization.NumberFormatInfo numberFormat; private enum formatTypes { General, Number, Currency, Percent }; private int numberFormatType; private bool groupingActivated; private string separator; private int digits; // CONSTRUCTORS public TextNumberFormat() { this.numberFormat = new System.Globalization.NumberFormatInfo(); this.numberFormatType = (int)TextNumberFormat.formatTypes.General; this.groupingActivated = true; this.separator = this.GetSeparator( (int)TextNumberFormat.formatTypes.General ); this.digits = 3; } private TextNumberFormat(TextNumberFormat.formatTypes theType, int digits) { this.numberFormat = System.Globalization.NumberFormatInfo.CurrentInfo; this.numberFormatType = (int)theType; this.groupingActivated = true; this.separator = this.GetSeparator( (int)theType ); this.digits = digits; } private TextNumberFormat(TextNumberFormat.formatTypes theType, System.Globalization.CultureInfo cultureNumberFormat, int digits) { this.numberFormat = cultureNumberFormat.NumberFormat; this.numberFormatType = (int)theType; this.groupingActivated = true; this.separator = this.GetSeparator( (int)theType ); this.digits = digits; } public static TextNumberFormat getTextNumberInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Number, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Currency, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Percent, 3); return instance; } public static TextNumberFormat getTextNumberInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Number, culture, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Currency, culture, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Percent, culture, 3); return instance; } public System.Object Clone() { return (System.Object)this; } public override bool Equals(System.Object textNumberObject) { return System.Object.Equals((System.Object)this, textNumberObject); } public string FormatDouble(double number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat)).Replace(this.separator,""); } } public string FormatLong(long number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat)).Replace(this.separator,""); } } public static System.Globalization.CultureInfo[] GetAvailableCultures() { return System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures); } public override int GetHashCode() { return this.GetHashCode(); } private string GetCurrentFormatString() { string currentFormatString = "n"; //Default value switch (this.numberFormatType) { case (int)TextNumberFormat.formatTypes.Currency: currentFormatString = "c"; break; case (int)TextNumberFormat.formatTypes.General: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int)TextNumberFormat.formatTypes.Number: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int)TextNumberFormat.formatTypes.Percent: currentFormatString = "p"; break; } return currentFormatString; } private string GetSeparator(int numberFormatType) { string separatorItem = " "; //Default Separator switch (numberFormatType) { case (int)TextNumberFormat.formatTypes.Currency: separatorItem = this.numberFormat.CurrencyGroupSeparator; break; case (int)TextNumberFormat.formatTypes.General: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int)TextNumberFormat.formatTypes.Number: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int)TextNumberFormat.formatTypes.Percent: separatorItem = this.numberFormat.PercentGroupSeparator; break; } return separatorItem; } public bool GroupingUsed { get { return (this.groupingActivated); } set { this.groupingActivated = value; } } public int Digits { get { return this.digits; } set { this.digits = value; } } } /*******************************/ public class DateTimeFormatManager { static public DateTimeFormatHashTable manager = new DateTimeFormatHashTable(); public class DateTimeFormatHashTable :System.Collections.Hashtable { public void SetDateFormatPattern(System.Globalization.DateTimeFormatInfo format, System.String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).DateFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.DateFormatPattern = newPattern; Add(format, tempProps); } } public string GetDateFormatPattern(System.Globalization.DateTimeFormatInfo format) { if (this[format] == null) return "d-MMM-yy"; else return ((DateTimeFormatProperties) this[format]).DateFormatPattern; } public void SetTimeFormatPattern(System.Globalization.DateTimeFormatInfo format, System.String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).TimeFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.TimeFormatPattern = newPattern; Add(format, tempProps); } } public string GetTimeFormatPattern(System.Globalization.DateTimeFormatInfo format) { if (this[format] == null) return "h:mm:ss tt"; else return ((DateTimeFormatProperties) this[format]).TimeFormatPattern; } class DateTimeFormatProperties { public string DateFormatPattern = "d-MMM-yy"; public string TimeFormatPattern = "h:mm:ss tt"; } } } /*******************************/ public static string FormatDateTime(System.Globalization.DateTimeFormatInfo format, System.DateTime date) { string timePattern = DateTimeFormatManager.manager.GetTimeFormatPattern(format); string datePattern = DateTimeFormatManager.manager.GetDateFormatPattern(format); return date.ToString(datePattern + " " + timePattern, format); } /*******************************/ public static System.Globalization.DateTimeFormatInfo GetDateTimeFormatInstance(int dateStyle, int timeStyle, System.Globalization.CultureInfo culture) { System.Globalization.DateTimeFormatInfo format = culture.DateTimeFormat; switch (timeStyle) { case -1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss 'o clock' tt zzz"); break; case 1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt zzz"); break; case 2: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt"); break; case 3: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm tt"); break; } switch (dateStyle) { case -1: DateTimeFormatManager.manager.SetDateFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetDateFormatPattern(format, "dddd, MMMM dd%, yyy"); break; case 1: DateTimeFormatManager.manager.SetDateFormatPattern(format, "MMMM dd%, yyy" ); break; case 2: DateTimeFormatManager.manager.SetDateFormatPattern(format, "d-MMM-yy" ); break; case 3: DateTimeFormatManager.manager.SetDateFormatPattern(format, "M/dd/yy"); break; } return format; } } --- NEW FILE: Velocity.cs --- namespace NVelocity.App { using System; using System.IO; using System.Text; using Commons.Collections; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// This class provides services to the application /// developer, such as : /// <ul> /// <li> Simple Velocity Runtime engine initialization methods. /// <li> Functions to apply the template engine to streams and strings /// to allow embedding and dynamic template generation. /// <li> Methods to access Velocimacros directly. /// </ul> /// <br><br> /// While the most common way to use NVelocity is via templates, as /// Velocity is a general-purpose template engine, there are other /// uses that NVelocity is well suited for, such as processing dynamically /// created templates, or processing content streams. /// <br><br> /// The methods herein were developed to allow easy access to the NVelocity /// facilities without direct spelunking of the internals. If there is /// something you feel is necessary to add here, please, send a patch. /// </summary> public class Velocity : RuntimeConstants { /// <summary> /// initialize the NVelocity runtime engine, using the default /// properties of the NVelocity distribution /// </summary> public static void Init() { RuntimeSingleton.init(); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the properties file passed in as the arg /// </summary> /// <param name="propsFilename"> /// file containing properties to use to initialize /// the Velocity runtime /// </param> public static void Init(String propsFilename) { RuntimeSingleton.init(propsFilename); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the passed in java.util.Properties object /// </summary> /// <param name="p"> /// Proprties object containing initialization properties /// </param> public static void Init(ExtendedProperties p) { RuntimeSingleton.init(p); } /// <summary> /// Set a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public static void SetProperty(String key, Object value_Renamed) { RuntimeSingleton.setProperty(key, value_Renamed); } /// <summary> /// Add a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public static void AddProperty(String key, Object value_Renamed) { RuntimeSingleton.addProperty(key, value_Renamed); } /// <summary> /// Clear a NVelocity Runtime property. /// </summary> /// <param name="key">of property to clear</param> public static void ClearProperty(String key) { RuntimeSingleton.clearProperty(key); } /// <summary> /// Set an entire configuration at once. This is /// useful in cases where the parent application uses /// the ExtendedProperties class and the velocity configuration /// is a subset of the parent application's configuration. /// </summary> /// <param name="ExtendedProperties">configuration</param> public static ExtendedProperties ExtendedProperties { set { RuntimeSingleton.Configuration = value; } } /// <summary> /// Get a Velocity Runtime property. /// </summary> /// <param name="key">property to retrieve</param> /// <returns>property value or null if the property not currently set</returns> public static Object GetProperty(String key) { return RuntimeSingleton.getProperty(key); } /// <summary> /// renders the input string using the context into the output writer. /// To be used when a template is dynamically constructed, or want to use /// Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log /// messages in case of error /// </param> /// <param name="instring">input string containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> public static bool Evaluate(IContext context, TextWriter out_Renamed, String logTag, String instring) { return Evaluate(context, out_Renamed, logTag, new StringReader(instring)); } /// <summary> /// Renders the input stream using the context into the output writer. /// To be used when a template is dynamically constructed, or want to /// use Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="instream">input stream containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> /// <deprecated>Use /// {@link #evaluate( Context context, Writer writer, /// String logTag, Reader reader ) } /// </deprecated> public static bool Evaluate(IContext context, TextWriter writer, String logTag, Stream instream) { /* * first, parse - convert ParseException if thrown */ TextReader reader = null; String encoding = null; try { encoding = RuntimeSingleton.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT); reader = new StreamReader(new StreamReader(instream, Encoding.GetEncoding(encoding)).BaseStream); } catch (IOException uce) { String msg = "Unsupported input encoding : " + encoding + " for template " + logTag; throw new ParseErrorException(msg); } return Evaluate(context, writer, logTag, reader); } /// <summary> /// Renders the input reader using the context into the output writer. /// To be used when a template is dynamically constructed, or want to /// use Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string</param> /// <param name="out"> Writer in which to render the output</param> /// <param name="logTag"> string to be used as the template name for log messages in case of error</param> /// <param name="reader">Reader containing the VTL to be rendered</param> /// <returns>true if successful, false otherwise. If false, see Velocity runtime log</returns> public static bool Evaluate(IContext context, TextWriter writer, String logTag, TextReader reader) { SimpleNode nodeTree = null; try { nodeTree = RuntimeSingleton.parse(reader, logTag); } catch (ParseException pex) { throw new ParseErrorException(pex.Message); } /* * now we want to init and render */ if (nodeTree != null) { InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context); ica.PushCurrentTemplateName(logTag); try { try { nodeTree.init(ica, RuntimeSingleton.RuntimeServices); } catch (Exception e) { RuntimeSingleton.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e); } /* * now render, and let any exceptions fly */ nodeTree.render(ica, writer); } finally { ica.PopCurrentTemplateName(); } return true; } return false; } /// <summary> /// Invokes a currently registered Velocimacro with the parms provided /// and places the rendered stream into the writer. /// <br> /// Note : currently only accepts args to the VM if they are in the context. /// </summary> /// <param name="vmName">name of Velocimacro to call /// </param> /// <param name="logTag">string to be used for template name in case of error /// </param> /// <param name="params[]">args used to invoke Velocimacro. In context key format : /// eg "foo","bar" (rather than "$foo","$bar") /// </param> /// <param name="context">Context object containing data/objects used for rendering. /// </param> /// <param name="writer"> Writer for output stream /// </param> /// <returns>true if Velocimacro exists and successfully invoked, false otherwise. /// </returns> public static bool InvokeVelocimacro(String vmName, String logTag, String[] params_Renamed, IContext context, TextWriter writer) { /* * check parms */ if (vmName == null || params_Renamed == null || context == null || writer == null || logTag == null) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : invalid parameter"); return false; } /* * does the VM exist? */ if (!RuntimeSingleton.isVelocimacro(vmName, logTag)) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : VM '" + vmName + "' not registered."); return false; } /* * now just create the VM call, and use evaluate */ StringBuilder construct = new StringBuilder("#"); construct.Append(vmName); construct.Append("("); for (int i = 0; i < params_Renamed.Length; i++) { construct.Append(" $"); construct.Append(params_Renamed[i]); } construct.Append(" )"); try { bool retval = Evaluate(context, writer, logTag, construct.ToString()); return retval; } catch (Exception e) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : error " + e); } return false; } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log. /// </returns> /// <deprecated>Use /// {@link #mergeTemplate( String templateName, String encoding, /// Context context, Writer writer )} /// </deprecated> public static bool MergeTemplate(String templateName, IContext context, TextWriter writer) { return MergeTemplate(templateName, RuntimeSingleton.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT), context, writer); } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="encoding">encoding used in template /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log /// @since Velocity v1.1 /// </returns> public static bool MergeTemplate(String templateName, String encoding, IContext context, TextWriter writer) { Template template = RuntimeSingleton.getTemplate(templateName, encoding); if (template == null) { RuntimeSingleton.error("Velocity.parseTemplate() failed loading template '" + templateName + "'"); return false; } else { template.Merge(context, writer); return true; } } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// </returns> public static Template GetTemplate(String name) { return RuntimeSingleton.getTemplate(name); } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <param name="encoding">The character encoding to use for the template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// @since Velocity v1.1 /// </returns> public static Template GetTemplate(String name, String encoding) { return RuntimeSingleton.getTemplate(name, encoding); } /// <summary> /// Determines if a template is accessable via the currently /// configured resource loaders. /// <br><br> /// Note that the current implementation will <b>not</b> /// change the state of the system in any real way - so this /// cannot be used to pre-load the resource cache, as the /// previous implementation did as a side-effect. /// <br><br> /// The previous implementation exhibited extreme lazyness and /// sloth, and the author has been flogged. /// </summary> /// <param name="templateName"> name of the temlpate to search for /// </param> /// <returns>true if found, false otherwise /// </returns> public static bool TemplateExists(String templateName) { return (RuntimeSingleton.getLoaderNameForResource(templateName) != null); } /// <summary> /// Log a warning message. /// </summary> /// <param name="Object">message to log /// </param> public static void Warn(Object message) { RuntimeSingleton.warn(message); } /// <summary> /// Log an info message. /// </summary> /// <param name="Object">message to log</param> public static void Info(Object message) { RuntimeSingleton.info(message); } /// <summary> /// Log an error message. /// </summary> /// <param name="Object">message to log</param> public static void Error(Object message) { RuntimeSingleton.error(message); } /// <summary> /// Log a debug message. /// </summary> /// <param name="Object">message to log</param> public static void Debug(Object message) { RuntimeSingleton.debug(message); } /// <summary> /// <p> /// Set the an ApplicationAttribue, which is an Object /// set by the application which is accessable from /// any component of the system that gets a RuntimeServices. /// This allows communication between the application /// environment and custom pluggable components of the /// Velocity engine, such as loaders and loggers. /// </p> /// <p> /// Note that there is no enfocement or rules for the key /// used - it is up to the application developer. However, to /// help make the intermixing of components possible, using /// the target Class name (e.g. com.foo.bar ) as the key /// might help avoid collision. /// </p> /// </summary> /// <param name="key">object 'name' under which the object is stored /// </param> /// <param name="value">object to store under this key /// </param> public static void SetApplicationAttribute(Object key, Object value_Renamed) { RuntimeSingleton.RuntimeInstance.setApplicationAttribute(key, value_Renamed); } } } --- NEW FILE: VelocityEngine.cs --- namespace NVelocity.App { using System; using System.IO; using System.Text; using Commons.Collections; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// <p> /// This class provides a separate new-able instance of the /// Velocity template engine. The alternative model for use /// is using the Velocity class which employs the singleton /// model. /// </p> /// <p> /// Please ensure that you call one of the init() variants. /// This is critical for proper behavior. /// </p> /// <p> Coming soon : Velocity will call /// the parameter-less init() at the first use of this class /// if the init() wasn't explicitly called. While this will /// ensure that Velocity functions, it almost certainly won't /// function in the way you intend, so please make sure to /// call init(). /// </p> /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> public class VelocityEngine : RuntimeConstants { private RuntimeInstance ri = new RuntimeInstance(); public VelocityEngine() { } /// <summary> /// Set an entire configuration at once. This is /// useful in cases where the parent application uses /// the ExtendedProperties class and the velocity configuration /// is a subset of the parent application's configuration. /// </summary> /// <param name="ExtendedProperties">configuration /// </param> public virtual ExtendedProperties ExtendedProperties { set { ri.Configuration = value; } } /// <summary> /// initialize the Velocity runtime engine, using the default /// properties of the Velocity distribution /// </summary> public virtual void Init() { ri.init(); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the properties file passed in as the arg /// </summary> /// <param name="propsFilename">file containing properties to use to initialize /// the Velocity runtime</param> public virtual void Init(String propsFilename) { ri.init(propsFilename); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the passed in java.util.Properties object /// </summary> /// <param name="p"> Proprties object containing initialization properties</param> public virtual void Init(ExtendedProperties p) { ri.init(p); } /// <summary> /// Set a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public virtual void SetProperty(String key, Object value_Renamed) { ri.setProperty(key, value_Renamed); } /// <summary> /// Add a Velocity Runtime property. /// </summary> /// <param name="String">key /// </param> /// <param name="Object">value /// </param> public virtual void AddProperty(String key, Object value_Renamed) { ri.addProperty(key, value_Renamed); } /// <summary> /// Clear a Velocity Runtime property. /// </summary> /// <param name="key">of property to clear /// </param> public virtual void ClearProperty(String key) { ri.clearProperty(key); } /// <summary> /// Get a Velocity Runtime property. /// </summary> /// <param name="key">property to retrieve /// </param> /// <returns>property value or null if the property /// not currently set /// </returns> public virtual Object GetProperty(String key) { return ri.getProperty(key); } /// <summary> /// renders the input string using the context into the output writer. /// To be used when a template is dynamically constructed, or want to use /// Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log /// messages in case of error /// </param> /// <param name="instring">input string containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> public virtual bool Evaluate(IContext context, TextWriter out_Renamed, String logTag, String instring) { return Evaluate(context, out_Renamed, logTag, new StringReader(instring)); } /// <summary> /// Renders the input stream using the context into the output writer. /// To be used when a template is dynamically constructed, or want to /// use Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="instream">input stream containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> /// <deprecated>Use /// {@link #evaluate( Context context, Writer writer, /// String logTag, Reader reader ) } /// </deprecated> public virtual bool Evaluate(IContext context, TextWriter writer, String logTag, Stream instream) { /* * first, parse - convert ParseException if thrown */ TextReader br = null; String encoding = null; try { encoding = ri.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT); br = new StreamReader(new StreamReader(instream, Encoding.GetEncoding(encoding)).BaseStream); } catch (IOException uce) { String msg = "Unsupported input encoding : " + encoding + " for template " + logTag; throw new ParseErrorException(msg); } return Evaluate(context, writer, logTag, br); } /// <summary> /// Renders the input reader using the context into the output writer. /// To be used when a template is dynamically constructed, or want to /// use Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="reader">Reader containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// @since Velocity v1.1 /// </returns> public virtual bool Evaluate(IContext context, TextWriter writer, String logTag, TextReader reader) { SimpleNode nodeTree = null; try { nodeTree = ri.parse(reader, logTag); } catch (ParseException pex) { throw new ParseErrorException(pex.Message); } /* * now we want to init and render */ if (nodeTree != null) { InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context); ica.PushCurrentTemplateName(logTag); try { try { nodeTree.init(ica, ri); } catch (Exception e) { ri.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e); } /* * now render, and let any exceptions fly */ nodeTree.render(ica, writer); } finally { ica.PopCurrentTemplateName(); } return true; } return false; } /// <summary> /// Invokes a currently registered Velocimacro with the parms provided /// and places the rendered stream into the writer. /// Note : currently only accepts args to the VM if they are in the context. /// </summary> /// <param name="vmName">name of Velocimacro to call /// </param> /// <param name="logTag">string to be used for template name in case of error /// </param> /// <param name="params[]">args used to invoke Velocimacro. In context key format : /// eg "foo","bar" (rather than "$foo","$bar") /// </param> /// <param name="context">Context object containing data/objects used for rendering. /// </param> /// <param name="writer"> Writer for output stream /// </param> /// <returns>true if Velocimacro exists and successfully invoked, false otherwise. /// </returns> public virtual bool InvokeVelocimacro(String vmName, String logTag, String[] params_Renamed, IContext context, TextWriter writer) { /* * check parms */ if (vmName == null || params_Renamed == null || context == null || writer == null || logTag == null) { ri.error("VelocityEngine.invokeVelocimacro() : invalid parameter"); return false; } /* * does the VM exist? */ if (!ri.isVelocimacro(vmName, logTag)) { ri.error("VelocityEngine.invokeVelocimacro() : VM '" + vmName + "' not registered."); return false; } /* * now just create the VM call, and use evaluate */ StringBuilder construct = new StringBuilder("#"); construct.Append(vmName); construct.Append("("); for (int i = 0; i < params_Renamed.Length; i++) { construct.Append(" $"); construct.Append(params_Renamed[i]); } construct.Append(" )"); try { bool retval = Evaluate(context, writer, logTag, construct.ToString()); return retval; } catch (Exception e) { ri.error("VelocityEngine.invokeVelocimacro() : error " + e); throw e; } } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log. /// </returns> /// <deprecated>Use /// {@link #mergeTemplate( String templateName, String encoding, /// Context context, Writer writer )} /// </deprecated> public virtual bool MergeTemplate(String templateName, IContext context, TextWriter writer) { return MergeTemplate(templateName, ri.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT), context, writer); } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="encoding">encoding used in template /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log /// @since Velocity v1.1 /// </returns> public virtual bool MergeTemplate(String templateName, String encoding, IContext context, TextWriter writer) { Template template = ri.getTemplate(templateName, encoding); if (template == null) { ri.error("Velocity.parseTemplate() failed loading template '" + templateName + "'"); return false; } else { template.Merge(context, writer); return true; } } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// </returns> public virtual Template GetTemplate(String name) { return ri.getTemplate(name); } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <param name="encoding">The character encoding to use for the template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// @since Velocity v1.1 /// </returns> public virtual Template GetTemplate(String name, String encoding) { return ri.getTemplate(name, encoding); } /// <summary> /// Determines if a template is accessable via the currently /// configured resource loaders. /// <br><br> /// Note that the current implementation will <b>not</b> /// change the state of the system in any real way - so this /// cannot be used to pre-load the resource cache, as the /// previous implementation did as a side-effect. /// <br><br> /// The previous implementation exhibited extreme lazyness and /// sloth, and the author has been flogged. /// </summary> /// <param name="templateName"> name of the temlpate to search for /// </param> /// <returns>true if found, false otherwise /// </returns> public virtual bool TemplateExists(String templateName) { return (ri.getLoaderNameForResource(templateName) != null); } /// <summary> /// Log a warning message. /// </summary> /// <param name="Object">message to log</param> public virtual void Warn(Object message) { ri.warn(message); } /// /// <summary> /// Log an info message. /// </summary> /// <param name="Object">message to log</param> public virtual void Info(Object message) { ri.info(message); } /// <summary> /// Log an error message. /// </summary> /// <param name="Object">message to log</param> public virtual void Error(Object message) { ri.error(message); } /// <summary> /// Log a debug message. /// </summary> /// <param name="Object">message to log</param> public virtual void Debug(Object message) { ri.debug(message); } /// <summary> /// <p> /// Set the an ApplicationAttribue, which is an Object /// set by the application which is accessable from /// any component of the system that gets a RuntimeServices. /// This allows communication between the application /// environment and custom pluggable components of the /// Velocity engine, such as loaders and loggers. /// </p> /// <p> /// Note that there is no enfocement or rules for the key /// used - it is up to the application developer. However, to /// help make the intermixing of components possible, using /// the target Class name (e.g. com.foo.bar ) as the key /// might help avoid collision. /// </p> /// </summary> /// <param name="key">object 'name' under which the object is stored</param> /// <param name="value">object to store under this key</param> public virtual void SetApplicationAttribute(Object key, Object value_Renamed) { ri.setApplicationAttribute(key, value_Renamed); } } } --- NEW FILE: FieldMethodizer.cs --- namespace NVelocity.App { using System; using System.Collections; using System.Reflection; /// <summary> /// <p>This is a small utility class allow easy access to static fields in a class, /// such as string constants. Velocity will not introspect for class /// fields (and won't in the future :), but writing setter/getter methods to do /// this really is a pain, so use this if you really have /// to access fields. /// /// <p>The idea it so enable access to the fields just like you would in Java. /// For example, in Java, you would access a static field like /// <blockquote><pre> /// MyClass.STRING_CONSTANT /// </pre></blockquote> /// and that is the same thing we are trying to allow here. /// /// <p>So to use in your Java code, do something like this : /// <blockquote><pre> /// context.put("runtime", new FieldMethodizer( "NVelocity.Runtime.Runtime" )); /// </pre></blockquote> /// and then in your template, you can access any of your static fields in this way : /// <blockquote><pre> /// $runtime.RUNTIME_LOG_WARN_STACKTRACE /// </pre></blockquote> /// /// <p>Right now, this class only methodizes <code>public static</code> fields. It seems /// that anything else is too dangerous. This class is for convenience accessing /// 'constants'. If you have fields that aren't <code>static</code> it may be better /// to handle them by explicitly placing them into the context. /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version>$Id: FieldMethodizer.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $</version> public class FieldMethodizer { /// <summary> /// Hold the field objects by field name /// </summary> private Hashtable fieldHash = new Hashtable(); /// <summary> /// Hold the class objects by field name /// </summary> private Hashtable classHash = new Hashtable(); /// <summary> /// Allow object to be initialized without any data. You would use /// addObject() to add data later. /// </summary> public FieldMethodizer() { } /// <summary> /// Constructor that takes as it's arg the name of the class /// to methodize. /// </summary> /// <param name="s">Name of class to methodize.</param> public FieldMethodizer(String s) { try { addObject(s); } catch (Exception e) { Console.Out.WriteLine(e); } } /// <summary> /// Constructor that takes as it's arg a living /// object to methodize. Note that it will still /// only methodized the public static fields of /// the class. /// </summary> /// <param name="o">object to methodize.</param> public FieldMethodizer(Object o) { try { addObject(o); } catch (Exception e) { Console.Out.WriteLine(e); } } /// <summary> /// Add the Name of the class to methodize /// </summary> public virtual void addObject(String s) { Type type = Type.GetType(s); inspect(type); } /// <summary> Add an Object to methodize /// </summary> public virtual void addObject(Object o) { inspect(o.GetType()); } /// <summary> /// Accessor method to get the fields by name. /// </summary> /// <param name="fieldName">Name of static field to retrieve</param> /// <returns>The value of the given field.</returns> public virtual Object Get(String fieldName) { try { FieldInfo f = (FieldInfo) fieldHash[fieldName]; if (f != null) return f.GetValue((Type) classHash[fieldName]); } catch (Exception e) { } return null; } /// <summary> Method that retrieves all public static fields /// in the class we are methodizing. /// </summary> private void inspect(Type clas) { FieldInfo[] fields = clas.GetFields(); for (int i = 0; i < fields.Length; i++) { /* * only if public and static */ if (fields[i].IsPublic && fields[i].IsStatic) { fieldHash[fields[i].Name] = fields[i]; classHash[fields[i].Name] = clas; } } } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime Added Files: RuntimeConstants.cs RuntimeInstance.cs RuntimeServices.cs RuntimeSingleton.cs VelocimacroFactory.cs VelocimacroManager.cs Log Message: --- NEW FILE: RuntimeConstants.cs --- namespace NVelocity.Runtime { using System; /// <summary> /// This class defines the keys that are used in the /// velocity.properties file so that they can be referenced as a constant /// within Java code. /// </summary> /// <author> <a href="mailto:jo...@la...">Jon S. Stevens</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> public struct RuntimeConstants_Fields { public const String RUNTIME_LOG = "runtime.log"; public const String RUNTIME_LOG_LOGSYSTEM = "runtime.log.logsystem"; public const String RUNTIME_LOG_LOGSYSTEM_CLASS = "runtime.log.logsystem.class"; public const String RUNTIME_LOG_ERROR_STACKTRACE = "runtime.log.error.stacktrace"; public const String RUNTIME_LOG_WARN_STACKTRACE = "runtime.log.warn.stacktrace"; public const String RUNTIME_LOG_INFO_STACKTRACE = "runtime.log.info.stacktrace"; public const String RUNTIME_LOG_REFERENCE_LOG_INVALID = "runtime.log.invalid.references"; public const String DEBUG_PREFIX = " [debug] "; public const String INFO_PREFIX = " [info] "; public const String WARN_PREFIX = " [warn] "; public const String ERROR_PREFIX = " [error] "; public const String UNKNOWN_PREFIX = " [unknown] "; public const String LOGSYSTEM_LOG4NET_CATEGORY = "runtime.log.logsystem.log4net.category"; public const String LOGSYSTEM_LOG4NET_PATTERN = "runtime.log.logsystem.log4net.pattern"; public const String LOGSYSTEM_LOG4NET_FILE_SIZE = "runtime.log.logsystem.log4net.file.size"; public const String LOGSYSTEM_LOG4NET_FILE_BACKUPS = "runtime.log.logsystem.log4net.file.backups"; public const String LOGSYSTEM_LOG4NET_SYSLOGD_HOST = "runtime.log.logsystem.log4net.syslogd.host"; public const String LOGSYSTEM_LOG4NET_SYSLOGD_FACILITY = "runtime.log.logsystem.log4net.syslogd.facility"; public const String LOGSYSTEM_LOG4NET_REMOTE_HOST = "runtime.log.logsystem.log4net.remote.host"; public const String LOGSYSTEM_LOG4NET_REMOTE_PORT = "runtime.log.logsystem.log4net.remote.port"; public const String LOGSYSTEM_LOG4NET_EMAIL_SERVER = "runtime.log.logsystem.log4net.email.server"; public const String LOGSYSTEM_LOG4NET_EMAIL_FROM = "runtime.log.logsystem.log4net.email.from"; public const String LOGSYSTEM_LOG4NET_EMAIL_TO = "runtime.log.logsystem.log4net.email.to"; public const String LOGSYSTEM_LOG4NET_EMAIL_SUBJECT = "runtime.log.logsystem.log4net.email.subject"; public const String LOGSYSTEM_LOG4NET_EMAIL_BUFFER_SIZE = "runtime.log.logsystem.log4net.email.buffer.size"; public const String COUNTER_NAME = "directive.foreach.counter.name"; public const String COUNTER_INITIAL_VALUE = "directive.foreach.counter.initial.value"; public const String ERRORMSG_START = "directive.include.output.errormsg.start"; public const String ERRORMSG_END = "directive.include.output.errormsg.end"; public const String PARSE_DIRECTIVE_MAXDEPTH = "directive.parse.max.depth"; public const String RESOURCE_MANAGER_CLASS = "resource.manager.class"; public const String RESOURCE_MANAGER_CACHE_CLASS = "resource.manager.cache.class"; public const String RESOURCE_MANAGER_LOGWHENFOUND = "resource.manager.logwhenfound"; public const String RESOURCE_LOADER = "resource.loader"; public const String FILE_RESOURCE_LOADER_PATH = "file.resource.loader.path"; public const String FILE_RESOURCE_LOADER_CACHE = "file.resource.loader.cache"; public const String VM_LIBRARY = "velocimacro.library"; public const String VM_LIBRARY_AUTORELOAD = "velocimacro.library.autoreload"; public const String VM_PERM_ALLOW_INLINE = "velocimacro.permissions.allow.inline"; public const String VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL = "velocimacro.permissions.allow.inline.to.replace.global"; public const String VM_PERM_INLINE_LOCAL = "velocimacro.permissions.allow.inline.local.scope"; public const String VM_MESSAGES_ON = "velocimacro.messages.on"; public const String VM_CONTEXT_LOCALSCOPE = "velocimacro.context.localscope"; public const String INTERPOLATE_STRINGLITERALS = "runtime.interpolate.string.literals"; public const String INPUT_ENCODING = "input.encoding"; public const String OUTPUT_ENCODING = "output.encoding"; public const String ENCODING_DEFAULT = "ISO-8859-1"; public const String DEFAULT_RUNTIME_PROPERTIES = "nvelocity.properties"; public const String DEFAULT_RUNTIME_DIRECTIVES = "directive.properties"; public const int NUMBER_OF_PARSERS = 20; public const String PARSER_POOL_SIZE = "parser.pool.size"; } public interface RuntimeConstants { /* * ---------------------------------------------------------------------- * These are public constants that are used as handles for the * properties that can be specified in your typical * nvelocity.properties file. * ---------------------------------------------------------------------- */ /* * ---------------------------------------------------------------------- * L O G G I N G C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /// /// <summary> Location of the velocity log file. /// </summary> /// <summary> externally provided logger /// </summary> /// <summary> class of log system to use /// </summary> /// /// <summary> Stack trace output for error messages. /// </summary> /// /// <summary> Stack trace output for warning messages. /// </summary> /// /// <summary> Stack trace output for info messages. /// </summary> /// <summary> Logging of invalid references. /// </summary> /// <summary> Log message prefixes /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /* * ---------------------------------------------------------------------- * D I R E C T I V E C O N F I G U R A T I O N * ---------------------------------------------------------------------- * Directive properties are of the form: * * directive.<directive-name>.<property> * ---------------------------------------------------------------------- */ /// /// <summary> Initial counter value in #foreach directives. /// </summary> /// /// <summary> Initial counter value in #foreach directives. /// </summary> /// <summary> Starting tag for error messages triggered by passing /// a parameter not allowed in the #include directive. Only /// string literals, and references are allowed. /// </summary> /// <summary> Ending tag for error messages triggered by passing /// a parameter not allowed in the #include directive. Only /// string literals, and references are allowed. /// </summary> /// <summary> Maximum recursion depth allowed for the #parse directive. /// </summary> /* * ---------------------------------------------------------------------- * R E S O U R C E M A N A G E R C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /* * ---------------------------------------------------------------------- * R E S O U R C E L O A D E R C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /// <summary> controls if the finding of a resource is logged /// </summary> /// <summary> Key used to retrieve the names of the resource loaders /// to be used. In a properties file they may appear as /// the following: /// * /// resource.loader = file,classpath /// </summary> /// <summary> The public handle for setting a path in /// the FileResourceLoader. /// </summary> /// <summary> The public handle for turning the caching on in the /// FileResourceLoader. /// </summary> /* * ---------------------------------------------------------------------- * V E L O C I M A C R O C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /// /// <summary> Name of local Velocimacro library template. /// </summary> /// /// <summary> switch for autoloading library-sourced VMs (for development) /// </summary> /// /// <summary> boolean (true/false) default true : allow /// inline (in-template) macro definitions /// </summary> /// <summary> boolean (true/false) default false : allow inline /// (in-template) macro definitions to replace existing /// </summary> /// /// <summary> Switch for forcing inline macros to be local : default false. /// </summary> /// /// <summary> Switch for VM blather : default true. /// </summary> /// /// <summary> switch for local context in VM : default false /// </summary> /* * ---------------------------------------------------------------------- * G E N E R A L R U N T I M E C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /// <summary> Switch for the interpolation facility for string literals /// </summary> /// /// <summary> The character encoding for the templates. Used by the parser in /// processing the input streams. /// </summary> /// <summary> Encoding for the output stream. Currently used by Anakia and /// VelocityServlet /// </summary> /* * ---------------------------------------------------------------------- * These constants are used internally by the Velocity runtime i.e. * the constansts listed below are strictly used in the Runtime * class itself. * ---------------------------------------------------------------------- */ /// /// <summary> Default Runtime properties. /// </summary> /// /// <summary> Default Runtime properties /// </summary> /// <summary> Number of parsers to create /// </summary> } } --- NEW FILE: RuntimeSingleton.cs --- namespace NVelocity.Runtime { using System; using System.IO; using Commons.Collections; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> This is the Runtime system for Velocity. It is the /// single access point for all functionality in Velocity. /// It adheres to the mediator pattern and is the only /// structure that developers need to be familiar with /// in order to get Velocity to perform. /// * /// The Runtime will also cooperate with external /// systems like Turbine. Runtime properties can /// set and then the Runtime is initialized. /// * /// Turbine for example knows where the templates /// are to be loaded from, and where the velocity /// log file should be placed. /// * /// So in the case of Velocity cooperating with Turbine /// the code might look something like the following: /// * /// <pre> /// Runtime.setProperty(Runtime.FILE_RESOURCE_LOADER_PATH, templatePath); /// Runtime.setProperty(Runtime.RUNTIME_LOG, pathToVelocityLog); /// Runtime.init(); /// </pre> /// * /// <pre> /// ----------------------------------------------------------------------- /// N O T E S O N R U N T I M E I N I T I A L I Z A T I O N /// ----------------------------------------------------------------------- /// Runtime.init() /// /// If Runtime.init() is called by itself the Runtime will /// initialize with a set of default values. /// ----------------------------------------------------------------------- /// Runtime.init(String/Properties) /// * /// In this case the default velocity properties are layed down /// first to provide a solid base, then any properties provided /// in the given properties object will override the corresponding /// default property. /// ----------------------------------------------------------------------- /// </pre> /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:jl...@ho...">Jeff Bowden</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magusson Jr.</a> /// </author> /// <version> $Id: RuntimeSingleton.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public class RuntimeSingleton : RuntimeConstants { public static RuntimeServices RuntimeServices { get { return (RuntimeServices) ri; } } public static ExtendedProperties Configuration { get { return ri.Configuration; } set { ri.Configuration = value; } } public static Introspector Introspector { get { return ri.Introspector; } } public static RuntimeInstance RuntimeInstance { get { return ri; } } private static RuntimeInstance ri = new RuntimeInstance(); /* * This is the primary initialization method in the Velocity * Runtime. The systems that are setup/initialized here are * as follows: * * <ul> * <li>Logging System</li> * <li>ResourceManager</li> * <li>Parser Pool</li> * <li>Global Cache</li> * <li>Static Content Include System</li> * <li>Velocimacro System</li> * </ul> */ public static void init() { lock (typeof (RuntimeSingleton)) { ri.init(); } } /// <summary> Allows an external system to set a property in /// the Velocity Runtime. /// * /// </summary> /// <param name="String">property key /// </param> /// <param name="String">property value /// /// </param> public static void setProperty(String key, Object value_Renamed) { ri.setProperty(key, value_Renamed); } /// <summary> Allow an external system to set an ExtendedProperties /// object to use. This is useful where the external /// system also uses the ExtendedProperties class and /// the velocity configuration is a subset of /// parent application's configuration. This is /// the case with Turbine. /// * /// </summary> /// <param name="ExtendedProperties">configuration /// /// </param> /// <summary> Add a property to the configuration. If it already /// exists then the value stated here will be added /// to the configuration entry. For example, if /// * /// resource.loader = file /// * /// is already present in the configuration and you /// * /// addProperty("resource.loader", "classpath") /// * /// Then you will end up with a Vector like the /// following: /// * /// ["file", "classpath"] /// * /// </summary> /// <param name="String">key /// </param> /// <param name="String">value /// /// </param> public static void addProperty(String key, Object value_Renamed) { ri.addProperty(key, value_Renamed); } /// <summary> Clear the values pertaining to a particular /// property. /// * /// </summary> /// <param name="String">key of property to clear /// /// </param> public static void clearProperty(String key) { ri.clearProperty(key); } /// <summary> Allows an external caller to get a property. The calling /// routine is required to know the type, as this routine /// will return an Object, as that is what properties can be. /// * /// </summary> /// <param name="key">property to return /// /// </param> public static Object getProperty(String key) { return ri.getProperty(key); } /// <summary> Initialize the Velocity Runtime with a Properties /// object. /// * /// </summary> /// <param name="">Properties /// /// </param> public static void init(ExtendedProperties p) { ri.init(p); } /// <summary> Initialize the Velocity Runtime with the name of /// ExtendedProperties object. /// * /// </summary> /// <param name="">Properties /// /// </param> public static void init(String configurationFile) { ri.init(configurationFile); } /// <summary> Returns a JavaCC generated Parser. /// * /// </summary> /// <returns>Parser javacc generated parser /// /// </returns> private static Parser.Parser createNewParser() { return ri.createNewParser(); } /// <summary> Parse the input and return the root of /// AST node structure. /// <br><br> /// In the event that it runs out of parsers in the /// pool, it will create and let them be GC'd /// dynamically, logging that it has to do that. This /// is considered an exceptional condition. It is /// expected that the user will set the /// PARSER_POOL_SIZE property appropriately for their /// application. We will revisit this. /// * /// </summary> /// <param name="InputStream">inputstream retrieved by a resource loader /// </param> /// <param name="String">name of the template being parsed /// /// </param> public static SimpleNode parse(TextReader reader, String templateName) { return ri.parse(reader, templateName); } /// <summary> Parse the input and return the root of the AST node structure. /// * /// </summary> /// <param name="InputStream">inputstream retrieved by a resource loader /// </param> /// <param name="String">name of the template being parsed /// </param> /// <param name="dumpNamespace">flag to dump the Velocimacro namespace for this template /// /// </param> public static SimpleNode parse(TextReader reader, String templateName, bool dumpNamespace) { return ri.parse(reader, templateName, dumpNamespace); } /// <summary> Returns a <code>Template</code> from the resource manager. /// This method assumes that the character encoding of the /// template is set by the <code>input.encoding</code> /// property. The default is "ISO-8859-1" /// * /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// /// </returns> public static Template getTemplate(String name) { return ri.getTemplate(name); } /// <summary> Returns a <code>Template</code> from the resource manager /// * /// </summary> /// <param name="name">The name of the desired template. /// </param> /// <param name="encoding">Character encoding of the template /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// /// </returns> public static Template getTemplate(String name, String encoding) { return ri.getTemplate(name, encoding); } /// <summary> Returns a static content resource from the /// resource manager. Uses the current value /// if INPUT_ENCODING as the character encoding. /// * /// </summary> /// <param name="name">Name of content resource to get /// </param> /// <returns>parsed ContentResource object ready for use /// @throws ResourceNotFoundException if template not found /// from any available source. /// /// </returns> public static ContentResource getContent(String name) { return ri.getContent(name); } /// <summary> Returns a static content resource from the /// resource manager. /// * /// </summary> /// <param name="name">Name of content resource to get /// </param> /// <param name="encoding">Character encoding to use /// </param> /// <returns>parsed ContentResource object ready for use /// @throws ResourceNotFoundException if template not found /// from any available source. /// /// </returns> public static ContentResource getContent(String name, String encoding) { return ri.getContent(name, encoding); } /// <summary> Determines is a template exists, and returns name of the loader that /// provides it. This is a slightly less hokey way to support /// the Velocity.templateExists() utility method, which was broken /// when per-template encoding was introduced. We can revisit this. /// * /// </summary> /// <param name="resourceName">Name of template or content resource /// </param> /// <returns>class name of loader than can provide it /// /// </returns> public static String getLoaderNameForResource(String resourceName) { return ri.getLoaderNameForResource(resourceName); } /// <summary> Log a warning message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> public static void warn(Object message) { ri.warn(message); } /// /// <summary> Log an info message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> public static void info(Object message) { ri.info(message); } /// <summary> Log an error message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> public static void error(Object message) { ri.error(message); } /// <summary> Log a debug message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> public static void debug(Object message) { ri.debug(message); } /// <summary> String property accessor method with default to hide the /// configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="String">defaultValue default value to return if key not /// found in resource manager. /// </param> /// <returns>String value of key or default /// /// </returns> public static String getString(String key, String defaultValue) { return ri.getString(key, defaultValue); } /// <summary> Returns the appropriate VelocimacroProxy object if strVMname /// is a valid current Velocimacro. /// * /// </summary> /// <param name="String">vmName Name of velocimacro requested /// </param> /// <returns>String VelocimacroProxy /// /// </returns> public static Directive.Directive getVelocimacro(String vmName, String templateName) { return ri.getVelocimacro(vmName, templateName); } /// <summary> Adds a new Velocimacro. Usually called by Macro only while parsing. /// * /// </summary> /// <param name="String">name Name of velocimacro /// </param> /// <param name="String">macro String form of macro body /// </param> /// <param name="String">argArray Array of strings, containing the /// #macro() arguments. the 0th is the name. /// </param> /// <returns>boolean True if added, false if rejected for some /// reason (either parameters or permission settings) /// /// </returns> public static bool addVelocimacro(String name, String macro, String[] argArray, String sourceTemplate) { return ri.addVelocimacro(name, macro, argArray, sourceTemplate); } /// <summary> Checks to see if a VM exists /// * /// </summary> /// <param name="name"> Name of velocimacro /// </param> /// <returns>boolean True if VM by that name exists, false if not /// /// </returns> public static bool isVelocimacro(String vmName, String templateName) { return ri.isVelocimacro(vmName, templateName); } /// <summary> tells the vmFactory to dump the specified namespace. This is to support /// clearing the VM list when in inline-VM-local-scope mode /// </summary> public static bool dumpVMNamespace(String namespace_Renamed) { return ri.dumpVMNamespace(namespace_Renamed); } /* -------------------------------------------------------------------- * R U N T I M E A C C E S S O R M E T H O D S * -------------------------------------------------------------------- * These are the getXXX() methods that are a simple wrapper * around the configuration object. This is an attempt * to make a the Velocity Runtime the single access point * for all things Velocity, and allow the Runtime to * adhere as closely as possible the the Mediator pattern * which is the ultimate goal. * -------------------------------------------------------------------- */ /// <summary> String property accessor method to hide the configuration implementation /// </summary> /// <param name="key"> property key /// </param> /// <returns> value of key or null /// /// </returns> public static String getString(String key) { return ri.getString(key); } /// <summary> Int property accessor method to hide the configuration implementation. /// * /// </summary> /// <param name="String">key property key /// </param> /// <returns>int value /// /// </returns> public static int getInt(String key) { return ri.getInt(key); } /// <summary> Int property accessor method to hide the configuration implementation. /// * /// </summary> /// <param name="key"> property key /// </param> /// <param name="int">default value /// </param> /// <returns>int value /// /// </returns> public static int getInt(String key, int defaultValue) { return ri.getInt(key, defaultValue); } /// <summary> Boolean property accessor method to hide the configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="boolean">default default value if property not found /// </param> /// <returns>boolean value of key or default value /// /// </returns> public static bool getBoolean(String key, bool def) { return ri.getBoolean(key, def); } /// <summary> Return the velocity runtime configuration object. /// * /// </summary> /// <returns>ExtendedProperties configuration object which houses /// the velocity runtime properties. /// /// </returns> /// <summary> Return the Introspector for this RuntimeInstance /// * /// </summary> /// <returns>Introspector object for this runtime instance /// /// </returns> /// <summary> returns the RuntimeInstance object for this singleton /// For internal use only :) /// * /// </summary> /// <returns>RuntimeInstance the RuntimeInstance used by this Singleton /// instance /// /// </returns> } } --- NEW FILE: VelocimacroFactory.cs --- namespace NVelocity.Runtime { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.Collections; using NVelocity.Runtime.Directive; /// <summary> VelocimacroFactory.java /// * /// manages the set of VMs in a running Velocity engine. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: VelocimacroFactory.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public class VelocimacroFactory { private bool TemplateLocalInline { get { return templateLocal; } set { templateLocal = value; } } private bool AddMacroPermission { set { bool b = addNewAllowed; addNewAllowed = value; // TODO: looks like original code must have returned the value that was replaced //return b; } } private bool ReplacementPermission { set { bool b = replaceAllowed; replaceAllowed = value; // TODO: looks like original code must have returned the value that was replaced //return b; } } private bool Blather { get { return blather; } set { blather = value; } } private bool Autoload { get { return autoReloadLibrary; } set { autoReloadLibrary = value; } } /// <summary> runtime services for this instance /// </summary> private RuntimeServices rsvc = null; /// <summary> VMManager : deal with namespace management /// and actually keeps all the VM definitions /// </summary> private VelocimacroManager vmManager = null; /// <summary> determines if replacement of global VMs are allowed /// controlled by VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL /// </summary> private bool replaceAllowed = false; /// <summary> controls if new VMs can be added. Set by /// VM_PERM_ALLOW_INLINE Note the assumption that only /// through inline defs can this happen. /// additions through autoloaded VMs is allowed /// </summary> private bool addNewAllowed = true; /// <summary> sets if template-local namespace in used /// </summary> private bool templateLocal = false; /// <summary> controls log output /// </summary> private bool blather = false; /// <summary> determines if the libraries are auto-loaded /// when they change /// </summary> private bool autoReloadLibrary = false; /// <summary> vector of the library names /// </summary> private ArrayList macroLibVec = null; /// <summary> map of the library Template objects /// used for reload determination /// </summary> private Hashtable libModMap; /// <summary> CTOR : requires a runtime services from now /// on /// </summary> public VelocimacroFactory(RuntimeServices rs) { this.rsvc = rs; /* * we always access in a synchronized(), so we * can use an unsynchronized hashmap */ libModMap = new Hashtable(); vmManager = new VelocimacroManager(rsvc); } /// <summary> initialize the factory - setup all permissions /// load all global libraries. /// </summary> public virtual void initVelocimacro() { /* * maybe I'm just paranoid... */ lock (this) { /* * allow replacements while we add the libraries, if exist */ ReplacementPermission = true; Blather = true; logVMMessageInfo("Velocimacro : initialization starting."); /* * add all library macros to the global namespace */ vmManager.NamespaceUsage = false; /* * now, if there is a global or local libraries specified, use them. * All we have to do is get the template. The template will be parsed; * VM's are added during the parse phase */ Object libfiles = rsvc.getProperty(RuntimeConstants_Fields.VM_LIBRARY); if (libfiles != null) { if (libfiles is ArrayList) { macroLibVec = (ArrayList) libfiles; } else if (libfiles is String) { macroLibVec = new ArrayList(); macroLibVec.Add(libfiles); } for (int i = 0; i < macroLibVec.Count; i++) { String lib = (String) macroLibVec[i]; /* * only if it's a non-empty string do we bother */ if (lib != null && !lib.Equals("")) { /* * let the VMManager know that the following is coming * from libraries - need to know for auto-load */ vmManager.RegisterFromLib = true; logVMMessageInfo("Velocimacro : adding VMs from " + "VM library template : " + lib); try { Template template = rsvc.getTemplate(lib); /* * save the template. This depends on the assumption * that the Template object won't change - currently * this is how the Resource manager works */ Twonk twonk = new Twonk(this); twonk.template = template; twonk.modificationTime = template.LastModified; libModMap[lib] = twonk; } catch (System.Exception e) { logVMMessageInfo("Velocimacro : error using VM " + "library template " + lib + " : " + e); } logVMMessageInfo("Velocimacro : VM library template " + "macro registration complete."); vmManager.RegisterFromLib = false; } } } /* * now, the permissions */ /* * allowinline : anything after this will be an inline macro, I think * there is the question if a #include is an inline, and I think so * * default = true */ AddMacroPermission = true; if (!rsvc.getBoolean(RuntimeConstants_Fields.VM_PERM_ALLOW_INLINE, true)) { AddMacroPermission = false; logVMMessageInfo("Velocimacro : allowInline = false : VMs can not " + "be defined inline in templates"); } else { logVMMessageInfo("Velocimacro : allowInline = true : VMs can be " + "defined inline in templates"); } /* * allowInlineToReplaceGlobal : allows an inline VM , if allowed at all, * to replace an existing global VM * * default = false */ ReplacementPermission = false; if (rsvc.getBoolean(RuntimeConstants_Fields.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, false)) { ReplacementPermission = true; logVMMessageInfo("Velocimacro : allowInlineToOverride = true : VMs " + "defined inline may replace previous VM definitions"); } else { logVMMessageInfo("Velocimacro : allowInlineToOverride = false : VMs " + "defined inline may NOT replace previous VM definitions"); } /* * now turn on namespace handling as far as permissions allow in the * manager, and also set it here for gating purposes */ vmManager.NamespaceUsage = true; /* * template-local inline VM mode : default is off */ TemplateLocalInline = rsvc.getBoolean(RuntimeConstants_Fields.VM_PERM_INLINE_LOCAL, false); if (TemplateLocalInline) { logVMMessageInfo("Velocimacro : allowInlineLocal = true : VMs " + "defined inline will be local to their defining template only."); } else { logVMMessageInfo("Velocimacro : allowInlineLocal = false : VMs " + "defined inline will be global in scope if allowed."); } vmManager.TemplateLocalInlineVM = TemplateLocalInline; /* * general message switch. default is on */ Blather = rsvc.getBoolean(RuntimeConstants_Fields.VM_MESSAGES_ON, true); if (Blather) { logVMMessageInfo("Velocimacro : messages on : VM system " + "will output logging messages"); } else { logVMMessageInfo("Velocimacro : messages off : VM system will be quiet"); } /* * autoload VM libraries */ Autoload = rsvc.getBoolean(RuntimeConstants_Fields.VM_LIBRARY_AUTORELOAD, false); if (Autoload) { logVMMessageInfo("Velocimacro : autoload on : VM system " + "will automatically reload global library macros"); } else { logVMMessageInfo("Velocimacro : autoload off : VM system " + "will not automatically reload global library macros"); } rsvc.info("Velocimacro : initialization complete."); } return; } /// <summary> adds a macro to the factory. /// </summary> public virtual bool addVelocimacro(String name, String macroBody, String[] argArray, String sourceTemplate) { /* * maybe we should throw an exception, maybe just tell * the caller like this... * * I hate this : maybe exceptions are in order here... */ if (name == null || macroBody == null || argArray == null || sourceTemplate == null) { logVMMessageWarn("Velocimacro : VM addition rejected : " + "programmer error : arg null"); return false; } /* * see if the current ruleset allows this addition */ if (!canAddVelocimacro(name, sourceTemplate)) { return false; } /* * seems like all is good. Lets do it. */ lock (this) { vmManager.addVM(name, macroBody, argArray, sourceTemplate); } /* * if we are to blather, blather... */ if (blather) { String s = "#" + argArray[0]; s += "("; for (int i = 1; i < argArray.Length; i++) { s += " "; s += argArray[i]; } s += " ) : source = "; s += sourceTemplate; logVMMessageInfo("Velocimacro : added new VM : " + s); } return true; } /// <summary> determines if a given macro/namespace (name, source) combo is allowed /// to be added /// * /// </summary> /// <param name="name">Name of VM to add /// </param> /// <param name="sourceTemplate">Source template that contains the defintion of the VM /// </param> /// <returns>true if it is allowed to be added, false otherwise /// /// </returns> private bool canAddVelocimacro(String name, String sourceTemplate) { /* * short circuit and do it if autoloader is on, and the * template is one of the library templates */ if (Autoload) { /* * see if this is a library template */ for (int i = 0; i < macroLibVec.Count; i++) { String lib = (String) macroLibVec[i]; if (lib.Equals(sourceTemplate)) { return true; } } } /* * maybe the rules should be in manager? I dunno. It's to manage * the namespace issues first, are we allowed to add VMs at all? * This trumps all. */ if (!addNewAllowed) { logVMMessageWarn("Velocimacro : VM addition rejected : " + name + " : inline VMs not allowed."); return false; } /* * are they local in scope? Then it is ok to add. */ if (!templateLocal) { /* * otherwise, if we have it already in global namespace, and they can't replace * since local templates are not allowed, the global namespace is implied. * remember, we don't know anything about namespace managment here, so lets * note do anything fancy like trying to give it the global namespace here * * so if we have it, and we aren't allowed to replace, bail */ if (isVelocimacro(name, sourceTemplate) && !replaceAllowed) { logVMMessageWarn("Velocimacro : VM addition rejected : " + name + " : inline not allowed to replace existing VM"); return false; } } return true; } /// <summary> localization of the logging logic /// </summary> private void logVMMessageInfo(String s) { if (blather) rsvc.info(s); } /// <summary> localization of the logging logic /// </summary> private void logVMMessageWarn(String s) { if (blather) rsvc.warn(s); } /// <summary> Tells the world if a given directive string is a Velocimacro /// </summary> public virtual bool isVelocimacro(String vm, String sourceTemplate) { lock (this) { /* * first we check the locals to see if we have * a local definition for this template */ if (vmManager.get(vm, sourceTemplate) != null) return true; } return false; } /// <summary> actual factory : creates a Directive that will /// behave correctly wrt getting the framework to /// dig out the correct # of args /// </summary> public virtual Directive.Directive getVelocimacro(String vmName, String sourceTemplate) { VelocimacroProxy vp = null; lock (this) { /* * don't ask - do */ vp = vmManager.get(vmName, sourceTemplate); /* * if this exists, and autoload is on, we need to check * where this VM came from */ if (vp != null && Autoload) { /* * see if this VM came from a library. Need to pass sourceTemplate * in the event namespaces are set, as it could be masked by local */ String lib = vmManager.getLibraryName(vmName, sourceTemplate); if (lib != null) { try { /* * get the template from our map */ Twonk tw = (Twonk) libModMap[lib]; if (tw != null) { Template template = tw.template; /* * now, compare the last modified time of the resource * with the last modified time of the template * if the file has changed, then reload. Otherwise, we should * be ok. */ long tt = tw.modificationTime; long ft = template.ResourceLoader.getLastModified(template); if (ft > tt) { logVMMessageInfo("Velocimacro : autoload reload for VMs from " + "VM library template : " + lib); /* * when there are VMs in a library that invoke each other, * there are calls into getVelocimacro() from the init() * process of the VM directive. To stop the infinite loop * we save the current time reported by the resource loader * and then be honest when the reload is complete */ tw.modificationTime = ft; template = rsvc.getTemplate(lib); /* * and now we be honest */ tw.template = template; tw.modificationTime = template.LastModified; /* * note that we don't need to put this twonk back * into the map, as we can just use the same reference * and this block is synchronized */ } } } catch (System.Exception e) { logVMMessageInfo("Velocimacro : error using VM " + "library template " + lib + " : " + e); } /* * and get again */ vp = vmManager.get(vmName, sourceTemplate); } } } return vp; } /// <summary> tells the vmManager to dump the specified namespace /// </summary> public virtual bool dumpVMNamespace(String namespace_Renamed) { return vmManager.dumpNamespace(namespace_Renamed); } /// <summary> sets permission to have VMs local in scope to their declaring template /// note that this is really taken care of in the VMManager class, but /// we need it here for gating purposes in addVM /// eventually, I will slide this all into the manager, maybe. /// </summary> /// <summary> sets the permission to add new macros /// </summary> /// <summary> sets the permission for allowing addMacro() calls to /// replace existing VM's /// </summary> /// <summary> set output message mode /// </summary> /// <summary> get output message mode /// </summary> /// <summary> set the switch for automatic reloading of /// global library-based VMs /// </summary> /// <summary> get the switch for automatic reloading of /// global library-based VMs /// </summary> /// <summary> small continer class to hold the duple /// of a template and modification time. /// We keep the modification time so we can /// 'override' it on a reload to prevent /// recursive reload due to inter-calling /// VMs in a library /// </summary> //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'Twonk' to access its enclosing instance. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1019"' private class Twonk { public Twonk(VelocimacroFactory enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(VelocimacroFactory enclosingInstance) { this.enclosingInstance = enclosingInstance; } private VelocimacroFactory enclosingInstance; public VelocimacroFactory Enclosing_Instance { get { return enclosingInstance; } } public Template template; public long modificationTime; } } } --- NEW FILE: RuntimeServices.cs --- namespace NVelocity.Runtime { using System; using System.IO; using Commons.Collections; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> Interface for internal runtime services that are needed by the /// various components w/in Velocity. This was taken from the old /// Runtime singleton, and anything not necessary was removed. /// /// Currently implemented by RuntimeInstance. /// </summary> public interface RuntimeServices { ExtendedProperties Configuration { get; set; } Introspector Introspector { get; } /* * This is the primary initialization method in the Velocity * Runtime. The systems that are setup/initialized here are * as follows: * * <ul> * <li>Logging System</li> * <li>ResourceManager</li> * <li>Parser Pool</li> * <li>Global Cache</li> * <li>Static Content Include System</li> * <li>Velocimacro System</li> * </ul> */ void init(); /// <summary> Allows an external system to set a property in /// the Velocity Runtime. /// * /// </summary> /// <param name="String">property key /// </param> /// <param name="String">property value /// /// </param> void setProperty(String key, Object value_Renamed); /// <summary> Allow an external system to set an ExtendedProperties /// object to use. This is useful where the external /// system also uses the ExtendedProperties class and /// the velocity configuration is a subset of /// parent application's configuration. This is /// the case with Turbine. /// * /// </summary> /// <param name="ExtendedProperties">configuration /// /// </param> /// <summary> Add a property to the configuration. If it already /// exists then the value stated here will be added /// to the configuration entry. For example, if /// * /// resource.loader = file /// * /// is already present in the configuration and you /// * /// addProperty("resource.loader", "classpath") /// * /// Then you will end up with a Vector like the /// following: /// * /// ["file", "classpath"] /// * /// </summary> /// <param name="String">key /// </param> /// <param name="String">value /// /// </param> void addProperty(String key, Object value_Renamed); /// <summary> Clear the values pertaining to a particular /// property. /// * /// </summary> /// <param name="String">key of property to clear /// /// </param> void clearProperty(String key); /// <summary> Allows an external caller to get a property. The calling /// routine is required to know the type, as this routine /// will return an Object, as that is what properties can be. /// * /// </summary> /// <param name="key">property to return /// /// </param> Object getProperty(String key); /// <summary> Initialize the Velocity Runtime with a Properties /// object. /// * /// </summary> /// <param name="">Properties /// /// </param> // TODO //void init(System.Configuration.AppSettingsReader p); /// <summary> Initialize the Velocity Runtime with the name of /// ExtendedProperties object. /// * /// </summary> /// <param name="">Properties /// /// </param> void init(String configurationFile); /// <summary> Parse the input and return the root of /// AST node structure. /// <br><br> /// In the event that it runs out of parsers in the /// pool, it will create and let them be GC'd /// dynamically, logging that it has to do that. This /// is considered an exceptional condition. It is /// expected that the user will set the /// PARSER_POOL_SIZE property appropriately for their /// application. We will revisit this. /// * /// </summary> /// <param name="InputStream">inputstream retrieved by a resource loader /// </param> /// <param name="String">name of the template being parsed /// /// </param> SimpleNode parse(TextReader reader, String templateName); /// <summary> Parse the input and return the root of the AST node structure. /// * /// </summary> /// <param name="InputStream">inputstream retrieved by a resource loader /// </param> /// <param name="String">name of the template being parsed /// </param> /// <param name="dumpNamespace">flag to dump the Velocimacro namespace for this template /// /// </param> SimpleNode parse(TextReader reader, String templateName, bool dumpNamespace); /// <summary> Returns a <code>Template</code> from the resource manager. /// This method assumes that the character encoding of the /// template is set by the <code>input.encoding</code> /// property. The default is "ISO-8859-1" /// * /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// /// </returns> Template getTemplate(String name); /// <summary> Returns a <code>Template</code> from the resource manager /// * /// </summary> /// <param name="name">The name of the desired template. /// </param> /// <param name="encoding">Character encoding of the template /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// /// </returns> Template getTemplate(String name, String encoding); /// <summary> Returns a static content resource from the /// resource manager. Uses the current value /// if INPUT_ENCODING as the character encoding. /// * /// </summary> /// <param name="name">Name of content resource to get /// </param> /// <returns>parsed ContentResource object ready for use /// @throws ResourceNotFoundException if template not found /// from any available source. /// /// </returns> ContentResource getContent(String name); /// <summary> Returns a static content resource from the /// resource manager. /// * /// </summary> /// <param name="name">Name of content resource to get /// </param> /// <param name="encoding">Character encoding to use /// </param> /// <returns>parsed ContentResource object ready for use /// @throws ResourceNotFoundException if template not found /// from any available source. /// /// </returns> ContentResource getContent(String name, String encoding); /// <summary> Determines is a template exists, and returns name of the loader that /// provides it. This is a slightly less hokey way to support /// the Velocity.templateExists() utility method, which was broken /// when per-template encoding was introduced. We can revisit this. /// * /// </summary> /// <param name="resourceName">Name of template or content resource /// </param> /// <returns>class name of loader than can provide it /// /// </returns> String getLoaderNameForResource(String resourceName); /// <summary> Log a warning message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> void warn(Object message); /// /// <summary> Log an info message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> void info(Object message); /// <summary> Log an error message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> void error(Object message); /// <summary> Log a debug message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> void debug(Object message); /// <summary> String property accessor method with default to hide the /// configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="String">defaultValue default value to return if key not /// found in resource manager. /// </param> /// <returns>String value of key or default /// /// </returns> String getString(String key, String defaultValue); /// <summary> Returns the appropriate VelocimacroProxy object if strVMname /// is a valid current Velocimacro. /// * /// </summary> /// <param name="String">vmName Name of velocimacro requested /// </param> /// <returns>String VelocimacroProxy /// /// </returns> Directive.Directive getVelocimacro(String vmName, String templateName); /// <summary> Adds a new Velocimacro. Usually called by Macro only while parsing. /// * /// </summary> /// <param name="String">name Name of velocimacro /// </param> /// <param name="String">macro String form of macro body /// </param> /// <param name="String">argArray Array of strings, containing the /// #macro() arguments. the 0th is the name. /// </param> /// <returns>boolean True if added, false if rejected for some /// reason (either parameters or permission settings) /// /// </returns> bool addVelocimacro(String name, String macro, String[] argArray, String sourceTemplate); /// <summary> Checks to see if a VM exists /// * /// </summary> /// <param name="name"> Name of velocimacro /// </param> /// <returns>boolean True if VM by that name exists, false if not /// /// </returns> bool isVelocimacro(String vmName, String templateName); /// <summary> tells the vmFactory to dump the specified namespace. This is to support /// clearing the VM list when in inline-VM-local-scope mode /// </summary> bool dumpVMNamespace(String namespace_Renamed); /// <summary> String property accessor method to hide the configuration implementation /// </summary> /// <param name="key"> property key /// </param> /// <returns> value of key or null /// /// </returns> String getString(String key); /// <summary> Int property accessor method to hide the configuration implementation. /// * /// </summary> /// <param name="String">key property key /// </param> /// <returns>int value /// /// </returns> int getInt(String key); /// <summary> Int property accessor method to hide the configuration implementation. /// * /// </summary> /// <param name="key"> property key /// </param> /// <param name="int">default value /// </param> /// <returns>int value /// /// </returns> int getInt(String key, int defaultValue); /// <summary> Boolean property accessor method to hide the configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="boolean">default default value if property not found /// </param> /// <returns>boolean value of key or default value /// /// </returns> bool getBoolean(String key, bool def); /// <summary> Return the velocity runtime configuration object. /// * /// </summary> /// <returns>ExtendedProperties configuration object which houses /// the velocity runtime properties. /// /// </returns> /* * Return this instance's Introspector */ /* * Return the specified applcation attribute */ Object getApplicationAttribute(Object key); } } --- NEW FILE: RuntimeInstance.cs --- namespace NVelocity.Runtime { using System; using System.Collections; using System.IO; using Commons.Collections; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Resource; using NVelocity.Runtime.Resource.Loader; using NVelocity.Util; using NVelocity.Util.Introspection; /// <summary> This is the Runtime system for Velocity. It is the /// single access point for all functionality in Velocity. /// It adheres to the mediator pattern and is the only /// structure that developers need to be familiar with /// in order to get Velocity to perform. /// * /// The Runtime will also cooperate with external [...1021 lines suppressed...] /// <summary> Return the velocity runtime configuration object. /// * /// </summary> /// <returns>ExtendedProperties configuration object which houses /// the velocity runtime properties. /// /// </returns> /// <summary> Return the Introspector for this instance /// </summary> public virtual Object getApplicationAttribute(Object key) { return applicationAttributes[key]; } public virtual Object setApplicationAttribute(Object key, Object o) { return applicationAttributes[key] = o; } } } --- NEW FILE: VelocimacroManager.cs --- namespace NVelocity.Runtime { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App/Tools In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/App/Tools Added Files: VelocityFormatter.cs Log Message: --- NEW FILE: VelocityFormatter.cs --- namespace NVelocity.App.Tools { /* * Copyright (c) 2001 The Java Apache Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the Java Apache * Project for use in the Apache JServ servlet engine project * <http://java.apache.org/>." * * 4. The names "Apache JServ", "Apache JServ Servlet Engine", "Turbine", * "Apache Turbine", "Turbine Project", "Apache Turbine Project" and * "Java Apache Project" must not be used to endorse or promote products * derived from this software without prior written permission. * * 5. Products derived from this software may not be called "Apache JServ" * nor may "Apache" nor "Apache JServ" appear in their names without * prior written permission of the Java Apache Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the Java Apache * Project for use in the Apache JServ servlet engine project * <http://java.apache.org/>." * * THIS SOFTWARE IS PROVIDED BY THE JAVA APACHE PROJECT "AS IS" AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JAVA APACHE PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many * individuals on behalf of the Java Apache Group. For more information * on the Java Apache Project and the Apache JServ Servlet Engine project, * please see <http://java.apache.org/>. * */ // Java Core Classes using System; using System.Collections; using System.Globalization; using System.Text; using NVelocity.Context; /// <summary> Formatting tool for inserting into the Velocity WebContext. Can /// format dates or lists of objects. /// * /// <p>Here's an example of some uses: /// * /// <code><pre> /// $formatter.formatShortDate($object.Date) /// $formatter.formatLongDate($db.getRecord(232).getDate()) /// $formatter.formatArray($array) /// $formatter.limitLen(30, $object.Description) /// </pre></code> /// /// </summary> /// <author> <a href="se...@so...">Sean Legassick</a> /// </author> /// <author> <a href="dl...@co...">Daniel Rall</a> /// </author> /// <version> $Id: VelocityFormatter.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public class VelocityFormatter { private void InitBlock() { nf = SupportClass.TextNumberFormat.getTextNumberInstance(); } internal IContext context = null; //UPGRADE_NOTE: The initialization of 'nf' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' internal SupportClass.TextNumberFormat nf; /// <summary> Constructor needs a backpointer to the context. /// * /// </summary> /// <param name="context">A Context. /// /// </param> public VelocityFormatter(IContext context) { InitBlock(); this.context = context; } /// <summary> Formats a date in 'short' style. /// * /// </summary> /// <param name="date">A Date. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatShortDate(DateTime date) { return SupportClass.FormatDateTime(SupportClass.GetDateTimeFormatInstance(3, -1, CultureInfo.CurrentCulture), date); } /// <summary> Formats a date in 'long' style. /// * /// </summary> /// <param name="date">A Date. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatLongDate(DateTime date) { return SupportClass.FormatDateTime(SupportClass.GetDateTimeFormatInstance(1, -1, CultureInfo.CurrentCulture), date); } /// <summary> Formats a date/time in 'short' style. /// * /// </summary> /// <param name="date">A Date. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatShortDateTime(DateTime date) { return SupportClass.FormatDateTime(SupportClass.GetDateTimeFormatInstance(3, 3, CultureInfo.CurrentCulture), date); } /// <summary> Formats a date/time in 'long' style. /// * /// </summary> /// <param name="date">A Date. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatLongDateTime(DateTime date) { return SupportClass.FormatDateTime(SupportClass.GetDateTimeFormatInstance(1, 1, CultureInfo.CurrentCulture), date); } /// <summary> Formats an array into the form "A, B and C". /// * /// </summary> /// <param name="array">An Object. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatArray(Object array) { return formatArray(array, ", ", " and "); } /// <summary> Formats an array into the form /// "A<delim>B<delim>C". /// * /// </summary> /// <param name="array">An Object. /// </param> /// <param name="delim">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatArray(Object array, String delim) { return formatArray(array, delim, delim); } /// <summary> Formats an array into the form /// "A<delim>B<finaldelim>C". /// * /// </summary> /// <param name="array">An Object. /// </param> /// <param name="delim">A String. /// </param> /// <param name="finalDelim">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatArray(Object array, String delim, String finaldelim) { // TODO: if this is not right - it will blow up Array a = (Array) array; StringBuilder sb = new StringBuilder(); int arrayLen = ((double[]) array).Length; for (int i = 0; i < arrayLen; i++) { // Use the Array.get method as this will automatically // wrap primitive types in a suitable Object-derived // wrapper if necessary. //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' //UPGRADE_ISSUE: Method 'java.lang.reflect.Array.get' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangreflectArrayget_javalangObject_int"' //TODO: not sure if this is right //sb.Append(Array.get(array, i).ToString()); sb.Append(a.GetValue(i).ToString()); if (i < arrayLen - 2) { sb.Append(delim); } else if (i < arrayLen - 1) { sb.Append(finaldelim); } } return sb.ToString(); } /// <summary> Formats a vector into the form "A, B and C". /// * /// </summary> /// <param name="vector">A Vector. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatVector(ArrayList vector) { return formatVector(vector, ", ", " and "); } /// <summary> Formats a vector into the form "A<delim>B<delim>C". /// * /// </summary> /// <param name="vector">A Vector. /// </param> /// <param name="delim">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatVector(ArrayList vector, String delim) { return formatVector(vector, delim, delim); } /// <summary> Formats a vector into the form /// "Adelim>B<finaldelim>C". /// * /// </summary> /// <param name="vector">A Vector. /// </param> /// <param name="delim">A String. /// </param> /// <param name="finalDelim">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatVector(ArrayList vector, String delim, String finaldelim) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < vector.Count; i++) { //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' sb.Append(vector[i].ToString()); if (i < vector.Count - 2) { sb.Append(delim); } else if (i < vector.Count - 1) { sb.Append(finaldelim); } } return sb.ToString(); } /// <summary> Limits 'string' to 'maxlen' characters. If the string gets /// curtailed, "..." is appended to it. /// * /// </summary> /// <param name="maxlen">An int with the maximum length. /// </param> /// <param name="string">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String limitLen(int maxlen, String string_Renamed) { return limitLen(maxlen, string_Renamed, "..."); } /// <summary> Limits 'string' to 'maxlen' character. If the string gets /// curtailed, 'suffix' is appended to it. /// * /// </summary> /// <param name="maxlen">An int with the maximum length. /// </param> /// <param name="string">A String. /// </param> /// <param name="suffix">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String limitLen(int maxlen, String string_Renamed, String suffix) { String ret = string_Renamed; if (string_Renamed.Length > maxlen) { ret = string_Renamed.Substring(0, (maxlen - suffix.Length) - (0)) + suffix; } return ret; } /// <summary> Class that returns alternating values in a template. It stores /// a list of alternate Strings, whenever alternate() is called it /// switches to the next in the list. The current alternate is /// retrieved through toString() - i.e. just by referencing the /// object in a Velocity template. For an example of usage see the /// makeAlternator() method below. /// </summary> //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'VelocityAlternator' to access its enclosing instance. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1019"' public class VelocityAlternator { private void InitBlock(VelocityFormatter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private VelocityFormatter enclosingInstance; public VelocityFormatter Enclosing_Instance { get { return enclosingInstance; } } protected internal String[] alternates = null; protected internal int current = 0; /// <summary> Constructor takes an array of Strings. /// * /// </summary> /// <param name="alternates">A String[]. /// /// </param> public VelocityAlternator(VelocityFormatter enclosingInstance, String[] alternates) { InitBlock(enclosingInstance); this.alternates = alternates; } /// <summary> Alternates to the next in the list. /// * /// </summary> /// <returns>The current alternate in the sequence. /// /// </returns> public virtual String alternate() { current++; current %= alternates.Length; return ""; } /// <summary> Returns the current alternate. /// * /// </summary> /// <returns>A String. /// /// </returns> public override String ToString() { return alternates[current]; } } /// <summary> As VelocityAlternator, but calls <code>alternate()</code> /// automatically on rendering in a template. /// </summary> //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'VelocityAutoAlternator' to access its enclosing instance. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1019"' public class VelocityAutoAlternator : VelocityAlternator { private void InitBlock(VelocityFormatter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private VelocityFormatter enclosingInstance; new public VelocityFormatter Enclosing_Instance { get { return enclosingInstance; } } /// <summary> Constructor takes an array of Strings. /// * /// </summary> /// <param name="alternates">A String[]. /// /// </param> public VelocityAutoAlternator(VelocityFormatter enclosingInstance, String[] alternates) : base(enclosingInstance, alternates) { InitBlock(enclosingInstance); } /// <summary> Returns the current alternate, and automatically alternates /// to the next alternate in its sequence (trigged upon /// rendering). /// * /// </summary> /// <returns>The current alternate in the sequence. /// /// </returns> public override String ToString() { String s = alternates[current]; alternate(); return s; } } /// <summary> Makes an alternator object that alternates between two values. /// * /// <p>Example usage in a Velocity template: /// * /// <code><pre> /// <table> /// $formatter.makeAlternator("rowcolor", "#c0c0c0", "#e0e0e0") /// #foreach $item in $items /// #begin /// <tr><td bgcolor="$rowcolor">$item.Name</td></tr> /// $rowcolor.alternate() /// #end /// </table> /// </pre></code> /// * /// </summary> /// <param name="name">The name for the alternator int the context. /// </param> /// <param name="alt1">The first alternate. /// </param> /// <param name="alt2">The second alternate. /// </param> /// <returns>The newly created instance. /// /// </returns> public virtual String makeAlternator(String name, String alt1, String alt2) { String[] alternates = new String[] {alt1, alt2}; context.Put(name, new VelocityAlternator(this, alternates)); return ""; } /// <summary> Makes an alternator object that alternates between three /// values. /// * /// </summary> /// <seealso cref=" #makeAlternator(String name, String alt1, String alt2) /// /// "/> public virtual String makeAlternator(String name, String alt1, String alt2, String alt3) { String[] alternates = new String[] {alt1, alt2, alt3}; context.Put(name, new VelocityAlternator(this, alternates)); return ""; } /// <summary> Makes an alternator object that alternates between four values. /// * /// </summary> /// <seealso cref=" #makeAlternator(String name, String alt1, String alt2) /// /// "/> public virtual String makeAlternator(String name, String alt1, String alt2, String alt3, String alt4) { String[] alternates = new String[] {alt1, alt2, alt3, alt4}; context.Put(name, new VelocityAlternator(this, alternates)); return ""; } /// <summary> Makes an alternator object that alternates between two values /// automatically. /// * /// </summary> /// <seealso cref=" #makeAlternator(String name, String alt1, String alt2) /// /// "/> public virtual String makeAutoAlternator(String name, String alt1, String alt2) { String[] alternates = new String[] {alt1, alt2}; context.Put(name, new VelocityAutoAlternator(this, alternates)); return ""; } /// <summary> Returns a default value if the object passed is null. /// </summary> public virtual Object isNull(Object o, Object dflt) { if (o == null) { return dflt; } else { return o; } } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Visitor In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime/Visitor Added Files: BaseVisitor.cs NodeViewMode.cs VMReferenceMungeVisitor.cs Log Message: --- NEW FILE: NodeViewMode.cs --- namespace NVelocity.Runtime.Visitor { using System; using System.Text; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> This class is simply a visitor implementation /// that traverses the AST, produced by the Velocity /// parsing process, and creates a visual structure /// of the AST. This is primarily used for /// debugging, but it useful for documentation /// as well. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: NodeViewMode.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public class NodeViewMode : BaseVisitor { private int indent = 0; private bool showTokens = true; /// <summary>Indent child nodes to help visually identify /// the structure of the AST. /// </summary> private String indentString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; ++i) { sb.Append(" "); } return sb.ToString(); } /// <summary> Display the type of nodes and optionally the /// first token. /// </summary> private Object showNode(INode node, Object data) { String tokens = ""; String special = ""; Token t; if (showTokens) { t = node.FirstToken; if (t.specialToken != null && !t.specialToken.image.StartsWith("##")) special = t.specialToken.image; tokens = " -> " + special + t.image; } Console.Out.WriteLine(indentString() + node + tokens); ++indent; data = node.childrenAccept(this, data); --indent; return data; } /// <summary>Display a SimpleNode /// </summary> public override Object visit(SimpleNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTprocess node /// </summary> public override Object visit(ASTprocess node, Object data) { return showNode(node, data); } /// <summary>Display an ASTExpression node /// </summary> public override Object visit(ASTExpression node, Object data) { return showNode(node, data); } /// <summary>Display an ASTAssignment node ( = ) /// </summary> public override Object visit(ASTAssignment node, Object data) { return showNode(node, data); } /// <summary>Display an ASTOrNode ( || ) /// </summary> public override Object visit(ASTOrNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTAndNode ( && ) /// </summary> public override Object visit(ASTAndNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTEQNode ( == ) /// </summary> public override Object visit(ASTEQNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTNENode ( != ) /// </summary> public override Object visit(ASTNENode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTLTNode ( < ) /// </summary> public override Object visit(ASTLTNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTGTNode ( > ) /// </summary> public override Object visit(ASTGTNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTLENode ( <= ) /// </summary> public override Object visit(ASTLENode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTGENode ( >= ) /// </summary> public override Object visit(ASTGENode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTAddNode ( + ) /// </summary> public override Object visit(ASTAddNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTSubtractNode ( - ) /// </summary> public override Object visit(ASTSubtractNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTMulNode ( * ) /// </summary> public override Object visit(ASTMulNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTDivNode ( / ) /// </summary> public override Object visit(ASTDivNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTModNode ( % ) /// </summary> public override Object visit(ASTModNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTNotNode ( ! ) /// </summary> public override Object visit(ASTNotNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTNumberLiteral node /// </summary> public override Object visit(ASTNumberLiteral node, Object data) { return showNode(node, data); } /// <summary>Display an ASTStringLiteral node /// </summary> public override Object visit(ASTStringLiteral node, Object data) { return showNode(node, data); } /// <summary>Display an ASTIdentifier node /// </summary> public override Object visit(ASTIdentifier node, Object data) { return showNode(node, data); } /// <summary>Display an ASTMethod node /// </summary> public override Object visit(ASTMethod node, Object data) { return showNode(node, data); } /// <summary>Display an ASTReference node /// </summary> public override Object visit(ASTReference node, Object data) { return showNode(node, data); } /// <summary>Display an ASTTrue node /// </summary> public override Object visit(ASTTrue node, Object data) { return showNode(node, data); } /// <summary>Display an ASTFalse node /// </summary> public override Object visit(ASTFalse node, Object data) { return showNode(node, data); } /// <summary>Display an ASTBlock node /// </summary> public override Object visit(ASTBlock node, Object data) { return showNode(node, data); } /// <summary>Display an ASTText node /// </summary> public override Object visit(ASTText node, Object data) { return showNode(node, data); } /// <summary>Display an ASTIfStatement node /// </summary> public override Object visit(ASTIfStatement node, Object data) { return showNode(node, data); } /// <summary>Display an ASTElseStatement node /// </summary> public override Object visit(ASTElseStatement node, Object data) { return showNode(node, data); } /// <summary>Display an ASTElseIfStatement node /// </summary> public override Object visit(ASTElseIfStatement node, Object data) { return showNode(node, data); } public override Object visit(ASTObjectArray node, Object data) { return showNode(node, data); } public override Object visit(ASTDirective node, Object data) { return showNode(node, data); } public override Object visit(ASTWord node, Object data) { return showNode(node, data); } public override Object visit(ASTSetDirective node, Object data) { return showNode(node, data); } } } --- NEW FILE: VMReferenceMungeVisitor.cs --- namespace NVelocity.Runtime.Visitor { using System; using System.Collections; using NVelocity.Runtime.Parser.Node; /// <summary> /// This class is a visitor used by the VM proxy to change the /// literal representation of a reference in a VM. The reason is /// to preserve the 'render literal if null' behavior w/o making /// the VMProxy stuff more complicated than it is already. /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: VMReferenceMungeVisitor.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $</version> public class VMReferenceMungeVisitor : BaseVisitor { /// <summary> /// Map containing VM arg to instance-use reference /// Passed in with CTOR /// </summary> private Hashtable argmap = null; /// <summary> /// CTOR - takes a map of args to reference /// </summary> public VMReferenceMungeVisitor(Hashtable map) { argmap = map; } /// <summary> /// Visitor method - if the literal is right, will /// set the literal in the ASTReference node /// </summary> /// <param name="node">ASTReference to work on</param> /// <param name="data">Object to pass down from caller</param> public override Object visit(ASTReference node, Object data) { /* * see if there is an override value for this * reference */ String override_Renamed = (String) argmap[node.literal().Substring(1)]; /* * if so, set in the node */ if (override_Renamed != null) { node.Literal = override_Renamed; } /* * feed the children... */ data = node.childrenAccept(this, data); return data; } } } --- NEW FILE: BaseVisitor.cs --- namespace NVelocity.Runtime.Visitor { using System; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Parser.Node; /// <summary> This is the base class for all visitors. /// For each AST node, this class will provide /// a bare-bones method for traversal. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: BaseVisitor.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public abstract class BaseVisitor : ParserVisitor { public virtual StreamWriter Writer { set { this.writer = value; } } public virtual InternalContextAdapter Context { set { this.context = value; } } /// <summary>Context used during traversal /// </summary> protected internal InternalContextAdapter context; /// <summary>Writer used as the output sink /// </summary> protected internal StreamWriter writer; public virtual Object visit(SimpleNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTprocess node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTExpression node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTAssignment node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTOrNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTAndNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTEQNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTNENode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTLTNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTGTNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTLENode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTGENode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTAddNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTSubtractNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTMulNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTDivNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTModNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTNotNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTNumberLiteral node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTStringLiteral node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTIdentifier node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTMethod node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTReference node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTTrue node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTFalse node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTBlock node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTText node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTIfStatement node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTElseStatement node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTElseIfStatement node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTComment node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTObjectArray node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTWord node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTSetDirective node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTDirective node, Object data) { data = node.childrenAccept(this, data); return data; } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Dvsl In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Dvsl Added Files: Dvsl.cs DvslContext.cs DvslNode.cs DvslNodeContext.cs DvslNodeImpl.cs TransformTool.cs Transformer.cs Log Message: --- NEW FILE: Transformer.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using System.IO; using System.Xml; using NVelocity.App; using NVelocity.Context; /// <summary> <p> /// Class responsible for actual transformation /// of documents. /// </p> /// <p> /// Note that this class is <em>not</em> threadsafe. /// </p> /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> internal class Transformer : TransformTool { /// <summary> /// Instance of VelocityEngine we are currently using. /// This must be reset with a stylesheeet change /// </summary> private VelocityEngine ve = null; /// <summary> /// basic context passed to us - can contain tools /// and such for use. Is protected from change via /// wrapping /// </summary> private IContext baseContext; /// <summary> /// context used during processing. Wraps the baseContext /// </summary> private DVSLNodeContext currentContext; private TemplateHandler templateHandler = null; /// <summary> /// HashMap to hold application values /// </summary> private Hashtable appValue = new Hashtable(); /// <summary> /// Sole public CTOR. We rely on the caller to give us a /// VelocityEngine ready with all macros registered. /// The context is the callers context with all tools and /// style drek. /// </summary> public Transformer(VelocityEngine ve, TemplateHandler th, IContext context, Hashtable applicationValues, bool validate) { this.ve = ve; this.baseContext = context; this.templateHandler = th; appValue = applicationValues; } /// <summary> /// Method that performs the transformation on /// a document /// </summary> /// <param name="reader">XML document char stream</param> /// <param name="writer">Writer to output transformation to</param> internal virtual long Transform(TextReader reader, TextWriter writer) { /* * parse the document */ XmlDocument document = new XmlDocument(); document.Load(reader); return Transform(document, writer); } internal virtual long Transform(XmlDocument dom4jdoc, TextWriter writer) { /* * wrap the document. We do this as we let the dom4j package * decide if we have a match against "/", so we need document * to do that */ DvslNode root = new DvslNodeImpl(dom4jdoc); return Transform(root, writer); } protected internal virtual long Transform(DvslNode root, TextWriter writer) { /* * wrap in a context to keep subsequent documents from * interacting with each other */ currentContext = new DVSLNodeContext(baseContext); long start = (DateTime.Now.Ticks - 621355968000000000)/10000; /* * push 'this' into the context as our TransformTool * and invoke the transformation */ currentContext.Put("context", this); Invoke(root, writer); long end = (DateTime.Now.Ticks - 621355968000000000)/10000; return end - start; } private void Invoke(DvslNode element, TextWriter writer) { String[] arr = new String[] {}; currentContext.PushNode(element); templateHandler.Render(element, currentContext, writer); currentContext.PopNode(); } public virtual Object Get(String key) { return currentContext.Get(key); } public virtual String ApplyTemplates(DvslNode node, String xpath) { /* * get the nodes that was asked for */ IList nodeset = node.SelectNodes(xpath); StringWriter sw = new StringWriter(); for (int i = 0; i < nodeset.Count; i++) { DvslNode n = (DvslNode) nodeset[i]; Invoke(n, sw); } return sw.ToString(); } public virtual String ApplyTemplates(DvslNode node) { StringWriter sw = new StringWriter(); Invoke(node, sw); return sw.ToString(); } public virtual String ApplyTemplates() { return ApplyTemplates(currentContext.PeekNode(), "*|@*|text()|comment()|processing-instruction()"); } public virtual String ApplyTemplates(String path) { DvslNode node = currentContext.PeekNode(); return ApplyTemplates(node, path); } public virtual String Copy() { /* * fakie, for now */ DvslNode node = currentContext.PeekNode(); return node.Copy(); } public virtual Object GetAppValue(Object key) { return appValue[key]; } public virtual Object PutAppValue(Object key, Object value) { return appValue[key] = value; } } } --- NEW FILE: DvslNodeContext.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using NVelocity.Context; /// <summary> <p> /// Context implementation that is the outer context /// during the transformation. Holds the node stack /// and also protects the 'special' context elements /// like 'node' /// </p> /// <p> /// There are special elements like 'node', which is /// readonly and corresponds to the current node, and /// 'attrib', which corresponds to a map of attributes /// for the current node. /// </p> /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> internal class DVSLNodeContext : VelocityContext { /// <summary> /// Magic context entity that corresponds /// to the current node /// </summary> private const String NODE = "node"; /// <summary> /// Magic context entity that corresponds to /// a Map of attributes for the current node /// </summary> private const String ATTRIB = "attrib"; /// <summary> /// Used to hold the nodes as we get invoked from /// within the document for applyTemplates() duties /// </summary> private Stack nodeStack = new Stack(); protected internal Hashtable ctx = new Hashtable(); public DVSLNodeContext(IContext context) : base(context) { } public DVSLNodeContext() { } /// <summary> /// retrieves value for key from internal storage /// </summary> /// <param name="key">name of value to get</param> /// <returns>value as object</returns> public override Object InternalGet(String key) { Object o = null; /* * special token : NODE * * returns current node */ if (key.Equals(NODE)) { return PeekNode(); } /* * ATTRIB - returns attribute map */ if (key.Equals(ATTRIB)) { DvslNode n = PeekNode(); return n.AttribMap; } /* * start with local storage */ return ctx[key]; } /// <summary> /// stores the value for key to internal /// storage /// </summary> /// <param name="key">name of value to store /// </param> /// <param name="value">value to store /// </param> /// <returns>previous value of key as Object /// </returns> public override Object InternalPut(String key, Object value) { /* * protect both NODE and ATTRIB for now. We * might want to let people set ATTRIB, but * I suspect not */ if (key.Equals(NODE)) return null; if (key.Equals(ATTRIB)) return null; return ctx[key] = value; } /// <summary> /// determines if there is a value for the /// given key /// </summary> /// <param name="key">name of value to check /// </param> /// <returns>true if non-null value in store /// </returns> public override bool InternalContainsKey(Object key) { return ctx.ContainsKey(key); } /// <summary> /// returns array of keys /// $$$ GMJ todo /// </summary> /// <returns>keys as [] /// </returns> public override Object[] InternalGetKeys() { return null; } /// <summary> /// remove a key/value pair from the internal storage /// </summary> /// <param name="key">name of value to remove</param> /// <returns>value removed</returns> public override Object InternalRemove(Object key) { Object o = ctx[key]; ctx.Remove(key); return o; } /* === routines to manage current node stack === */ internal virtual DvslNode PushNode(DvslNode n) { nodeStack.Push(n); return n; } internal virtual DvslNode PeekNode() { return (DvslNode) nodeStack.Peek(); } internal virtual DvslNode PopNode() { return (DvslNode) nodeStack.Pop(); } internal virtual void ClearNode() { nodeStack.Clear(); return; } } } --- NEW FILE: DvslContext.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using NVelocity.Context; /// <summary> /// Context implementation that handles wrapping several /// contexts simultaneously. The style context gets /// special treatment, getting checked first. /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> internal class DvslContext : VelocityContext { protected internal IContext styleContext = null; protected internal IList contextList = new ArrayList(); /// <summary> /// Used to hold the nodes as we get invoked from /// within the document for applyTemplates() duties /// </summary> private Stack nodeStack = new Stack(); protected internal Hashtable ctx = new Hashtable(); public DvslContext() { } public virtual DvslNode PushNode(DvslNode n) { nodeStack.Push(n); return n; } public virtual DvslNode PeekNode() { return (DvslNode) nodeStack.Peek(); } public virtual DvslNode PopNode() { return (DvslNode) nodeStack.Pop(); } public virtual void ClearNode() { nodeStack.Clear(); return; } public virtual void ClearContexts() { styleContext = null; contextList.Clear(); } public virtual void AddContext(IContext c) { if (c != null) contextList.Add(c); } /// <summary> /// retrieves value for key from internal storage /// </summary> /// <param name="key">name of value to get</param> /// <returns>value as object</returns> public override Object InternalGet(String key) { Object o = null; /* * special tokens */ if (key.Equals("node")) { return PeekNode(); } /* * start with local storage */ o = ctx[key]; if (o != null) return o; /* * if that doesn't work, try style first * then others */ if (styleContext != null) { o = styleContext.Get(key); if (o != null) return o; } for (int i = 0; i < contextList.Count; i++) { IContext c = (IContext) contextList[i]; o = c.Get(key); if (o != null) return o; } return null; } /// <summary> /// stores the value for key to internal storage /// </summary> /// <param name="key">name of value to store</param> /// <param name="value">value to store</param> /// <returns>previous value of key as Object</returns> public override Object InternalPut(String key, Object value) { if (key.Equals("node")) return null; return ctx[key] = value; } /// <summary> /// determines if there is a value for the given key /// </summary> /// <param name="key">name of value to check</param> /// <returns>true if non-null value in store</returns> public override bool InternalContainsKey(Object key) { /* * start with local storage */ if (ctx.ContainsKey(key)) return true; /* * if that doesn't work, try style first * then others */ if (styleContext != null && styleContext.ContainsKey(key)) return true; for (int i = 0; i < contextList.Count; i++) { IContext c = (IContext) contextList[i]; if (c.ContainsKey(key)) return true; } return false; } /// <summary> /// returns array of keys /// /// $$$ GMJ todo /// /// </summary> /// <returns>keys as []</returns> public override Object[] InternalGetKeys() { return null; } /// <summary> /// remove a key/value pair from the /// internal storage /// </summary> /// <param name="key">name of value to remove</param> /// <returns>value removed</returns> public override Object InternalRemove(Object key) { Object o = ctx[key]; ctx.Remove(key); return o; } public virtual IContext StyleContext { set { styleContext = value; } } } } --- NEW FILE: TransformTool.cs --- namespace NVelocity.Dvsl { using System; /// <summary> /// This is the tool interface exposed to the stylesheet. /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public interface TransformTool { /// <summary> /// Applies templates in the current stylesheet /// to the nodeset returned by the XPath expression /// </summary> /// <param name="xpath">XPath expression to select nodes</param> /// <returns>The rendered result</returns> String ApplyTemplates(String xpath); String ApplyTemplates(DvslNode node); String ApplyTemplates(DvslNode node, String xpath); String ApplyTemplates(); String Copy(); Object Get(String key); Object GetAppValue(Object key); Object PutAppValue(Object key, Object value); } } --- NEW FILE: Dvsl.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using System.IO; using System.Xml; using Commons.Collections; using NVelocity.App; using NVelocity.Context; using NVelocity.Runtime; /// <summary> /// Main DVSL class - use this as the helper class for apps /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:bi...@pr...">Bill Burton.</a></author> public class Dvsl { private static String TOOL_PROP_PREFIX = "toolbox.tool."; private static String STRING_PROP_PREFIX = "toolbox.string."; private static String INTEGER_PROP_PREFIX = "toolbox.integer."; private static String TOOLBOX_NAME = "toolbox.contextname."; private VelocityEngine ve = null; private XmlDocument currentDocument = null; private StreamWriter currentWriter = null; private IContext toolContext; private IContext userContext; private IContext styleContext; private DvslContext baseContext = new DvslContext(); private Transformer transformer; private bool ready = false; private Hashtable velConfig = null; private FileInfo logFile; private Hashtable appVals = new Hashtable(); private TemplateHandler templateHandler = new TemplateHandler(); internal bool validate = false; /// <summary> /// lets the user specify a filename for logging. /// </summary> public virtual FileInfo LogFile { set { this.logFile = value; if (velConfig == null) { velConfig = new Hashtable(); } velConfig[RuntimeConstants_Fields.RUNTIME_LOG] = value.FullName; } } /// <summary> /// lets the user pass a java.util.Properties containing /// properties for the configuration of the VelocityEngine /// used by DVSL /// </summary> public virtual Hashtable VelocityConfig { set { if (velConfig != null) { foreach (Object key in velConfig.Keys) { value.Add(key, velConfig[key]); } } velConfig = value; } } /// <summary> /// Sets the user context. The user context is /// a Velocity Context containing user-supplied /// objects and data that are to be made available /// in the template /// </summary> /// <param name="ctx">User context of data</param> public virtual IContext UserContext { set { ready = false; userContext = value; } } /// <summary> /// Uses a validating parser on all input documents /// </summary> /// <param name="">validate</param> public virtual bool ValidatingParser { set { validate = value; } } /// <summary> /// <p>Loads the toolbox from the input Properties.</p> /// <p>Currently supports specification of the Toolbox /// name in the context, creating classes, and string /// and integer values. Ex : /// </p> /// /// <pre> /// toolbox.contextname = floyd /// toolbox.tool.footool = Footool /// toolbox.string.mystring = Hello there! /// toolbox.integer.myint = 7 /// toolbox.string.sourcebase = ./xdocs/ /// </pre> /// /// <p> /// So in template, this toolbox and it's values would /// be accessed as : /// </p> /// <pre> /// $context.floyd.footool.getFoo() /// $context.floyd.mystring /// $context.floyd.myint /// </pre> /// </summary> public virtual ExtendedProperties Toolbox { set { ready = false; /* * for each key that looks like * toolbox.tool.<token> = class */ Hashtable toolbox = new Hashtable(); String toolboxname = "toolbox"; IEnumerator it = value.Keys; while (it.MoveNext()) { String key = it.Current.ToString(); String val = value.GetString(key); if (key.StartsWith(TOOL_PROP_PREFIX)) { String toolname = key.Substring(TOOL_PROP_PREFIX.Length); Type type = Type.GetType(val); Object o = Activator.CreateInstance(type); toolbox[toolname] = o; } else if (key.StartsWith(INTEGER_PROP_PREFIX)) { String toolname = key.Substring(INTEGER_PROP_PREFIX.Length); int i = 0; try { i = Int32.Parse(val); } catch (Exception ee) { } toolbox[toolname] = i; } else if (key.StartsWith(STRING_PROP_PREFIX)) { String toolname = key.Substring(STRING_PROP_PREFIX.Length); toolbox[toolname] = val; } else if (key.StartsWith(TOOLBOX_NAME)) { toolboxname = val; } } toolContext = new VelocityContext(); toolContext.Put(toolboxname, toolbox); } } /// <summary> /// Convenience function. See... /// </summary> public virtual void SetStylesheet(String value) { SetStylesheet(new FileInfo(value)); } /// <summary> /// Convenience function. See... /// </summary> public virtual void SetStylesheet(FileInfo value) { StreamReader fr = null; try { fr = new StreamReader(value.FullName); SetStylesheet(fr); } catch (Exception e) { throw; } finally { if (fr != null) { fr.Close(); } } } /// <summary> /// <p> /// Sets the stylesheet for this transformation set /// </p> /// /// <p> /// Note that don't need this for each document you want /// to transform. Just do it once, and transform away... /// </p> /// </summary> /// <param name="styleReader">Reader with stylesheet char stream</param> public virtual void SetStylesheet(TextReader value) { ready = false; /* * now initialize Velocity - we need to do that * on change of stylesheet */ ve = new VelocityEngine(); /* * if there are user properties, set those first - carefully */ if (velConfig != null) { ConfigureVelocityEngine(ve, velConfig); } /* * register our template() directive */ ve.SetProperty("userdirective", "NVelocity.Dvsl.Directive.MatchDirective;NVelocity"); ve.Init(); /* * add our template accumulator */ ve.SetApplicationAttribute("NVelocity.Dvsl.TemplateHandler", templateHandler); /* * load and render the stylesheet * * this sets stylesheet specific context * values */ StringWriter junkWriter = new StringWriter(); styleContext = new VelocityContext(); ve.Evaluate(styleContext, junkWriter, "DVSL:stylesheet", value); /* * now run the base template through for the rules */ // TODO - use ResourceLocator or something else - I don't like the path to the resource Stream s = this.GetType().Assembly.GetManifestResourceStream("NVelocity.Dvsl.Resource.defaultroot.dvsl"); if (s == null) { Console.Out.WriteLine("DEFAULT TRANSFORM RULES NOT FOUND "); } else { ve.Evaluate(new VelocityContext(), junkWriter, "defaultroot.dvsl", new StreamReader(s)); s.Close(); } /* * need a new transformer, as it depends on the * velocity engine */ transformer = new Transformer(ve, templateHandler, baseContext, appVals, validate); } /// <summary> /// <p> /// Add mapped properties from hashtable on VelocityEngine. /// </p> /// <p> /// If you are going to use this, ensure you do it *before* setting /// the stylesheet, as that creates the VelocityEngine /// </p> /// </summary> private void ConfigureVelocityEngine(VelocityEngine ve, Hashtable map) { if (ve == null || map == null) { return; } foreach (DictionaryEntry entry in map) { ve.SetProperty((String) entry.Key, entry.Value); } } /// <summary> /// sets up all the context goodies /// </summary> protected internal virtual void MakeReady() { /* * put all the contexts together */ baseContext.ClearContexts(); baseContext.AddContext(userContext); baseContext.AddContext(toolContext); baseContext.StyleContext = styleContext; ready = true; } /// <summary> /// does the transformation of the inputstream into /// the output writer /// </summary> protected internal virtual long XForm(TextReader reader, TextWriter writer) { if (!ready) { MakeReady(); } return transformer.Transform(reader, writer); } protected internal virtual long XForm(XmlDocument dom4jdoc, TextWriter writer) { if (!ready) { MakeReady(); } return transformer.Transform(dom4jdoc, writer); } public virtual long Transform(FileInfo f, TextWriter writer) { StreamReader reader = null; try { reader = new StreamReader(f.FullName); return XForm(reader, writer); } catch (Exception e) { throw e; } finally { if (reader != null) { reader.Close(); } } } public virtual long Transform(TextReader reader, TextWriter writer) { return XForm(reader, writer); } public virtual long Transform(Stream stream, TextWriter writer) { return XForm(new StreamReader(stream), writer); } /// <summary> /// Transforms the given dom4j Document into the writer. /// </summary> /// <param name="dom4jdoc">dom4j Document object</param> /// <param name="writer">Writer for output</param> public virtual long Transform(XmlDocument dom4jdoc, TextWriter writer) { return XForm(dom4jdoc, writer); } public virtual long Transform(String infile, TextWriter writer) { StreamReader reader = null; try { reader = new StreamReader(infile); return XForm(reader, writer); } catch (Exception e) { throw e; } finally { if (reader != null) { reader.Close(); } } } /// <summary> /// Gets the application value for the specified key /// </summary> /// <param name="key">key to use to retrieve value</param> /// <returns>value if found, null otherwise</returns> public virtual Object GetAppValue(Object key) { return appVals[key]; } /// <summary> /// Sets the application value for the specified key /// </summary> /// <param name="key">key to use to store value</param> /// <param name="value">value to be stored</param> /// <returns>old value if any, null otherwise</returns> public virtual Object PutAppValue(Object key, Object value) { return appVals[key] = value; } /// <summary> /// <p> /// Allows command-line access. /// </p> /// <p> /// Usage : Dvsl.exe -STYLE stylesheeet [-IN infile] [-OUT outfile] [-TOOL toolboxname] /// </p> /// </summary> [STAThread] public static void Main(String[] args) { Dvsl dvsl = new Dvsl(); TextReader reader = Console.In; String infile = null; String style = null; String outfile = null; TextWriter writer = Console.Out; String toolfile = null; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-IN")) infile = args[++i]; else if (args[i].Equals("-OUT")) outfile = args[++i]; else if (args[i].Equals("-STYLE")) style = args[++i]; else if (args[i].Equals("-TOOL")) toolfile = args[++i]; } if (style == null) { Console.Out.WriteLine("usage :need to specify a stylesheet. "); Console.Out.WriteLine("Dvsl.exe -STYLE stylesheeet [-IN infile] [-OUT outfile] [-TOOL toolboxname]"); return; } if (style != null) dvsl.SetStylesheet(style); if (toolfile != null) { ExtendedProperties p = new ExtendedProperties(); Stream fis = new FileStream(toolfile, FileMode.Open, FileAccess.Read); p.Load(fis); dvsl.Toolbox = p; } if (infile != null) reader = new StreamReader(infile); if (outfile != null) writer = new StreamWriter(outfile); long time = dvsl.Transform(reader, writer); writer.Flush(); } } } --- NEW FILE: DvslNodeImpl.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using System.IO; using System.Xml; /// <summary> /// wrapper class for .Net nodes to implement the /// DVSLNode interface for template use /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public class DvslNodeImpl : DvslNode { protected internal XmlNode element = null; protected internal Hashtable attributes = null; /// <summary> /// this is a bit yecchy - need to revamp /// </summary> public DvslNodeImpl(XmlElement e) { element = e; } public DvslNodeImpl(XmlDocument e) { element = e; } public DvslNodeImpl(XmlText e) { element = e; } public DvslNodeImpl(XmlAttribute e) { element = e; } public DvslNodeImpl(XmlComment e) { element = e; } public DvslNodeImpl(XmlCDataSection e) { element = e; } public DvslNodeImpl() { } public virtual Object NodeImpl { get { return element; } } public virtual Hashtable AttribMap { get { /* * $$$ GMJ sync issue? yes. Do I care? */ if (attributes == null) { attributes = new Hashtable(); } /* * only Elements have attributes */ if (element is XmlElement) { XmlElement e = (XmlElement) element; foreach (XmlAttribute at in e.Attributes) { attributes[at.Name] = at.Value; } } return attributes; } } /// <summary> /// returns the name of the node /// </summary> public virtual String Name { get { return element.Name; } } /// <summary> /// returns a specificed attributeattribute /// </summary> public virtual String Attribute(String attribute) { if (element is XmlElement) { return ((XmlElement) element).Attributes[attribute].Value; } return null; } /// <summary> /// returns a list of nodes that satisfy the xpath /// </summary> public virtual IList SelectNodes(String xpath) { XmlNodeList l = element.SelectNodes(xpath); IList list = new ArrayList(); for (int i = 0; i < l.Count; i++) { XmlNode n = l[i]; if (n != null) { DvslNode dn = MakeDvslNode(n); if (dn != null) { list.Add(dn); } } } return list; } public virtual DvslNode SelectSingleNode(String xpath) { XmlNode n = element.SelectSingleNode(xpath); return MakeDvslNode(n); } public virtual DvslNode Get(String xpath) { return SelectSingleNode(xpath); } public virtual String Value { get { return element.InnerText; } } public virtual Object ValueOf(String xpath) { Object o = element.CreateNavigator().Evaluate(xpath); return o; } public override String ToString() { return Value; } public virtual IList Children() { IList list = new ArrayList(); if (element.NodeType == XmlNodeType.Element) { XmlNodeList nodes = ((XmlElement) element).ChildNodes; for (int i = 0; i < nodes.Count; i++) list.Add(MakeDvslNode(nodes[i])); } return list; } /// <summary> /// assumes a list of DVSLNodes /// </summary> public virtual String Copy(IList nodes) { if (nodes == null) return ""; StringWriter sw = new StringWriter(); for (int i = 0; i < nodes.Count; i++) { DvslNode dn = (DvslNode) nodes[i]; sw.Write(((XmlNode) dn.NodeImpl).OuterXml); } return sw.ToString(); } public virtual String Copy() { return element.OuterXml; } public virtual String Render() { try { StringWriter sw = new StringWriter(); XmlTextWriter tw = new XmlTextWriter(sw); element.WriteContentTo(tw); return tw.ToString(); } catch (Exception e) { } return ""; } public virtual String Attrib(String name) { if (element is XmlElement) { XmlAttribute attrib = ((XmlElement) element).Attributes[name]; if (attrib != null) { return attrib.Value; } } return null; } /// <summary> /// will recast all of this later /// </summary> private DvslNode MakeDvslNode(XmlNode n) { if (n == null) { return null; } if (n.NodeType == XmlNodeType.Element) { return new DvslNodeImpl((XmlElement) n); } else if (n.NodeType == XmlNodeType.Text) { return new DvslNodeImpl((XmlText) n); } else if (n.NodeType == XmlNodeType.Attribute) { return new DvslNodeImpl((XmlAttribute) n); } else if (n.NodeType == XmlNodeType.Comment) { return new DvslNodeImpl((XmlComment) n); } else if (n.NodeType == XmlNodeType.CDATA) { return new DvslNodeImpl((XmlCDataSection) n); } else if (n.NodeType == XmlNodeType.ProcessingInstruction) { // not a supported node type return null; } //TODO: log the unknown node type so that it can be determined is something is missing return null; } } } --- NEW FILE: DvslNode.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; /// <summary> /// wrapper interface for nodes exposed in the /// template. Isolates the in-VSL DOM from that /// of the underlying implementation /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public interface DvslNode { /// <summary> /// returns the name of the node /// </summary> String Name { get; } /// <summary> /// returns the 'value' of the node /// </summary> String Value { get; } /// <summary> /// returns the value of the XPath /// expression /// </summary> Object ValueOf(String xpath); /// <summary> /// returns attribute /// </summary> String Attrib(String attribute); /// <summary> /// returns a list of nodes that satisfy /// the xpath /// </summary> IList SelectNodes(String xpath); /// <summary> returns a single node that satisfies /// the xpath /// </summary> DvslNode SelectSingleNode(String xpath); DvslNode Get(String xpath); /// <summary> /// renders a deep copy of the XML tree /// below the current node to the output /// </summary> String Copy(); /// <summary> /// renders a deep copy of the nodes in /// the list ot the output /// </summary> String Copy(IList nodeList); /// <summary> /// returns a list of all children of the current node /// </summary> IList Children(); /// <summary> /// returns the 'value' of the node /// </summary> String ToString(); /// <summary> /// returns the object corresponding to the node /// in the implementaion that we are using. /// use only with the greatest of care /// </summary> Object NodeImpl { get; } Hashtable AttribMap { get; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Tool In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Tool Added Files: DataInfo.cs IToolInfo.cs ToolLoader.cs Log Message: --- NEW FILE: ToolLoader.cs --- namespace NVelocity.Tool { using System; /// <summary> /// <p>A view tool that allows template designers to load /// an arbitrary object into the context. Any object /// with a public constructor without parameters can be used /// as a view tool.</p> /// <p>THIS CLASS IS HERE AS A PROOF OF CONCEPT ONLY. IT IS NOT /// INTENDED FOR USE IN PRODUCTION ENVIRONMENTS. USE AT YOUR OWN RISK.</p> /// </summary> /// <author><a href="mailto:si...@te...">Gabe Sidler</a></author> /// <author><a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public class ToolLoader { public ToolLoader() { } /// <summary> /// Creates and returns an object of the specified classname. /// The object must have a valid default constructor. /// </summary> /// <param name="clazz">the fully qualified class name of the object</param> /// <returns>an instance of the specified class or null if the class /// could not be instantiated.</returns> public virtual Object Load(String clazz) { try { Type type = Type.GetType(clazz); Object o = Activator.CreateInstance(type); return o; } catch (Exception) { return null; } } } } --- NEW FILE: IToolInfo.cs --- namespace NVelocity.Tool { using System; /// <summary> Interface to simplify and abstract tool handling. /// * /// Implementations of this class should hold both the context /// key for the tool and sufficient information to return /// an instance of the tool. /// * /// </summary> /// <author> <a href="mailto:na...@es...">Nathan Bubna</a> /// * /// </author> /// <version> $Id: IToolInfo.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public interface IToolInfo { String Key { get; } String Classname { get; } /// <returns>the context key for the tool /// /// </returns> /// <returns>the fully qualified classname for the tool /// /// </returns> /// <summary> Returns an instance of the tool. /// * /// Instances returned may be new on each call, pooled, or /// the be same instance every time depending on the /// implementation. The object passed to this method may /// be used to initialize or create the tool that is returned, /// or it may be null if no such data is required. /// * /// </summary> /// <param name="initData">an object that may be used to initialize the instance /// </param> /// <returns>an instance of the tool /// /// </returns> Object getInstance(Object initData); } } --- NEW FILE: DataInfo.cs --- namespace NVelocity.Tool { using System; /// <summary> ToolInfo implementation to handle "primitive" data types. /// It currently supports String, Number, and Boolean data. /// * /// </summary> /// <author> <a href="mailto:na...@es...">Nathan Bubna</a> /// * /// </author> /// <version> $Id: DataInfo.cs,v 1.3 2005/11/16 05:45:24 intesar66 Exp $ /// /// </version> public class DataInfo : IToolInfo { public virtual String Key { get { return key; } } public virtual String Classname { get { return data.GetType().FullName; } } public static String TYPE_STRING = "string"; public static String TYPE_NUMBER = "number"; public static String TYPE_BOOLEAN = "boolean"; private String key; private Object data; /// <summary> Parses the value string into a recognized type. If /// the type specified is not supported, the data will /// be held and returned as a string. /// * /// </summary> /// <param name="key">the context key for the data /// </param> /// <param name="type">the data type /// </param> /// <param name="value">the data /// /// </param> public DataInfo(String key, String type, String value_Renamed) { this.key = key; if (type.ToUpper().Equals(TYPE_BOOLEAN.ToUpper())) { this.data = Boolean.Parse(value_Renamed); } else if (type.ToUpper().Equals(TYPE_NUMBER.ToUpper())) { if (value_Renamed.IndexOf((Char) '.') >= 0) { //UPGRADE_TODO: Format of parameters of constructor 'java.lang.Double.Double' are different in the equivalent in .NET. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1092"' this.data = Double.Parse(value_Renamed); } else { this.data = Int32.Parse(value_Renamed); } } else { this.data = value_Renamed; } } /// <summary> Returns the data. Always returns the same /// object since the data is a constant. Initialization /// data is ignored. /// </summary> public virtual Object getInstance(Object initData) { return data; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Resource/Loader In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime/Resource/Loader Added Files: FileResourceLoader.cs ResourceLoader.cs ResourceLoaderFactory.cs ResourceLocator.cs Log Message: --- NEW FILE: ResourceLocator.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using System.Collections; using System.IO; using System.Reflection; /// <summary> /// Locates a resource (file) in the file system or as a resource in an assembly. /// </summary> public class ResourceLocator { private String filename = String.Empty; private FileInfo file = null; private Boolean isFile = false; private Boolean isResource = false; private IList assemblies = new ArrayList(); private Assembly assembly = null; public ResourceLocator(String filename) { this.filename = filename; file = new FileInfo(this.filename); if (file.Exists) { this.filename = file.FullName; isFile = true; } else { // the calling Executing and Entry assemblies may not have links to each other - // so attempt to get assemblies from all possible paths. GetReferencedAssemblies(Assembly.GetExecutingAssembly(), assemblies); if (Assembly.GetEntryAssembly() != null) { GetReferencedAssemblies(Assembly.GetEntryAssembly(), assemblies); } if (Assembly.GetCallingAssembly() != null) { GetReferencedAssemblies(Assembly.GetCallingAssembly(), assemblies); } String fn = filename.ToLower().Replace(".\\", ""); fn = fn.Replace("\\", "."); fn = fn.Replace("/", "."); foreach (Assembly a in assemblies) { String prefix = a.FullName.Substring(0, a.FullName.IndexOf(",")).ToLower(); String[] names = a.GetManifestResourceNames(); foreach (String s in names) { if (s.ToLower().Equals(fn) || s.ToLower().Equals(prefix + "." + fn)) { this.filename = s; assembly = a; isResource = true; } } } } } public static void GetReferencedAssemblies(Assembly a, IList list) { String s = a.GetName().FullName; foreach (AssemblyName an in a.GetReferencedAssemblies()) { Assembly c = Assembly.Load(an); if (!list.Contains(c)) { list.Add(c); GetReferencedAssemblies(c, list); } } if (!list.Contains(a)) { list.Add(a); } } public Stream OpenRead() { if (isFile) { return file.OpenRead(); } else if (isResource) { return assembly.GetManifestResourceStream(filename); } else { throw new FileNotFoundException("Resource could not be found", filename); } } public String FullName { get { return this.filename; } } public Boolean Exists { get { return (isFile || isResource); } } private Stream FindResource(String path, String template) { try { FileInfo file = new FileInfo(path + "\\" + template); if (file.Exists) { return new BufferedStream(new FileStream(file.FullName, FileMode.Open, FileAccess.Read)); } else { IList list = new ArrayList(); GetReferencedAssemblies(Assembly.GetEntryAssembly(), list); foreach (Assembly a in list) { Stream s = a.GetManifestResourceStream(template); if (s != null) { return s; } } return null; } } catch (FileNotFoundException fnfe) { /* * log and convert to a general Velocity ResourceNotFoundException */ return null; } } } } --- NEW FILE: ResourceLoader.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using System.IO; using Commons.Collections; /// <summary> /// This is abstract class the all text resource loaders should extend. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: ResourceLoader.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $</version> public abstract class ResourceLoader { public virtual String ClassName { get { return className; } } public virtual bool CachingOn { set { isCachingOn_Renamed_Field = value; } } public virtual long ModificationCheckInterval { get { return modificationCheckInterval; } set { this.modificationCheckInterval = value; } } /// /// <summary> Does this loader want templates produced with it /// cached in the Runtime. /// </summary> protected internal bool isCachingOn_Renamed_Field = false; /// <summary> This property will be passed on to the templates /// that are created with this loader. /// </summary> protected internal long modificationCheckInterval = 2; /// <summary> Class name for this loader, for logging/debuggin /// purposes. /// </summary> protected internal String className = null; protected internal RuntimeServices rsvc = null; /// <summary> This initialization is used by all resource /// loaders and must be called to set up common /// properties shared by all resource loaders /// </summary> public virtual void commonInit(RuntimeServices rs, ExtendedProperties configuration) { this.rsvc = rs; /* * these two properties are not required for all loaders. * For example, for ClasspathLoader, what would cache mean? * so adding default values which I think are the safest * * don't cache, and modCheckInterval irrelevant... */ isCachingOn_Renamed_Field = configuration.GetBoolean("cache", false); modificationCheckInterval = configuration.GetLong("modificationCheckInterval", 0); /* * this is a must! */ className = configuration.GetString("class"); } /// /// <summary> Initialize the template loader with a /// a resources class. /// </summary> public abstract void init(ExtendedProperties configuration); /// /// <summary> Get the InputStream that the Runtime will parse /// to create a template. /// </summary> public abstract Stream getResourceStream(String source); /// <summary> Given a template, check to see if the source of InputStream /// has been modified. /// </summary> public abstract bool isSourceModified(Resource resource); /// <summary> Get the last modified time of the InputStream source /// that was used to create the template. We need the template /// here because we have to extract the name of the template /// in order to locate the InputStream source. /// </summary> public abstract long getLastModified(Resource resource); /// <summary> Return the class name of this resource Loader /// </summary> /// <summary> Set the caching state. If true, then this loader /// would like the Runtime to cache templates that /// have been created with InputStreams provided /// by this loader. /// </summary> /// <summary> The Runtime uses this to find out whether this /// template loader wants the Runtime to cache /// templates created with InputStreams provided /// by this loader. /// </summary> public virtual bool isCachingOn() { return isCachingOn_Renamed_Field; } /// <summary> Set the interval at which the InputStream source /// should be checked for modifications. /// </summary> /// <summary> Get the interval at which the InputStream source /// should be checked for modifications. /// </summary> } } --- NEW FILE: FileResourceLoader.cs --- /* 122704 SMM Removed code that calls StringUtils.normalizepath, since it caused the parse directive not to work correctly */ namespace NVelocity.Runtime.Resource.Loader { using System; using System.Collections; using System.IO; using Commons.Collections; using NVelocity.Exception; using NVelocity.Util; /// <summary> /// A loader for templates stored on the file system. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> </author> public class FileResourceLoader : ResourceLoader { /// <summary> /// The paths to search for templates. /// </summary> protected ArrayList paths = null; /// <summary> /// Used to map the path that a template was found on /// so that we can properly check the modification /// times of the files. /// </summary> protected Hashtable templatePaths = new Hashtable(); public FileResourceLoader() { } public override void init(ExtendedProperties configuration) { rsvc.info("FileResourceLoader : initialization starting."); paths = configuration.GetVector("path"); // lets tell people what paths we will be using foreach (String path in paths) { rsvc.info("FileResourceLoader : adding path '" + path + "'"); } rsvc.info("FileResourceLoader : initialization complete."); } /// <summary> /// Get an InputStream so that the Runtime can build a /// template with it. /// </summary> /// <param name="name">name of template to get</param> /// <returns>InputStream containing the template /// @throws ResourceNotFoundException if template not found /// in the file template path. /// </returns> public override Stream getResourceStream(String templateName) { lock (this) { String template = null; int size = paths.Count; for (int i = 0; i < size; i++) { String path = (String) paths[i]; // Make sure we have a valid templateName. if (templateName == null || templateName.Length == 0) { // If we don't get a properly formed templateName // then there's not much we can do. So // we'll forget about trying to search // any more paths for the template. throw new ResourceNotFoundException("Need to specify a file name or file path!"); } // template = StringUtils.normalizePath(templateName); // if (template == null || template.Length == 0) // { // String msg = "File resource error : argument " + template + " contains .. and may be trying to access " + "content outside of template root. Rejected."; // // rsvc.error("FileResourceLoader : " + msg); // // throw new ResourceNotFoundException(msg); // } // if a / leads off, then just nip that :) // if (template.StartsWith("/")) // { // template = template.Substring(1); // } Stream inputStream = findTemplate(templateName); if (inputStream != null) { // Store the path that this template came // from so that we can check its modification // time. SupportClass.PutElement(templatePaths, templateName, path); return inputStream; } } // We have now searched all the paths for // templates and we didn't find anything so // throw an exception. String msg2 = "FileResourceLoader Error: cannot find resource " + template; throw new ResourceNotFoundException(msg2); } } /// <summary> /// Try to find a template given a normalized path. /// </summary> /// <param name="String">a normalized path</param> /// <returns>InputStream input stream that will be parsed</returns> private Stream findTemplate(String template) { try { ResourceLocator rl = new ResourceLocator(template); if (rl.Exists) { return new BufferedStream(rl.OpenRead()); } else { return null; } } catch (FileNotFoundException fnfe) { // log and convert to a general Velocity ResourceNotFoundException return null; } } /// <summary> /// How to keep track of all the modified times /// across the paths. /// </summary> public override bool isSourceModified(Resource resource) { String path = (String) templatePaths[resource.Name]; FileInfo file = new FileInfo(path + "\\" + resource.Name); if (file.Exists) { if (file.LastWriteTime.Ticks != resource.LastModified) { return true; } else { return false; } } // If the file is now unreadable, or it has // just plain disappeared then we'll just say // that it's modified :-) When the loader attempts // to load the stream it will fail and the error // will be reported then. return true; } public override long getLastModified(Resource resource) { String path = (String) templatePaths[resource.Name]; FileInfo file = new FileInfo(resource.Name); if (file.Exists) { return file.LastWriteTime.Ticks; } else { return 0; } } } } --- NEW FILE: ResourceLoaderFactory.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using NVelocity.Util; /// <summary> /// Factory to grab a template loader. /// </summary> /// <author><a href="mailto:jv...@ap...">Jason van Zyl</a></author> public class ResourceLoaderFactory { /// <summary> /// Gets the loader specified in the configuration file. /// </summary> /// <returns>TemplateLoader</returns> public static ResourceLoader getLoader(RuntimeServices rs, String loaderClassName) { ResourceLoader loader = null; try { // since properties are parsed into arrays with commas, something else needed to be used loaderClassName = loaderClassName.Replace(';', ','); Type loaderType = Type.GetType(loaderClassName); Object o = Activator.CreateInstance(loaderType); loader = (ResourceLoader) o; rs.info("Resource Loader Instantiated: " + loader.GetType().FullName); return loader; } catch (Exception e) { rs.error("Problem instantiating the template loader.\n" + "Look at your properties file and make sure the\n" + "name of the template loader is correct. Here is the\n" + "error: " + StringUtils.stackTrace(e)); throw new Exception("Problem initializing template loader: " + loaderClassName + "\nError is: " + StringUtils.stackTrace(e)); } } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Defaults In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime/Defaults Added Files: directive.properties nvelocity.properties Log Message: --- NEW FILE: nvelocity.properties --- #---------------------------------------------------------------------------- # These are the default properties for the # NVelocity Runtime. These values are used when # Runtime.init() is called, and when Runtime.init(properties) # fails to find the specificed properties file. #---------------------------------------------------------------------------- #---------------------------------------------------------------------------- # R U N T I M E L O G #---------------------------------------------------------------------------- #---------------------------------------------------------------------------- # default LogSystem to use: default: SimpleLog4NetLogSystem #---------------------------------------------------------------------------- runtime.log.logsystem.class = NVelocity.Runtime.Log.SimpleLog4NetLogSystem #--------------------------------------------------------------------------- # This is the location of the NVelocity Runtime log. #---------------------------------------------------------------------------- runtime.log = nvelocity.log #---------------------------------------------------------------------------- # This controls if Runtime.error(), info() and warn() messages include the # whole stack trace. The last property controls whether invalid references # are logged. #---------------------------------------------------------------------------- runtime.log.error.stacktrace = false runtime.log.warn.stacktrace = false runtime.log.info.stacktrace = false runtime.log.invalid.reference = true #---------------------------------------------------------------------------- # Configuration for the Log4NetLogSystem. # You must define the runtime.log.logsystem.class property to be: # NVelocity.Runtime.Log.Log4NetLogSystem # # You must also include log4net dll files into your classpath. They are # included with the Velocity distribution in the build/lib directory. # # There are several different options that you can configure. # Uncomment the ones that you want and also define their settings. #---------------------------------------------------------------------------- #runtime.log.logsystem.log4net.pattern=%d - %m%n #runtime.log.logsystem.log4net.file.size=100000 #runtime.log.logsystem.log4net.file.backups=1 #runtime.log.logsystem.log4net.syslogd.host=my.syslog.server.com #runtime.log.logsystem.log4net.syslogd.facility=LOG_DAEMON #runtime.log.logsystem.log4net.remote.host=my.remote.server.com #runtime.log.logsystem.log4net.remote.port=1099 #runtime.log.logsystem.log4net.email.server=localhost #runtime.log.logsystem.log4net.email.from=root@localhost #runtime.log.logsystem.log4net.email.to=root@localhost #runtime.log.logsystem.log4net.email.subject=NVelocity Error Report #runtime.log.logsystem.log4net.email.buffer.size=512 #---------------------------------------------------------------------------- # T E M P L A T E E N C O D I N G #---------------------------------------------------------------------------- input.encoding=ISO-8859-1 output.encoding=ISO-8859-1 #---------------------------------------------------------------------------- # F O R E A C H P R O P E R T I E S #---------------------------------------------------------------------------- # These properties control how the counter is accessed in the #foreach # directive. By default the reference $velocityCount will be available # in the body of the #foreach directive. The default starting value # for this reference is 1. #---------------------------------------------------------------------------- directive.foreach.counter.name = velocityCount directive.foreach.counter.initial.value = 1 #---------------------------------------------------------------------------- # I N C L U D E P R O P E R T I E S #---------------------------------------------------------------------------- # These are the properties that governed the way #include'd content # is governed. #---------------------------------------------------------------------------- directive.include.output.errormsg.start = <!-- include error : directive.include.output.errormsg.end = see error log --> #---------------------------------------------------------------------------- # P A R S E P R O P E R T I E S #---------------------------------------------------------------------------- directive.parse.max.depth = 10 #---------------------------------------------------------------------------- # T E M P L A T E L O A D E R S #---------------------------------------------------------------------------- # # #---------------------------------------------------------------------------- resource.loader = file file.resource.loader.description = NVelocity File Resource Loader file.resource.loader.class = NVelocity.Runtime.Resource.Loader.FileResourceLoader file.resource.loader.path = . file.resource.loader.cache = false file.resource.loader.modificationCheckInterval = 2 #---------------------------------------------------------------------------- # VELOCIMACRO PROPERTIES #---------------------------------------------------------------------------- # global : name of default global library. It is expected to be in the regular # template path. You may remove it (either the file or this property) if # you wish with no harm. #---------------------------------------------------------------------------- velocimacro.library = VM_global_library.vm velocimacro.permissions.allow.inline = true velocimacro.permissions.allow.inline.to.replace.global = false velocimacro.permissions.allow.inline.local.scope = false velocimacro.context.localscope = false #---------------------------------------------------------------------------- # INTERPOLATION #---------------------------------------------------------------------------- # turn off and on interpolation of references and directives in string # literals. ON by default :) #---------------------------------------------------------------------------- runtime.interpolate.string.literals = true #---------------------------------------------------------------------------- # RESOURCE MANAGEMENT #---------------------------------------------------------------------------- # Allows alternative ResourceManager and ResourceCache implementations # to be plugged in. #---------------------------------------------------------------------------- resource.manager.class = NVelocity.Runtime.Resource.ResourceManagerImpl resource.manager.cache.class = NVelocity.Runtime.Resource.ResourceCacheImpl --- NEW FILE: directive.properties --- directive.1=NVelocity.Runtime.Directive.Foreach directive.2=NVelocity.Runtime.Directive.Include directive.3=NVelocity.Runtime.Directive.Parse directive.4=NVelocity.Runtime.Directive.Macro directive.5=NVelocity.Runtime.Directive.Literal |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Exception In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Exception Added Files: MethodInvocationException.cs ParseErrorException.cs ResourceNotFoundException.cs VelocityException.cs Log Message: --- NEW FILE: VelocityException.cs --- namespace NVelocity.Exception { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Base class for Velocity exceptions thrown to the /// application layer. /// * /// </summary> /// <author> <a href="mailto:kd...@am...">Kyle F. Downey</a> /// </author> /// <version> $Id: VelocityException.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public class VelocityException : Exception { public VelocityException(String exceptionMessage) : base(exceptionMessage) { } } } --- NEW FILE: MethodInvocationException.cs --- namespace NVelocity.Exception { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Application-level exception thrown when a reference method is /// invoked and an exception is thrown. /// <br> /// When this exception is thrown, a best effort will be made to have /// useful information in the exception's message. For complete /// information, consult the runtime log. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: MethodInvocationException.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public class MethodInvocationException : VelocityException { public virtual String MethodName { get { return methodName; } } public virtual Exception WrappedThrowable { get { return wrapped; } } public virtual String ReferenceName { get { return referenceName; } set { referenceName = value; } } private String methodName = ""; private String referenceName = ""; //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' private Exception wrapped = null; /// <summary> CTOR - wraps the passed in exception for /// examination later /// * /// </summary> /// <param name="message"> /// </param> /// <param name="e">Throwable that we are wrapping /// </param> /// <param name="methodName">name of method that threw the exception /// /// </param> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' public MethodInvocationException(String message, Exception e, String methodName) : base(message) { this.wrapped = e; this.methodName = methodName; } /// <summary> Returns the name of the method that threw the /// exception /// * /// </summary> /// <returns>String name of method /// /// </returns> /// <summary> returns the wrapped Throwable that caused this /// MethodInvocationException to be thrown /// /// </summary> /// <returns>Throwable thrown by method invocation /// /// </returns> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' /// <summary> Sets the reference name that threw this exception /// * /// </summary> /// <param name="reference">name of reference /// /// </param> /// <summary> Retrieves the name of the reference that caused the /// exception /// * /// </summary> /// <returns>name of reference /// /// </returns> } } --- NEW FILE: ResourceNotFoundException.cs --- namespace NVelocity.Exception { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Application-level exception thrown when a resource of any type /// isn't found by the Velocity engine. /// <br> /// When this exception is thrown, a best effort will be made to have /// useful information in the exception's message. For complete /// information, consult the runtime log. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:dl...@fi...">Daniel Rall</a> /// </author> /// <version> $Id: ResourceNotFoundException.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public class ResourceNotFoundException : VelocityException { public ResourceNotFoundException(String exceptionMessage) : base(exceptionMessage) { } } } --- NEW FILE: ParseErrorException.cs --- namespace NVelocity.Exception { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Application-level exception thrown when a resource of any type /// has a syntax or other error which prevents it from being parsed. /// <br> /// When this resource is thrown, a best effort will be made to have /// useful information in the exception's message. For complete /// information, consult the runtime log. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ParseErrorException.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public class ParseErrorException : VelocityException { public ParseErrorException(String exceptionMessage) : base(exceptionMessage) { } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/IO In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/IO Added Files: VelocityWriter.cs Log Message: --- NEW FILE: VelocityWriter.cs --- //package org.apache.velocity.io; // // //import java.io.IOException; //import java.io.OutputStreamWriter; //import java.io.Writer; namespace NVelocity.IO { using System; using System.IO; using System.Text; /** * Implementation of a fast Writer. It was originally taken from JspWriter * and modified to have less syncronization going on. * * @author <a href="mailto:jv...@ap...">Jason van Zyl</a> * @author <a href="mailto:jo...@la...">Jon S. Stevens</a> * @author Anil K. Vijendran * @version $Id: VelocityWriter.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ */ // TODO: class was final and it appears that readonly and final are not the same thing - most of the methods were final as well public class VelocityWriter : TextWriter { /** * constant indicating that the Writer is not buffering output */ public static readonly int NO_BUFFER = 0; /** * constant indicating that the Writer is buffered and is using the * implementation default buffer size */ public static readonly int DEFAULT_BUFFER = -1; /** * constant indicating that the Writer is buffered and is unbounded; * this is used in BodyContent */ public static readonly int UNBOUNDED_BUFFER = -2; protected int bufferSize; protected Boolean autoFlush; private TextWriter writer; private char[] cb; private int nextChar; private static int defaultCharBufferSize = 8*1024; private Boolean flushed = false; /** * Create a buffered character-output stream that uses a default-sized * output buffer. * * @param response A Servlet Response */ public VelocityWriter(TextWriter writer) : this(writer, defaultCharBufferSize, true) { } /** * private constructor. */ private VelocityWriter(int bufferSize, Boolean autoFlush) { this.bufferSize = bufferSize; this.autoFlush = autoFlush; } /** * This method returns the size of the buffer used by the JspWriter. * * @return the size of the buffer in bytes, or 0 is unbuffered. */ public int getBufferSize() { return bufferSize; } /** * This method indicates whether the JspWriter is autoFlushing. * * @return if this JspWriter is auto flushing or throwing IOExceptions on * buffer overflow conditions */ public Boolean isAutoFlush() { return autoFlush; } /** * Create a new buffered character-output stream that uses an output * buffer of the given size. * * @param response A Servlet Response * @param sz Output-buffer size, a positive integer * * @exception IllegalArgumentException If sz is <= 0 */ public VelocityWriter(TextWriter writer, int sz, Boolean autoFlush) : this(sz, autoFlush) { if (sz < 0) throw new ArgumentOutOfRangeException("Buffer size <= 0"); this.writer = writer; cb = sz == 0 ? null : new char[sz]; nextChar = 0; } private void init(TextWriter writer, int sz, Boolean autoFlush) { this.writer = writer; if (sz > 0 && (cb == null || sz > cb.Length)) cb = new char[sz]; nextChar = 0; this.autoFlush = autoFlush; this.bufferSize = sz; } /** * Flush the output buffer to the underlying character stream, without * flushing the stream itself. This method is non-private only so that it * may be invoked by PrintStream. */ private void flushBuffer() { //throws IOException if (bufferSize == 0) return; flushed = true; if (nextChar == 0) return; writer.Write(cb, 0, nextChar); nextChar = 0; } /** * Discard the output buffer. */ public void clear() { nextChar = 0; } private void bufferOverflow() { // throws IOException throw new IOException("overflow"); } /** * Flush the stream. * */ public void flush() { // throws IOException flushBuffer(); if (writer != null) { writer.Flush(); } } /** * Close the stream. * */ public void close() { //throws IOException { if (writer == null) return; flush(); } /** * @return the number of bytes unused in the buffer */ public int getRemaining() { return bufferSize - nextChar; } /** * Write a single character. * */ public void write(int c) { //throws IOException { if (bufferSize == 0) { writer.Write(c); } else { if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); cb[nextChar++] = (char) c; } } /** * Our own little min method, to avoid loading java.lang.Math if we've run * out of file descriptors and we're trying to print a stack trace. */ private int min(int a, int b) { if (a < b) return a; return b; } /** * Write a portion of an array of characters. * * <p> Ordinarily this method stores characters from the given array into * this stream's buffer, flushing the buffer to the underlying stream as * needed. If the requested length is at least as large as the buffer, * however, then this method will flush the buffer and write the characters * directly to the underlying stream. Thus redundant * <code>DiscardableBufferedWriter</code>s will not copy data unnecessarily. * * @param cbuf A character array * @param off Offset from which to start reading characters * @param len Number of characters to write * */ public void write(char[] cbuf, int off, int len) { //throws IOException { if (bufferSize == 0) { writer.Write(cbuf, off, len); return; } if (len == 0) { return; } if (len >= bufferSize) { /* If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ if (autoFlush) flushBuffer(); else bufferOverflow(); writer.Write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); Array.Copy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } } /** * Write an array of characters. This method cannot be inherited from the * Writer class because it must suppress I/O exceptions. */ public void write(char[] buf) { //throws IOException { write(buf, 0, buf.Length); } /** * Write a portion of a String. * * @param s String to be written * @param off Offset from which to start reading characters * @param len Number of characters to be written * */ public void write(String s, int off, int len) { //throws IOException { if (bufferSize == 0) { writer.Write(s, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); Array.Copy(s.ToCharArray(), b, cb, nextChar, b + d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } } /** * Write a string. This method cannot be inherited from the Writer class * because it must suppress I/O exceptions. */ public void write(String s) { //throws IOException { write(s, 0, s.Length); } /** * resets this class so that it can be reused * */ public void recycle(TextWriter writer) { this.writer = writer; flushed = false; clear(); } // needed to extend TextWriter public override Encoding Encoding { get { return writer.Encoding; } } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Context In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Context Added Files: AbstractContext.cs IContext.cs InternalContextAdapter.cs InternalContextAdapterImpl.cs InternalContextBase.cs InternalEventContext.cs InternalHousekeepingContext.cs InternalWrapperContext.cs VMContext.cs Log Message: --- NEW FILE: InternalEventContext.cs --- namespace NVelocity.Context { using NVelocity.App.Events; /// <summary> /// Interface for event support. Note that this is a public internal /// interface, as it is something that will be accessed from outside /// of the .context package. /// </summary> public interface InternalEventContext { EventCartridge EventCartridge { get; } EventCartridge AttachEventCartridge(EventCartridge ec); } } --- NEW FILE: InternalContextBase.cs --- namespace NVelocity.Context { using System; using System.Collections; using NVelocity.App.Events; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> class to encapsulate the 'stuff' for internal operation of velocity. /// We use the context as a thread-safe storage : we take advantage of the /// fact that it's a visitor of sorts to all nodes (that matter) of the /// AST during init() and render(). /// Currently, it carries the template name for namespace /// support, as well as node-local context data introspection caching. /// * /// Note that this is not a public class. It is for package access only to /// keep application code from accessing the internals, as AbstractContext /// is derived from this. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: InternalContextBase.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> [Serializable] public class InternalContextBase : InternalHousekeepingContext, InternalEventContext { //, System.Runtime.Serialization.ISerializable { public InternalContextBase() { InitBlock(); } private void InitBlock() { introspectionCache = new Hashtable(33); templateNameStack = new Stack(); } public virtual String CurrentTemplateName { get { if ((templateNameStack.Count == 0)) return "<undef>"; else return (String) templateNameStack.Peek(); } } public virtual Object[] TemplateNameStack { get { return templateNameStack.ToArray(); } } public virtual Resource CurrentResource { get { return currentResource; } set { currentResource = value; } } public virtual EventCartridge EventCartridge { get { return eventCartridge; } } /// <summary> cache for node/context specific introspection information /// </summary> //UPGRADE_NOTE: The initialization of 'introspectionCache' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Hashtable introspectionCache; /// <summary> Template name stack. The stack top contains the current template name. /// </summary> //UPGRADE_NOTE: The initialization of 'templateNameStack' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Stack templateNameStack; /// <summary> EventCartridge we are to carry. Set by application /// </summary> private EventCartridge eventCartridge = null; /// <summary> Current resource - used for carrying encoding and other /// information down into the rendering process /// </summary> private Resource currentResource = null; /// <summary> set the current template name on top of stack /// * /// </summary> /// <param name="s">current template name /// /// </param> public virtual void PushCurrentTemplateName(String s) { Object temp_object; temp_object = s; Object generatedAux = temp_object; templateNameStack.Push(temp_object); return; } /// <summary> remove the current template name from stack /// </summary> public virtual void PopCurrentTemplateName() { templateNameStack.Pop(); return; } /// <summary> get the current template name /// * /// </summary> /// <returns>String current template name /// /// </returns> /// <summary> get the current template name stack /// * /// </summary> /// <returns>Object[] with the template name stack contents. /// /// </returns> /// <seealso cref=" IntrospectionCacheData) /// object if exists for the key /// * /// "/> /// <param name="key"> key to find in cache /// </param> /// <returns>cache object /// /// </returns> public virtual IntrospectionCacheData ICacheGet(Object key) { return (IntrospectionCacheData) introspectionCache[key]; } /// <seealso cref=" IntrospectionCacheData) /// element in the cache for specified key /// * /// "/> /// <param name="key"> key /// </param> /// <param name="o"> IntrospectionCacheData object to place in cache /// /// </param> public virtual void ICachePut(Object key, IntrospectionCacheData o) { introspectionCache[key] = o; } public virtual EventCartridge AttachEventCartridge(EventCartridge ec) { EventCartridge temp = eventCartridge; eventCartridge = ec; return temp; } } } --- NEW FILE: InternalWrapperContext.cs --- namespace NVelocity.Context { /// <summary> /// interface for internal context wrapping functionality /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: InternalWrapperContext.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ </version> public interface InternalWrapperContext { /// <summary> /// returns the wrapped user context /// </summary> IContext InternalUserContext { get; } /// <summary> /// returns the base full context impl /// </summary> InternalContextAdapter BaseContext { get; } } } --- NEW FILE: AbstractContext.cs --- namespace NVelocity.Context { using System; /// <summary> This class is the abstract base class for all conventional /// Velocity Context implementations. Simply extend this class /// and implement the abstract routines that access your preferred /// storage method. /// * /// Takes care of context chaining. /// * /// Also handles / enforces policy on null keys and values : /// * /// <ul> /// <li> Null keys and values are accepted and basically dropped. /// <li> If you place an object into the context with a null key, it /// will be ignored and logged. /// <li> If you try to place a null into the context with any key, it /// will be dropped and logged. /// </ul> /// * /// The default implementation of this for application use is /// org.apache.velocity.VelocityContext. /// * /// All thanks to Fedor for the chaining idea. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:fed...@ho...">Fedor Karpelevitch</a> /// </author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: AbstractContext.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> [Serializable] public abstract class AbstractContext : InternalContextBase, IContext { //, System.Runtime.Serialization.ISerializable public virtual Object[] Keys { get { return InternalGetKeys(); } } public virtual IContext ChainedContext { get { return innerContext; } } /// <summary> the chained Context if any /// </summary> private IContext innerContext = null; /// /// <summary> Implement to return a value from the context storage. /// <br><br> /// The implementation of this method is required for proper /// operation of a Context implementation in general /// Velocity use. /// /// </summary> /// <param name="key">key whose associated value is to be returned /// </param> /// <returns>object stored in the context /// /// </returns> public abstract Object InternalGet(String key); /// /// <summary> Implement to put a value into the context storage. /// <br><br> /// The implementation of this method is required for /// proper operation of a Context implementation in /// general Velocity use. /// * /// </summary> /// <param name="key">key with which to associate the value /// </param> /// <param name="value">value to be associated with the key /// </param> /// <returns>previously stored value if exists, or null /// /// </returns> public abstract Object InternalPut(String key, Object value_Renamed); /// /// <summary> Implement to determine if a key is in the storage. /// <br><br> /// Currently, this method is not used internally by /// the Velocity core. /// * /// </summary> /// <param name="key">key to test for existance /// </param> /// <returns>true if found, false if not /// /// </returns> public abstract bool InternalContainsKey(Object key); /// /// <summary> Implement to return an object array of key /// strings from your storage. /// <br><br> /// Currently, this method is not used internally by /// the Velocity core. /// * /// </summary> /// <returns>array of keys /// /// </returns> public abstract Object[] InternalGetKeys(); /// /// <summary> I mplement to remove an item from your storage. /// <br><br> /// Currently, this method is not used internally by /// the Velocity core. /// * /// </summary> /// <param name="key">key to remove /// </param> /// <returns>object removed if exists, else null /// /// </returns> public abstract Object InternalRemove(Object key); /// <summary> default CTOR /// </summary> public AbstractContext() { } /// <summary> Chaining constructor accepts a Context argument. /// It will relay get() operations into this Context /// in the even the 'local' get() returns null. /// /// </summary> /// <param name="inner">context to be chained /// /// </param> public AbstractContext(IContext inner) { innerContext = inner; /* * now, do a 'forward pull' of event cartridge so * it's accessable, bringing to the top level. */ if (innerContext is InternalEventContext) { AttachEventCartridge(((InternalEventContext) innerContext).EventCartridge); } } /// <summary> Adds a name/value pair to the context. /// /// </summary> /// <param name="key"> The name to key the provided value with. /// </param> /// <param name="value">The corresponding value. /// </param> /// <returns>Object that was replaced in the the Context if /// applicable or null if not. /// /// </returns> public virtual Object Put(String key, Object value_Renamed) { /* * don't even continue if key or value is null */ if (key == null) { return null; } else if (value_Renamed == null) { return null; } return InternalPut(key, value_Renamed); } /// <summary> Gets the value corresponding to the provided key from the context. /// * /// Supports the chaining context mechanism. If the 'local' context /// doesn't have the value, we try to get it from the chained context. /// * /// </summary> /// <param name="key">The name of the desired value. /// </param> /// <returns> The value corresponding to the provided key or null if /// the key param is null. /// /// </returns> public virtual Object Get(String key) { /* * punt if key is null */ if (key == null) { return null; } /* * get the object for this key. If null, and we are chaining another Context * call the get() on it. */ Object o = InternalGet(key); if (o == null && innerContext != null) { o = innerContext.Get(key); } return o; } /// <summary> Indicates whether the specified key is in the context. Provided for /// debugging purposes. /// * /// </summary> /// <param name="key">The key to look for. /// </param> /// <returns>true if the key is in the context, false if not. /// /// </returns> public virtual bool ContainsKey(Object key) { if (key == null) { return false; } return InternalContainsKey(key); } /// <summary> Get all the keys for the values in the context /// </summary> /// <returns>Object[] of keys in the Context. Does not return /// keys in chained context. /// /// </returns> /// <summary> Removes the value associated with the specified key from the context. /// * /// </summary> /// <param name="key">The name of the value to remove. /// </param> /// <returns> The value that the key was mapped to, or <code>null</code> /// if unmapped. /// /// </returns> public virtual Object Remove(Object key) { if (key == null) { return null; } return InternalRemove(key); } /// <summary> returns innerContext if one is chained /// * /// </summary> /// <returns>Context if chained, <code>null</code> if not /// /// </returns> } } --- NEW FILE: InternalContextAdapterImpl.cs --- namespace NVelocity.Context { using System; using NVelocity.App.Events; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> This adapter class is the container for all context types for internal /// use. The AST now uses this class rather than the app-level Context /// interface to allow flexibility in the future. /// * /// Currently, we have two context interfaces which must be supported : /// <ul> /// <li> Context : used for application/template data access /// <li> InternalHousekeepingContext : used for internal housekeeping and caching /// <li> InternalWrapperContext : used for getting root cache context and other /// such. /// <li> InternalEventContext : for event handling. /// </ul> /// * /// This class implements the two interfaces to ensure that all methods are /// supported. When adding to the interfaces, or adding more context /// functionality, the interface is the primary definition, so alter that first /// and then all classes as necessary. As of this writing, this would be /// the only class affected by changes to InternalContext /// * /// This class ensures that an InternalContextBase is available for internal /// use. If an application constructs their own Context-implementing /// object w/o subclassing AbstractContext, it may be that support for /// InternalContext is not available. Therefore, InternalContextAdapter will /// create an InternalContextBase if necessary for this support. Note that /// if this is necessary, internal information such as node-cache data will be /// lost from use to use of the context. This may or may not be important, /// depending upon application. /// /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: InternalContextAdapterImpl.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> //TODO: class was sealed public class InternalContextAdapterImpl : InternalContextAdapter { public virtual String CurrentTemplateName { get { return icb.CurrentTemplateName; } } public virtual Object[] TemplateNameStack { get { return icb.TemplateNameStack; } } public virtual Resource CurrentResource { get { return icb.CurrentResource; } set { icb.CurrentResource = value; } } public virtual Object[] Keys { get { return context.Keys; } } public virtual IContext InternalUserContext { get { return context; } } public virtual InternalContextAdapter BaseContext { get { return this; } } public virtual EventCartridge EventCartridge { get { if (iec != null) { return iec.EventCartridge; } return null; } } /// /// <summary> the user data Context that we are wrapping /// </summary> internal IContext context = null; /// /// <summary> the ICB we are wrapping. We may need to make one /// if the user data context implementation doesn't /// support one. The default AbstractContext-derived /// VelocityContext does, and it's recommended that /// people derive new contexts from AbstractContext /// rather than piecing things together /// </summary> internal InternalHousekeepingContext icb = null; /// <summary> The InternalEventContext that we are wrapping. If /// the context passed to us doesn't support it, no /// biggie. We don't make it for them - since its a /// user context thing, nothing gained by making one /// for them now /// </summary> internal InternalEventContext iec = null; /// <summary> CTOR takes a Context and wraps it, delegating all 'data' calls /// to it. /// /// For support of internal contexts, it will create an InternalContextBase /// if need be. /// </summary> public InternalContextAdapterImpl(IContext c) { context = c; if (!(c is InternalHousekeepingContext)) { icb = new InternalContextBase(); } else { icb = (InternalHousekeepingContext) context; } if (c is InternalEventContext) { iec = (InternalEventContext) context; } } /* --- InternalHousekeepingContext interface methods --- */ public void PushCurrentTemplateName(String s) { icb.PushCurrentTemplateName(s); } public void PopCurrentTemplateName() { icb.PopCurrentTemplateName(); } public IntrospectionCacheData ICacheGet(Object key) { return icb.ICacheGet(key); } public void ICachePut(Object key, IntrospectionCacheData o) { icb.ICachePut(key, o); } /* --- Context interface methods --- */ public Object Put(String key, Object value_Renamed) { return context.Put(key, value_Renamed); } public Object Get(String key) { return context.Get(key); } public bool ContainsKey(Object key) { return context.ContainsKey(key); } public Object Remove(Object key) { return context.Remove(key); } /* ---- InternalWrapperContext --- */ /// <summary> returns the user data context that /// we are wrapping /// </summary> /// <summary> Returns the base context that we are /// wrapping. Here, its this, but for other thing /// like VM related context contortions, it can /// be something else /// </summary> /* ----- InternalEventContext ---- */ public EventCartridge AttachEventCartridge(EventCartridge ec) { if (iec != null) { return iec.AttachEventCartridge(ec); } return null; } } } --- NEW FILE: VMContext.cs --- namespace NVelocity.Context { using System; using System.Collections; using NVelocity.App.Events; using NVelocity.Runtime; using NVelocity.Runtime.Directive; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> This is a special, internal-use-only context implementation to be /// used for the new Velocimacro implementation. /// * /// The main distinguishing feature is the management of the VMProxyArg objects /// in the put() and get() methods. /// * /// Further, this context also supports the 'VM local context' mode, where /// any get() or put() of references that aren't args to the VM are considered /// local to the vm, protecting the global context. /// /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: VMContext.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public class VMContext : InternalContextAdapter { private void InitBlock() { vmproxyhash = new Hashtable(); localcontext = new Hashtable(); } public virtual IContext InternalUserContext { get { return innerContext.InternalUserContext; } } public virtual InternalContextAdapter BaseContext { get { return innerContext.BaseContext; } } public virtual Object[] Keys { get { // TODO //return vmproxyhash.keySet().toArray(); throw new NotImplementedException(); } } public virtual String CurrentTemplateName { get { return innerContext.CurrentTemplateName; } } public virtual Object[] TemplateNameStack { get { return innerContext.TemplateNameStack; } } public virtual EventCartridge EventCartridge { get { return innerContext.EventCartridge; } } public virtual Resource CurrentResource { get { return innerContext.CurrentResource; } set { innerContext.CurrentResource = value; } } /// <summary>container for our VMProxy Objects /// </summary> //UPGRADE_NOTE: The initialization of 'vmproxyhash' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' internal Hashtable vmproxyhash; /// <summary>container for any local or constant VMProxy items /// </summary> //UPGRADE_NOTE: The initialization of 'localcontext' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' internal Hashtable localcontext; /// <summary>the base context store. This is the 'global' context /// </summary> internal InternalContextAdapter innerContext = null; /// <summary>context that we are wrapping /// </summary> internal InternalContextAdapter wrappedContext = null; /// <summary>support for local context scope feature, where all references are local /// </summary> private bool localcontextscope = false; /// <summary> CTOR, wraps an ICA /// </summary> public VMContext(InternalContextAdapter inner, RuntimeServices rsvc) { InitBlock(); localcontextscope = rsvc.getBoolean(RuntimeConstants_Fields.VM_CONTEXT_LOCALSCOPE, false); wrappedContext = inner; innerContext = inner.BaseContext; } /// <summary> return the inner / user context /// </summary> /// <summary> Used to put VMProxyArgs into this context. It separates /// the VMProxyArgs into constant and non-constant types /// pulling out the value of the constant types so they can /// be modified w/o damaging the VMProxyArg, and leaving the /// dynamic ones, as they modify context rather than their own /// state /// </summary> /// <param name="vmpa">VMProxyArg to add /// /// </param> public virtual void AddVMProxyArg(VMProxyArg vmpa) { /* * ask if it's a constant : if so, get the value and put into the * local context, otherwise, put the vmpa in our vmproxyhash */ String key = vmpa.ContextReference; if (vmpa.isConstant()) { localcontext[key] = vmpa.getObject(wrappedContext); } else { vmproxyhash[key] = vmpa; } } /// <summary> Impl of the Context.put() method. /// * /// </summary> /// <param name="key">name of item to set /// </param> /// <param name="value">object to set to key /// </param> /// <returns>old stored object /// /// </returns> public virtual Object Put(String key, Object value_Renamed) { /* * first see if this is a vmpa */ VMProxyArg vmpa = (VMProxyArg) vmproxyhash[key]; if (vmpa != null) { return vmpa.setObject(wrappedContext, value_Renamed); } else { if (localcontextscope) { /* * if we have localcontextscope mode, then just * put in the local context */ return localcontext[key] = value_Renamed; } else { /* * ok, how about the local context? */ if (localcontext.ContainsKey(key)) { return localcontext[key] = value_Renamed; } else { /* * otherwise, let them push it into the 'global' context */ return innerContext.Put(key, value_Renamed); } } } } /// <summary> Impl of the Context.gut() method. /// * /// </summary> /// <param name="key">name of item to get /// </param> /// <returns> stored object or null /// /// </returns> public virtual Object Get(String key) { /* * first, see if it's a VMPA */ Object o = null; VMProxyArg vmpa = (VMProxyArg) vmproxyhash[key]; if (vmpa != null) { o = vmpa.getObject(wrappedContext); } else { if (localcontextscope) { /* * if we have localcontextscope mode, then just * put in the local context */ o = localcontext[key]; } else { /* * try the local context */ o = localcontext[key]; if (o == null) { /* * last chance */ o = innerContext.Get(key); } } } return o; } /// <summary> not yet impl /// </summary> public virtual bool ContainsKey(Object key) { return false; } /// <summary> impl badly /// </summary> /// <summary> impl badly /// </summary> public virtual Object Remove(Object key) { Object o = vmproxyhash[key]; vmproxyhash.Remove(key); return o; } public virtual void PushCurrentTemplateName(String s) { innerContext.PushCurrentTemplateName(s); } public virtual void PopCurrentTemplateName() { innerContext.PopCurrentTemplateName(); } public virtual IntrospectionCacheData ICacheGet(Object key) { return innerContext.ICacheGet(key); } public virtual void ICachePut(Object key, IntrospectionCacheData o) { innerContext.ICachePut(key, o); } public virtual EventCartridge AttachEventCartridge(EventCartridge ec) { return innerContext.AttachEventCartridge(ec); } } } --- NEW FILE: InternalContextAdapter.cs --- namespace NVelocity.Context { /// <summary> interface to bring all necessary internal and user contexts together. /// this is what the AST expects to deal with. If anything new comes /// along, add it here. /// * /// I will rename soon :) /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: InternalContextAdapter.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public interface InternalContextAdapter : InternalHousekeepingContext, IContext, InternalWrapperContext, InternalEventContext { } } --- NEW FILE: InternalHousekeepingContext.cs --- namespace NVelocity.Context { using System; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> /// interface to encapsulate the 'stuff' for internal operation of velocity. /// We use the context as a thread-safe storage : we take advantage of the /// fact that it's a visitor of sorts to all nodes (that matter) of the /// AST during init() and render(). /// /// Currently, it carries the template name for namespace /// support, as well as node-local context data introspection caching. /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:Chr...@dl...">Christoph Reck</a></author> /// <version> $Id: InternalHousekeepingContext.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $</version> public interface InternalHousekeepingContext { String CurrentTemplateName { get; } Object[] TemplateNameStack { get; } Resource CurrentResource { get; set; } /// <summary> /// set the current template name on top of stack /// </summary> /// <param name="s">current template name</param> void PushCurrentTemplateName(String s); /// <summary> /// remove the current template name from stack /// </summary> void PopCurrentTemplateName(); /// <summary> get the current template name /// * /// </summary> /// <returns>String current template name /// /// </returns> /// <summary> Returns the template name stack in form of an array. /// * /// </summary> /// <returns>Object[] with the template name stack contents. /// /// </returns> /// <seealso cref=" IntrospectionCacheData) /// object if exists for the key /// * /// "/> /// <param name="key"> key to find in cache /// </param> /// <returns>cache object /// /// </returns> IntrospectionCacheData ICacheGet(Object key); /// <seealso cref=" IntrospectionCacheData) /// element in the cache for specified key /// * /// "/> /// <param name="key"> key /// </param> /// <param name="o"> IntrospectionCacheData object to place in cache /// /// </param> void ICachePut(Object key, IntrospectionCacheData o); /// <summary> /// temporary fix to enable #include() to figure out /// current encoding. /// </summary> } } --- NEW FILE: IContext.cs --- namespace NVelocity.Context { using System; /// <summary> /// Interface describing the application data context. This set of /// routines is used by the application to set and remove 'named' data /// object to pass them to the template engine to use when rendering /// a template. /// /// This is the same set of methods supported by the original Context /// class /// </summary> /// <seealso cref="NVelocity.Context.AbstractContext"/> /// <seealso cref="NVelocity.VelocityContext"/> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> public interface IContext { /// <summary> /// Adds a name/value pair to the context. /// </summary> /// <param name="key">The name to key the provided value with.</param> /// <param name="value">The corresponding value.</param> Object Put(String key, Object value); /// <summary> /// Gets the value corresponding to the provided key from the context. /// </summary> /// <param name="key">The name of the desired value.</param> /// <returns>The value corresponding to the provided key.</returns> Object Get(String key); /// <summary> /// Indicates whether the specified key is in the context. /// </summary> /// <param name="key">The key to look for.</param> /// <returns>Whether the key is in the context.</returns> Boolean ContainsKey(Object key); /// <summary> /// Get all the keys for the values in the context /// </summary> Object[] Keys { get; } /// <summary> /// Removes the value associated with the specified key from the context. /// </summary> /// <param name="key">The name of the value to remove.</param> /// <returns>The value that the key was mapped to, or <code>null</code> if unmapped.</returns> Object Remove(Object key); } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:32
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Directive In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime/Directive Added Files: Directive.cs DirectiveConstants.cs Foreach.cs Include.cs Literal.cs Macro.cs Parse.cs ParseDirectiveException.cs VMProxyArg.cs VelocimacroProxy.cs Log Message: --- NEW FILE: Directive.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Parser.Node; /// <summary> Base class for all directives used in Velocity. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: Directive.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public abstract class Directive : DirectiveConstants //,System.ICloneable { public abstract String Name { get; set; } public abstract int Type { get; } public virtual int Line { get { return line; } } public virtual int Column { get { return column; } } private int line = 0; private int column = 0; protected internal RuntimeServices rsvc = null; /// <summary>Return the name of this directive /// </summary> /// <summary>Get the directive type BLOCK/LINE /// </summary> /// <summary>Allows the template location to be set /// </summary> public virtual void setLocation(int line, int column) { this.line = line; this.column = column; } /// <summary>for log msg purposes /// </summary> /// <summary>for log msg purposes /// </summary> /// <summary> How this directive is to be initialized. /// </summary> public virtual void init(RuntimeServices rs, InternalContextAdapter context, INode node) { rsvc = rs; // int i, k = node.jjtGetNumChildren(); //for (i = 0; i < k; i++) // node.jjtGetChild(i).init(context, rs); } /// <summary> How this directive is to be rendered /// </summary> public abstract bool render(InternalContextAdapter context, TextWriter writer, INode node); } } --- NEW FILE: VelocimacroProxy.cs --- namespace NVelocity.Runtime.Directive { using System; using System.Collections; using System.IO; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Visitor; using NVelocity.Util; /// <summary> /// VelocimacroProxy.java /// a proxy Directive-derived object to fit with the current directive system /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: VelocimacroProxy.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ </version> public class VelocimacroProxy : Directive { public VelocimacroProxy() { InitBlock(); } private void InitBlock() { proxyArgHash = new Hashtable(); } public override String Name { get { return macroName; } set { macroName = value; } } public override int Type { get { return DirectiveConstants_Fields.LINE; } } public virtual String[] ArgArray { set { argArray = value; /* * get the arg count from the arg array. remember that the arg array * has the macro name as it's 0th element */ numMacroArgs = argArray.Length - 1; } } public virtual SimpleNode NodeTree { set { nodeTree = value; } } public virtual int NumArgs { get { return numMacroArgs; } } public virtual String Macrobody { set { macroBody = value; } } public virtual String Namespace { set { this.namespace_Renamed = value; } } private String macroName = ""; private String macroBody = ""; private String[] argArray = null; private SimpleNode nodeTree = null; private int numMacroArgs = 0; private String namespace_Renamed = ""; //UPGRADE_NOTE: Field init was renamed. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1029"' private bool init_Renamed_Field = false; private String[] callingArgs; private int[] callingArgTypes; //UPGRADE_NOTE: The initialization of 'proxyArgHash' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Hashtable proxyArgHash; /// <summary> Return name of this Velocimacro. /// </summary> /// <summary> Velocimacros are always LINE /// type directives. /// </summary> /// <summary> sets the directive name of this VM /// </summary> /// <summary> sets the array of arguments specified in the macro definition /// </summary> /// <summary> returns the number of ars needed for this VM /// </summary> /// <summary> Sets the orignal macro body. This is simply the cat of the macroArray, but the /// Macro object creates this once during parsing, and everyone shares it. /// Note : it must not be modified. /// </summary> /// <summary> Renders the macro using the context /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, INode node) { try { /* * it's possible the tree hasn't been parsed yet, so get * the VMManager to parse and init it */ if (nodeTree != null) { if (!init_Renamed_Field) { nodeTree.init(context, rsvc); init_Renamed_Field = true; } /* * wrap the current context and add the VMProxyArg objects */ VMContext vmc = new VMContext(context, rsvc); for (int i = 1; i < argArray.Length; i++) { /* * we can do this as VMProxyArgs don't change state. They change * the context. */ VMProxyArg arg = (VMProxyArg) proxyArgHash[argArray[i]]; vmc.AddVMProxyArg(arg); } /* * now render the VM */ nodeTree.render(vmc, writer); } else { rsvc.error("VM error : " + macroName + ". Null AST"); } } catch (Exception e) { /* * if it's a MIE, it came from the render.... throw it... */ if (e is MethodInvocationException) { throw (MethodInvocationException) e; } rsvc.error("VelocimacroProxy.render() : exception VM = #" + macroName + "() : " + StringUtils.stackTrace(e)); } return true; } /// <summary> The major meat of VelocimacroProxy, init() checks the # of arguments, patches the /// macro body, renders the macro into an AST, and then inits the AST, so it is ready /// for quick rendering. Note that this is only AST dependant stuff. Not context. /// </summary> public override void init(RuntimeServices rs, InternalContextAdapter context, INode node) { base.init(rs, context, node); /* * how many args did we get? */ int i = node.jjtGetNumChildren(); /* * right number of args? */ if (NumArgs != i) { rsvc.error("VM #" + macroName + ": error : too " + ((NumArgs > i) ? "few" : "many") + " arguments to macro. Wanted " + NumArgs + " got " + i); return; } /* * get the argument list to the instance use of the VM */ callingArgs = getArgArray(node); /* * now proxy each arg in the context */ setupMacro(callingArgs, callingArgTypes); return; } /// <summary> /// basic VM setup. Sets up the proxy args for this /// use, and parses the tree /// </summary> public virtual bool setupMacro(String[] callArgs, int[] callArgTypes) { setupProxyArgs(callArgs, callArgTypes); parseTree(callArgs); return true; } /// <summary> /// parses the macro. We need to do this here, at init time, or else /// the local-scope template feature is hard to get to work :) /// </summary> private void parseTree(String[] callArgs) { try { //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' TextReader br = new StringReader(macroBody); /* * now parse the macro - and don't dump the namespace */ nodeTree = rsvc.parse(br, namespace_Renamed, false); /* * now, to make null references render as proper schmoo * we need to tweak the tree and change the literal of * the appropriate references * * we only do this at init time, so it's the overhead * is irrelevant */ Hashtable hm = new Hashtable(); for (int i = 1; i < argArray.Length; i++) { String arg = callArgs[i - 1]; /* * if the calling arg is indeed a reference * then we add to the map. We ignore other * stuff */ if (arg[0] == '$') { hm[argArray[i]] = arg; } } /* * now make one of our reference-munging visitor, and * let 'er rip */ VMReferenceMungeVisitor v = new VMReferenceMungeVisitor(hm); nodeTree.jjtAccept(v, null); } catch (Exception e) { rsvc.error("VelocimacroManager.parseTree() : exception " + macroName + " : " + StringUtils.stackTrace(e)); } } private void setupProxyArgs(String[] callArgs, int[] callArgTypes) { /* * for each of the args, make a ProxyArg */ for (int i = 1; i < argArray.Length; i++) { VMProxyArg arg = new VMProxyArg(rsvc, argArray[i], callArgs[i - 1], callArgTypes[i - 1]); proxyArgHash[argArray[i]] = arg; } } /// <summary> gets the args to the VM from the instance-use AST /// </summary> private String[] getArgArray(INode node) { int numArgs = node.jjtGetNumChildren(); String[] args = new String[numArgs]; callingArgTypes = new int[numArgs]; /* * eat the args */ int i = 0; Token t = null; Token tLast = null; while (i < numArgs) { args[i] = ""; /* * we want string literalss to lose the quotes. #foo( "blargh" ) should have 'blargh' patched * into macro body. So for each arg in the use-instance, treat the stringlierals specially... */ callingArgTypes[i] = node.jjtGetChild(i).Type; if (false && node.jjtGetChild(i).Type == ParserTreeConstants.JJTSTRINGLITERAL) { args[i] += node.jjtGetChild(i).FirstToken.image.Substring(1, (node.jjtGetChild(i).FirstToken.image.Length - 1) - (1)); } else { /* * just wander down the token list, concatenating everything together */ t = node.jjtGetChild(i).FirstToken; tLast = node.jjtGetChild(i).LastToken; while (t != tLast) { args[i] += t.image; t = t.next; } /* * don't forget the last one... :) */ args[i] += t.image; } i++; } return args; } } } --- NEW FILE: Literal.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Parser.Node; /// <summary> A very simple directive that leverages the Node.literal() /// to grab the literal rendition of a node. We basically /// grab the literal value on init(), then repeatedly use /// that during render(). /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: Literal.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class Literal : Directive { public override String Name { get { return "literal"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.BLOCK; } } internal String literalText; /// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> /// <summary> Store the literal rendition of a node using /// the Node.literal(). /// </summary> public override void init(RuntimeServices rs, InternalContextAdapter context, INode node) { base.init(rs, context, node); literalText = node.jjtGetChild(0).literal(); } /// <summary> Throw the literal rendition of the block between /// #literal()/#end into the writer. /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, INode node) { writer.Write(literalText); return true; } } } --- NEW FILE: Parse.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; using System.Text; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Resource; using Node = Parser.Node.INode; /// <summary> Pluggable directive that handles the #parse() statement in VTL. /// * /// Notes: /// ----- /// 1) The parsed source material can only come from somewhere in /// the TemplateRoot tree for security reasons. There is no way /// around this. If you want to include content from elsewhere on /// your disk, use a link from somwhere under Template Root to that /// content. /// * /// 2) There is a limited parse depth. It is set as a property /// "parse_directive.maxdepth = 10" for example. There is a 20 iteration /// safety in the event that the parameter isn't set. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:Chr...@dl...">Christoph Reck</a> /// </author> /// <version> $Id: Parse.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class Parse : Directive { public override String Name { get { return "parse"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.LINE; } } private bool ready = false; /// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> /// <summary> iterates through the argument list and renders every /// argument that is appropriate. Any non appropriate /// arguments are logged, but render() continues. /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, Node node) { /* * did we get an argument? */ if (node.jjtGetChild(0) == null) { rsvc.error("#parse() error : null argument"); return false; } /* * does it have a value? If you have a null reference, then no. */ Object value_Renamed = node.jjtGetChild(0).value_Renamed(context); if (value_Renamed == null) { rsvc.error("#parse() error : null argument"); return false; } /* * get the path */ //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' String arg = value_Renamed.ToString(); /* * see if we have exceeded the configured depth. * If it isn't configured, put a stop at 20 just in case. */ Object[] templateStack = context.TemplateNameStack; if (templateStack.Length >= rsvc.getInt(RuntimeConstants_Fields.PARSE_DIRECTIVE_MAXDEPTH, 20)) { StringBuilder path = new StringBuilder(); for (int i = 0; i < templateStack.Length; ++i) { path.Append(" > " + templateStack[i]); } rsvc.error("Max recursion depth reached (" + templateStack.Length + ")" + " File stack:" + path); return false; } Resource current = context.CurrentResource; /* * get the resource, and assume that we use the encoding of the current template * the 'current resource' can be null if we are processing a stream.... */ String encoding = null; if (current != null) { encoding = current.Encoding; } else { encoding = (String) rsvc.getProperty(RuntimeConstants_Fields.INPUT_ENCODING); } /* * now use the Runtime resource loader to get the template */ Template t = null; try { FileInfo f = new FileInfo(context.CurrentTemplateName); string directory = f.DirectoryName; if(arg.IndexOf("\\") < 0) arg = Path.Combine(directory, arg); t = rsvc.getTemplate(arg, encoding); } catch (ResourceNotFoundException rnfe) { /* * the arg wasn't found. Note it and throw */ rsvc.error("#parse(): cannot find template '" + arg + "', called from template " + context.CurrentTemplateName + " at (" + Line + ", " + Column + ")"); throw rnfe; } catch (ParseErrorException pee) { /* * the arg was found, but didn't parse - syntax error * note it and throw */ rsvc.error("#parse(): syntax error in #parse()-ed template '" + arg + "', called from template " + context.CurrentTemplateName + " at (" + Line + ", " + Column + ")"); throw pee; } catch (Exception e) { rsvc.error("#parse() : arg = " + arg + ". Exception : " + e); return false; } /* * and render it */ try { context.PushCurrentTemplateName(arg); ((SimpleNode) t.Data).render(context, writer); } catch (Exception e) { /* * if it's a MIE, it came from the render.... throw it... */ if (e is MethodInvocationException) { throw (MethodInvocationException) e; } rsvc.error("Exception rendering #parse( " + arg + " ) : " + e); return false; } finally { context.PopCurrentTemplateName(); } return true; } } } --- NEW FILE: Macro.cs --- using Node = NVelocity.Runtime.Parser.Node.INode; namespace NVelocity.Runtime.Directive { using System; using System.Collections; using System.IO; using System.Text; using NVelocity.Context; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// Macro.java /// /// Macro implements the macro definition directive of VTL. /// /// example : /// /// #macro( isnull $i ) /// #if( $i ) /// $i /// #end /// #end /// /// This object is used at parse time to mainly process and register the /// macro. It is used inline in the parser when processing a directive. /// /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: Macro.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $</version> public class Macro : Directive { public override String Name { get { return "macro"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.BLOCK; } } private static bool debugMode = false; /// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> /// <summary> render() doesn't do anything in the final output rendering. /// There is no output from a #macro() directive. /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, Node node) { /* * do nothing : We never render. The VelocimacroProxy object does that */ return true; } public override void init(RuntimeServices rs, InternalContextAdapter context, Node node) { base.init(rs, context, node); /* * again, don't do squat. We want the AST of the macro * block to hang off of this but we don't want to * init it... it's useless... */ return; } /// <summary> /// Used by Parser.java to process VMs withing the parsing process /// /// processAndRegister() doesn't actually render the macro to the output /// Processes the macro body into the internal representation used by the /// VelocimacroProxy objects, and if not currently used, adds it /// to the macro Factory /// </summary> public static void processAndRegister(RuntimeServices rs, Node node, String sourceTemplate) { /* * There must be at least one arg to #macro, * the name of the VM. Note that 0 following * args is ok for naming blocks of HTML */ int numArgs = node.jjtGetNumChildren(); /* * this number is the # of args + 1. The + 1 * is for the block tree */ if (numArgs < 2) { /* * error - they didn't name the macro or * define a block */ rs.error("#macro error : Velocimacro must have name as 1st " + "argument to #macro()"); return; } /* * get the arguments to the use of the VM */ String[] argArray = getArgArray(node); /* * now, try and eat the code block. Pass the root. */ IList macroArray = getASTAsStringArray(node.jjtGetChild(numArgs - 1)); /* * make a big string out of our macro */ StringBuilder temp = new StringBuilder(); for (int i = 0; i < macroArray.Count; i++) temp.Append(macroArray[i]); String macroBody = temp.ToString(); /* * now, try to add it. The Factory controls permissions, * so just give it a whack... */ bool bRet = rs.addVelocimacro(argArray[0], macroBody, argArray, sourceTemplate); return; } /// <summary> creates an array containing the literal /// strings in the macro arguement /// </summary> private static String[] getArgArray(Node node) { /* * remember : this includes the block tree */ int numArgs = node.jjtGetNumChildren(); numArgs--; // avoid the block tree... String[] argArray = new String[numArgs]; int i = 0; /* * eat the args */ while (i < numArgs) { argArray[i] = node.jjtGetChild(i).FirstToken.image; /* * trim off the leading $ for the args after the macro name. * saves everyone else from having to do it */ if (i > 0) { if (argArray[i].StartsWith("$")) argArray[i] = argArray[i].Substring(1, (argArray[i].Length) - (1)); } i++; } if (debugMode) { Console.Out.WriteLine("Macro.getArgArray() : #args = " + numArgs); Console.Out.Write(argArray[0] + "("); for (i = 1; i < numArgs; i++) Console.Out.Write(" " + argArray[i]); Console.Out.WriteLine(" )"); } return argArray; } /// <summary> Returns an array of the literal rep of the AST /// </summary> private static IList getASTAsStringArray(Node rootNode) { /* * this assumes that we are passed in the root * node of the code block */ Token t = rootNode.FirstToken; Token tLast = rootNode.LastToken; /* * now, run down the part of the tree bounded by * our first and last tokens */ ArrayList list = new ArrayList(); t = rootNode.FirstToken; while (t != tLast) { list.Add(NodeUtils.tokenLiteral(t)); t = t.next; } /* * make sure we get the last one... */ list.Add(NodeUtils.tokenLiteral(t)); return list; } } } --- NEW FILE: VMProxyArg.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; using NVelocity.Util; /// <summary> The function of this class is to proxy for the calling parameter to the VM. /// * /// This class is designed to be used in conjunction with the VMContext class /// which knows how to get and set values via it, rather than a simple get() /// or put() from a hashtable-like object. /// * /// There is probably a lot of undocumented subtlty here, so step lightly. /// * /// We rely on the observation that an instance of this object has a constant /// state throughout its lifetime as it's bound to the use-instance of a VM. /// In other words, it's created by the VelocimacroProxy class, to represent /// one of the arguments to a VM in a specific template. Since the template /// is fixed (it's a file...), we don't have to worry that the args to the VM /// will change. Yes, the VM will be called in other templates, or in other /// places on the same template, bit those are different use-instances. /// * /// These arguments can be, in the lingo of /// the parser, one of : /// <ul> /// <li> Reference() : anything that starts with '$' /// <li> StringLiteral() : something like "$foo" or "hello geir" /// <li> NumberLiteral() : 1, 2 etc /// <li> IntegerRange() : [ 1..2] or [$foo .. $bar] /// <li> ObjectArray() : [ "a", "b", "c"] /// <li> True() : true /// <li> False() : false /// <li>Word() : not likely - this is simply allowed by the parser so we can have /// syntactical sugar like #foreach($a in $b) where 'in' is the Word /// </ul> /// Now, Reference(), StringLit, NumberLit, IntRange, ObjArr are all dynamic things, so /// their value is gotten with the use of a context. The others are constants. The trick /// we rely on is that the context rather than this class really represents the /// state of the argument. We are simply proxying for the thing, returning the proper value /// when asked, and storing the proper value in the appropriate context when asked. /// * /// So, the hope here, so an instance of this can be shared across threads, is to /// keep any dynamic stuff out of it, relying on trick of having the appropriate /// context handed to us, and when a constant argument, letting VMContext punch that /// into a local context. /// /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: VMProxyArg.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class VMProxyArg { public virtual String CallerReference { get { return callerReference; } } public virtual String ContextReference { get { return contextReference; } } public virtual SimpleNode NodeTree { get { return nodeTree; } } public virtual Object StaticObject { get { return staticObject; } } public virtual int Type { get { return type; } } /// <summary>type of arg I will have /// </summary> private int type = 0; /// <summary>the AST if the type is such that it's dynamic (ex. JJTREFERENCE ) /// </summary> private SimpleNode nodeTree = null; /// <summary>reference for the object if we proxy for a static arg like an NumberLiteral /// </summary> private Object staticObject = null; /// <summary>not used in this impl : carries the appropriate user context /// </summary> private InternalContextAdapter usercontext = null; /// <summary>number of children in our tree if a reference /// </summary> private int numTreeChildren = 0; /// <summary>our identity in the current context /// </summary> private String contextReference = null; /// <summary>the reference we are proxying for /// </summary> private String callerReference = null; /// <summary>the 'de-dollared' reference if we are a ref but don't have a method attached /// </summary> private String singleLevelRef = null; /// <summary>by default, we are dynamic. safest /// </summary> private bool constant = false; /// <summary>in the event our type is switched - we don't care really what it is /// </summary> private const int GENERALSTATIC = - 1; private RuntimeServices rsvc = null; /// <summary> ctor for current impl /// * /// takes the reference literal we are proxying for, the literal /// the VM we are for is called with... /// * /// </summary> /// <param name="contextRef">reference arg in the definition of the VM, used in the VM /// </param> /// <param name="callerRef"> reference used by the caller as an arg to the VM /// </param> /// <param name="t"> type of arg : JJTREFERENCE, JJTTRUE, etc /// /// </param> public VMProxyArg(RuntimeServices rs, String contextRef, String callerRef, int t) { rsvc = rs; contextReference = contextRef; callerReference = callerRef; type = t; /* * make our AST if necessary */ setup(); /* * if we are multi-node tree, then save the size to * avoid fn call overhead */ if (nodeTree != null) numTreeChildren = nodeTree.jjtGetNumChildren(); /* * if we are a reference, and 'scalar' (i.e. $foo ) * then get the de-dollared ref so we can * hit our context directly, avoiding the AST */ if (type == ParserTreeConstants.JJTREFERENCE) { if (numTreeChildren == 0) { /* * do this properly and use the Reference node */ singleLevelRef = ((ASTReference) nodeTree).RootString; } } } /// <summary> tells if arg we are poxying for is /// dynamic or constant. /// * /// </summary> /// <returns>true of constant, false otherwise /// /// </returns> public virtual bool isConstant() { return constant; } /// <summary> Invoked by VMContext when Context.put() is called for a proxied reference. /// * /// </summary> /// <param name="context">context to modify via direct placement, or AST.setValue() /// </param> /// <param name="o"> new value of reference /// </param> /// <returns>Object currently null /// /// </returns> public virtual Object setObject(InternalContextAdapter context, Object o) { /* * if we are a reference, we could be updating a property */ if (type == ParserTreeConstants.JJTREFERENCE) { if (numTreeChildren > 0) { /* * we are a property, and being updated such as * #foo( $bar.BangStart) */ try { ((ASTReference) nodeTree).setValue(context, o); } catch (MethodInvocationException mie) { rsvc.error("VMProxyArg.getObject() : method invocation error setting value : " + mie); } } else { /* * we are a 'single level' reference like $foo, so we can set * out context directly */ context.Put(singleLevelRef, o); // alternate impl : usercontext.put( singleLevelRef, o); } } else { /* * if we aren't a reference, then we simply switch type, * get a new value, and it doesn't go into the context * * in current impl, this shouldn't happen. */ type = GENERALSTATIC; staticObject = o; rsvc.error("VMProxyArg.setObject() : Programmer error : I am a constant! No setting! : " + contextReference + " / " + callerReference); } return null; } /// <summary> returns the value of the reference. Generally, this is only /// called for dynamic proxies, as the static ones should have /// been stored in the VMContext's localcontext store /// * /// </summary> /// <param name="context">Context to use for getting current value /// </param> /// <returns>Object value /// * /// /// </returns> public virtual Object getObject(InternalContextAdapter context) { try { /* * we need to output based on our type */ Object retObject = null; if (type == ParserTreeConstants.JJTREFERENCE) { /* * two cases : scalar reference ($foo) or multi-level ($foo.bar....) */ if (numTreeChildren == 0) { /* * if I am a single-level reference, can I not get get it out of my context? */ retObject = context.Get(singleLevelRef); } else { /* * I need to let the AST produce it for me. */ retObject = nodeTree.execute(null, context); } } else if (type == ParserTreeConstants.JJTOBJECTARRAY) { retObject = nodeTree.value_Renamed(context); } else if (type == ParserTreeConstants.JJTINTEGERRANGE) { retObject = nodeTree.value_Renamed(context); } else if (type == ParserTreeConstants.JJTTRUE) { retObject = staticObject; } else if (type == ParserTreeConstants.JJTFALSE) { retObject = staticObject; } else if (type == ParserTreeConstants.JJTSTRINGLITERAL) { retObject = nodeTree.value_Renamed(context); } else if (type == ParserTreeConstants.JJTNUMBERLITERAL) { retObject = staticObject; } else if (type == ParserTreeConstants.JJTTEXT) { /* * this really shouldn't happen. text is just a thowaway arg for #foreach() */ try { StringWriter writer = new StringWriter(); nodeTree.render(context, writer); retObject = writer; } catch (Exception e) { rsvc.error("VMProxyArg.getObject() : error rendering reference : " + e); } } else if (type == GENERALSTATIC) { retObject = staticObject; } else { rsvc.error("Unsupported VM arg type : VM arg = " + callerReference + " type = " + type + "( VMProxyArg.getObject() )"); } return retObject; } catch (MethodInvocationException mie) { /* * not ideal, but otherwise we propogate out to the * VMContext, and the Context interface's put/get * don't throw. So this is a the best compromise * I can think of */ rsvc.error("VMProxyArg.getObject() : method invocation error getting value : " + mie); return null; } } /// <summary> does the housekeeping upon creationg. If a dynamic type /// it needs to make an AST for further get()/set() operations /// Anything else is constant. /// </summary> private void setup() { switch (type) { case ParserTreeConstants.JJTINTEGERRANGE: case ParserTreeConstants.JJTREFERENCE: case ParserTreeConstants.JJTOBJECTARRAY: case ParserTreeConstants.JJTSTRINGLITERAL: case ParserTreeConstants.JJTTEXT: { /* * dynamic types, just render */ constant = false; try { /* * fakie : wrap in directive to get the parser to treat our args as args * it doesn't matter that #include() can't take all these types, because we * just want the parser to consider our arg as a Directive/VM arg rather than * as if inline in schmoo */ String buff = "#include(" + callerReference + " ) "; //ByteArrayInputStream inStream = new ByteArrayInputStream( buff.getBytes() ); //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' TextReader br = new StringReader(buff); nodeTree = rsvc.parse(br, "VMProxyArg:" + callerReference, true); /* * now, our tree really is the first DirectiveArg(), and only one */ nodeTree = (SimpleNode) nodeTree.jjtGetChild(0).jjtGetChild(0); /* * sanity check */ if (nodeTree != null && nodeTree.Type != type) { rsvc.error("VMProxyArg.setup() : programmer error : type doesn't match node type."); } /* * init. We can do this as they are only references */ nodeTree.init(null, rsvc); } catch (Exception e) { rsvc.error("VMProxyArg.setup() : exception " + callerReference + " : " + StringUtils.stackTrace(e)); } break; } case ParserTreeConstants.JJTTRUE: { constant = true; staticObject = true; break; } case ParserTreeConstants.JJTFALSE: { constant = true; staticObject = false; break; } case ParserTreeConstants.JJTNUMBERLITERAL: { constant = true; staticObject = Int32.Parse(callerReference); break; } case ParserTreeConstants.JJTWORD: { /* * this is technically an error... */ rsvc.error("Unsupported arg type : " + callerReference + " You most likely intended to call a VM with a string literal, so enclose with ' or \" characters. (VMProxyArg.setup())"); constant = true; staticObject = new String(callerReference.ToCharArray()); break; } default: { rsvc.error(" VMProxyArg.setup() : unsupported type : " + callerReference); } break; } } /* * CODE FOR ALTERNATE IMPL : please ignore. I will remove when confortable with current. */ /// <summary> not used in current impl /// * /// Constructor for alternate impl where VelProxy class would make new /// VMProxyArg objects, and use this contructor to avoid reparsing the /// reference args /// * /// that impl also had the VMProxyArg carry it's context /// </summary> public VMProxyArg(VMProxyArg model, InternalContextAdapter c) { usercontext = c; contextReference = model.ContextReference; callerReference = model.CallerReference; nodeTree = model.NodeTree; staticObject = model.StaticObject; type = model.Type; if (nodeTree != null) numTreeChildren = nodeTree.jjtGetNumChildren(); if (type == ParserTreeConstants.JJTREFERENCE) { if (numTreeChildren == 0) { /* * use the reference node to do this... */ singleLevelRef = ((ASTReference) nodeTree).RootString; } } } } } --- NEW FILE: ParseDirectiveException.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.Collections; /// <summary> Exception for #parse() problems /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ParseDirectiveException.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ParseDirectiveException : Exception { private void InitBlock() { filenameStack = new Stack(); } public override String Message { get { String returnStr = "#parse() exception : depth = " + depthCount + " -> " + msg; returnStr += " File stack : "; try { while (!(filenameStack.Count == 0)) { returnStr += (String) filenameStack.Pop(); returnStr += " -> "; } } catch (Exception e) { } return returnStr; } } //UPGRADE_NOTE: The initialization of 'filenameStack' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Stack filenameStack; private String msg = ""; private int depthCount = 0; /// <summary> Constructor /// </summary> internal ParseDirectiveException(String m, int i) { InitBlock(); msg = m; depthCount = i; } /// <summary> Get a message. /// </summary> /// <summary> Add a file to the filename stack /// </summary> public virtual void addFile(String s) { Object temp_object; temp_object = s; Object generatedAux = temp_object; filenameStack.Push(temp_object); } } } --- NEW FILE: Foreach.cs --- //using ArrayIterator = NVelocity.Util.ArrayIterator; //using EnumerationIterator = NVelocity.Util.EnumerationIterator; namespace NVelocity.Runtime.Directive { using System; using System.Collections; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Parser.Node; using NVelocity.Util.Introspection; /// <summary> /// Foreach directive used for moving through arrays, /// or objects that provide an Iterator. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: Foreach.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $</version> public class Foreach : Directive { public override String Name { get { return "foreach"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.BLOCK; } } /// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> private static int UNKNOWN = - 1; /// <summary> Flag to indicate that the list object being used /// in an array. /// </summary> private const int INFO_ARRAY = 1; /// <summary> Flag to indicate that the list object being used /// provides an Iterator. /// </summary> private const int INFO_ITERATOR = 2; /// <summary> Flag to indicate that the list object being used /// is a Map. /// </summary> private const int INFO_MAP = 3; /// <summary> Flag to indicate that the list object being used /// is a Collection. /// </summary> private const int INFO_COLLECTION = 4; /// <summary> Flag to indicate that the list object being used /// is an Enumeration /// </summary> private const int INFO_ENUMERATION = 5; /// <summary> Flag to indicate that the list object being used /// is an IEnumerable /// </summary> private const int INFO_ENUMERABLE = 6; /// <summary> The name of the variable to use when placing /// the counter value into the context. Right /// now the default is $velocityCount. /// </summary> private String counterName; /// <summary> What value to start the loop counter at. /// </summary> private int counterInitialValue; /// <summary> The reference name used to access each /// of the elements in the list object. It /// is the $item in the following: /// /// #foreach ($item in $list) /// /// This can be used class wide because /// it is immutable. /// </summary> private String elementKey; /// <summary> simple init - init the tree and get the elementKey from /// the AST /// </summary> public override void init(RuntimeServices rs, InternalContextAdapter context, INode node) { base.init(rs, context, node); counterName = rsvc.getString(RuntimeConstants_Fields.COUNTER_NAME); counterInitialValue = rsvc.getInt(RuntimeConstants_Fields.COUNTER_INITIAL_VALUE); /* * this is really the only thing we can do here as everything * else is context sensitive */ elementKey = node.jjtGetChild(0).FirstToken.image.Substring(1); } /// <summary> returns an Iterator to the collection in the #foreach() /// /// </summary> /// <param name="context"> current context /// </param> /// <param name="node"> AST node /// </param> /// <returns>Iterator to do the dataset /// /// </returns> private IEnumerator getIterator(InternalContextAdapter context, INode node) { /* * get our list object, and punt if it's null. */ Object listObject = node.jjtGetChild(2).value_Renamed(context); if (listObject == null) return null; /* * See if we already know what type this is. * Use the introspection cache */ int type = UNKNOWN; IntrospectionCacheData icd = context.ICacheGet(this); Type c = listObject.GetType(); /* * if we have an entry in the cache, and the Class we have * cached is the same as the Class of the data object * then we are ok */ if (icd != null && icd.contextData == c) { /* dig the type out of the cata object */ type = ((Int32) icd.thingy); } /* * If we still don't know what this is, * figure out what type of object the list * element is, and get the iterator for it */ if (type == UNKNOWN) { if (listObject.GetType().IsArray) type = INFO_ARRAY; // NOTE: IDictionary needs to come before ICollection as it support ICollection else if (listObject is IDictionary) type = INFO_MAP; else if (listObject is ICollection) type = INFO_COLLECTION; else if (listObject is IEnumerable) type = INFO_ENUMERABLE; else if (listObject is IEnumerator) type = INFO_ENUMERATION; /* * if we did figure it out, cache it */ if (type != UNKNOWN) { icd = new IntrospectionCacheData(); icd.thingy = type; icd.contextData = c; context.ICachePut(this, icd); } } /* * now based on the type from either cache or examination... */ switch (type) { case INFO_COLLECTION: return ((ICollection) listObject).GetEnumerator(); case INFO_ENUMERABLE: return ((IEnumerable) listObject).GetEnumerator(); case INFO_ENUMERATION: rsvc.warn("Warning! The reference " + node.jjtGetChild(2).FirstToken.image + " is an Enumeration in the #foreach() loop at [" + Line + "," + Column + "]" + " in template " + context.CurrentTemplateName + ". Because it's not resetable," + " if used in more than once, this may lead to" + " unexpected results."); return (IEnumerator) listObject; case INFO_ARRAY: return ((Array) listObject).GetEnumerator(); case INFO_MAP: return ((IDictionary) listObject).GetEnumerator(); default: /* we have no clue what this is */ rsvc.warn("Could not determine type of enumerator (" + listObject.GetType().Name + ") in " + "#foreach loop for " + node.jjtGetChild(2).FirstToken.image + " at [" + Line + "," + Column + "]" + " in template " + context.CurrentTemplateName); return null; } } /// <summary> renders the #foreach() block /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, INode node) { /* * do our introspection to see what our collection is */ IEnumerator i = getIterator(context, node); if (i == null) return false; int counter = counterInitialValue; /* * save the element key if there is one, * and the loop counter */ Object o = context.Get(elementKey); Object ctr = context.Get(counterName); while (i.MoveNext()) { context.Put(counterName, counter); context.Put(elementKey, i.Current); node.jjtGetChild(3).render(context, writer); counter++; } /* * restores the loop counter (if we were nested) * if we have one, else just removes */ if (ctr != null) { context.Put(counterName, ctr); } else { context.Remove(counterName); } /* * restores element key if exists * otherwise just removes */ if (o != null) { context.Put(elementKey, o); } else { context.Remove(elementKey); } return true; } } } --- NEW FILE: DirectiveConstants.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * O... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 05:45:32
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Exception In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Runtime/Exception Added Files: NodeException.cs ReferenceException.cs Log Message: --- NEW FILE: NodeException.cs --- namespace NVelocity.Runtime.Exception { using System; using NVelocity.Runtime.Parser.Node; public class NodeException : Exception { public NodeException(String exceptionMessage, INode node) : base(exceptionMessage + ": " + node.literal() + " [line " + node.Line + ",column " + node.Column + "]") { } } } --- NEW FILE: ReferenceException.cs --- namespace NVelocity.Runtime.Exception { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Runtime.Parser.Node; /// <summary> Exception thrown when a bad reference is found. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ReferenceException.cs,v 1.3 2005/11/16 05:45:23 intesar66 Exp $ /// /// </version> public class ReferenceException : Exception { public ReferenceException(String exceptionMessage, INode node) : base(exceptionMessage + " [line " + node.Line + ",column " + node.Column + "] : " + node.literal() + " is not a valid reference.") { } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Commons/Collections In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Commons/Collections Added Files: CollectionsUtil.cs ExtendedProperties.cs PropertiesReader.cs PropertiesTokenizer.cs StringTokenizer.cs Log Message: --- NEW FILE: StringTokenizer.cs --- namespace Commons.Collections { using System; using System.Collections; public class StringTokenizer { private ArrayList elements; private string source; //The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character private string delimiters = " \t\n\r"; public StringTokenizer(string source) { this.elements = new ArrayList(); this.elements.AddRange(source.Split(this.delimiters.ToCharArray())); this.RemoveEmptyStrings(); this.source = source; } public StringTokenizer(string source, string delimiters) { this.elements = new ArrayList(); this.delimiters = delimiters; this.elements.AddRange(source.Split(this.delimiters.ToCharArray())); this.RemoveEmptyStrings(); this.source = source; } public int Count { get { return (this.elements.Count); } } public bool HasMoreTokens() { return (this.elements.Count > 0); } public string NextToken() { string result; if (source == "") { throw new Exception(); } else { this.elements = new ArrayList(); this.elements.AddRange(this.source.Split(delimiters.ToCharArray())); RemoveEmptyStrings(); result = (string) this.elements[0]; this.elements.RemoveAt(0); this.source = this.source.Replace(result, ""); this.source = this.source.TrimStart(this.delimiters.ToCharArray()); return result; } } public string NextToken(string delimiters) { this.delimiters = delimiters; return NextToken(); } private void RemoveEmptyStrings() { //VJ++ does not treat empty strings as tokens for (int index = 0; index < this.elements.Count; index++) if ((string) this.elements[index] == "") { this.elements.RemoveAt(index); index--; } } } } --- NEW FILE: PropertiesTokenizer.cs --- namespace Commons.Collections { using System; using System.Text; /// <summary> This class divides into tokens a property value. Token /// separator is "," but commas into the property value are escaped /// using the backslash in front. /// </summary> internal class PropertiesTokenizer : StringTokenizer { /// <summary> The property delimiter used while parsing (a comma). /// </summary> internal const String DELIMITER = ","; /// <summary> Constructor. /// </summary> /// <param name="string">A String. /// </param> public PropertiesTokenizer(String string_Renamed) : base(string_Renamed, DELIMITER) { } /// <summary> Check whether the object has more tokens. /// </summary> /// <returns>True if the object has more tokens. /// </returns> //UPGRADE_TODO: The equivalent of method java.util.StringTokenizer.hasMoreTokens is not an override method. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca5065"' public bool HasMoreTokens() { return base.HasMoreTokens(); } /// <summary> Get next token. /// </summary> /// <returns>A String. /// </returns> //UPGRADE_TODO: The equivalent of method java.util.StringTokenizer.nextToken is not an override method. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca5065"' public String NextToken() { StringBuilder buffer = new StringBuilder(); while (HasMoreTokens()) { String token = base.NextToken(); if (token.EndsWith("\\")) { buffer.Append(token.Substring(0, (token.Length - 1) - (0))); buffer.Append(DELIMITER); } else { buffer.Append(token); break; } } return buffer.ToString().Trim(); } } } --- NEW FILE: CollectionsUtil.cs --- namespace Commons.Collections { using System; using System.Collections; /// <summary> /// Static utility methods for collections /// </summary> public class CollectionsUtil { public static Object PutElement(Hashtable hashTable, Object key, Object newValue) { Object element = hashTable[key]; hashTable[key] = newValue; return element; } } } --- NEW FILE: ExtendedProperties.cs --- namespace Commons.Collections { using System; using System.Collections; using System.IO; using System.Text; /// <summary> This class extends normal Java properties by adding the possibility /// to use the same key many times concatenating the value strings /// instead of overwriting them. /// /// <p>The Extended Properties syntax is explained here: /// /// <ul> /// <li> /// Each property has the syntax <code>key = value</code> /// </li> /// <li> /// The <i>key</i> may use any character but the equal sign '='. [...1664 lines suppressed...] /// </param> /// <returns>ExtendedProperties configuration created from the /// properties object. /// /// </returns> public static ExtendedProperties ConvertProperties(ExtendedProperties p) { ExtendedProperties c = new ExtendedProperties(); for (IEnumerator e = (IEnumerator) p.Keys; e.MoveNext(); ) { String key = (String) e.Current; String value = p.GetProperty(key).ToString(); c.SetProperty(key, value); } return c; } } } --- NEW FILE: PropertiesReader.cs --- namespace Commons.Collections { using System; using System.IO; using System.Text; /// <summary> This class is used to read properties lines. These lines do /// not terminate with new-line chars but rather when there is no /// backslash sign a the end of the line. This is used to /// concatenate multiple lines for readability. /// </summary> internal class PropertiesReader : StreamReader { /// <summary> Constructor. /// * /// </summary> /// <param name="reader">A Reader. /// /// </param> public PropertiesReader(StreamReader reader) : base(reader.BaseStream) { } /// <summary> Read a property. /// * /// </summary> /// <returns>A String. /// </returns> /// <exception cref="">IOException. /// /// </exception> public virtual String ReadProperty() { StringBuilder buffer = new StringBuilder(); try { while (true) { String line = ReadLine().Trim(); if ((line.Length != 0) && (line[0] != '#')) { if (line.EndsWith("\\")) { line = line.Substring(0, (line.Length - 1) - (0)); buffer.Append(line); } else { buffer.Append(line); break; } } } } catch (NullReferenceException e) { return null; } return buffer.ToString(); } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App/Events In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/App/Events Added Files: EventCartridge.cs EventHandler.cs MethodExceptionEventHandler.cs NullSetEventHandler.cs ReferenceInsertionEventHandler.cs Log Message: --- NEW FILE: EventCartridge.cs --- namespace NVelocity.App.Events { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; /// <summary> 'Package' of event handlers... /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:j_a...@ya...">Jose Alberto Fernandez</a> /// </author> /// <version> $Id: EventCartridge.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public class EventCartridge : ReferenceInsertionEventHandler, NullSetEventHandler, MethodExceptionEventHandler { private ReferenceInsertionEventHandler rieh = null; private NullSetEventHandler nseh = null; private MethodExceptionEventHandler meeh = null; /// <summary> Adds an event handler(s) to the Cartridge. This method /// will find all possible event handler interfaces supported /// by the passed in object. /// * /// </summary> /// <param name="ev">object impementing a valid EventHandler-derived interface /// </param> /// <returns>true if a supported interface, false otherwise or if null /// /// </returns> public virtual bool addEventHandler(EventHandler ev) { if (ev == null) { return false; } bool found = false; if (ev is ReferenceInsertionEventHandler) { rieh = (ReferenceInsertionEventHandler) ev; found = true; } if (ev is NullSetEventHandler) { nseh = (NullSetEventHandler) ev; found = true; } if (ev is MethodExceptionEventHandler) { meeh = (MethodExceptionEventHandler) ev; found = true; } return found; } /// <summary> Removes an event handler(s) from the Cartridge. This method /// will find all possible event handler interfaces supported /// by the passed in object and remove them. /// * /// </summary> /// <param name="ev">object impementing a valid EventHandler-derived interface /// </param> /// <returns>true if a supported interface, false otherwise or if null /// /// </returns> public virtual bool removeEventHandler(EventHandler ev) { if (ev == null) { return false; } bool found = false; if (ev == rieh) { rieh = null; found = true; } if (ev == nseh) { nseh = null; found = true; } if (ev == meeh) { meeh = null; found = true; } return found; } /// <summary> Implementation of ReferenceInsertionEventHandler method /// <code>referenceInsert()</code>. /// * /// Called during Velocity merge before a reference value will /// be inserted into the output stream. /// * /// </summary> /// <param name="reference">reference from template about to be inserted /// </param> /// <param name="value"> value about to be inserted (after toString() ) /// </param> /// <returns>Object on which toString() should be called for output. /// /// </returns> public virtual Object referenceInsert(String reference, Object value_Renamed) { if (rieh == null) { return value_Renamed; } return rieh.referenceInsert(reference, value_Renamed); } /// <summary> Implementation of NullSetEventHandler method /// <code>shouldLogOnNullSet()</code>. /// * /// Called during Velocity merge to determine if when /// a #set() results in a null assignment, a warning /// is logged. /// * /// </summary> /// <param name="reference">reference from template about to be inserted /// </param> /// <returns>true if to be logged, false otherwise /// /// </returns> public virtual bool shouldLogOnNullSet(String lhs, String rhs) { if (nseh == null) { return true; } return nseh.shouldLogOnNullSet(lhs, rhs); } /// <summary> Implementation of MethodExceptionEventHandler method /// <code>methodException()</code>. /// * /// Called during Velocity merge if a reference is null /// * /// </summary> /// <param name="claz"> Class that is causing the exception /// </param> /// <param name="method">method called that causes the exception /// </param> /// <param name="e">Exception thrown by the method /// </param> /// <returns>Object to return as method result /// @throws exception to be wrapped and propogated to app /// /// </returns> public virtual Object methodException(Type claz, String method, Exception e) { /* * if we don't have a handler, just throw what we were handed */ if (meeh == null) { throw e; } /* * otherwise, call it.. */ return meeh.methodException(claz, method, e); } /// <summary> Attached the EventCartridge to the context /// * /// Final because not something one should mess with lightly :) /// * /// </summary> /// <param name="context">context to attach to /// </param> /// <returns>true if successful, false otherwise /// /// </returns> public bool attachToContext(IContext context) { if (context is InternalEventContext) { InternalEventContext iec = (InternalEventContext) context; iec.AttachEventCartridge(this); return true; } else { return false; } } } } --- NEW FILE: EventHandler.cs --- namespace NVelocity.App.Events { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Base interface for all event handlers /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: EventHandler.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public interface EventHandler { } } --- NEW FILE: MethodExceptionEventHandler.cs --- namespace NVelocity.App.Events { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Called when a method throws an exception. This gives the /// application a chance to deal with it and either /// return something nice, or throw. /// * /// Please return what you want rendered into the output stream. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: MethodExceptionEventHandler.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public interface MethodExceptionEventHandler : EventHandler { Object methodException(Type claz, String method, Exception e); } } --- NEW FILE: NullSetEventHandler.cs --- namespace NVelocity.App.Events { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Event handler : lets an app approve / veto /// writing a log message when RHS of #set() is null. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: NullSetEventHandler.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public interface NullSetEventHandler : EventHandler { /// <summary> Called when the RHS of a #set() is null, which will result /// in a null LHS. /// * /// </summary> /// <param name="lhs"> reference literal of left-hand-side of set statement /// </param> /// <param name="rhs"> reference literal of right-hand-side of set statement /// </param> /// <returns>true if log message should be written, false otherwise /// /// </returns> bool shouldLogOnNullSet(String lhs, String rhs); } } --- NEW FILE: ReferenceInsertionEventHandler.cs --- namespace NVelocity.App.Events { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Reference 'Stream insertion' event handler. Called with object /// that will be inserted into stream via value.toString(). /// * /// Please return an Object that will toString() nicely :) /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ReferenceInsertionEventHandler.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $ /// /// </version> public interface ReferenceInsertionEventHandler : EventHandler { /// <summary> A call-back which is executed during Velocity merge before a /// reference value is inserted into the output stream. /// * /// </summary> /// <param name="reference">Reference from template about to be inserted. /// </param> /// <param name="value">Value about to be inserted (after its /// <code>toString()</code> method is called). /// </param> /// <returns>Object on which <code>toString()</code> should be /// called for output. /// /// </returns> Object referenceInsert(String reference, Object value_Renamed); } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:30
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Dvsl/Directive In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Dvsl/Directive Added Files: MatchDirective.cs NameDirective.cs Log Message: --- NEW FILE: NameDirective.cs --- namespace NVelocity.Dvsl.Directive { using System; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Directive; using NVelocity.Runtime.Parser.Node; /// <summary> /// To implement the functionality of <xsl:template name=> /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public class NameDirective : Directive { public override String Name { get { return "name"; } set { throw new NotSupportedException(); } } public override Int32 Type { get { return DirectiveConstants_Fields.BLOCK; } } public override Boolean render(InternalContextAdapter context, TextWriter writer, INode node) { return true; } } } --- NEW FILE: MatchDirective.cs --- namespace NVelocity.Dvsl.Directive { using System; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Directive; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// Velocity Directive to handle template registration of /// match declarations (like the XSLT match=) /// </summary> /// <author><a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public class MatchDirective : Directive { public override String Name { get { return "match"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.BLOCK; } } public override bool render(InternalContextAdapter context, TextWriter writer, INode node) { /* * what is our arg? */ INode n = node.jjtGetChild(0); if (n.Type == ParserTreeConstants.JJTSTRINGLITERAL) { try { String element = (String) node.jjtGetChild(0).value_Renamed(context); TemplateHandler th = (TemplateHandler) rsvc.getApplicationAttribute("NVelocity.Dvsl.TemplateHandler"); th.RegisterMatch(element, (SimpleNode) node.jjtGetChild(node.jjtGetNumChildren() - 1)); } catch (Exception ee) { } } return true; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:45:30
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Dvsl/Resource In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/Dvsl/Resource Added Files: defaultroot.dvsl Log Message: --- NEW FILE: defaultroot.dvsl --- ## ## This is the default root template, to make it behave like XSLT ## #match( "/" )$context.applyTemplates()#end #match("*")$context.applyTemplates()#end ## #match("text()")$node.value()#end ## #match("@*")$node.value()#end |
From: Sean M. <int...@us...> - 2005-11-16 05:45:29
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity Added Files: Adapdev.NVelocity.csproj SupportClass.cs VelocityContext.cs readme.txt Log Message: --- NEW FILE: VelocityContext.cs --- namespace NVelocity { using System; using System.Collections; using NVelocity.Context; /// <summary> /// General purpose implemention of the application Context /// interface for general application use. This class should /// be used in place of the original Context class. /// </summary> /// <seealso cref=" java.util.HashMap ) /// for data storage. /// /// This context implementation cannot be shared between threads /// without those threads synchronizing access between them, as /// the HashMap is not synchronized, nor are some of the fundamentals /// of AbstractContext. If you need to share a Context between /// threads with simultaneous access for some reason, please create /// your own and extend the interface Context /// /// "/> /// <seealso cref="NVelocity.Context.Context"/> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:fed...@ho...">Fedor Karpelevitch</a></author> /// <author> <a href="mailto:dl...@fi...">Daniel Rall</a></author> /// <version> $Id: VelocityContext.cs,v 1.3 2005/11/16 05:45:21 intesar66 Exp $</version> public class VelocityContext : AbstractContext { /// <summary> /// Storage for key/value pairs. /// </summary> private Hashtable context = null; /// <summary> /// Creates a new instance (with no inner context). /// </summary> public VelocityContext() : this(null, null) { } /// /// <summary> /// Creates a new instance with the provided storage (and no inner context). /// </summary> public VelocityContext(Hashtable context) : this(context, null) { } /// <summary> /// Chaining constructor, used when you want to /// wrap a context in another. The inner context /// will be 'read only' - put() calls to the /// wrapping context will only effect the outermost /// context /// </summary> /// <param name="innerContext">The <code>Context</code> implementation to wrap.</param> public VelocityContext(IContext innerContext) : this(null, innerContext) { } /// <summary> /// Initializes internal storage (never to <code>null</code>), and /// inner context. /// </summary> /// <param name="context">Internal storage, or <code>null</code> to /// create default storage. /// </param> /// <param name="innerContext">Inner context. /// /// </param> public VelocityContext(Hashtable context, IContext innerContext) : base(innerContext) { this.context = (context == null ? new Hashtable() : context); } /// <summary> /// retrieves value for key from internal /// storage /// </summary> /// <param name="key">name of value to get</param> /// <returns>value as object</returns> public override Object InternalGet(String key) { return context[key]; } /// <summary> /// stores the value for key to internal /// storage /// </summary> /// <param name="key">name of value to store</param> /// <param name="value">value to store</param> /// <returns>previous value of key as Object</returns> public override Object InternalPut(String key, Object value_Renamed) { return context[key] = value_Renamed; } /// <summary> /// determines if there is a value for the /// given key /// </summary> /// <param name="key">name of value to check</param> /// <returns>true if non-null value in store</returns> public override bool InternalContainsKey(Object key) { return context.ContainsKey(key); } /// <summary> /// returns array of keys /// </summary> /// <returns>keys as []</returns> public override Object[] InternalGetKeys() { throw new NotImplementedException(); //TODO //return context.keySet().toArray(); } /// <summary> /// remove a key/value pair from the /// internal storage /// </summary> /// <param name="key">name of value to remove</param> /// <returns>value removed</returns> public override Object InternalRemove(Object key) { Object o = context[key]; context.Remove(key); return o; } /// <summary> /// Clones this context object. /// </summary> /// <returns>A deep copy of this <code>Context</code>.</returns> public Object Clone() { VelocityContext clone = null; try { clone = (VelocityContext) base.MemberwiseClone(); clone.context = new Hashtable(context); } catch (System.Exception) { // ignore } return clone; } } } --- NEW FILE: SupportClass.cs --- namespace NVelocity { using System; using System.Collections; using System.Data; using System.Data.OleDb; using System.Globalization; using System.IO; public class SupportClass { public static sbyte[] ToSByteArray(byte[] byteArray) { sbyte[] sbyteArray = new sbyte[byteArray.Length]; for (int index = 0; index < byteArray.Length; index++) sbyteArray[index] = (sbyte) byteArray[index]; return sbyteArray; } /*******************************/ public static byte[] ToByteArray(sbyte[] sbyteArray) { byte[] byteArray = new byte[sbyteArray.Length]; for (int index = 0; index < sbyteArray.Length; index++) byteArray[index] = (byte) sbyteArray[index]; return byteArray; } /*******************************/ public static Object PutElement(Hashtable hashTable, Object key, Object newValue) { Object element = hashTable[key]; hashTable[key] = newValue; return element; } /*******************************/ public class TransactionManager { public static ConnectionHashTable manager = new ConnectionHashTable(); public class ConnectionHashTable : Hashtable { public OleDbCommand CreateStatement(OleDbConnection connection) { OleDbCommand command = connection.CreateCommand(); OleDbTransaction transaction; if (this[connection] != null) { ConnectionProperties Properties = ((ConnectionProperties) this[connection]); transaction = Properties.Transaction; command.Transaction = transaction; } else { ConnectionProperties TempProp = new ConnectionProperties(); TempProp.AutoCommit = false; TempProp.TransactionLevel = 0; command.Transaction = TempProp.Transaction; Add(connection, TempProp); } return command; } public void Commit(OleDbConnection connection) { if (this[connection] != null && ((ConnectionProperties) this[connection]).AutoCommit) { OleDbTransaction transaction = ((ConnectionProperties) this[connection]).Transaction; transaction.Commit(); } } public void RollBack(OleDbConnection connection) { if (this[connection] != null && ((ConnectionProperties) this[connection]).AutoCommit) { OleDbTransaction transaction = ((ConnectionProperties) this[connection]).Transaction; transaction.Rollback(); } } public void SetAutoCommit(OleDbConnection connection, bool boolean) { if (this[connection] != null) { ConnectionProperties Properties = ((ConnectionProperties) this[connection]); Properties.AutoCommit = boolean; if (!boolean) { OleDbTransaction transaction = Properties.Transaction; if (Properties.TransactionLevel == 0) { transaction = connection.BeginTransaction(); } else { transaction = connection.BeginTransaction(Properties.TransactionLevel); } } } else { ConnectionProperties TempProp = new ConnectionProperties(); TempProp.AutoCommit = boolean; TempProp.TransactionLevel = 0; if (boolean) TempProp.Transaction = connection.BeginTransaction(); Add(connection, TempProp); } } public OleDbCommand PrepareStatement(OleDbConnection connection, string sql) { OleDbCommand command = this.CreateStatement(connection); command.CommandText = sql; return command; } public OleDbCommand PrepareCall(OleDbConnection connection, string sql) { OleDbCommand command = this.CreateStatement(connection); command.CommandText = sql; return command; } public void SetTransactionIsolation(OleDbConnection connection, int level) { if (this[connection] != null) { ConnectionProperties Properties = ((ConnectionProperties) this[connection]); Properties.TransactionLevel = (IsolationLevel) level; } else { ConnectionProperties TempProp = new ConnectionProperties(); TempProp.AutoCommit = false; TempProp.TransactionLevel = (IsolationLevel) level; Add(connection, TempProp); } } public int GetTransactionIsolation(OleDbConnection connection) { if (this[connection] != null) { ConnectionProperties Properties = ((ConnectionProperties) this[connection]); if (Properties.TransactionLevel != 0) return (int) Properties.TransactionLevel; else return 2; } else return 2; } public bool GetAutoCommit(OleDbConnection connection) { if (this[connection] != null) { return ((ConnectionProperties) this[connection]).AutoCommit; } else return false; } private class ConnectionProperties { public bool AutoCommit; public OleDbTransaction Transaction; public IsolationLevel TransactionLevel; } } } /*******************************/ public class Tokenizer { private ArrayList elements; private string source; //The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character private string delimiters = " \t\n\r"; public Tokenizer(string source) { this.elements = new ArrayList(); this.elements.AddRange(source.Split(this.delimiters.ToCharArray())); this.RemoveEmptyStrings(); this.source = source; } public Tokenizer(string source, string delimiters) { this.elements = new ArrayList(); this.delimiters = delimiters; this.elements.AddRange(source.Split(this.delimiters.ToCharArray())); this.RemoveEmptyStrings(); this.source = source; } public int Count { get { return (this.elements.Count); } } public bool HasMoreTokens() { return (this.elements.Count > 0); } public string NextToken() { string result; if (source == "") throw new System.Exception(); else { this.elements = new ArrayList(); this.elements.AddRange(this.source.Split(delimiters.ToCharArray())); RemoveEmptyStrings(); result = (string) this.elements[0]; this.elements.RemoveAt(0); this.source = this.source.Replace(result, ""); this.source = this.source.TrimStart(this.delimiters.ToCharArray()); return result; } } public string NextToken(string delimiters) { this.delimiters = delimiters; return NextToken(); } private void RemoveEmptyStrings() { //VJ++ does not treat empty strings as tokens for (int index = 0; index < this.elements.Count; index++) if ((string) this.elements[index] == "") { this.elements.RemoveAt(index); index--; } } } /*******************************/ public static long FileLength(FileInfo file) { if (Directory.Exists(file.FullName)) return 0; else return file.Length; } /*******************************/ public static void WriteStackTrace(System.Exception throwable, TextWriter stream) { stream.Write(throwable.StackTrace); stream.Flush(); } public class TextNumberFormat { // Declaration of fields private NumberFormatInfo numberFormat; private enum formatTypes { General, Number, Currency, Percent } ; private int numberFormatType; private bool groupingActivated; private string separator; private int digits; // CONSTRUCTORS public TextNumberFormat() { this.numberFormat = new NumberFormatInfo(); this.numberFormatType = (int) formatTypes.General; this.groupingActivated = true; this.separator = this.GetSeparator((int) formatTypes.General); this.digits = 3; } private TextNumberFormat(formatTypes theType, int digits) { this.numberFormat = NumberFormatInfo.CurrentInfo; this.numberFormatType = (int) theType; this.groupingActivated = true; this.separator = this.GetSeparator((int) theType); this.digits = digits; } private TextNumberFormat(formatTypes theType, CultureInfo cultureNumberFormat, int digits) { this.numberFormat = cultureNumberFormat.NumberFormat; this.numberFormatType = (int) theType; this.groupingActivated = true; this.separator = this.GetSeparator((int) theType); this.digits = digits; } public static TextNumberFormat getTextNumberInstance() { TextNumberFormat instance = new TextNumberFormat(formatTypes.Number, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance() { TextNumberFormat instance = new TextNumberFormat(formatTypes.Currency, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance() { TextNumberFormat instance = new TextNumberFormat(formatTypes.Percent, 3); return instance; } public static TextNumberFormat getTextNumberInstance(CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(formatTypes.Number, culture, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance(CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(formatTypes.Currency, culture, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance(CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(formatTypes.Percent, culture, 3); return instance; } public Object Clone() { return (Object) this; } public override bool Equals(Object textNumberObject) { return Object.Equals((Object) this, textNumberObject); } public string FormatDouble(double number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits, this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits, this.numberFormat)).Replace(this.separator, ""); } } public string FormatLong(long number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits, this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits, this.numberFormat)).Replace(this.separator, ""); } } public static CultureInfo[] GetAvailableCultures() { return CultureInfo.GetCultures(CultureTypes.AllCultures); } public override int GetHashCode() { return this.GetHashCode(); } private string GetCurrentFormatString() { string currentFormatString = "n"; //Default value switch (this.numberFormatType) { case (int) formatTypes.Currency: currentFormatString = "c"; break; case (int) formatTypes.General: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int) formatTypes.Number: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int) formatTypes.Percent: currentFormatString = "p"; break; } return currentFormatString; } private string GetSeparator(int numberFormatType) { string separatorItem = " "; //Default Separator switch (numberFormatType) { case (int) formatTypes.Currency: separatorItem = this.numberFormat.CurrencyGroupSeparator; break; case (int) formatTypes.General: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int) formatTypes.Number: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int) formatTypes.Percent: separatorItem = this.numberFormat.PercentGroupSeparator; break; } return separatorItem; } public bool GroupingUsed { get { return (this.groupingActivated); } set { this.groupingActivated = value; } } public int Digits { get { return this.digits; } set { this.digits = value; } } } /*******************************/ public class DateTimeFormatManager { public static DateTimeFormatHashTable manager = new DateTimeFormatHashTable(); public class DateTimeFormatHashTable : Hashtable { public void SetDateFormatPattern(DateTimeFormatInfo format, String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).DateFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.DateFormatPattern = newPattern; Add(format, tempProps); } } public string GetDateFormatPattern(DateTimeFormatInfo format) { if (this[format] == null) return "d-MMM-yy"; else return ((DateTimeFormatProperties) this[format]).DateFormatPattern; } public void SetTimeFormatPattern(DateTimeFormatInfo format, String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).TimeFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.TimeFormatPattern = newPattern; Add(format, tempProps); } } public string GetTimeFormatPattern(DateTimeFormatInfo format) { if (this[format] == null) return "h:mm:ss tt"; else return ((DateTimeFormatProperties) this[format]).TimeFormatPattern; } private class DateTimeFormatProperties { public string DateFormatPattern = "d-MMM-yy"; public string TimeFormatPattern = "h:mm:ss tt"; } } } /*******************************/ public static string FormatDateTime(DateTimeFormatInfo format, DateTime date) { string timePattern = DateTimeFormatManager.manager.GetTimeFormatPattern(format); string datePattern = DateTimeFormatManager.manager.GetDateFormatPattern(format); return date.ToString(datePattern + " " + timePattern, format); } /*******************************/ public static DateTimeFormatInfo GetDateTimeFormatInstance(int dateStyle, int timeStyle, CultureInfo culture) { DateTimeFormatInfo format = culture.DateTimeFormat; switch (timeStyle) { case -1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss 'o clock' tt zzz"); break; case 1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt zzz"); break; case 2: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt"); break; case 3: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm tt"); break; } switch (dateStyle) { case -1: DateTimeFormatManager.manager.SetDateFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetDateFormatPattern(format, "dddd, MMMM dd%, yyy"); break; case 1: DateTimeFormatManager.manager.SetDateFormatPattern(format, "MMMM dd%, yyy"); break; case 2: DateTimeFormatManager.manager.SetDateFormatPattern(format, "d-MMM-yy"); break; case 3: DateTimeFormatManager.manager.SetDateFormatPattern(format, "M/dd/yy"); break; } return format; } } } --- NEW FILE: readme.txt --- Adapdev.NVelocity is a modified version of the NVelocity project (http://nvelocity.sourceforge.net/). The following changes have taken place: - Switched to Adapdev.NET library version - Signed with Adapdev.NET key - Removed Html portions of library - Removed logging portions of library - Fixed issue with relative file path references in #parse call --- NEW FILE: Adapdev.NVelocity.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{75D57D5C-250A-447C-80BC-2FF9DC8A14D2}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.NVelocity" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.NVelocity" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "readme.txt" BuildAction = "Content" /> <File RelPath = "SupportClass.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Template.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "VelocityContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\AppSupportClass.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\FieldMethodizer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Velocity.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\VelocityEngine.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\EventCartridge.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\EventHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\MethodExceptionEventHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\NullSetEventHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\ReferenceInsertionEventHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Tools\VelocityFormatter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\CollectionsUtil.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\ExtendedProperties.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\PropertiesReader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\PropertiesTokenizer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\StringTokenizer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\AbstractContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\IContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalContextAdapter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalContextAdapterImpl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalContextBase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalEventContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalHousekeepingContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalWrapperContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\VMContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Dvsl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\DvslContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\DvslNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\DvslNodeContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\DvslNodeImpl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\TemplateHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Transformer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\TransformTool.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Directive\MatchDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Directive\NameDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Resource\defaultroot.dvsl" BuildAction = "None" /> <File RelPath = "Exception\MethodInvocationException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Exception\ParseErrorException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Exception\ResourceNotFoundException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Exception\VelocityException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IO\VelocityWriter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\RuntimeConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\RuntimeInstance.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\RuntimeServices.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\RuntimeSingleton.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\VelocimacroFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\VelocimacroManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Defaults\directive.properties" BuildAction = "None" /> <File RelPath = "Runtime\Defaults\nvelocity.properties" BuildAction = "None" /> <File RelPath = "Runtime\Directive\Directive.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\DirectiveConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Foreach.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Include.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Literal.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Macro.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Parse.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\ParseDirectiveException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\VelocimacroProxy.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\VMProxyArg.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Exception\NodeException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Exception\ReferenceException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\CharStream.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\JJTParserState.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\ParseException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Parser.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\ParserConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\ParserTokenManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\ParserTreeConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Token.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\TokenMgrError.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\VelocityCharStream.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\AbstractExecutor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTAddNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTAndNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTAssignment.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTBlock.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTComment.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTDivNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTElseIfStatement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTElseStatement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTEQNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTEscape.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTEscapedDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTExpression.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTFalse.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTGENode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTGTNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTIdentifier.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTIfStatement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTIncludeStatement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTIntegerRange.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTLENode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTLTNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTMethod.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTModNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTMulNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTNENode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTNotNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTNumberLiteral.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTObjectArray.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTOrNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTParameters.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTprocess.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTReference.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTSetDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTStringLiteral.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTSubtractNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTText.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTTrue.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTVariable.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTWord.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\BooleanPropertyExecutor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\GetExecutor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\INode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\NodeUtils.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ParserVisitor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\PropertyExecutor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\SimpleNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ContentResource.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Resource.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceCacheImpl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceManagerImpl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Loader\FileResourceLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Loader\ResourceLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Loader\ResourceLoaderFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Loader\ResourceLocator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Visitor\BaseVisitor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Visitor\NodeViewMode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Visitor\VMReferenceMungeVisitor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Tool\DataInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Tool\IToolInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Tool\ToolLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Iterator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\SimplePool.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\StringUtils.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\AmbiguousException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\ClassMap.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\IntrospectionCacheData.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\Introspector.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\IntrospectorBase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\MethodMap.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\Twonk.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> |